Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f924161d6 | ||
|
|
d31b7b62d8 | ||
|
|
00ed2796f1 | ||
|
|
313d8f34de | ||
|
|
954fbfc65b | ||
|
|
3f84b0b50b | ||
|
|
ca2004112b | ||
|
|
458c9df105 | ||
|
|
50706080c2 | ||
|
|
b6ef8a31bc | ||
|
|
4cd908d7af | ||
|
|
c0dfa8ef19 | ||
|
|
fa14698115 | ||
|
|
8a73120dbb | ||
|
|
c2eca90644 | ||
|
|
bcd19c9cd0 | ||
|
|
10ade7fc41 | ||
|
|
5286cb2bfd | ||
|
|
65fcc307bb | ||
|
|
14a4f80aab | ||
|
|
f52eca74ce | ||
|
|
2789a82ef4 | ||
|
|
2344e5dae1 | ||
|
|
c3b5e6e13b | ||
|
|
ffd50fa147 | ||
|
|
7ec61d18e6 | ||
|
|
b8bdb0f20c |
No files matched your search
@@ -4,6 +4,7 @@
|
||||
# CHANGELOG section for that version as the body. A gate failure in any build means no release.
|
||||
#
|
||||
# ygol-engine-win64.zip ygol-engine.dll, ygol-engine.pdb, engine.json
|
||||
# ygol-engine-binding.zip YGOLegacy.Engine.dll, YGOLegacy.Engine.pdb (the C# binding, built and tested by dotnet)
|
||||
# ygol-engine-linux-x64.tar.gz libygol-engine.so, engine.json
|
||||
# ygoserver-linux-x64.tar.gz ygoserver, engine.json
|
||||
# ygol-engine-android-arm64.tar.gz libygol-engine.so, engine.json
|
||||
@@ -32,7 +33,7 @@ env:
|
||||
|
||||
jobs:
|
||||
windows:
|
||||
runs-on: unity-windows
|
||||
runs-on: [winold, windows]
|
||||
defaults:
|
||||
run:
|
||||
shell: powershell
|
||||
@@ -56,7 +57,7 @@ jobs:
|
||||
git clean -fdx -e out
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
|
||||
- name: Build (contract check, export gate 334, engine.json)
|
||||
- name: Build (contract check, export gate 336, engine.json)
|
||||
id: build
|
||||
run: |
|
||||
$version = "local"
|
||||
@@ -80,11 +81,30 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
Get-ChildItem $stage | Format-Table Name, Length
|
||||
|
||||
- name: Binding (dotnet build + test, ygol-engine-binding.zip)
|
||||
run: |
|
||||
$version = "local"
|
||||
if ($env:GITHUB_REF -like "refs/tags/v*") { $version = $env:GITHUB_REF_NAME }
|
||||
Set-Location $env:CHECKOUT_DIR
|
||||
dotnet build binding\YGOLegacy.Engine -c Release -p:EngineVersion=$version
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
dotnet test binding\YGOLegacy.Engine.Tests -c Release -p:EngineVersion=$version
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
$bin = "$env:CHECKOUT_DIR\binding\YGOLegacy.Engine\bin\Release\netstandard2.1"
|
||||
$got = (Get-Item "$bin\YGOLegacy.Engine.dll").VersionInfo.ProductVersion
|
||||
Write-Host "YGOLegacy.Engine.dll ProductVersion = $got"
|
||||
if ($got -ne $version) { Write-Host "##[error]YGOLegacy.Engine.dll is stamped '$got', expected '$version'"; exit 1 }
|
||||
$stage = "$env:OUT_DIR\$version"
|
||||
Copy-Item "$bin\YGOLegacy.Engine.dll", "$bin\YGOLegacy.Engine.pdb" $stage
|
||||
tar.exe -a -cf "$stage\ygol-engine-binding.zip" -C $stage YGOLegacy.Engine.dll YGOLegacy.Engine.pdb
|
||||
if ($LASTEXITCODE -ne 0) { exit 1 }
|
||||
Get-ChildItem $stage | Format-Table Name, Length
|
||||
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build (contract check, export gate 855, engine.json)
|
||||
- name: Build (contract check, export gate 857, engine.json)
|
||||
run: |
|
||||
version=local
|
||||
case "$GITHUB_REF" in refs/tags/v*) version="$GITHUB_REF_NAME";; esac
|
||||
@@ -106,7 +126,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build (contract check, export gate 849, engine.json)
|
||||
- name: Build (contract check, export gate 851, engine.json)
|
||||
run: |
|
||||
version=local
|
||||
case "$GITHUB_REF" in refs/tags/v*) version="$GITHUB_REF_NAME";; esac
|
||||
@@ -139,16 +159,16 @@ jobs:
|
||||
run: |
|
||||
set -eu
|
||||
tag="$GITHUB_REF_NAME"
|
||||
for f in dist/linux-x64/engine.json dist/android-arm64/engine.json; do
|
||||
v=$(jq -r .version "$f"); [ "$v" = "$tag" ] || { echo "::error::$f says version $v, tag is $tag"; exit 1; }
|
||||
done
|
||||
echo "$WINDOWS_ENGINE" | jq -c . > dist/engine-windows.json
|
||||
[ "$(jq -r .version dist/engine-windows.json)" = "$tag" ] || { echo "::error::Windows engine.json does not say $tag"; exit 1; }
|
||||
# the export count is per platform; protocol and capabilities must agree everywhere
|
||||
for f in dist/engine-windows.json dist/linux-x64/engine.json dist/android-arm64/engine.json; do
|
||||
jq -c '{version, protocol, capabilities}' "$f"
|
||||
v=$(jq -r .version "$f"); [ "$v" = "$tag" ] || { echo "::error::$f says version $v, tag is $tag"; exit 1; }
|
||||
b=$(jq -r .binding "$f"); [ "$b" = "$tag" ] || { echo "::error::$f says binding $b, tag is $tag"; exit 1; }
|
||||
done
|
||||
# the export count is per platform; version, protocol, capabilities and binding must agree everywhere
|
||||
for f in dist/engine-windows.json dist/linux-x64/engine.json dist/android-arm64/engine.json; do
|
||||
jq -c '{version, protocol, capabilities, binding}' "$f"
|
||||
done | sort -u | tee dist/agree.txt
|
||||
[ "$(wc -l < dist/agree.txt)" -eq 1 ] || { echo "::error::the platforms disagree on version / protocol / capabilities"; exit 1; }
|
||||
[ "$(wc -l < dist/agree.txt)" -eq 1 ] || { echo "::error::the platforms disagree on version / protocol / capabilities / binding"; exit 1; }
|
||||
cp dist/linux-x64/engine.json dist/engine.json
|
||||
- name: The CHANGELOG section for this version is the release body
|
||||
run: |
|
||||
@@ -186,24 +206,26 @@ jobs:
|
||||
attach-windows:
|
||||
needs: [windows, release]
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: unity-windows
|
||||
runs-on: [winold, windows]
|
||||
defaults:
|
||||
run:
|
||||
shell: powershell
|
||||
steps:
|
||||
- name: Attach ygol-engine-win64.zip
|
||||
- name: Attach ygol-engine-win64.zip and ygol-engine-binding.zip
|
||||
run: |
|
||||
$tag = $env:GITHUB_REF_NAME
|
||||
$zip = "$env:OUT_DIR\$tag\ygol-engine-win64.zip"
|
||||
if (-not (Test-Path $zip)) { Write-Host "##[error]$zip is missing"; exit 1 }
|
||||
$id = "${{ needs.release.outputs.id }}"
|
||||
$respFile = Join-Path $env:TEMP "ygol-engine-upload.txt"
|
||||
$status = & curl.exe -s -o $respFile -w "%{http_code}" -X POST `
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -F "attachment=@$zip" `
|
||||
"$env:API/releases/$id/assets?name=ygol-engine-win64.zip"
|
||||
if ($LASTEXITCODE -ne 0 -or [int]$status -ge 400) {
|
||||
Write-Host "curl exit=$LASTEXITCODE http=$status"
|
||||
if (Test-Path $respFile) { Get-Content $respFile -TotalCount 20 }
|
||||
exit 1
|
||||
foreach ($name in @("ygol-engine-win64.zip", "ygol-engine-binding.zip")) {
|
||||
$zip = "$env:OUT_DIR\$tag\$name"
|
||||
if (-not (Test-Path $zip)) { Write-Host "##[error]$zip is missing"; exit 1 }
|
||||
$status = & curl.exe -s -o $respFile -w "%{http_code}" -X POST `
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -F "attachment=@$zip" `
|
||||
"$env:API/releases/$id/assets?name=$name"
|
||||
if ($LASTEXITCODE -ne 0 -or [int]$status -ge 400) {
|
||||
Write-Host "curl exit=$LASTEXITCODE http=$status"
|
||||
if (Test-Path $respFile) { Get-Content $respFile -TotalCount 20 }
|
||||
exit 1
|
||||
}
|
||||
Write-Host "attached $name to release $id ($tag)"
|
||||
}
|
||||
Write-Host "attached ygol-engine-win64.zip to release $id ($tag)"
|
||||
@@ -3,6 +3,8 @@
|
||||
/server/obj/
|
||||
/server/bin/
|
||||
/out/
|
||||
binding/**/bin/
|
||||
binding/**/obj/
|
||||
|
||||
# what libevent's Windows prebuild step copies from WIN32-Code into include/
|
||||
/server/event/include/evconfig-private.h
|
||||
|
||||
+117
-2
@@ -5,9 +5,124 @@ wire protocol, the engine message stream, the setup pairs and the Lua API. A row
|
||||
change first shipped in the Unity repo, the ticket, and the contract part it touched. Rows 0001-0024
|
||||
are the fork patches replayed into this repo as commits (`git log --oneline -- server/gframe core`).
|
||||
|
||||
## Unreleased
|
||||
## v1.7.2 — 2026-11-12
|
||||
|
||||
Nothing yet.
|
||||
In Tag, a Field Spell takes the team's free Field slot when the playing partner's slot is taken. No new export, message
|
||||
or capability bit: exports 336 / 857 / 851, protocol 12, capabilities `0xF7FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-11-12 | Core: `field::get_fzone_landing` sent a Field Spell to the playing partner's slot and replaced the card there even when the other partner's slot was free; only a control change took the free slot. A partner who got both of the team's Fields back to the hand ("Giant Trunade") and played them one after the other lost the first. Now any Field Spell that lands (activated, Set, `Duel.MoveToField` to `LOCATION_FZONE`) while the playing partner's slot is taken and the other is free takes the free one; when both are taken it replaces the playing partner's, as before. A Set offers that landing slot's bit. Probe: room "tag, two in one turn". | none (owner) | (d) Lua API: behaviour |
|
||||
|
||||
## v1.7.1 — 2026-11-11
|
||||
|
||||
A card whose cdb alias names another card keeps its own setcodes. No new export, message or capability bit:
|
||||
exports 336 / 857 / 851, protocol 12, capabilities `0xF7FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-11-11 | Core: a card read with a `rule_code` (a cdb alias outside the artwork range, which the readers turn into `rule_code`) answered `is_set_card` from the NAMED card's setcodes only, so a custom card that adds an archetype its base card lacks lost it in the duel ("Vennominon" 810000878, setcode `0x50`, named 72677437, setcode 0: "Venom Fangs" could not equip it; 21 cards of the custom pack). `card::check_code_setcode`: while the card's code is its own `rule_code`, its own `data.setcode` answers too, then the named card's. Used by `is_set_card`, `is_pre_set_card` and `is_special_summon_set_card`. A card renamed by `EFFECT_CHANGE_CODE` takes the new name's setcodes only, as before. Card.IsSetCard / IsPreviousSetCard / IsSummonSetCard. | none (owner) | (d) Lua API: behaviour |
|
||||
|
||||
## v1.7.0 — 2026-11-08
|
||||
|
||||
Prompt context (proposal 55): right before every prompt the answering seat learns which card and which effect asks.
|
||||
One export, one message, capability `0x8000`, protocol 12: exports 336 / 857 / 851, capabilities `0xF7FF`. Record 23 bytes, message 24 bytes.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-11-08 | Core: `ygol_query_prompt_context(pduel, playerid, out)` (23 bytes: version, has effect, code, controller, location, sequence, position, u64 description, u16 effect index, phase, chain link, announce kind: 1 `Duel.AnnounceLevel`, 2 a visible `CATEGORY_DICE` effect, on `MSG_ANNOUNCE_NUMBER` only). `field::execute_cost` / `execute_target` / `execute_operation` push the running effect (handler, description, index, phase 1 / 2 / 3, chain link) on `core.ygol_running` at step 0 and pop it when the function finishes; the innermost one answers. The core's own "use this effect?" asks (optional trigger, lone quick trigger desc 221, desc 94, replacements 218 / 219 / 220, Scrap Chimera) carry the asked effect in their `PROCESSOR_SELECT_EFFECTYN` / `SELECT_YESNO` unit and push it as phase 4 (ask) while the prompt is open. `effect::ygol_script_index`: `card::add_effect` stamps `initial_effect.size()` while the card loads (`STATUS_INITIALIZING`), `0xFFFF` otherwise. A handler the asking player does not control and that is not face-up answers code 0, index `0xFFFF`, description 0. | TICKET-451 | (a) new export |
|
||||
| 2026-11-08 | Server: `STOC_PROMPT_CONTEXT` `0x44` = those 23 bytes + the prompt's `MSG_*` id (24 bytes), to the answering seat (Tag: `cur_player`) right before every relayed prompt but rock-paper-scissors, only when its capability has the bit; never observers, recorders or replays. `FEATURE_PROMPT_CONTEXT` `0x8000` advertised by Single and Tag rooms, protocol 11 -> 12; no room refuses a joiner without it. Export gates 335 / 856 / 850 -> 336 / 857 / 851. | TICKET-451 | Wire: message `0x44`, capability bit `0x8000`, protocol 12 |
|
||||
| 2026-11-08 | Binding: `StocMessage.PromptContext`, `FeatureFlags.PromptContext` (in `All`), the `PromptContext` record + `StocCodecs.PromptContext`, `EngineApi.ygol_query_prompt_context`, `Capability.ProtocolVersion` 12. Probe: the prompt context rooms (Single, a second Single duel whose opponent lacks the bit, Tag): a card asks in its cost, target and operation, a Fusion's material procedure asks inside that operation and the outer context comes back, the Fusion's optional End Phase trigger is asked with phase 4, announces say kind 0 / 1 / 2, then the card hides itself in the Deck and asks both players; a second duel with another deck order has the same indexes. | TICKET-451 | (e) C# binding |
|
||||
|
||||
## v1.6.0 — 2026-11-02
|
||||
|
||||
Tag shared Extra Deck (proposal 53): a setup pair gives a Tag team one Extra Deck, and each card keeps the partner who
|
||||
brought it. No new export or message; capability `0x4000`, protocol 11: exports 335 / 856 / 850, capabilities `0x77FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-11-02 | Core: option `DUEL_TAG_SHARED_EXTRA` `0x200`: `start_duel` moves `tag_list_extra` into `list_extra` and renumbers, for both teams; `tag_swap` skips its Extra block. `card::tag_member` (0 `new_card`, 1 `new_tag_card`), `QUERY_TAG_MEMBER` `0x1000000` written last in `get_infos`. Bit `0x100000` stays unused: old flags set it with no value. | TICKET-433 | (a) `start_duel` option; (c) Query records |
|
||||
| 2026-11-02 | Server: `ygol.tag.extra=shared` is the fourth server-read pair. `TagDuel` sets the option in `opt`, sends the sum of both partners' Extra Decks in the opening `MSG_START`, runs the opening `RefreshExtra` after `start_duel`, and adds `QUERY_TAG_MEMBER` in `RefreshExtra`. `FEATURE_TAG_SHARED_EXTRA` `0x4000` advertised by Single and Tag rooms, protocol 10 -> 11; a Tag room refuses a joiner without the bit. | TICKET-433 | Wire: capability bit `0x4000`, protocol 11; (d) setup pair `ygol.tag.extra`; `0x5F` Extra count 0 in such a duel |
|
||||
| 2026-11-02 | Binding: `FeatureFlags.TagSharedExtra` (in `All`), `Capability.ProtocolVersion` 11. Probe: the tag shared Extra Deck rooms (pair present, pair absent, a Summon of the waiting partner's monster, the replay played back through the library, the Tag refusal, the Single room that keeps an old client). | TICKET-433 | (e) C# binding |
|
||||
|
||||
## v1.5.0 — 2026-10-24
|
||||
|
||||
Tag two Field slots (proposal 45): a Tag team on Master Rule 4/5 holds one Field Spell per partner. No new
|
||||
export or message; capability `0x1000`, protocol 10: exports 335 / 856 / 850, capabilities `0x37FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-24 | Core: `field::has_two_fields()` (`DUEL_TAG_MODE` on Master Rule 4 or 5) gives each team a Field slot per partner, Spell/Trap sequence 5 for the partner who plays the team's first turn and 6 for the other (`player_info::tag_partner`, flipped in `tag_swap`; `get_szone_size` is 7 there). A Field Spell lands in the playing partner's slot (`get_fzone_landing`) and replaces only that card; a control change takes the free slot when the playing partner's is taken. A Set offers only the landing slot's bit. `LOCATION_FZONE` covers both slots in `card_state::is_location`, `filter_matching_card`, `filter_field_card`, `is_location_useable` and `Duel.IsEnvironment`; `get_field_card(p, LOCATION_FZONE, 0)` is the playing partner's field, else the other, and 1 the remaining one. Singles, Match and Master Rule 3 unchanged. | TICKET-384 | (c) `MSG_MOVE` / `MSG_RELOAD_FIELD` carry Spell/Trap sequence 6 (rules only); (d) Lua API: a second answer for `Duel.GetFieldCard` / `Duel.CheckLocation` with `LOCATION_FZONE` |
|
||||
| 2026-10-24 | Server: `FEATURE_TAG_TWO_FIELDS` `0x1000` advertised by Single and Tag rooms, protocol 9 -> 10; a Tag room answers a `CTOS_CAPABILITY` without the bit with `STOC_ERROR_MSG` `ERRMSG_VERERROR` and closes the connection (`TagDuel::Capability`). | TICKET-384 | Wire: capability bit `0x1000`, protocol 10 |
|
||||
| 2026-10-24 | Binding: `FeatureFlags.TagTwoFields` (in `All`), `Capability.ProtocolVersion` 10. Probe: the tag two Field slots rooms (a Tag room's placement on turns 1, 3 and 5 with the core's own view reported by the Probe Field's script, the Tag refusal, the Single room that keeps an old client). | TICKET-384 | (e) C# binding |
|
||||
|
||||
## v1.4.2 — 2026-10-24
|
||||
|
||||
Tag partner cards follow every change. Same message, same payload, no new export or capability bit:
|
||||
exports 335 / 856 / 850, protocol 9, capabilities `0x27FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-24 | `STOC_TAG_PARTNER_CARDS 0x5F` has a fourth send point: after every engine batch (beside `FlushDeckLists`, not when the duel ended) `TagDuel::FlushTagPartnerCards` queries `ygol_query_tag_cards` per side and broadcasts it when the bytes differ from the last broadcast for that side (a Summon out of the waiting member's Extra Deck, Time Fusion), to the same receivers. Every broadcast (start, swap, change) records its bytes; a resync to one player does not. Server. | TICKET-424 | Wire `0x5F` |
|
||||
|
||||
## v1.4.1 — 2026-10-16
|
||||
|
||||
Tag: a card the waiting partner holds can be moved. No new export or capability bit: exports 335 / 856 /
|
||||
850, protocol 9, capabilities `0x27FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-16 | Fix in the core's tag lists (upstream code, reached through core patch 0015's swap order): an effect that keeps a card across the tag swap and moves it later (Time Fusion: the Fusion picked from the Extra Deck at activation, Summoned at the team's next Standby Phase, when the partner's Extra Deck is the active one) moved a card of `tag_list_main` / `tag_list_hand` / `tag_list_extra`; `remove_card` erased the ACTIVE list at the card's sequence, past the end of a shorter list (an empty Extra Deck: `memcpy` crash in `field::remove_card`) or the wrong card. Such a card now leaves the list that holds it (`field::tag_list_holding`) and goes where the move says; the next `MSG_TAG_SWAP` lists one card fewer. Core. | TICKET-415 | Engine message stream: `MSG_TAG_SWAP` (rules only) |
|
||||
|
||||
## v1.4.0 — 2026-10-16
|
||||
|
||||
Life points per side: the setup pair `ygol.side.b.lp=<n>` gives seat side B its own start LP. No new
|
||||
export or capability bit: exports 335 / 856 / 850, protocol 9, capabilities `0x27FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-16 | `ygol.side.b.lp=<n>`: seat side B (seat 1; Tag seats 2 and 3) starts at `n` LP, side A at slot 8; `set_player_info` per duel player, `MSG_START` (start and late-watcher snapshot) carries `lp[0]`, `lp[1]` in duel player order through the first-turn swap, and the replay gets flag `0x20000000` + `i32 lp[0]`, `i32 lp[1]` after `opt` when the two differ. Single, Match, Tag. Server. | - | Setup pair `ygol.side.b.lp`; engine message stream `MSG_START`; replay flag `0x20000000` |
|
||||
|
||||
## v1.3.0 — 2026-10-16
|
||||
|
||||
Spectators with Show all get the Tag partner cards of both teams. Same message, same payload, no new
|
||||
export or capability bit: exports 335 / 856 / 850, protocol 9, capabilities `0x27FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-16 | `STOC_TAG_PARTNER_CARDS` `0x5F` also goes to every observer, both sides, when spectators see all (no `ygol.room.spectatorview=hidden`): after `start_duel`, after every `MSG_TAG_SWAP`, and both sides in an observer's field resync and the late-watcher snapshot. Hidden rooms and seated duelists unchanged. Server. | TICKET-412 | Wire: STOC `0x5F` recipients; join snapshot |
|
||||
|
||||
## v1.2.0 — 2026-10-15
|
||||
|
||||
Tag partner cards: the waiting teammate's hand, Extra Deck and deck reach that team's two seats. One new
|
||||
export (Windows 335, Linux 856, Android 850), one new message, capability `0x2000`, protocol 9 (capabilities
|
||||
`0x27FF`).
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-15 | `ygol_query_tag_cards(pduel, playerid, out)`: the waiting tag partner's hand, Extra Deck (bit 31 = face-up) and deck codes (sorted) of one side, read only; returns the byte length, 0 when not a tag duel. Core. | TICKET-405 | C API: 1 export |
|
||||
| 2026-10-15 | `STOC_TAG_PARTNER_CARDS` `0x5F` = `u8 side` + the export's bytes, no stamp, to that side's two seats only (never the other team, never an observer): after `start_duel`, after every `MSG_TAG_SWAP`, and in a seated duelist's field resync. `FEATURE_TAG_PARTNER_CARDS` `0x2000` (`0x800` and `0x1000` stay reserved for proposals 44 and 45), protocol 8 -> 9. Server. | TICKET-405 | Wire: STOC `0x5F`, capability bit `0x2000`, protocol 9 |
|
||||
| 2026-10-15 | Binding: `StocMessage.TagPartnerCards`, `FeatureFlags.TagPartnerCards`, the `TagPartnerCards` record + `StocCodecs.TagPartnerCards`, `EngineApi.ygol_query_tag_cards`, `Capability.ProtocolVersion` 9. | TICKET-405 | (e) C# binding |
|
||||
|
||||
## v1.1.1 — 2026-10-15
|
||||
|
||||
A rules fix in the core only. No contract change: same exports, protocol 8, capabilities `0x7FF`.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-15 | Tag duel opening turns: no Battle Phase on turns 1, 2 and 3 (duelists 1A, 2A, 1B); the fourth duelist (2B) is the first who can battle, as the official Tag Duel rules say. Single duels keep turn 1 only. `DUEL_ATTACK_FIRST_TURN` still lifts the block. Core (`field::is_opening_turn_without_bp`, used by the idle command and `Duel.IsAbleToEnterBP`). | - | Rules only; no contract change |
|
||||
|
||||
## v1.1.0 — 2026-10-15
|
||||
|
||||
The C# binding joins the release: `ygol-engine-binding.zip` (`YGOLegacy.Engine.dll` + `.pdb`) beside
|
||||
the five assets of v1.0.0, and `engine.json` names it in `binding`. The native libraries are
|
||||
unchanged in content (same exports, protocol 8, capabilities `0x7FF`); only `ygol_engine_version()`
|
||||
answers the new tag.
|
||||
|
||||
| Date | Change | Ticket | Contract part |
|
||||
|---|---|---|---|
|
||||
| 2026-10-15 | `binding/YGOLegacy.Engine` (`netstandard2.1`) carries the wire protocol, namespaces `YGOLegacy.Protocol.*` unchanged, with its NUnit fixtures; the `windows` job builds and tests it and ships `ygol-engine-binding.zip`; `engine.json` gains `binding`. | TICKET-397 | (e) C# binding: new |
|
||||
| 2026-10-15 | Namespace `YGOLegacy.Engine`: `EngineApi` (all 45 exports of `contract/ocgapi.h`, one typed extern each, header parity test), `MessageScan` (the message-layout scanner, moved from the Unity bot host), `GameMessage` (one enum from the 84 `MSG_*` defines, header parity test), `EngineBinding` (`Version`, `CheckNative()`); contract section (e) written. | TICKET-398 | (e) C# binding: the four types; `engine.json`: `binding` documented |
|
||||
|
||||
## v1.0.0 — 2026-10-15
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ library per platform, `ygol-engine`, behind a written contract. Proposal 47 in t
|
||||
| `build/windows.ps1` | Builds `out/win64/ygol-engine.dll` (+ `engine.json`), checks the contract header, runs the export gate. |
|
||||
| `build/Dockerfile` | The Linux x64 and Android arm64 builds, targets `linux` and `android`, same checks and gates. |
|
||||
| `build/linux.sh`, `build/android.sh` | Run the Docker targets into `out/linux-x64/` and `out/android-arm64/`. Need Docker and nothing else. |
|
||||
| `binding/` | The C# binding `YGOLegacy.Engine` (the wire protocol: contracts, codecs, framing, routing; `EngineApi`, `MessageScan`, `GameMessage`, `EngineBinding`) and its NUnit tests. See "Binding". |
|
||||
| `contract/` | The contract: `engine-contract.md` (the one spec), `ocgapi.h` (the public header), `probe-feature-messages.py` (the wire gate), `lua-reference/` (the generated Lua API). |
|
||||
| `CHANGELOG.md` | One row per contract change; the replayed patches 0001-0024 first. |
|
||||
|
||||
@@ -74,14 +75,15 @@ pwsh C:\ygol-engine\build\windows.ps1 -Version v0.0.1
|
||||
- Before building, the script checks `contract/ocgapi.h` against `core/ocgapi.h` + the server's
|
||||
`YGOSERVER_API` lines in `gframe/serverapi.h`; a drift fails the build.
|
||||
- Output: `out/win64/ygol-engine.dll` (+ `.pdb`) and `out/win64/engine.json`
|
||||
(`{ version, exports, protocol, capabilities }`; protocol and capabilities are read from
|
||||
`gframe/network.h` and the `cap.flags` line of `single_duel.cpp` / `tag_duel.cpp`, never typed in).
|
||||
(`{ version, exports, protocol, capabilities, binding }`; protocol and capabilities are read from
|
||||
`gframe/network.h` and the `cap.flags` line of `single_duel.cpp` / `tag_duel.cpp`, never typed in;
|
||||
`binding` is the version of the C# binding released with this engine, the same string as `version`).
|
||||
|
||||
### The export gate is the truth
|
||||
|
||||
The script FAILS unless the DLL exports exactly **334** symbols: `start_server`, `stop_server`,
|
||||
The script FAILS unless the DLL exports exactly **336** symbols: `start_server`, `stop_server`,
|
||||
`ygol_engine_version`, and the core's whole C API re-exported, including the six `ygol_sb_*` Sandbox
|
||||
exports and `ygol_preview_attack` (45 contract exports + 289 `sqlite3_*`; see the contract). A different count means the wrong tree, not "a small difference". For the
|
||||
exports and `ygol_preview_attack` (47 contract exports, `ygol_query_tag_cards` and `ygol_query_prompt_context` included, + 289 `sqlite3_*`; see the contract). A different count means the wrong tree, not "a small difference". For the
|
||||
record: the Unity repo's old `ygoserver.dll` exported 327 because its build applied patch 0008
|
||||
(the `ygol_sb_*` six) only to `ocgcore.dll`, never to the server's own core copy; with one core they
|
||||
are in the one library.
|
||||
@@ -117,14 +119,43 @@ Windows VM: it has no nested virtualisation). From a clean clone on any Linux bo
|
||||
built any more.
|
||||
- The same contract-header check runs first, and the same export gate runs last, with the plain C
|
||||
export count (`nm --dynamic --defined-only --extern-only`, names without a leading underscore; C++
|
||||
symbols are `_Z`-mangled) and every name in `contract/ocgapi.h` present. Expected: **Linux 855**,
|
||||
**Android 849** (the shipped Android server had 842: 841 + `ygol_preview_attack`; one core adds
|
||||
symbols are `_Z`-mangled) and every name in `contract/ocgapi.h` present. Expected: **Linux 857**,
|
||||
**Android 851** (the shipped Android server had 842: 841 + `ygol_preview_attack`; one core adds
|
||||
the six `ygol_sb_*` and `ygol_engine_version`; `lua_*`, `event_*`, `z*`, ... count on these
|
||||
platforms, unlike on Windows, so the numbers differ from 334; Linux has one more than Android,
|
||||
platforms, unlike on Windows, so the numbers differ from 336; Linux has one more than Android,
|
||||
`evutil_secure_rng_add_bytes`, which libevent only builds where glibc has no `arc4random`, so the
|
||||
number belongs to the pinned base image). `engine.json` is written the same way as on Windows. A
|
||||
`docker build` that fails the gate leaves nothing in `out/`.
|
||||
|
||||
## Binding
|
||||
|
||||
`binding/YGOLegacy.Engine/` is the managed side of the engine: a `netstandard2.1` class library
|
||||
(`YGOLegacy.Engine.dll`, LangVersion 9, unsafe allowed, no package and no Unity reference) that
|
||||
holds the wire protocol under `Protocol/` in the namespaces `YGOLegacy.Protocol.{Contracts,
|
||||
Codecs, Framing, Routing}`: the message ids and payload records, the CTOS / STOC codecs, the
|
||||
frame codec and the STOC router, and the namespace `YGOLegacy.Engine`: `EngineApi` (one typed
|
||||
extern per export of `contract/ocgapi.h`, plus the three callback delegates), `MessageScan` (the
|
||||
engine message-layout scanner), `GameMessage` (one enum from the `MSG_*` defines) and
|
||||
`EngineBinding` (`Version` and `CheckNative()`, which throws when the native library's
|
||||
`ygol_engine_version()` is not the binding's version). Unity, the tools and the server repo's
|
||||
card-tester consume this DLL instead of their own copies of the sources and call `CheckNative()`
|
||||
once at start. `binding/YGOLegacy.Engine.Tests/` (`net8.0`, NUnit) holds the fixtures, including the
|
||||
two parity tests that parse the headers; nothing in the tests touches the native library. Contract
|
||||
section (e) documents the DLL.
|
||||
|
||||
```powershell
|
||||
dotnet build binding\YGOLegacy.Engine -c Release -p:EngineVersion=v0.0.1
|
||||
dotnet test binding\YGOLegacy.Engine.Tests -c Release
|
||||
(Get-Item binding\YGOLegacy.Engine\bin\Release\netstandard2.1\YGOLegacy.Engine.dll).VersionInfo.ProductVersion
|
||||
```
|
||||
|
||||
`EngineVersion` is stamped into the assembly's informational version (`local` when not given), so
|
||||
`ProductVersion` prints the tag the DLL was built for. The release workflow's `windows` job builds
|
||||
and tests the binding after the native gates and ships `ygol-engine-binding.zip`
|
||||
(`YGOLegacy.Engine.dll`, `YGOLegacy.Engine.pdb`); `engine.json`'s `binding` field names the same tag.
|
||||
The binding is built on Windows only (the Linux and Android jobs run in Docker without dotnet); it
|
||||
needs the dotnet 8 SDK, and the test project restores NUnit from nuget.org.
|
||||
|
||||
## Release
|
||||
|
||||
`.gitea/workflows/release.yml`. Every push and pull request runs the three builds and their gates
|
||||
@@ -137,12 +168,13 @@ git tag vX.Y.Z && git push gitea main vX.Y.Z
|
||||
```
|
||||
|
||||
Then wait for the run (`Actions` tab). The release named after the tag appears only when every
|
||||
build passed its gate, every platform's `engine.json` names the tag and agrees on protocol and
|
||||
capabilities, and `ygol_engine_version()` on the Windows DLL returns the tag. A tag whose release
|
||||
build passed its gate, the binding built and its tests passed, every platform's `engine.json` names
|
||||
the tag (as `version` and `binding`) and agrees on protocol and capabilities, and
|
||||
`ygol_engine_version()` on the Windows DLL returns the tag. A tag whose release
|
||||
already exists is refused: a bad release gets a new patch tag, never a re-upload.
|
||||
|
||||
The Windows runner needs premake 5.0.0-beta8 at `C:\premake\premake5.exe`, VS 2022 Build Tools with
|
||||
the C++ workload, Python 3 and `tar.exe` (Windows 10+); its checkout is
|
||||
the C++ workload, Python 3, the dotnet 8 SDK (the binding) and `tar.exe` (Windows 10+); its checkout is
|
||||
`C:\gitea-runner\checkout\yugioh-legacy-engine` (no spaces) and the Windows bundle is staged under
|
||||
`C:\gitea-runner\release-out\ygol-engine\<tag>\` for the last job to attach. The release token is
|
||||
the run's own `GITHUB_TOKEN`.
|
||||
@@ -154,10 +186,11 @@ the run's own `GITHUB_TOKEN`.
|
||||
| Asset | Contents |
|
||||
|---|---|
|
||||
| `ygol-engine-win64.zip` | `ygol-engine.dll`, `ygol-engine.pdb`, `engine.json` |
|
||||
| `ygol-engine-binding.zip` | `YGOLegacy.Engine.dll`, `YGOLegacy.Engine.pdb` (the C# binding; its `ProductVersion` is the tag) |
|
||||
| `ygol-engine-linux-x64.tar.gz` | `libygol-engine.so`, `engine.json` |
|
||||
| `ygoserver-linux-x64.tar.gz` | `ygoserver` (the plain server executable), `engine.json` |
|
||||
| `ygol-engine-android-arm64.tar.gz` | `libygol-engine.so`, `engine.json` |
|
||||
| `engine.json` | `{ version, exports, protocol, capabilities }`; `exports` is the Windows count, the rest is identical in every bundle |
|
||||
| `engine.json` | `{ version, exports, protocol, capabilities, binding }`; a copy of the Linux bundle's. `version`, `protocol`, `capabilities` and `binding` are identical in every bundle (the release job checks); `exports` is each platform's own count (336 / 857 / 851) |
|
||||
|
||||
## Line endings
|
||||
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Protocol.Codecs;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Tests
|
||||
{
|
||||
public class CtosCodecTests
|
||||
{
|
||||
private static byte[] Bytes(Action<BinaryWriter> write)
|
||||
{
|
||||
using (var stream = new MemoryStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static BinaryReader Reader(byte[] bytes)
|
||||
{
|
||||
return new BinaryReader(new MemoryStream(bytes));
|
||||
}
|
||||
|
||||
private static byte[] Utf16(string text)
|
||||
{
|
||||
return Encoding.Unicode.GetBytes(text);
|
||||
}
|
||||
|
||||
private static byte[] Concat(params byte[][] parts)
|
||||
{
|
||||
return parts.SelectMany(p => p).ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Packet(CtosMessage id, Action<BinaryWriter> write)
|
||||
{
|
||||
var writer = CtosPacket.Begin(id);
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
return ((MemoryStream)writer.BaseStream).ToArray();
|
||||
}
|
||||
|
||||
private static byte[] LegacyWindBotIntPacket(CtosMessage id, int value)
|
||||
{
|
||||
return Bytes(w =>
|
||||
{
|
||||
w.Write((byte)id);
|
||||
w.Write(value);
|
||||
});
|
||||
}
|
||||
|
||||
private static byte[] LegacyUnityChat(string text)
|
||||
{
|
||||
return Bytes(w => MDPro3.BinaryExtensions.WriteUnicode(w, text, text.Length + 1));
|
||||
}
|
||||
|
||||
private static byte[] LegacyWindBotChat(string text)
|
||||
{
|
||||
return Bytes(w => YGOSharp.Network.Utils.BinaryExtensions.WriteUnicodeAutoLength(w, text, 255));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Response_WritesTheEngineBytesUnchanged()
|
||||
{
|
||||
var answer = new byte[] { 0x02, 0x00, 0x00, 0x00 };
|
||||
var ours = Bytes(w => DuelCodecs.Response.Write(w, new Response(answer)));
|
||||
var unity = Bytes(w => w.Write(answer));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(answer));
|
||||
Assert.That(ours, Is.EqualTo(unity));
|
||||
Assert.That(DuelCodecs.Response.Read(Reader(ours)).Bytes, Is.EqualTo(answer));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Response_WriteInt_EqualsBinaryWriterInt32()
|
||||
{
|
||||
var ours = Bytes(w => DuelCodecs.Response.Write(w, -1));
|
||||
var legacy = Bytes(w => w.Write(-1));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(legacy));
|
||||
Assert.That(ours, Is.EqualTo(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }));
|
||||
Assert.That(Packet(DuelCodecs.Response.Id, w => DuelCodecs.Response.Write(w, 7)), Is.EqualTo(LegacyWindBotIntPacket(CtosMessage.Response, 7)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Response_Packet_MatchesTheOldFactoryForm()
|
||||
{
|
||||
var answer = new byte[] { 0x01, 0x03, 0x05 };
|
||||
var ours = Packet(DuelCodecs.Response.Id, w => DuelCodecs.Response.Write(w, new Response(answer)));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Concat(new byte[] { 0x01 }, answer)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Response_Null_WritesNothing()
|
||||
{
|
||||
Assert.That(Bytes(w => DuelCodecs.Response.Write(w, default(Response))), Is.Empty);
|
||||
Assert.That(Bytes(w => DuelCodecs.Response.Write(w, new Response(null))), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HandResult_IsOneByte_OnBothClients()
|
||||
{
|
||||
var ours = Bytes(w => DuelCodecs.HandResult.Write(w, new HandResult(2)));
|
||||
var unity = Bytes(w => w.Write((byte)2));
|
||||
var packet = Packet(DuelCodecs.HandResult.Id, w => DuelCodecs.HandResult.Write(w, new HandResult(2)));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(unity));
|
||||
Assert.That(packet, Is.EqualTo(new byte[] { 0x03, 0x02 }));
|
||||
Assert.That(packet, Is.Not.EqualTo(LegacyWindBotIntPacket(CtosMessage.HandResult, 2)));
|
||||
Assert.That(LegacyWindBotIntPacket(CtosMessage.HandResult, 2).Length, Is.EqualTo(5));
|
||||
Assert.That(DuelCodecs.HandResult.Read(Reader(ours)).Result, Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TpResult_IsOneByte_OnBothClients()
|
||||
{
|
||||
var first = Packet(DuelCodecs.TpResult.Id, w => DuelCodecs.TpResult.Write(w, new TpResult(true)));
|
||||
var second = Packet(DuelCodecs.TpResult.Id, w => DuelCodecs.TpResult.Write(w, new TpResult(false)));
|
||||
|
||||
Assert.That(first, Is.EqualTo(new byte[] { 0x04, 0x01 }));
|
||||
Assert.That(second, Is.EqualTo(new byte[] { 0x04, 0x00 }));
|
||||
Assert.That(first.Skip(1), Is.EqualTo(Bytes(w => w.Write((byte)1))));
|
||||
Assert.That(first, Is.Not.EqualTo(LegacyWindBotIntPacket(CtosMessage.TpResult, 1)));
|
||||
Assert.That(DuelCodecs.TpResult.Read(Reader(first.Skip(1).ToArray())).GoFirst, Is.True);
|
||||
Assert.That(DuelCodecs.TpResult.Read(Reader(second.Skip(1).ToArray())).GoFirst, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NoDataIds_WriteZeroBytes()
|
||||
{
|
||||
var codecs = new[]
|
||||
{
|
||||
LobbyCodecs.LeaveGame, DuelCodecs.Surrender, DuelCodecs.TimeConfirm,
|
||||
LobbyCodecs.HsToDuelist, LobbyCodecs.HsToObserver, LobbyCodecs.HsReady,
|
||||
LobbyCodecs.HsNotReady, LobbyCodecs.HsStart,
|
||||
};
|
||||
var expected = new[]
|
||||
{
|
||||
CtosMessage.LeaveGame, CtosMessage.Surrender, CtosMessage.TimeConfirm,
|
||||
CtosMessage.HsToDuelist, CtosMessage.HsToObserver, CtosMessage.HsReady,
|
||||
CtosMessage.HsNotReady, CtosMessage.HsStart,
|
||||
};
|
||||
|
||||
for (var i = 0; i < codecs.Length; i++)
|
||||
{
|
||||
Assert.That(codecs[i].Id, Is.EqualTo(expected[i]));
|
||||
Assert.That(Bytes(w => codecs[i].Write(w)), Is.Empty, expected[i].ToString());
|
||||
Assert.That(Bytes(w => codecs[i].Write(w, default(NoPayload))), Is.Empty, expected[i].ToString());
|
||||
Assert.That(Packet(codecs[i].Id, w => codecs[i].Write(w)), Is.EqualTo(new[] { (byte)expected[i] }));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Kick_IsOneByte()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.HsKick.Write(w, new Kick(1)));
|
||||
var packet = Packet(LobbyCodecs.HsKick.Id, w => LobbyCodecs.HsKick.Write(w, new Kick(1)));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Bytes(w => w.Write((byte)1))));
|
||||
Assert.That(packet, Is.EqualTo(new byte[] { 0x24, 0x01 }));
|
||||
Assert.That(LobbyCodecs.HsKick.Read(Reader(ours)).Position, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Chat_ShortText_MatchesBothClientsExactly()
|
||||
{
|
||||
const string text = "gg wp";
|
||||
var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text)));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Utf16(text + "\0")));
|
||||
Assert.That(ours, Is.EqualTo(LegacyUnityChat(text)));
|
||||
Assert.That(ours, Is.EqualTo(LegacyWindBotChat(text)));
|
||||
Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Chat_Empty_WritesTheTerminatorOnly()
|
||||
{
|
||||
Assert.That(Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(""))), Is.EqualTo(new byte[] { 0, 0 }));
|
||||
Assert.That(Bytes(w => LobbyCodecs.Chat.Write(w, default(Chat))), Is.EqualTo(new byte[] { 0, 0 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Chat_300Chars_ClipsTo255UnitsPlusTerminator()
|
||||
{
|
||||
var text = new string('x', 300);
|
||||
var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text)));
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(512));
|
||||
Assert.That(ours.Skip(510), Is.All.EqualTo(0));
|
||||
Assert.That(ours.Take(510), Is.EqualTo(Utf16(text.Substring(0, 255))));
|
||||
Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text.Substring(0, 255)));
|
||||
Assert.That(LegacyUnityChat(text).Length, Is.EqualTo(602));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Chat_255Chars_KeepsAll_WhereWindBotKept254()
|
||||
{
|
||||
var text = new string('y', 255);
|
||||
var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text)));
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(512));
|
||||
Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text));
|
||||
Assert.That(ours, Is.EqualTo(LegacyUnityChat(text)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Chat_SurrogatePairAtTheCap_IsNotSplit()
|
||||
{
|
||||
var text = new string('a', 254) + "\U0001F600";
|
||||
var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text)));
|
||||
|
||||
Assert.That(text.Length, Is.EqualTo(256));
|
||||
Assert.That(ours.Length, Is.EqualTo(510));
|
||||
Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(new string('a', 254)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Chat_SurrogatePairThatFits_RoundTrips()
|
||||
{
|
||||
var text = new string('a', 253) + "\U0001F600";
|
||||
var ours = Bytes(w => LobbyCodecs.Chat.Write(w, new Chat(text)));
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(512));
|
||||
Assert.That(LobbyCodecs.Chat.Read(Reader(ours)).Text, Is.EqualTo(text));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CodecIds_MatchTheCatalog()
|
||||
{
|
||||
Assert.That((int)DuelCodecs.Response.Id, Is.EqualTo(0x01));
|
||||
Assert.That((int)DuelCodecs.HandResult.Id, Is.EqualTo(0x03));
|
||||
Assert.That((int)DuelCodecs.TpResult.Id, Is.EqualTo(0x04));
|
||||
Assert.That((int)LobbyCodecs.LeaveGame.Id, Is.EqualTo(0x13));
|
||||
Assert.That((int)DuelCodecs.Surrender.Id, Is.EqualTo(0x14));
|
||||
Assert.That((int)DuelCodecs.TimeConfirm.Id, Is.EqualTo(0x15));
|
||||
Assert.That((int)LobbyCodecs.Chat.Id, Is.EqualTo(0x16));
|
||||
Assert.That((int)LobbyCodecs.HsToDuelist.Id, Is.EqualTo(0x20));
|
||||
Assert.That((int)LobbyCodecs.HsToObserver.Id, Is.EqualTo(0x21));
|
||||
Assert.That((int)LobbyCodecs.HsReady.Id, Is.EqualTo(0x22));
|
||||
Assert.That((int)LobbyCodecs.HsNotReady.Id, Is.EqualTo(0x23));
|
||||
Assert.That((int)LobbyCodecs.HsKick.Id, Is.EqualTo(0x24));
|
||||
Assert.That((int)LobbyCodecs.HsStart.Id, Is.EqualTo(0x25));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Engine;
|
||||
|
||||
namespace YGOLegacy.Engine.Tests
|
||||
{
|
||||
internal static class ContractFiles
|
||||
{
|
||||
private const string RepoRoot = "../../../../..";
|
||||
|
||||
public static string OcgApiHeader => Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, RepoRoot, "contract", "ocgapi.h"));
|
||||
public static string CommonHeader => Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, RepoRoot, "core", "common.h"));
|
||||
}
|
||||
|
||||
public class EngineApiParityTests
|
||||
{
|
||||
private static readonly Regex Export = new Regex(@"^\s*(?:OCGCORE_API|YGOSERVER_API)\s+.*?\b(\w+)\s*\(", RegexOptions.Compiled);
|
||||
|
||||
private static List<string> HeaderNames()
|
||||
{
|
||||
return File.ReadLines(ContractFiles.OcgApiHeader)
|
||||
.Select(line => Export.Match(line))
|
||||
.Where(m => m.Success)
|
||||
.Select(m => m.Groups[1].Value)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static List<string> ExternNames()
|
||||
{
|
||||
return typeof(EngineApi)
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly)
|
||||
.Where(m => m.GetCustomAttribute<DllImportAttribute>() != null)
|
||||
.Select(m => m.Name)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeaderHas47Exports()
|
||||
{
|
||||
Assert.That(HeaderNames().Count, Is.EqualTo(47));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryHeaderExportHasAnExtern()
|
||||
{
|
||||
var missing = HeaderNames().Except(ExternNames()).ToList();
|
||||
Assert.That(missing, Is.Empty, "header exports without an EngineApi extern");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryExternIsAHeaderExport()
|
||||
{
|
||||
var extra = ExternNames().Except(HeaderNames()).ToList();
|
||||
Assert.That(extra, Is.Empty, "EngineApi externs that are not in contract/ocgapi.h");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryExternIsPublicCdeclOnYgolEngine()
|
||||
{
|
||||
var methods = typeof(EngineApi)
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly)
|
||||
.Where(m => m.GetCustomAttribute<DllImportAttribute>() != null)
|
||||
.ToList();
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var import = method.GetCustomAttribute<DllImportAttribute>();
|
||||
Assert.That(method.IsPublic, method.Name + " is not public");
|
||||
Assert.That(import.Value, Is.EqualTo("ygol-engine"), method.Name);
|
||||
Assert.That(import.CallingConvention, Is.EqualTo(CallingConvention.Cdecl), method.Name);
|
||||
Assert.That(import.EntryPoint, Is.Null.Or.EqualTo(method.Name), method.Name + " renames its entry point");
|
||||
Assert.That(import.CharSet, Is.Not.EqualTo(CharSet.Unicode), method.Name + " uses CharSet.Unicode");
|
||||
}
|
||||
Assert.That(methods.Select(m => m.Name).Distinct().Count(), Is.EqualTo(methods.Count), "an export has an overload");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Protocol.Codecs;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Tests
|
||||
{
|
||||
public class FeatureCodecTests
|
||||
{
|
||||
private static byte[] Bytes(Action<BinaryWriter> write)
|
||||
{
|
||||
using (var stream = new MemoryStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static BinaryReader Reader(byte[] bytes)
|
||||
{
|
||||
return new BinaryReader(new MemoryStream(bytes));
|
||||
}
|
||||
|
||||
private static byte[] Utf16(string text)
|
||||
{
|
||||
return Encoding.Unicode.GetBytes(text);
|
||||
}
|
||||
|
||||
private static byte[] Utf16Fixed(string text, int chars)
|
||||
{
|
||||
return Concat(Utf16(text), Zeros(chars * 2 - text.Length * 2));
|
||||
}
|
||||
|
||||
private static byte[] Concat(params byte[][] parts)
|
||||
{
|
||||
return parts.SelectMany(p => p).ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Le16(int value)
|
||||
{
|
||||
return new[] { (byte)value, (byte)(value >> 8) };
|
||||
}
|
||||
|
||||
private static byte[] Le32(int value)
|
||||
{
|
||||
return new[] { (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24) };
|
||||
}
|
||||
|
||||
private static byte[] Zeros(int count)
|
||||
{
|
||||
return new byte[count];
|
||||
}
|
||||
|
||||
// The probe's reference bytes: appearance_bytes(1), dialogue_bytes(4), capability_bytes().
|
||||
private static readonly int[] ProbeItems = { 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017 };
|
||||
|
||||
private static byte[] ProbeAppearance()
|
||||
{
|
||||
return Concat(
|
||||
Concat(ProbeItems.Select(Le32).ToArray()),
|
||||
Utf16Fixed("deck-1", 48),
|
||||
Utf16Fixed("character-1", 64),
|
||||
Utf16Fixed("group-1", 48));
|
||||
}
|
||||
|
||||
private static byte[] ProbeDialogue()
|
||||
{
|
||||
return Concat(
|
||||
new byte[] { 1, 1 },
|
||||
Le16(4),
|
||||
Le32(4004),
|
||||
Le32(5004),
|
||||
Utf16Fixed("corpus-4", 48),
|
||||
Utf16Fixed("event-4", 48));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Ids_MatchTheCatalog_InTheForkBlock()
|
||||
{
|
||||
Assert.That((int)LobbyCodecs.Capability.Id, Is.EqualTo(0x40));
|
||||
Assert.That((int)LobbyCodecs.Appearance.Id, Is.EqualTo(0x41));
|
||||
Assert.That((int)LobbyCodecs.Dialogue.Id, Is.EqualTo(0x42));
|
||||
Assert.That(StocCodecs.Capability.Id, Is.EqualTo(StocMessage.Capability));
|
||||
Assert.That(StocCodecs.Appearance.Id, Is.EqualTo(StocMessage.Appearance));
|
||||
Assert.That(StocCodecs.Dialogue.Id, Is.EqualTo(StocMessage.Dialogue));
|
||||
Assert.That((int)StocMessage.Capability, Is.EqualTo(0x40));
|
||||
Assert.That((int)StocMessage.Appearance, Is.EqualTo(0x41));
|
||||
Assert.That((int)StocMessage.Dialogue, Is.EqualTo(0x42));
|
||||
Assert.That(StocCodecs.SetupPairs.Id, Is.EqualTo(StocMessage.SetupPairs));
|
||||
Assert.That((int)StocMessage.SetupPairs, Is.EqualTo(0x43));
|
||||
Assert.That((int)LobbyCodecs.SeatPlan.Id, Is.EqualTo(0x50));
|
||||
Assert.That((int)LobbyCodecs.SeatRequest.Id, Is.EqualTo(0x51));
|
||||
Assert.That((int)LobbyCodecs.SeatSwap.Id, Is.EqualTo(0x52));
|
||||
Assert.That((int)LobbyCodecs.SeatMove.Id, Is.EqualTo(0x53));
|
||||
Assert.That((int)StocCodecs.SeatPlan.Id, Is.EqualTo(0x50));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeatPlan_Ctos_Is91Bytes_AndRoundTripsTokens()
|
||||
{
|
||||
var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray();
|
||||
var plan = new SeatPlan(null, 0, 7, 4, new[] { SeatPlanKind.Open, SeatPlanKind.Cpu, SeatPlanKind.Open, SeatPlanKind.Cpu }, new[] { null, token, null, token });
|
||||
var bytes = Bytes(w => LobbyCodecs.SeatPlan.Write(w, plan));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(91));
|
||||
Assert.That(bytes.Skip(20).Take(7), Is.EqualTo(Concat(Le16(7), new byte[] { 4, 0, 1, 0, 1 })));
|
||||
Assert.That(bytes.Skip(27 + 16).Take(16), Is.EqualTo(token));
|
||||
|
||||
var read = LobbyCodecs.SeatPlan.Read(Reader(bytes));
|
||||
Assert.That(read.Revision, Is.EqualTo(7));
|
||||
Assert.That(read.Kind(3), Is.EqualTo(SeatPlanKind.Cpu));
|
||||
Assert.That(read.Tokens[0], Is.EqualTo(Zeros(16)));
|
||||
Assert.That(SeatIds.FromHex(SeatIds.ToHex(token)), Is.EqualTo(token));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeatPlan_Stoc_Is25Bytes_CarriesNoTokens_AndAShortReadThrows()
|
||||
{
|
||||
var plan = new SeatPlan(null, 9, 3, 2, new[] { SeatPlanKind.Open, SeatPlanKind.Cpu }, new[] { Zeros(16), Zeros(16) });
|
||||
var bytes = Bytes(w => StocCodecs.SeatPlan.Write(w, new Stamped<SeatPlan>(0xFF, plan)));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(25));
|
||||
Assert.That(bytes.Skip(18), Is.EqualTo(Concat(Le16(3), new byte[] { 2, 0, 1, 0, 0 })));
|
||||
var read = StocCodecs.SeatPlan.Read(Reader(bytes));
|
||||
Assert.That(read.Seat, Is.EqualTo(Capability.ServerSender));
|
||||
Assert.That(read.Payload.Kind(1), Is.EqualTo(SeatPlanKind.Cpu));
|
||||
Assert.That(read.Payload.Kind(3), Is.EqualTo(SeatPlanKind.Open));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.SeatPlan.Read(Reader(bytes.Take(24).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeatRequest_SwapAndMove_HaveTheirPinnedSizes()
|
||||
{
|
||||
Assert.That(Bytes(w => LobbyCodecs.SeatRequest.Write(w, new SeatRequest(2, null, 3, null))).Length, Is.EqualTo(35));
|
||||
Assert.That(Bytes(w => LobbyCodecs.SeatSwap.Write(w, new SeatSwap(0, 3))), Is.EqualTo(new byte[] { 0, 3 }));
|
||||
Assert.That(Bytes(w => LobbyCodecs.SeatMove.Write(w, new SeatMove(1, SeatMove.Watchers))), Is.EqualTo(new byte[] { 1, 0xFF }));
|
||||
var request = LobbyCodecs.SeatRequest.Read(Reader(Bytes(w => LobbyCodecs.SeatRequest.Write(w, new SeatRequest(2, null, 3, Enumerable.Repeat((byte)9, 16).ToArray())))));
|
||||
Assert.That(request.Seat, Is.EqualTo(3));
|
||||
Assert.That(request.Token[15], Is.EqualTo(9));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Restart_Ids_AndCtosSizes_ArePinned_101_17_17_18_32()
|
||||
{
|
||||
Assert.That((int)LobbyCodecs.RestartPrepare.Id, Is.EqualTo(0x54));
|
||||
Assert.That((int)LobbyCodecs.RestartAck.Id, Is.EqualTo(0x55));
|
||||
Assert.That((int)LobbyCodecs.RestartControl.Id, Is.EqualTo(0x56));
|
||||
Assert.That((int)LobbyCodecs.SeatResume.Id, Is.EqualTo(0x57));
|
||||
Assert.That((int)LobbyCodecs.RestartOpen.Id, Is.EqualTo(0x58));
|
||||
Assert.That((int)StocCodecs.RoomRestarting.Id, Is.EqualTo(0x54));
|
||||
Assert.That((int)StocCodecs.RestartStatus.Id, Is.EqualTo(0x56));
|
||||
Assert.That((int)StocCodecs.SeatResumeResult.Id, Is.EqualTo(0x57));
|
||||
Assert.That((int)StocCodecs.RestartOpened.Id, Is.EqualTo(0x58));
|
||||
Assert.That(FeatureFlags.RulesRestart, Is.EqualTo(0x10));
|
||||
Assert.That(FeatureFlags.All, Is.EqualTo(0xF7FB));
|
||||
|
||||
var id = Enumerable.Repeat((byte)0xAB, 16).ToArray();
|
||||
var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray();
|
||||
var prepare = Bytes(w => LobbyCodecs.RestartPrepare.Write(w, new RestartPrepare(id, 30000, 2, new[] { token, null }, token)));
|
||||
Assert.That(prepare.Length, Is.EqualTo(101));
|
||||
Assert.That(prepare, Is.EqualTo(Concat(id, Le32(30000), new byte[] { 2 }, token, Zeros(48), token)));
|
||||
Assert.That(Bytes(w => LobbyCodecs.RestartAck.Write(w, new RestartAck(id, RestartPhase.Commit))), Is.EqualTo(Concat(id, new byte[] { 2 })));
|
||||
Assert.That(Bytes(w => LobbyCodecs.RestartControl.Write(w, new RestartControl(id, RestartPhase.Abort))), Is.EqualTo(Concat(id, new byte[] { 3 })));
|
||||
Assert.That(Bytes(w => LobbyCodecs.SeatResume.Write(w, new SeatResume(id, SeatResumeAction.Release, 7))), Is.EqualTo(Concat(id, new byte[] { 2, 7 })));
|
||||
Assert.That(Bytes(w => LobbyCodecs.RestartOpen.Write(w, new RestartOpen(id, token))), Is.EqualTo(Concat(id, token)));
|
||||
var read = LobbyCodecs.RestartPrepare.Read(Reader(prepare));
|
||||
Assert.That(read.SeatTokens[0], Is.EqualTo(token));
|
||||
Assert.That(read.SeatTokens[1], Is.EqualTo(Zeros(16)));
|
||||
Assert.That(read.ObserverToken, Is.EqualTo(token));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MatchOver_Id_Flag_AndSize_ArePinned_0x5A_0x40_8()
|
||||
{
|
||||
Assert.That((int)StocCodecs.MatchOver.Id, Is.EqualTo(0x5A));
|
||||
Assert.That(FeatureFlags.LobbyAfterMatch, Is.EqualTo(0x40));
|
||||
var over = Bytes(w => StocCodecs.MatchOver.Write(w, new Stamped<MatchOver>(0xFF, new MatchOver(4, new[] { false, true, true, true }))));
|
||||
Assert.That(over, Is.EqualTo(Concat(Le16(0xFF), new byte[] { 1, 4, 0, 1, 1, 1 })));
|
||||
var read = StocCodecs.MatchOver.Read(Reader(over));
|
||||
Assert.That(read.Seat, Is.EqualTo(0xFF));
|
||||
Assert.That(read.Payload.Version, Is.EqualTo(1));
|
||||
Assert.That(read.Payload.SeatCount, Is.EqualTo(4));
|
||||
Assert.That(new[] { read.Payload.Occupied(0), read.Payload.Occupied(1), read.Payload.Occupied(2), read.Payload.Occupied(3) }, Is.EqualTo(new[] { false, true, true, true }));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.MatchOver.Read(Reader(over.Take(7).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CoinToss_Id_Flag_Protocol_AndSize_ArePinned_0x5B_0x80_5_4()
|
||||
{
|
||||
Assert.That((int)StocCodecs.CoinToss.Id, Is.EqualTo(0x5B));
|
||||
Assert.That(FeatureFlags.CoinToss, Is.EqualTo(0x80));
|
||||
var toss = Bytes(w => StocCodecs.CoinToss.Write(w, new CoinTossAnnounce(2, CoinTossAnnounce.Tails, 30)));
|
||||
Assert.That(toss, Is.EqualTo(new byte[] { 1, 2, 1, 30 }));
|
||||
var read = StocCodecs.CoinToss.Read(Reader(toss));
|
||||
Assert.That(read.Version, Is.EqualTo(1));
|
||||
Assert.That(read.ChooserSeat, Is.EqualTo(2));
|
||||
Assert.That(read.Face, Is.EqualTo(CoinTossAnnounce.Tails));
|
||||
Assert.That(read.ChooseSeconds, Is.EqualTo(30));
|
||||
Assert.That(StocCodecs.CoinToss.Read(Reader(new byte[] { 1, 0, 0xFF, 15 })).Tossed, Is.False);
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.CoinToss.Read(Reader(toss.Take(3).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Profile_Id_Flag_AndSizes_ArePinned_0x5D_0x200_98_100()
|
||||
{
|
||||
Assert.That((int)LobbyCodecs.Profile.Id, Is.EqualTo(0x5D));
|
||||
Assert.That((int)StocCodecs.Profile.Id, Is.EqualTo(0x5D));
|
||||
Assert.That(FeatureFlags.Profile, Is.EqualTo(0x200));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.Profile, Is.EqualTo(FeatureFlags.Profile));
|
||||
Assert.That(ProfileCodec.Size, Is.EqualTo(98));
|
||||
Assert.That(ProfileCodec.StampedSize, Is.EqualTo(100));
|
||||
var sent = Bytes(w => LobbyCodecs.Profile.Write(w, new ProfileState("atem", "gold")));
|
||||
Assert.That(sent.Length, Is.EqualTo(98));
|
||||
Assert.That(sent.Take(2), Is.EqualTo(new byte[] { 1, 0 }));
|
||||
Assert.That(sent.Skip(2).Take(8), Is.EqualTo(new byte[] { (byte)'a', 0, (byte)'t', 0, (byte)'e', 0, (byte)'m', 0 }));
|
||||
Assert.That(sent.Skip(10).Take(56), Is.EqualTo(Zeros(56)));
|
||||
Assert.That(sent.Skip(66).Take(8), Is.EqualTo(new byte[] { (byte)'g', 0, (byte)'o', 0, (byte)'l', 0, (byte)'d', 0 }));
|
||||
var stamped = Bytes(w => StocCodecs.Profile.Write(w, new Stamped<ProfileState>(3, new ProfileState("mai-ori", string.Empty))));
|
||||
Assert.That(stamped.Length, Is.EqualTo(100));
|
||||
Assert.That(stamped.Take(2), Is.EqualTo(Le16(3)));
|
||||
var read = StocCodecs.Profile.Read(Reader(stamped));
|
||||
Assert.That(read.Seat, Is.EqualTo(3));
|
||||
Assert.That(read.Payload.Version, Is.EqualTo(1));
|
||||
Assert.That(read.Payload.AvatarId, Is.EqualTo("mai-ori"));
|
||||
Assert.That(read.Payload.FrameId, Is.EqualTo(string.Empty));
|
||||
var longId = Bytes(w => LobbyCodecs.Profile.Write(w, new ProfileState(new string('x', 40), new string('y', 20))));
|
||||
Assert.That(longId.Length, Is.EqualTo(98));
|
||||
var clipped = LobbyCodecs.Profile.Read(Reader(longId));
|
||||
Assert.That(clipped.AvatarId.Length, Is.EqualTo(31));
|
||||
Assert.That(clipped.FrameId.Length, Is.EqualTo(15));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.Profile.Read(Reader(stamped.Take(99).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AttackPreview_Id_Flag_AndSizes_ArePinned_0x5E_0x400_4_28()
|
||||
{
|
||||
Assert.That((int)LobbyCodecs.AttackPreview.Id, Is.EqualTo(0x5E));
|
||||
Assert.That((int)StocCodecs.AttackPreview.Id, Is.EqualTo(0x5E));
|
||||
Assert.That(FeatureFlags.AttackPreview, Is.EqualTo(0x400));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.AttackPreview, Is.EqualTo(FeatureFlags.AttackPreview));
|
||||
Assert.That(AttackPreviewPair.Size, Is.EqualTo(4));
|
||||
Assert.That(AttackPreviewEntry.Size, Is.EqualTo(28));
|
||||
|
||||
var query = new AttackPreviewQuery(new[] { new AttackPreviewPair(0x04, 2, 0x04, 1), AttackPreviewPair.Direct(0x04, 2) });
|
||||
var asked = Bytes(w => LobbyCodecs.AttackPreview.Write(w, query));
|
||||
Assert.That(asked, Is.EqualTo(new byte[] { 1, 2, 0x04, 2, 0x04, 1, 0x04, 2, 0xFF, 0 }));
|
||||
var readQuery = LobbyCodecs.AttackPreview.Read(Reader(asked));
|
||||
Assert.That(readQuery.Version, Is.EqualTo(1));
|
||||
Assert.That(readQuery.Pairs.Length, Is.EqualTo(2));
|
||||
Assert.That(readQuery.Pairs[1].IsDirect, Is.True);
|
||||
Assert.That(readQuery.Pairs[0].TargetSequence, Is.EqualTo(1));
|
||||
Assert.That(Bytes(w => LobbyCodecs.AttackPreview.Write(w, new AttackPreviewQuery(null))), Is.EqualTo(new byte[] { 1, 0 }));
|
||||
|
||||
var answer = Enumerable.Range(0, 24).Select(i => (byte)(100 + i)).ToArray();
|
||||
var result = new AttackPreviewResult(new[] { new AttackPreviewEntry(query.Pairs[0], answer) });
|
||||
var answered = Bytes(w => StocCodecs.AttackPreview.Write(w, result));
|
||||
Assert.That(answered.Length, Is.EqualTo(2 + 28));
|
||||
Assert.That(answered, Is.EqualTo(Concat(new byte[] { 1, 1, 0x04, 2, 0x04, 1 }, answer)));
|
||||
var readResult = StocCodecs.AttackPreview.Read(Reader(answered));
|
||||
Assert.That(readResult.Version, Is.EqualTo(1));
|
||||
Assert.That(readResult.Entries.Length, Is.EqualTo(1));
|
||||
Assert.That(readResult.Entries[0].Pair.AttackerSequence, Is.EqualTo(2));
|
||||
Assert.That(readResult.Entries[0].Answer, Is.EqualTo(answer));
|
||||
Assert.That(StocCodecs.AttackPreview.Read(Reader(new byte[] { 1, 0 })).Entries, Is.Empty);
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.AttackPreview.Read(Reader(answered.Take(29).ToArray())));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.AttackPreview.Read(Reader(new byte[] { 1 })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TagTwoFields_Flag_IsPinned_0x1000()
|
||||
{
|
||||
Assert.That(FeatureFlags.TagTwoFields, Is.EqualTo(0x1000));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.TagTwoFields, Is.EqualTo(FeatureFlags.TagTwoFields));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TagSharedExtra_Flag_IsPinned_0x4000()
|
||||
{
|
||||
Assert.That(FeatureFlags.TagSharedExtra, Is.EqualTo(0x4000));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.TagSharedExtra, Is.EqualTo(FeatureFlags.TagSharedExtra));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PromptContext_Id_Flag_Protocol_AndRoundTrip_ArePinned_0x44_0x8000_12_24()
|
||||
{
|
||||
Assert.That((int)StocCodecs.PromptContext.Id, Is.EqualTo(0x44));
|
||||
Assert.That((int)StocMessage.PromptContext, Is.EqualTo(0x44));
|
||||
Assert.That(FeatureFlags.PromptContext, Is.EqualTo(0x8000));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.PromptContext, Is.EqualTo(FeatureFlags.PromptContext));
|
||||
Assert.That(Capability.ProtocolVersion, Is.EqualTo(12));
|
||||
Assert.That(PromptContextCodec.Size, Is.EqualTo(24));
|
||||
Assert.That(new[] { PromptContext.AnnouncePlain, PromptContext.AnnounceLevel, PromptContext.AnnounceDice }, Is.EqualTo(new byte[] { 0, 1, 2 }));
|
||||
Assert.That(new[] { PromptContext.PhaseOther, PromptContext.PhaseCost, PromptContext.PhaseTarget, PromptContext.PhaseOperation, PromptContext.PhaseAsk }, Is.EqualTo(new byte[] { 0, 1, 2, 3, 4 }));
|
||||
|
||||
const ulong description = 12960005233ul;
|
||||
var payload = new PromptContext(true, 16178681u, 1, 0x04, 2, 0x1, description, 3, PromptContext.PhaseOperation, 2, PromptContext.AnnounceDice, 143);
|
||||
var bytes = Bytes(w => StocCodecs.PromptContext.Write(w, payload));
|
||||
Assert.That(bytes.Length, Is.EqualTo(24));
|
||||
Assert.That(bytes[0], Is.EqualTo(1));
|
||||
Assert.That(bytes[1], Is.EqualTo(1));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 2), Is.EqualTo(16178681u));
|
||||
Assert.That(bytes.Skip(6).Take(4).ToArray(), Is.EqualTo(new byte[] { 1, 0x04, 2, 0x1 }));
|
||||
Assert.That(BitConverter.ToUInt64(bytes, 10), Is.EqualTo(description));
|
||||
Assert.That(BitConverter.ToUInt16(bytes, 18), Is.EqualTo(3));
|
||||
Assert.That(bytes.Skip(20).ToArray(), Is.EqualTo(new byte[] { 3, 2, 2, 143 }));
|
||||
|
||||
var read = StocCodecs.PromptContext.Read(Reader(bytes));
|
||||
Assert.That(read.Version, Is.EqualTo(1));
|
||||
Assert.That(read.HasEffect, Is.True);
|
||||
Assert.That(read.IsHidden, Is.False);
|
||||
Assert.That(read.Code, Is.EqualTo(16178681u));
|
||||
Assert.That(read.Controller, Is.EqualTo(1));
|
||||
Assert.That(read.Location, Is.EqualTo(0x04));
|
||||
Assert.That(read.Sequence, Is.EqualTo(2));
|
||||
Assert.That(read.Position, Is.EqualTo(0x1));
|
||||
Assert.That(read.Description, Is.EqualTo(description));
|
||||
Assert.That(read.EffectIndex, Is.EqualTo(3));
|
||||
Assert.That(read.Phase, Is.EqualTo(PromptContext.PhaseOperation));
|
||||
Assert.That(read.ChainLink, Is.EqualTo(2));
|
||||
Assert.That(read.AnnounceKind, Is.EqualTo(PromptContext.AnnounceDice));
|
||||
Assert.That(read.Prompt, Is.EqualTo(143));
|
||||
|
||||
var none = Bytes(w => StocCodecs.PromptContext.Write(w, PromptContext.None(10)));
|
||||
Assert.That(none, Is.EqualTo(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 10 }));
|
||||
Assert.That(StocCodecs.PromptContext.Read(Reader(none)).HasEffect, Is.False);
|
||||
var hidden = StocCodecs.PromptContext.Read(Reader(Bytes(w => StocCodecs.PromptContext.Write(w, new PromptContext(true, 0, 1, 0x02, 0, 0x8, 0, PromptContext.UnknownIndex, PromptContext.PhaseCost, 1, PromptContext.AnnouncePlain, 13)))));
|
||||
Assert.That(hidden.IsHidden, Is.True);
|
||||
Assert.That(hidden.EffectIndex, Is.EqualTo(PromptContext.UnknownIndex));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.PromptContext.Read(Reader(bytes.Take(23).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TagPartnerCards_Id_Flag_Protocol_AndRoundTrip_ArePinned_0x5F_0x2000_9()
|
||||
{
|
||||
Assert.That((int)StocCodecs.TagPartnerCards.Id, Is.EqualTo(0x5F));
|
||||
Assert.That(FeatureFlags.TagPartnerCards, Is.EqualTo(0x2000));
|
||||
Assert.That(FeatureFlags.All & FeatureFlags.TagPartnerCards, Is.EqualTo(FeatureFlags.TagPartnerCards));
|
||||
Assert.That(TagPartnerCardsCodec.HeaderSize, Is.EqualTo(7));
|
||||
|
||||
var faceUpPendulum = 0x80000000u | 16178681u;
|
||||
var payload = new TagPartnerCards(1, new uint[] { 89631139u, 46986414u }, new uint[] { faceUpPendulum, 44508094u }, new[] { 10, 20, 30 });
|
||||
var bytes = Bytes(w => StocCodecs.TagPartnerCards.Write(w, payload));
|
||||
Assert.That(bytes.Length, Is.EqualTo(7 + 4 * 7));
|
||||
Assert.That(bytes.Take(7).ToArray(), Is.EqualTo(new byte[] { 1, 1, 2, 2, 0, 3, 0 }));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 7), Is.EqualTo(89631139u));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 15), Is.EqualTo(faceUpPendulum));
|
||||
Assert.That(BitConverter.ToUInt32(bytes, 23), Is.EqualTo(10u));
|
||||
|
||||
var read = StocCodecs.TagPartnerCards.Read(Reader(bytes));
|
||||
Assert.That(read.Version, Is.EqualTo(1));
|
||||
Assert.That(read.Side, Is.EqualTo(1));
|
||||
Assert.That(read.Hand, Is.EqualTo(payload.Hand));
|
||||
Assert.That(read.Extra, Is.EqualTo(payload.Extra));
|
||||
Assert.That(read.Deck, Is.EqualTo(payload.Deck));
|
||||
Assert.That(TagPartnerCards.IsFaceUp(read.Extra[0]), Is.True);
|
||||
Assert.That(TagPartnerCards.CodeOf(read.Extra[0]), Is.EqualTo(16178681));
|
||||
Assert.That(TagPartnerCards.IsFaceUp(read.Extra[1]), Is.False);
|
||||
|
||||
var empty = StocCodecs.TagPartnerCards.Read(Reader(new byte[] { 0, 1, 0, 0, 0, 0, 0 }));
|
||||
Assert.That(empty.Side, Is.EqualTo(0));
|
||||
Assert.That(empty.Hand, Is.Empty);
|
||||
Assert.That(empty.Extra, Is.Empty);
|
||||
Assert.That(empty.Deck, Is.Empty);
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.TagPartnerCards.Read(Reader(bytes.Take(bytes.Length - 1).ToArray())));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.TagPartnerCards.Read(Reader(new byte[] { 0, 1, 0 })));
|
||||
Assert.Throws<InvalidDataException>(() => StocCodecs.TagPartnerCards.Read(Reader(new byte[] { 0, 1, 0, 0, 0, 0xFB, 0 })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeatState_Id_Flag_AndSizes_ArePinned_0x59_0x20_4_6()
|
||||
{
|
||||
Assert.That((int)LobbyCodecs.SeatState.Id, Is.EqualTo(0x59));
|
||||
Assert.That((int)StocCodecs.SeatState.Id, Is.EqualTo(0x59));
|
||||
Assert.That(FeatureFlags.SeatState, Is.EqualTo(0x20));
|
||||
var picking = Bytes(w => LobbyCodecs.SeatState.Write(w, new SeatState(SeatStateKind.PickingDeck)));
|
||||
Assert.That(picking, Is.EqualTo(new byte[] { 1, 1, 0, 0 }));
|
||||
var none = Bytes(w => LobbyCodecs.SeatState.Write(w, new SeatState(SeatStateKind.None)));
|
||||
Assert.That(none, Is.EqualTo(new byte[] { 1, 0, 0, 0 }));
|
||||
var stamped = Bytes(w => StocCodecs.SeatState.Write(w, new Stamped<SeatState>(2, new SeatState(SeatStateKind.PickingDeck, 7))));
|
||||
Assert.That(stamped, Is.EqualTo(Concat(Le16(2), new byte[] { 1, 1 }, Le16(7))));
|
||||
var read = StocCodecs.SeatState.Read(Reader(stamped));
|
||||
Assert.That(read.Seat, Is.EqualTo(2));
|
||||
Assert.That(read.Payload.Kind, Is.EqualTo(SeatStateKind.PickingDeck));
|
||||
Assert.That(read.Payload.Value, Is.EqualTo(7));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.SeatState.Read(Reader(stamped.Take(5).ToArray())));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Restart_StocSizes_ArePinned_40_23_21_19_AndShortReadsThrow()
|
||||
{
|
||||
var id = Enumerable.Repeat((byte)0xAB, 16).ToArray();
|
||||
var token = Enumerable.Range(1, 16).Select(i => (byte)i).ToArray();
|
||||
var restarting = Bytes(w => StocCodecs.RoomRestarting.Write(w, new Stamped<RoomRestarting>(0xFF, new RoomRestarting(RestartPhase.Prepare, id, 0xFF, token, 30000))));
|
||||
Assert.That(restarting.Length, Is.EqualTo(40));
|
||||
Assert.That(restarting, Is.EqualTo(Concat(Le16(0xFF), new byte[] { 1 }, id, new byte[] { 0xFF }, token, Le32(30000))));
|
||||
var readRestarting = StocCodecs.RoomRestarting.Read(Reader(restarting));
|
||||
Assert.That(readRestarting.Payload.Phase, Is.EqualTo(RestartPhase.Prepare));
|
||||
Assert.That(readRestarting.Payload.Seat, Is.EqualTo(SeatRequest.Observer));
|
||||
Assert.That(readRestarting.Payload.Token, Is.EqualTo(token));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.RoomRestarting.Read(Reader(restarting.Take(39).ToArray())));
|
||||
|
||||
var status = Bytes(w => StocCodecs.RestartStatus.Write(w, new Stamped<RestartStatus>(0xFF, new RestartStatus(RestartPhase.Commit, id, 2, 3, false, RestartReason.AckTimeout))));
|
||||
Assert.That(status.Length, Is.EqualTo(23));
|
||||
Assert.That(status, Is.EqualTo(Concat(Le16(0xFF), new byte[] { 2 }, id, new byte[] { 2, 3, 0, 2 })));
|
||||
Assert.That(StocCodecs.RestartStatus.Read(Reader(status)).Payload.Reason, Is.EqualTo(RestartReason.AckTimeout));
|
||||
|
||||
var result = Bytes(w => StocCodecs.SeatResumeResult.Write(w, new Stamped<SeatResumeResult>(0xFF, new SeatResumeResult(id, true, 1, 0))));
|
||||
Assert.That(result.Length, Is.EqualTo(21));
|
||||
Assert.That(result, Is.EqualTo(Concat(Le16(0xFF), id, new byte[] { 1, 1, 0 })));
|
||||
Assert.That(StocCodecs.SeatResumeResult.Read(Reader(result)).Payload.Accepted, Is.True);
|
||||
|
||||
var opened = Bytes(w => StocCodecs.RestartOpened.Write(w, new Stamped<RestartOpened>(0xFF, new RestartOpened(id, true))));
|
||||
Assert.That(opened.Length, Is.EqualTo(19));
|
||||
Assert.That(opened, Is.EqualTo(Concat(Le16(0xFF), id, new byte[] { 1 })));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.RestartOpened.Read(Reader(opened.Take(18).ToArray())));
|
||||
Assert.That(SeatIds.Same(id, SeatIds.Fixed(id)), Is.True);
|
||||
Assert.That(SeatIds.IsZero(Zeros(16)), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetupPairs_GoldenBytes_MatchPatch0009_AndRoundTrip()
|
||||
{
|
||||
var tokens = new[] { "ygol.ruleset=rush", "ygol.scripts=a.lua,b%20c.lua" };
|
||||
var golden = Concat(Le16(0xFF), Le16(2),
|
||||
Le16(tokens[0].Length), Encoding.ASCII.GetBytes(tokens[0]),
|
||||
Le16(tokens[1].Length), Encoding.ASCII.GetBytes(tokens[1]));
|
||||
var pairs = tokens.Select(SetupPair.FromToken).ToList();
|
||||
|
||||
Assert.That(Bytes(w => StocCodecs.SetupPairs.Write(w, new Stamped<IReadOnlyList<SetupPair>>(0xFF, pairs))), Is.EqualTo(golden));
|
||||
var read = StocCodecs.SetupPairs.Read(Reader(golden));
|
||||
Assert.That(read.Seat, Is.EqualTo(Capability.ServerSender));
|
||||
Assert.That(read.Payload.Select(p => p.Key), Is.EqualTo(new[] { "ygol.ruleset", "ygol.scripts" }));
|
||||
Assert.That(read.Payload.Select(p => p.Value), Is.EqualTo(new[] { "rush", "a.lua,b%20c.lua" }));
|
||||
Assert.That(SetupPair.FromToken("ygol.x=a=b").Value, Is.EqualTo("a=b"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetupPairs_EmptyBlock_IsFourBytes_AndATruncatedTokenThrows()
|
||||
{
|
||||
var empty = Bytes(w => StocCodecs.SetupPairs.Write(w, new Stamped<IReadOnlyList<SetupPair>>(0xFF, new SetupPair[0])));
|
||||
Assert.That(empty, Is.EqualTo(new byte[] { 0xFF, 0, 0, 0 }));
|
||||
Assert.That(StocCodecs.SetupPairs.Read(Reader(empty)).Payload, Is.Empty);
|
||||
var truncated = Concat(Le16(0xFF), Le16(1), Le16(10), Encoding.ASCII.GetBytes("ygol.a"));
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.SetupPairs.Read(Reader(truncated)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SetupPairs_ReplayBlock_IsLengthPrefixed_AndLeavesTheNamesNext()
|
||||
{
|
||||
var pairs = new[] { SetupPair.FromToken("ygol.ruleset=rush") };
|
||||
var bytes = Bytes(w =>
|
||||
{
|
||||
SetupPairsCodec.WriteReplayBlock(w, pairs);
|
||||
w.Write(Utf16Fixed("Alice", 20));
|
||||
});
|
||||
Assert.That(bytes.Take(4), Is.EqualTo(Le32(2 + 2 + 17)));
|
||||
using var reader = Reader(bytes);
|
||||
Assert.That(SetupPairsCodec.ReadReplayBlock(reader).Single().Token, Is.EqualTo("ygol.ruleset=rush"));
|
||||
Assert.That(Encoding.Unicode.GetString(reader.ReadBytes(10)), Is.EqualTo("Alice"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Sizes_ArePinned_6_8_352_354_204_206()
|
||||
{
|
||||
Assert.That(CapabilityCodec.Size, Is.EqualTo(6));
|
||||
Assert.That(CapabilityCodec.StampedSize, Is.EqualTo(8));
|
||||
Assert.That(AppearanceCodec.Size, Is.EqualTo(352));
|
||||
Assert.That(AppearanceCodec.StampedSize, Is.EqualTo(354));
|
||||
Assert.That(DialogueCodec.Size, Is.EqualTo(204));
|
||||
Assert.That(DialogueCodec.StampedSize, Is.EqualTo(206));
|
||||
Assert.That(StocCodecs.Capability.Size, Is.EqualTo(8));
|
||||
Assert.That(StocCodecs.Appearance.Size, Is.EqualTo(354));
|
||||
Assert.That(StocCodecs.Dialogue.Size, Is.EqualTo(206));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Capability_GoldenBytes_MatchTheProbe_AndRoundTrip()
|
||||
{
|
||||
var bytes = Bytes(w => LobbyCodecs.Capability.Write(w, new Capability(Capability.ProtocolVersion, FeatureFlags.All)));
|
||||
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Le16(12), Le32(0xF7FB))));
|
||||
|
||||
var read = LobbyCodecs.Capability.Read(Reader(bytes));
|
||||
Assert.That(read.Protocol, Is.EqualTo(Capability.ProtocolVersion));
|
||||
Assert.That(read.Flags, Is.EqualTo(FeatureFlags.All));
|
||||
Assert.That(read.Has(FeatureFlags.Appearance), Is.True);
|
||||
Assert.That(read.Has(FeatureFlags.Dialogue), Is.True);
|
||||
|
||||
var appearanceOnly = LobbyCodecs.Capability.Read(Reader(Concat(Le16(1), Le32(1))));
|
||||
Assert.That(appearanceOnly.Has(FeatureFlags.Appearance), Is.True);
|
||||
Assert.That(appearanceOnly.Has(FeatureFlags.Dialogue), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Capability_TheServersOwnLine_ReadsAsSeat0xFF()
|
||||
{
|
||||
var bytes = Concat(Le16(0xFF), Le16(1), Le32(3));
|
||||
|
||||
var read = StocCodecs.Capability.Read(Reader(bytes));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(8));
|
||||
Assert.That(read.Seat, Is.EqualTo(Capability.ServerSender));
|
||||
Assert.That(read.Payload.Protocol, Is.EqualTo(1));
|
||||
Assert.That(read.Payload.Flags, Is.EqualTo(3));
|
||||
|
||||
var seated = StocCodecs.Capability.Read(Reader(Bytes(w =>
|
||||
StocCodecs.Capability.Write(w, new Stamped<Capability>(2, new Capability(1, 1))))));
|
||||
Assert.That(seated.Seat, Is.EqualTo(2));
|
||||
Assert.That(seated.Payload.Flags, Is.EqualTo(1));
|
||||
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.Capability.Read(Reader(Concat(Le16(0xFF), Le16(1)))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Appearance_GoldenBytes_MatchTheProbe_AndRoundTrip()
|
||||
{
|
||||
var state = new AppearanceState(ProbeItems, "deck-1", "character-1", "group-1");
|
||||
var bytes = Bytes(w => LobbyCodecs.Appearance.Write(w, state));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(352));
|
||||
Assert.That(bytes, Is.EqualTo(ProbeAppearance()));
|
||||
|
||||
var read = LobbyCodecs.Appearance.Read(Reader(bytes));
|
||||
Assert.That(read.Items, Is.EqualTo(ProbeItems));
|
||||
Assert.That(read.DeckName, Is.EqualTo("deck-1"));
|
||||
Assert.That(read.CharacterId, Is.EqualTo("character-1"));
|
||||
Assert.That(read.DeckGroup, Is.EqualTo("group-1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Appearance_Stamped_Is354Bytes_AndA353ByteReadThrows()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.Appearance.Write(w,
|
||||
new Stamped<AppearanceState>(1, new AppearanceState(ProbeItems, "deck-1", "character-1", "group-1"))));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(354));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Le16(1), ProbeAppearance())));
|
||||
|
||||
var read = StocCodecs.Appearance.Read(Reader(bytes));
|
||||
Assert.That(read.Seat, Is.EqualTo(1));
|
||||
Assert.That(read.Payload.DeckName, Is.EqualTo("deck-1"));
|
||||
Assert.That(read.Payload.Items[7], Is.EqualTo(1017));
|
||||
|
||||
var short353 = bytes.Take(353).ToArray();
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.Appearance.Read(Reader(short353)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Appearance_A49CharDeckName_ClipsTo47PlusTerminator()
|
||||
{
|
||||
var name = new string('x', 49);
|
||||
var bytes = Bytes(w => LobbyCodecs.Appearance.Write(w, new AppearanceState(ProbeItems, name, "", "")));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(352));
|
||||
var nameSlot = bytes.Skip(32).Take(96).ToArray();
|
||||
Assert.That(nameSlot, Is.EqualTo(Concat(Utf16(new string('x', 47)), Zeros(2))));
|
||||
Assert.That(LobbyCodecs.Appearance.Read(Reader(bytes)).DeckName, Is.EqualTo(new string('x', 47)));
|
||||
Assert.That(LobbyCodecs.Appearance.Read(Reader(bytes)).CharacterId, Is.EqualTo(""));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Appearance_NullFields_WriteZeros_AndReadEmpty()
|
||||
{
|
||||
var bytes = Bytes(w => LobbyCodecs.Appearance.Write(w, new AppearanceState(null, null, null, null)));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(352));
|
||||
Assert.That(bytes, Is.All.EqualTo(0));
|
||||
|
||||
var read = LobbyCodecs.Appearance.Read(Reader(bytes));
|
||||
Assert.That(read.Items, Is.All.EqualTo(0));
|
||||
Assert.That(read.DeckName, Is.EqualTo(""));
|
||||
Assert.That(read.CharacterId, Is.EqualTo(""));
|
||||
Assert.That(read.DeckGroup, Is.EqualTo(""));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Dialogue_GoldenBytes_MatchTheProbe_AndRoundTrip()
|
||||
{
|
||||
var line = new DialogueLine(1, true, 4, 4004, 5004, "corpus-4", "event-4");
|
||||
var bytes = Bytes(w => LobbyCodecs.Dialogue.Write(w, line));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(204));
|
||||
Assert.That(bytes, Is.EqualTo(ProbeDialogue()));
|
||||
|
||||
var read = LobbyCodecs.Dialogue.Read(Reader(bytes));
|
||||
Assert.That(read.Version, Is.EqualTo(1));
|
||||
Assert.That(read.TargetFaceDown, Is.True);
|
||||
Assert.That(read.Index, Is.EqualTo(4));
|
||||
Assert.That(read.CardCode, Is.EqualTo(4004));
|
||||
Assert.That(read.TargetCode, Is.EqualTo(5004));
|
||||
Assert.That(read.CorpusKey, Is.EqualTo("corpus-4"));
|
||||
Assert.That(read.EventKey, Is.EqualTo("event-4"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Dialogue_Stamped_Is206Bytes_AndAHelloLineRoundTrips()
|
||||
{
|
||||
var hello = new DialogueLine(DialogueLine.CurrentVersion, false, -1, 0, 0, null, null);
|
||||
var bytes = Bytes(w => StocCodecs.Dialogue.Write(w, new Stamped<DialogueLine>(0, hello)));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(206));
|
||||
Assert.That(bytes.Skip(2).Take(2), Is.EqualTo(new byte[] { 1, 0 }));
|
||||
Assert.That(bytes.Skip(4).Take(2), Is.EqualTo(Le16(unchecked((short)-1))));
|
||||
|
||||
var read = StocCodecs.Dialogue.Read(Reader(bytes));
|
||||
Assert.That(read.Seat, Is.EqualTo(0));
|
||||
Assert.That(read.Payload.Index, Is.EqualTo(-1));
|
||||
Assert.That(read.Payload.TargetFaceDown, Is.False);
|
||||
Assert.That(read.Payload.CorpusKey, Is.EqualTo(""));
|
||||
Assert.That(read.Payload.EventKey, Is.EqualTo(""));
|
||||
|
||||
Assert.Throws<EndOfStreamException>(() => StocCodecs.Dialogue.Read(Reader(bytes.Take(205).ToArray())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Protocol.Codecs;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
using YGOLegacy.Protocol.Framing;
|
||||
|
||||
namespace YGOLegacy.Protocol.Tests
|
||||
{
|
||||
public class FrameCodecTests
|
||||
{
|
||||
private static byte[] Bytes(Action<BinaryWriter> write)
|
||||
{
|
||||
using (var stream = new MemoryStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Concat(params byte[][] parts)
|
||||
{
|
||||
return parts.SelectMany(p => p).ToArray();
|
||||
}
|
||||
|
||||
private static byte[] LegacyUnityFrame(int function, byte[] data)
|
||||
{
|
||||
return Bytes(b =>
|
||||
{
|
||||
b.Write(BitConverter.GetBytes((short)(data.Length + 1)), 0, 2);
|
||||
b.Write(BitConverter.GetBytes((short)function), 0, 1);
|
||||
b.Write(data, 0, data.Length);
|
||||
});
|
||||
}
|
||||
|
||||
private static byte[] LegacyWindBotFrame(byte[] packet)
|
||||
{
|
||||
var header = BitConverter.GetBytes((ushort)packet.Length);
|
||||
var data = new byte[packet.Length + 2];
|
||||
Array.Copy(header, 0, data, 0, header.Length);
|
||||
Array.Copy(packet, 0, data, header.Length, packet.Length);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static byte[] PlayerInfoPayload()
|
||||
{
|
||||
return Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice")));
|
||||
}
|
||||
|
||||
private static byte[] PlayerInfoPacket()
|
||||
{
|
||||
var packet = CtosPacket.Begin(LobbyCodecs.PlayerInfo.Id);
|
||||
LobbyCodecs.PlayerInfo.Write(packet, new PlayerInfo("Alice"));
|
||||
return ((MemoryStream)packet.BaseStream).ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Frame(byte[] packet)
|
||||
{
|
||||
return Bytes(w => FrameCodec.Write(w, packet));
|
||||
}
|
||||
|
||||
private static List<byte[]> Drain(FrameExtractor extractor)
|
||||
{
|
||||
var taken = new List<byte[]>();
|
||||
byte[] packet;
|
||||
while (extractor.TryTake(out packet))
|
||||
taken.Add(packet);
|
||||
return taken;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_FramedFromIdAndPayload_MatchesUnitySender()
|
||||
{
|
||||
var payload = PlayerInfoPayload();
|
||||
var ours = Bytes(w => FrameCodec.Write(w, (byte)LobbyCodecs.PlayerInfo.Id, payload));
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(43));
|
||||
Assert.That(ours.Take(3), Is.EqualTo(new byte[] { 0x29, 0x00, 0x10 }));
|
||||
Assert.That(ours, Is.EqualTo(LegacyUnityFrame((int)LobbyCodecs.PlayerInfo.Id, payload)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_FramedFromPacket_MatchesWindBotSend()
|
||||
{
|
||||
var packet = PlayerInfoPacket();
|
||||
var ours = Frame(packet);
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(43));
|
||||
Assert.That(ours, Is.EqualTo(LegacyWindBotFrame(packet)));
|
||||
Assert.That(ours, Is.EqualTo(Bytes(w => FrameCodec.Write(w, (byte)LobbyCodecs.PlayerInfo.Id, PlayerInfoPayload()))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HsReady_FramesAsThreeBytes()
|
||||
{
|
||||
var fromId = Bytes(w => FrameCodec.Write(w, (byte)CtosMessage.HsReady, new byte[0]));
|
||||
var fromNull = Bytes(w => FrameCodec.Write(w, (byte)CtosMessage.HsReady, null));
|
||||
var fromPacket = Frame(new[] { (byte)CtosMessage.HsReady });
|
||||
|
||||
Assert.That(fromId, Is.EqualTo(new byte[] { 0x01, 0x00, 0x22 }));
|
||||
Assert.That(fromNull, Is.EqualTo(fromId));
|
||||
Assert.That(fromPacket, Is.EqualTo(fromId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FortyThousandBytePayload_HeaderEqualsTheOldShortCast()
|
||||
{
|
||||
var payload = new byte[40000];
|
||||
var ours = Bytes(w => FrameCodec.Write(w, 0x01, payload));
|
||||
|
||||
Assert.That(ours.Take(2), Is.EqualTo(new byte[] { 0x41, 0x9C }));
|
||||
Assert.That(ours.Take(2), Is.EqualTo(BitConverter.GetBytes((short)(payload.Length + 1))));
|
||||
Assert.That(FrameCodec.ReadLength(ours), Is.EqualTo(40001));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Write_OverTheCeiling_Throws()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, 0x01, new byte[FrameCodec.MaxFrame])));
|
||||
Assert.Throws<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, new byte[FrameCodec.MaxFrame + 1])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Write_EmptyPacket_Throws()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, new byte[0])));
|
||||
Assert.Throws<ArgumentException>(() => Bytes(w => FrameCodec.Write(w, null)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MaxFramePacket_RoundTrips()
|
||||
{
|
||||
var packet = new byte[FrameCodec.MaxFrame];
|
||||
for (var i = 0; i < packet.Length; i++)
|
||||
packet[i] = (byte)i;
|
||||
var frame = Frame(packet);
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(frame, frame.Length);
|
||||
var taken = Drain(extractor);
|
||||
|
||||
Assert.That(frame.Take(2), Is.EqualTo(new byte[] { 0xFE, 0xFF }));
|
||||
Assert.That(taken.Count, Is.EqualTo(1));
|
||||
Assert.That(taken[0], Is.EqualTo(packet));
|
||||
Assert.That(extractor.Faulted, Is.False);
|
||||
Assert.That(extractor.Buffered, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_FrameSplitAtEveryByte_ComesOutWhole()
|
||||
{
|
||||
var packet = PlayerInfoPacket();
|
||||
var frame = Frame(packet);
|
||||
for (var split = 1; split < frame.Length; split++)
|
||||
{
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(frame, split);
|
||||
Assert.That(Drain(extractor), Is.Empty, "split " + split);
|
||||
extractor.Feed(frame.Skip(split).ToArray(), frame.Length - split);
|
||||
var taken = Drain(extractor);
|
||||
Assert.That(taken.Count, Is.EqualTo(1), "split " + split);
|
||||
Assert.That(taken[0], Is.EqualTo(packet), "split " + split);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_OneByteAtATime_ComesOutWhole()
|
||||
{
|
||||
var packet = PlayerInfoPacket();
|
||||
var frame = Frame(packet);
|
||||
var extractor = new FrameExtractor();
|
||||
var taken = new List<byte[]>();
|
||||
foreach (var b in frame)
|
||||
{
|
||||
extractor.Feed(new[] { b }, 1);
|
||||
taken.AddRange(Drain(extractor));
|
||||
}
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(1));
|
||||
Assert.That(taken[0], Is.EqualTo(packet));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_ThreeFramesInOneChunk_AllComeOut()
|
||||
{
|
||||
var a = new[] { (byte)CtosMessage.HsReady };
|
||||
var b = PlayerInfoPacket();
|
||||
var c = new byte[] { (byte)CtosMessage.HsKick, 0x01 };
|
||||
var chunk = Concat(Frame(a), Frame(b), Frame(c));
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(chunk, chunk.Length);
|
||||
var taken = Drain(extractor);
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(3));
|
||||
Assert.That(taken[0], Is.EqualTo(a));
|
||||
Assert.That(taken[1], Is.EqualTo(b));
|
||||
Assert.That(taken[2], Is.EqualTo(c));
|
||||
Assert.That(extractor.Buffered, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_HeaderSplitAcrossChunks_ComesOutWhole()
|
||||
{
|
||||
var packet = PlayerInfoPacket();
|
||||
var frame = Frame(packet);
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(frame, 1);
|
||||
Assert.That(Drain(extractor), Is.Empty);
|
||||
extractor.Feed(frame.Skip(1).ToArray(), frame.Length - 1);
|
||||
var taken = Drain(extractor);
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(1));
|
||||
Assert.That(taken[0], Is.EqualTo(packet));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_ZeroLengthFrameBetweenTwoRealOnes_IsDroppedAndCounted()
|
||||
{
|
||||
var a = PlayerInfoPacket();
|
||||
var c = new[] { (byte)CtosMessage.HsStart };
|
||||
var chunk = Concat(Frame(a), new byte[] { 0x00, 0x00 }, Frame(c));
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(chunk, chunk.Length);
|
||||
var taken = Drain(extractor);
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(2));
|
||||
Assert.That(taken[0], Is.EqualTo(a));
|
||||
Assert.That(taken[1], Is.EqualTo(c));
|
||||
Assert.That(extractor.DroppedEmpty, Is.EqualTo(1));
|
||||
Assert.That(extractor.Faulted, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_LengthOverTheCeiling_FaultsAndTakesNothing()
|
||||
{
|
||||
var chunk = Concat(new byte[] { 0xFF, 0xFF }, new byte[100]);
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(chunk, chunk.Length);
|
||||
byte[] packet;
|
||||
|
||||
Assert.That(extractor.TryTake(out packet), Is.False);
|
||||
Assert.That(packet, Is.Null);
|
||||
Assert.That(extractor.Faulted, Is.True);
|
||||
|
||||
extractor.Feed(Frame(PlayerInfoPacket()), 43);
|
||||
Assert.That(extractor.TryTake(out packet), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_RealFrameBeforeTheFault_IsStillTaken()
|
||||
{
|
||||
var a = PlayerInfoPacket();
|
||||
var chunk = Concat(Frame(a), new byte[] { 0xFF, 0xFF });
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(chunk, chunk.Length);
|
||||
var taken = Drain(extractor);
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(1));
|
||||
Assert.That(taken[0], Is.EqualTo(a));
|
||||
Assert.That(extractor.Faulted, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_ManyFramesAcrossManyChunks_KeepsOrder()
|
||||
{
|
||||
var packets = Enumerable.Range(0, 300).Select(i => Enumerable.Range(0, 1 + i % 97).Select(j => (byte)(i + j)).ToArray()).ToList();
|
||||
var stream = Concat(packets.Select(Frame).ToArray());
|
||||
var extractor = new FrameExtractor();
|
||||
var taken = new List<byte[]>();
|
||||
var offset = 0;
|
||||
var chunkSize = 7;
|
||||
while (offset < stream.Length)
|
||||
{
|
||||
var n = Math.Min(chunkSize, stream.Length - offset);
|
||||
extractor.Feed(stream.Skip(offset).Take(n).ToArray(), n);
|
||||
taken.AddRange(Drain(extractor));
|
||||
offset += n;
|
||||
chunkSize = chunkSize * 3 % 251 + 1;
|
||||
}
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(packets.Count));
|
||||
for (var i = 0; i < packets.Count; i++)
|
||||
Assert.That(taken[i], Is.EqualTo(packets[i]), "packet " + i);
|
||||
Assert.That(extractor.Buffered, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Extractor_FeedCountBeyondChunk_IsClamped()
|
||||
{
|
||||
var frame = Frame(new[] { (byte)CtosMessage.HsReady });
|
||||
var extractor = new FrameExtractor();
|
||||
extractor.Feed(frame, 999);
|
||||
var taken = Drain(extractor);
|
||||
|
||||
Assert.That(taken.Count, Is.EqualTo(1));
|
||||
Assert.That(taken[0], Is.EqualTo(new[] { (byte)CtosMessage.HsReady }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadLength_IsLittleEndian()
|
||||
{
|
||||
Assert.That(FrameCodec.ReadLength(new byte[] { 0x29, 0x00 }), Is.EqualTo(41));
|
||||
Assert.That(FrameCodec.ReadLength(new byte[] { 0x41, 0x9C }), Is.EqualTo(40001));
|
||||
Assert.That(FrameCodec.ReadLength(new byte[] { 0xFF, 0xFF }), Is.EqualTo(0xFFFF));
|
||||
Assert.That(FrameCodec.ReadLength(new byte[] { 0x29, 0x00 }), Is.EqualTo(BitConverter.ToUInt16(new byte[] { 0x29, 0x00 }, 0)));
|
||||
Assert.Throws<ArgumentException>(() => FrameCodec.ReadLength(new byte[] { 0x01 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Engine;
|
||||
|
||||
namespace YGOLegacy.Engine.Tests
|
||||
{
|
||||
public class GameMessageParityTests
|
||||
{
|
||||
private static readonly Regex Define = new Regex(@"^#define\s+MSG_([A-Z0-9_]+)\s+(\d+)\b", RegexOptions.Compiled);
|
||||
|
||||
private static string Pascal(string name)
|
||||
{
|
||||
return string.Concat(name.Split('_').Select(p => p.Substring(0, 1).ToUpperInvariant() + p.Substring(1).ToLowerInvariant()));
|
||||
}
|
||||
|
||||
private static Dictionary<string, int> HeaderMessages()
|
||||
{
|
||||
return File.ReadLines(ContractFiles.CommonHeader)
|
||||
.Select(line => Define.Match(line))
|
||||
.Where(m => m.Success)
|
||||
.ToDictionary(m => Pascal(m.Groups[1].Value), m => int.Parse(m.Groups[2].Value));
|
||||
}
|
||||
|
||||
private static Dictionary<string, int> EnumMessages()
|
||||
{
|
||||
return Enum.GetNames(typeof(GameMessage))
|
||||
.ToDictionary(name => name, name => (int)(byte)Enum.Parse(typeof(GameMessage), name));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeaderHas84Messages()
|
||||
{
|
||||
Assert.That(HeaderMessages().Count, Is.EqualTo(84));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryHeaderMessageIsAMember()
|
||||
{
|
||||
var missing = HeaderMessages().Keys.Except(EnumMessages().Keys).ToList();
|
||||
Assert.That(missing, Is.Empty, "MSG_ defines without a GameMessage member");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryMemberIsAHeaderMessage()
|
||||
{
|
||||
var extra = EnumMessages().Keys.Except(HeaderMessages().Keys).ToList();
|
||||
Assert.That(extra, Is.Empty, "GameMessage members that are not a MSG_ define");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EveryMemberHasTheHeaderValue()
|
||||
{
|
||||
var header = HeaderMessages();
|
||||
var renumbered = EnumMessages()
|
||||
.Where(kv => header.TryGetValue(kv.Key, out var value) && value != kv.Value)
|
||||
.Select(kv => kv.Key + " = " + kv.Value + ", header says " + header[kv.Key])
|
||||
.ToList();
|
||||
Assert.That(renumbered, Is.Empty, "GameMessage members whose value differs from the header");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Frozen copies of the legacy Unity (MDPro3) and WindBot (YGOSharp) readers the parity tests
|
||||
// compare the shared codec against. Copied verbatim from the Unity repo on 2026-10-15
|
||||
// (Assets/Scripts/MDPro3/Duel/TcpHelper.cs, Assets/Scripts/YGOSharp/YGOSharp.Network/);
|
||||
// only MDPro3's Debug.Log in its catch is dropped. Test-only; never shipped.
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace MDPro3
|
||||
{
|
||||
public static class BinaryExtensions
|
||||
{
|
||||
public static void WriteUnicode(this BinaryWriter writer, string text, int len)
|
||||
{
|
||||
try
|
||||
{
|
||||
var unicode = Encoding.Unicode.GetBytes(text);
|
||||
var result = new byte[len * 2];
|
||||
for (var i = 0; i < result.Length; i++) result[i] = 204;
|
||||
var max = len * 2 - 2;
|
||||
Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length);
|
||||
result[unicode.Length] = 0;
|
||||
result[unicode.Length + 1] = 0;
|
||||
writer.Write(result);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public static string ReadUnicode(this BinaryReader reader, int len)
|
||||
{
|
||||
var unicode = reader.ReadBytes(len * 2);
|
||||
var text = Encoding.Unicode.GetString(unicode);
|
||||
text = text[..text.IndexOf('\0')];
|
||||
return text;
|
||||
}
|
||||
|
||||
public static string ReadALLUnicode(this BinaryReader reader)
|
||||
{
|
||||
var unicode = reader.ReadToEnd();
|
||||
var text = Encoding.Unicode.GetString(unicode);
|
||||
text = text.Substring(0, text.IndexOf('\0'));
|
||||
return text;
|
||||
}
|
||||
|
||||
public static byte[] ReadToEnd(this BinaryReader reader)
|
||||
{
|
||||
return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace YGOSharp.Network.Utils
|
||||
{
|
||||
public static class BinaryExtensions
|
||||
{
|
||||
// fixed length strings
|
||||
public static void WriteUnicode(this BinaryWriter writer, string text, int len)
|
||||
{
|
||||
byte[] unicode = Encoding.Unicode.GetBytes(text);
|
||||
byte[] result = new byte[len * 2];
|
||||
int copy = unicode.Length;
|
||||
if (unicode.Length > len * 2 - 2)
|
||||
{
|
||||
copy = len * 2 - 2;
|
||||
#if DEBUG
|
||||
throw new ArgumentException("String '" + text + "' is too long for fixed length " + len + ".");
|
||||
#endif
|
||||
}
|
||||
Array.Copy(unicode, result, copy);
|
||||
writer.Write(result);
|
||||
}
|
||||
|
||||
// variable length strings
|
||||
public static void WriteUnicodeAutoLength(this BinaryWriter writer, string text, int maxlen)
|
||||
{
|
||||
byte[] result = Encoding.Unicode.GetBytes(text + "\0");
|
||||
int len = result.Length / 2;
|
||||
if (len > maxlen)
|
||||
{
|
||||
len = maxlen;
|
||||
result[len * 2 - 2] = 0;
|
||||
result[len * 2 - 1] = 0;
|
||||
#if DEBUG
|
||||
throw new ArgumentException("String '" + text + "' is too long for max length " + maxlen + ".");
|
||||
#endif
|
||||
}
|
||||
writer.Write(result, 0, len * 2);
|
||||
}
|
||||
|
||||
public static string ReadUnicode(this BinaryReader reader, int len)
|
||||
{
|
||||
byte[] unicode = reader.ReadBytes(len * 2);
|
||||
string text = Encoding.Unicode.GetString(unicode);
|
||||
int index = text.IndexOf('\0');
|
||||
if (index > 0) text = text.Substring(0, index);
|
||||
return text;
|
||||
}
|
||||
|
||||
public static byte[] ReadToEnd(this BinaryReader reader)
|
||||
{
|
||||
return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace YGOSharp.Network.Enums
|
||||
{
|
||||
public enum CtosMessage
|
||||
{
|
||||
Response = 0x1,
|
||||
UpdateDeck = 0x2,
|
||||
HandResult = 0x3,
|
||||
TpResult = 0x4,
|
||||
PlayerInfo = 0x10,
|
||||
CreateGame = 0x11,
|
||||
JoinGame = 0x12,
|
||||
LeaveGame = 0x13,
|
||||
Surrender = 0x14,
|
||||
TimeConfirm = 0x15,
|
||||
Chat = 0x16,
|
||||
ExternalAddress = 0x17,
|
||||
HsToDuelist = 0x20,
|
||||
HsToObserver = 0x21,
|
||||
HsReady = 0x22,
|
||||
HsNotReady = 0x23,
|
||||
HsKick = 0x24,
|
||||
HsStart = 0x25
|
||||
}
|
||||
|
||||
public enum StocMessage
|
||||
{
|
||||
GameMsg = 0x1,
|
||||
ErrorMsg = 0x2,
|
||||
SelectHand = 0x3,
|
||||
SelectTp = 0x4,
|
||||
HandResult = 0x5,
|
||||
TpResult = 0x6,
|
||||
ChangeSide = 0x7,
|
||||
WaitingSide = 0x8,
|
||||
CreateGame = 0x11,
|
||||
JoinGame = 0x12,
|
||||
TypeChange = 0x13,
|
||||
LeaveGame = 0x14,
|
||||
DuelStart = 0x15,
|
||||
DuelEnd = 0x16,
|
||||
Replay = 0x17,
|
||||
TimeLimit = 0x18,
|
||||
Chat = 0x19,
|
||||
HsPlayerEnter = 0x20,
|
||||
HsPlayerChange = 0x21,
|
||||
HsWatchChange = 0x22,
|
||||
TeammateSurrender = 0x23
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Protocol.Codecs;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Tests
|
||||
{
|
||||
public class ProtocolCodecTests
|
||||
{
|
||||
private const ushort Version = 0x1362;
|
||||
|
||||
private static byte[] Bytes(Action<BinaryWriter> write)
|
||||
{
|
||||
using (var stream = new MemoryStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static BinaryReader Reader(byte[] bytes)
|
||||
{
|
||||
return new BinaryReader(new MemoryStream(bytes));
|
||||
}
|
||||
|
||||
private static byte[] Utf16(string text)
|
||||
{
|
||||
return Encoding.Unicode.GetBytes(text);
|
||||
}
|
||||
|
||||
private static byte[] Concat(params byte[][] parts)
|
||||
{
|
||||
return parts.SelectMany(p => p).ToArray();
|
||||
}
|
||||
|
||||
private static void AssertEqualExceptPadding(byte[] ours, byte[] legacy, int paddingFrom, byte legacyPad)
|
||||
{
|
||||
Assert.That(ours.Length, Is.EqualTo(legacy.Length));
|
||||
Assert.That(ours.Take(paddingFrom), Is.EqualTo(legacy.Take(paddingFrom)));
|
||||
Assert.That(ours.Skip(paddingFrom), Is.All.EqualTo(0));
|
||||
Assert.That(legacy.Skip(paddingFrom), Is.All.EqualTo(legacyPad));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_WritesFortyZeroPaddedBytes()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice")));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Concat(Utf16("Alice\0"), new byte[28])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_MatchesWindBotExactly_AndUnityExceptPadding()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice")));
|
||||
var windbot = Bytes(w => YGOSharp.Network.Utils.BinaryExtensions.WriteUnicode(w, "Alice", 20));
|
||||
var unity = Bytes(w => MDPro3.BinaryExtensions.WriteUnicode(w, "Alice", 20));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(windbot));
|
||||
AssertEqualExceptPadding(ours, unity, 12, 0xCC);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_OverlongName_KeepsNineteenUnitsAndTerminator()
|
||||
{
|
||||
var name = new string('n', 25);
|
||||
byte[] ours = null;
|
||||
|
||||
Assert.DoesNotThrow(() => ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo(name))));
|
||||
Assert.That(ours.Length, Is.EqualTo(40));
|
||||
Assert.That(ours.Skip(38), Is.All.EqualTo(0));
|
||||
Assert.That(LobbyCodecs.PlayerInfo.Read(Reader(ours)).Name, Is.EqualTo(name.Substring(0, 19)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_EmojiAtTheBoundary_IsNotSplit()
|
||||
{
|
||||
var name = new string('a', 18) + "\U0001F600";
|
||||
var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo(name)));
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(40));
|
||||
Assert.That(ours.Skip(36), Is.All.EqualTo(0));
|
||||
Assert.That(LobbyCodecs.PlayerInfo.Read(Reader(ours)).Name, Is.EqualTo(new string('a', 18)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_EmojiThatFits_RoundTrips()
|
||||
{
|
||||
var name = new string('a', 17) + "\U0001F600";
|
||||
var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo(name)));
|
||||
|
||||
Assert.That(ours.Length, Is.EqualTo(40));
|
||||
Assert.That(LobbyCodecs.PlayerInfo.Read(Reader(ours)).Name, Is.EqualTo(name));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerInfo_NullName_WritesZeros()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.PlayerInfo.Write(w, default(PlayerInfo)));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(new byte[40]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadFixed_TerminatorAtZero_ReadsEmpty()
|
||||
{
|
||||
Assert.That(UnicodeCodec.ReadFixed(Reader(new byte[40]), 20), Is.EqualTo(string.Empty));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadFixed_NoTerminator_ReadsWholeBuffer()
|
||||
{
|
||||
var full = new string('x', 20);
|
||||
|
||||
Assert.That(UnicodeCodec.ReadFixed(Reader(Utf16(full)), 20), Is.EqualTo(full));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WriteTerminated_CapsAtMaxCharsIncludingTerminator()
|
||||
{
|
||||
var ours = Bytes(w => UnicodeCodec.WriteTerminated(w, "abcdef", 4));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Utf16("abc\0")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WriteTerminated_EmojiAtTheCap_IsNotSplit()
|
||||
{
|
||||
var ours = Bytes(w => UnicodeCodec.WriteTerminated(w, "a\U0001F600", 3));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Utf16("a\0")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JoinGame_WritesFortyEightBytes()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.JoinGame.Write(w, new JoinGame(Version, "abc")));
|
||||
var head = new byte[] { 0x62, 0x13, 0xCC, 0xCC, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Concat(head, Utf16("abc\0"), new byte[32])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JoinGame_MatchesWindBotExactly_AndUnityExceptPadding()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.JoinGame.Write(w, new JoinGame(Version, "abc")));
|
||||
var windbot = Bytes(w =>
|
||||
{
|
||||
w.Write((short)Version);
|
||||
w.Write(new byte[] { 0xCC, 0xCC, 0x00, 0x00, 0x00, 0x00 });
|
||||
YGOSharp.Network.Utils.BinaryExtensions.WriteUnicode(w, "abc", 20);
|
||||
});
|
||||
var unity = Bytes(w =>
|
||||
{
|
||||
w.Write((short)Version);
|
||||
w.Write((byte)204);
|
||||
w.Write((byte)204);
|
||||
w.Write(0);
|
||||
MDPro3.BinaryExtensions.WriteUnicode(w, "abc", 20);
|
||||
});
|
||||
|
||||
Assert.That(ours, Is.EqualTo(windbot));
|
||||
AssertEqualExceptPadding(ours, unity, 16, 0xCC);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JoinGame_RoundTrips()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.JoinGame.Write(w, new JoinGame(Version, "secret")));
|
||||
var read = LobbyCodecs.JoinGame.Read(Reader(ours));
|
||||
|
||||
Assert.That(read.Version, Is.EqualTo(Version));
|
||||
Assert.That(read.Password, Is.EqualTo("secret"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExternalAddress_WritesZeroIpThenTerminatedHost()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.ExternalAddress.Write(w, new ExternalAddress("127.0.0.1")));
|
||||
|
||||
Assert.That(ours, Is.EqualTo(Concat(new byte[4], Utf16("127.0.0.1\0"))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExternalAddress_MatchesBothClientsExactly()
|
||||
{
|
||||
const string host = "127.0.0.1";
|
||||
var ours = Bytes(w => LobbyCodecs.ExternalAddress.Write(w, new ExternalAddress(host)));
|
||||
var windbot = Bytes(w =>
|
||||
{
|
||||
w.Write((uint)0);
|
||||
YGOSharp.Network.Utils.BinaryExtensions.WriteUnicodeAutoLength(w, host, 255);
|
||||
});
|
||||
var unity = Bytes(w =>
|
||||
{
|
||||
w.Write((uint)0);
|
||||
MDPro3.BinaryExtensions.WriteUnicode(w, host, host.Length + 1);
|
||||
});
|
||||
|
||||
Assert.That(ours, Is.EqualTo(windbot));
|
||||
Assert.That(ours, Is.EqualTo(unity));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExternalAddress_RoundTrips()
|
||||
{
|
||||
var ours = Bytes(w => LobbyCodecs.ExternalAddress.Write(w, new ExternalAddress("gitea.dev.blueoceanswim.com")));
|
||||
|
||||
Assert.That(LobbyCodecs.ExternalAddress.Read(Reader(ours)).Host, Is.EqualTo("gitea.dev.blueoceanswim.com"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateDeck_WritesCountsThenIds()
|
||||
{
|
||||
var deck = new UpdateDeck(new[] { 1, 2 }, new[] { 3 }, new[] { 4 });
|
||||
var ours = Bytes(w => LobbyCodecs.UpdateDeck.Write(w, deck));
|
||||
var legacy = Bytes(w =>
|
||||
{
|
||||
w.Write(2 + 1);
|
||||
w.Write(1);
|
||||
w.Write(1);
|
||||
w.Write(2);
|
||||
w.Write(3);
|
||||
w.Write(4);
|
||||
});
|
||||
|
||||
Assert.That(ours, Is.EqualTo(legacy));
|
||||
Assert.That(ours.Length, Is.EqualTo(24));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UpdateDeck_ReadsMainAndExtraAsOneList()
|
||||
{
|
||||
var deck = new UpdateDeck(new[] { 1, 2 }, new[] { 3 }, new[] { 4 });
|
||||
var read = LobbyCodecs.UpdateDeck.Read(Reader(Bytes(w => LobbyCodecs.UpdateDeck.Write(w, deck))));
|
||||
|
||||
Assert.That(read.Main, Is.EqualTo(new[] { 1, 2, 3 }));
|
||||
Assert.That(read.Extra, Is.Empty);
|
||||
Assert.That(read.Side, Is.EqualTo(new[] { 4 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CtosPacket_PutsTheIdByteBeforeThePayload()
|
||||
{
|
||||
var packet = CtosPacket.Begin(LobbyCodecs.PlayerInfo.Id);
|
||||
LobbyCodecs.PlayerInfo.Write(packet, new PlayerInfo("Alice"));
|
||||
var bytes = ((MemoryStream)packet.BaseStream).ToArray();
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(41));
|
||||
Assert.That(bytes[0], Is.EqualTo(0x10));
|
||||
Assert.That(bytes.Skip(1), Is.EqualTo(Bytes(w => LobbyCodecs.PlayerInfo.Write(w, new PlayerInfo("Alice")))));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CodecIds_MatchTheCatalog()
|
||||
{
|
||||
Assert.That((int)LobbyCodecs.ExternalAddress.Id, Is.EqualTo(0x17));
|
||||
Assert.That((int)LobbyCodecs.PlayerInfo.Id, Is.EqualTo(0x10));
|
||||
Assert.That((int)LobbyCodecs.JoinGame.Id, Is.EqualTo(0x12));
|
||||
Assert.That((int)LobbyCodecs.UpdateDeck.Id, Is.EqualTo(0x02));
|
||||
Assert.That((int)LobbyCodecs.Profile.Id, Is.EqualTo(0x5D));
|
||||
Assert.That((int)StocCodecs.Profile.Id, Is.EqualTo(0x5D));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CtosCatalog_AgreesWithWindBotEnum()
|
||||
{
|
||||
AssertCatalogParity(typeof(CtosMessage),
|
||||
new[] { typeof(YGOSharp.Network.Enums.CtosMessage) },
|
||||
new[] { "RequestField", "Capability", "Appearance", "Dialogue", "SeatPlan", "SeatRequest", "SeatSwap", "SeatMove",
|
||||
"RestartPrepare", "RestartAck", "RestartControl", "SeatResume", "RestartOpen", "SeatState", "Profile", "AttackPreview" });
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StocCatalog_AgreesWithWindBotEnum()
|
||||
{
|
||||
Assert.That((int)StocMessage.DeckCount, Is.EqualTo(0x09));
|
||||
AssertCatalogParity(typeof(StocMessage),
|
||||
new[] { typeof(YGOSharp.Network.Enums.StocMessage) },
|
||||
new[] { "DeckCount", "FieldFinish", "SrvproRoomList", "Capability", "Appearance", "Dialogue", "SetupPairs", "SeatPlan",
|
||||
"RoomRestarting", "RestartStatus", "SeatResumeResult", "RestartOpen", "SeatState", "MatchOver", "CoinToss", "DeckList", "Profile", "AttackPreview", "TagPartnerCards", "PromptContext" });
|
||||
}
|
||||
|
||||
private static void AssertCatalogParity(Type catalog, Type[] legacyEnums, string[] expectedExtras)
|
||||
{
|
||||
var legacyNames = legacyEnums.SelectMany(Enum.GetNames).Distinct().ToArray();
|
||||
foreach (var legacy in legacyEnums)
|
||||
{
|
||||
foreach (var name in Enum.GetNames(legacy))
|
||||
{
|
||||
Assert.That(Enum.IsDefined(catalog, name), Is.True, legacy.FullName + "." + name + " is missing from the catalog");
|
||||
Assert.That(Convert.ToInt32(Enum.Parse(catalog, name)), Is.EqualTo(Convert.ToInt32(Enum.Parse(legacy, name))), name);
|
||||
}
|
||||
}
|
||||
var extras = Enum.GetNames(catalog).Except(legacyNames).OrderBy(n => n).ToArray();
|
||||
Assert.That(extras, Is.EqualTo(expectedExtras.OrderBy(n => n).ToArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Protocol.Codecs;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Tests
|
||||
{
|
||||
public class StocCodecTests
|
||||
{
|
||||
private static byte[] Bytes(Action<BinaryWriter> write)
|
||||
{
|
||||
using (var stream = new MemoryStream())
|
||||
using (var writer = new BinaryWriter(stream))
|
||||
{
|
||||
write(writer);
|
||||
writer.Flush();
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static BinaryReader Reader(byte[] bytes)
|
||||
{
|
||||
return new BinaryReader(new MemoryStream(bytes));
|
||||
}
|
||||
|
||||
private static byte[] Utf16(string text)
|
||||
{
|
||||
return Encoding.Unicode.GetBytes(text);
|
||||
}
|
||||
|
||||
private static byte[] Concat(params byte[][] parts)
|
||||
{
|
||||
return parts.SelectMany(p => p).ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Le16(int value)
|
||||
{
|
||||
return new[] { (byte)value, (byte)(value >> 8) };
|
||||
}
|
||||
|
||||
private static byte[] Le32(int value)
|
||||
{
|
||||
return new[] { (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24) };
|
||||
}
|
||||
|
||||
private static byte[] Zeros(int count)
|
||||
{
|
||||
return new byte[count];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Ids_MatchTheStocCatalog()
|
||||
{
|
||||
Assert.That(StocCodecs.ErrorMsg.Id, Is.EqualTo(StocMessage.ErrorMsg));
|
||||
Assert.That(StocCodecs.HandResult.Id, Is.EqualTo(StocMessage.HandResult));
|
||||
Assert.That(StocCodecs.JoinGame.Id, Is.EqualTo(StocMessage.JoinGame));
|
||||
Assert.That(StocCodecs.TypeChange.Id, Is.EqualTo(StocMessage.TypeChange));
|
||||
Assert.That(StocCodecs.TimeLimit.Id, Is.EqualTo(StocMessage.TimeLimit));
|
||||
Assert.That(StocCodecs.Chat.Id, Is.EqualTo(StocMessage.Chat));
|
||||
Assert.That(StocCodecs.HsPlayerEnter.Id, Is.EqualTo(StocMessage.HsPlayerEnter));
|
||||
Assert.That(StocCodecs.HsPlayerChange.Id, Is.EqualTo(StocMessage.HsPlayerChange));
|
||||
Assert.That(StocCodecs.HsWatchChange.Id, Is.EqualTo(StocMessage.HsWatchChange));
|
||||
Assert.That(StocCodecs.DeckCount.Id, Is.EqualTo(StocMessage.DeckCount));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ErrorMsg_GoldenBytes_MatchTheNativeStruct()
|
||||
{
|
||||
var code = (4 << 28) | 12345;
|
||||
var bytes = Bytes(w => StocCodecs.ErrorMsg.Write(w, new ErrorMsg(2, code)));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(8));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(new byte[] { 2 }, Zeros(3), Le32(code))));
|
||||
|
||||
var read = StocCodecs.ErrorMsg.Read(Reader(bytes));
|
||||
Assert.That(read.Msg, Is.EqualTo(2));
|
||||
Assert.That(read.Code, Is.EqualTo(code));
|
||||
Assert.That(read.Code >> 28, Is.EqualTo(4));
|
||||
Assert.That(read.Code & 0xFFFFFFF, Is.EqualTo(12345));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ErrorMsg_ReadsWhatBothLegacyHandlersRead()
|
||||
{
|
||||
var bytes = Concat(new byte[] { 1 }, new byte[] { 0xAA, 0xBB, 0xCC }, Le32(2));
|
||||
var legacy = Reader(bytes);
|
||||
int legacyMsg = legacy.ReadByte();
|
||||
legacy.ReadByte();
|
||||
legacy.ReadByte();
|
||||
legacy.ReadByte();
|
||||
var legacyCode = legacy.ReadInt32();
|
||||
|
||||
var read = StocCodecs.ErrorMsg.Read(Reader(bytes));
|
||||
Assert.That(read.Msg, Is.EqualTo(legacyMsg));
|
||||
Assert.That(read.Code, Is.EqualTo(legacyCode));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HandResult_GoldenBytes_AndShortPacket()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.HandResult.Write(w, new HandResultAnnounce(1, 3)));
|
||||
Assert.That(bytes, Is.EqualTo(new byte[] { 1, 3 }));
|
||||
|
||||
var read = StocCodecs.HandResult.Read(Reader(bytes));
|
||||
Assert.That(read.First, Is.EqualTo(1));
|
||||
Assert.That(read.Second, Is.EqualTo(3));
|
||||
|
||||
var shortRead = StocCodecs.HandResult.Read(Reader(new byte[] { 2 }));
|
||||
Assert.That(shortRead.First, Is.EqualTo(2));
|
||||
Assert.That(shortRead.Second, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HostInfo_GoldenBytes_MatchTheNative20ByteStruct()
|
||||
{
|
||||
var info = new HostInfo(0xDEADBEEF, 5, 2, 5, true, false, 8000, 5, 1, 180);
|
||||
var bytes = Bytes(w => StocCodecs.JoinGame.Write(w, info));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(20));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(
|
||||
Le32(unchecked((int)0xDEADBEEF)),
|
||||
new byte[] { 5, 2, 5, 1, 0 },
|
||||
Zeros(3),
|
||||
Le32(8000),
|
||||
new byte[] { 5, 1 },
|
||||
Le16(180))));
|
||||
Assert.That(bytes.Skip(9).Take(3), Is.All.EqualTo(0));
|
||||
|
||||
var read = StocCodecs.JoinGame.Read(Reader(bytes));
|
||||
Assert.That(read.Lflist, Is.EqualTo(0xDEADBEEF));
|
||||
Assert.That(read.Rule, Is.EqualTo(5));
|
||||
Assert.That(read.Mode, Is.EqualTo(2));
|
||||
Assert.That(read.DuelRule, Is.EqualTo(5));
|
||||
Assert.That(read.NoCheckDeck, Is.True);
|
||||
Assert.That(read.NoShuffleDeck, Is.False);
|
||||
Assert.That(read.StartLp, Is.EqualTo(8000));
|
||||
Assert.That(read.StartHand, Is.EqualTo(5));
|
||||
Assert.That(read.DrawCount, Is.EqualTo(1));
|
||||
Assert.That(read.TimeLimit, Is.EqualTo(180));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HostInfo_ReadsWhatUnitysLegacyFieldSequenceRead()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.JoinGame.Write(w, new HostInfo(7, 0, 1, 4, false, true, 16000, 4, 2, 240)));
|
||||
|
||||
var legacy = Reader(bytes);
|
||||
var lflist = legacy.ReadUInt32();
|
||||
var rule = legacy.ReadByte();
|
||||
var mode = legacy.ReadByte();
|
||||
int masterRule = legacy.ReadChar();
|
||||
var noCheck = legacy.ReadBoolean();
|
||||
var noShuffle = legacy.ReadBoolean();
|
||||
legacy.ReadByte();
|
||||
legacy.ReadByte();
|
||||
legacy.ReadByte();
|
||||
var startLp = legacy.ReadInt32();
|
||||
var startHand = legacy.ReadByte();
|
||||
var drawCount = legacy.ReadByte();
|
||||
var timeLimit = legacy.ReadInt16();
|
||||
|
||||
var read = StocCodecs.JoinGame.Read(Reader(bytes));
|
||||
Assert.That(read.Lflist, Is.EqualTo(lflist));
|
||||
Assert.That(read.Rule, Is.EqualTo(rule));
|
||||
Assert.That(read.Mode, Is.EqualTo(mode));
|
||||
Assert.That((int)read.DuelRule, Is.EqualTo(masterRule));
|
||||
Assert.That(read.NoCheckDeck, Is.EqualTo(noCheck));
|
||||
Assert.That(read.NoShuffleDeck, Is.EqualTo(noShuffle));
|
||||
Assert.That(read.StartLp, Is.EqualTo(startLp));
|
||||
Assert.That(read.StartHand, Is.EqualTo(startHand));
|
||||
Assert.That(read.DrawCount, Is.EqualTo(drawCount));
|
||||
Assert.That((short)read.TimeLimit, Is.EqualTo(timeLimit));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TypeChange_NibblesRoundTrip()
|
||||
{
|
||||
for (byte position = 0; position < 4; position++)
|
||||
{
|
||||
foreach (var isHost in new[] { false, true })
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.TypeChange.Write(w, new TypeChange(position, isHost)));
|
||||
Assert.That(bytes, Is.EqualTo(new[] { (byte)(position | (isHost ? 0x10 : 0)) }));
|
||||
|
||||
var read = StocCodecs.TypeChange.Read(Reader(bytes));
|
||||
Assert.That(read.Position, Is.EqualTo(position));
|
||||
Assert.That(read.IsHost, Is.EqualTo(isHost));
|
||||
}
|
||||
}
|
||||
|
||||
var observer = StocCodecs.TypeChange.Read(Reader(new byte[] { 0x07 }));
|
||||
Assert.That(observer.Position, Is.EqualTo(7));
|
||||
Assert.That(observer.IsHost, Is.False);
|
||||
|
||||
var hostByOtherBit = StocCodecs.TypeChange.Read(Reader(new byte[] { 0x21 }));
|
||||
Assert.That(hostByOtherBit.Position, Is.EqualTo(1));
|
||||
Assert.That(hostByOtherBit.IsHost, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TimeLimit_GoldenBytes_AndShortPackets()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.TimeLimit.Write(w, new TimeLimit(1, 300)));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(new byte[] { 1, 0 }, Le16(300))));
|
||||
|
||||
var read = StocCodecs.TimeLimit.Read(Reader(bytes));
|
||||
Assert.That(read.Player, Is.EqualTo(1));
|
||||
Assert.That(read.LeftTime, Is.EqualTo(300));
|
||||
|
||||
var twoBytes = StocCodecs.TimeLimit.Read(Reader(new byte[] { 0, 0 }));
|
||||
Assert.That(twoBytes.Player, Is.EqualTo(0));
|
||||
Assert.That(twoBytes.LeftTime, Is.EqualTo(0));
|
||||
|
||||
var oneByte = StocCodecs.TimeLimit.Read(Reader(new byte[] { 1 }));
|
||||
Assert.That(oneByte.Player, Is.EqualTo(1));
|
||||
Assert.That(oneByte.LeftTime, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ServerChat_GoldenBytes_PlayerThenTextThenTerminator()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.Chat.Write(w, new ServerChat(1, "hi")));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Le16(1), Utf16("hi"), Zeros(2))));
|
||||
|
||||
var read = StocCodecs.Chat.Read(Reader(bytes));
|
||||
Assert.That(read.Player, Is.EqualTo(1));
|
||||
Assert.That(read.Text, Is.EqualTo("hi"));
|
||||
|
||||
var system = StocCodecs.Chat.Read(Reader(Concat(Le16(8), Utf16("watch"), Zeros(2))));
|
||||
Assert.That(system.Player, Is.EqualTo(8));
|
||||
Assert.That(system.Text, Is.EqualTo("watch"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ServerChat_ReadsWhatBothLegacyHandlersRead()
|
||||
{
|
||||
var bytes = Concat(Le16(2), Utf16("twenty byte chat msg"), Zeros(2));
|
||||
|
||||
var unity = Reader(bytes);
|
||||
int unityPlayer = unity.ReadInt16();
|
||||
var unityText = MDPro3.BinaryExtensions.ReadUnicode(unity, (int)((unity.BaseStream.Length - unity.BaseStream.Position) / 2));
|
||||
|
||||
var windbot = Reader(bytes);
|
||||
int windbotPlayer = windbot.ReadInt16();
|
||||
var windbotText = YGOSharp.Network.Utils.BinaryExtensions.ReadUnicode(windbot, 256);
|
||||
|
||||
var read = StocCodecs.Chat.Read(Reader(bytes));
|
||||
Assert.That(read.Player, Is.EqualTo(unityPlayer));
|
||||
Assert.That(read.Player, Is.EqualTo(windbotPlayer));
|
||||
Assert.That(read.Text, Is.EqualTo(unityText));
|
||||
Assert.That(read.Text, Is.EqualTo(windbotText));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ServerChat_WithoutTerminator_ReadsTheWholeTail()
|
||||
{
|
||||
var bytes = Concat(Le16(0), Utf16("no terminator"));
|
||||
|
||||
var read = StocCodecs.Chat.Read(Reader(bytes));
|
||||
Assert.That(read.Text, Is.EqualTo("no terminator"));
|
||||
|
||||
var unity = Reader(bytes);
|
||||
unity.ReadInt16();
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() =>
|
||||
MDPro3.BinaryExtensions.ReadUnicode(unity, (int)((unity.BaseStream.Length - unity.BaseStream.Position) / 2)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ServerChat_EmptyText_ReadsEmpty()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.Chat.Write(w, new ServerChat(0, "")));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Le16(0), Zeros(2))));
|
||||
Assert.That(StocCodecs.Chat.Read(Reader(bytes)).Text, Is.EqualTo(""));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerEnter_GoldenBytes_MatchThePacked41ByteStruct()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter("Joey", 1)));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(41));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Utf16("Joey"), Zeros(32), new byte[] { 1 })));
|
||||
|
||||
var read = StocCodecs.HsPlayerEnter.Read(Reader(bytes));
|
||||
Assert.That(read.Name, Is.EqualTo("Joey"));
|
||||
Assert.That(read.Position, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerEnter_ReadsWhatBothLegacyHandlersRead()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter("Mai Valentine B", 0)));
|
||||
|
||||
var unity = Reader(bytes);
|
||||
var unityName = MDPro3.BinaryExtensions.ReadUnicode(unity, 20);
|
||||
var unityPos = unity.ReadByte() & 3;
|
||||
|
||||
var windbot = Reader(bytes);
|
||||
var windbotName = YGOSharp.Network.Utils.BinaryExtensions.ReadUnicode(windbot, 20);
|
||||
int windbotPos = windbot.ReadByte();
|
||||
|
||||
var read = StocCodecs.HsPlayerEnter.Read(Reader(bytes));
|
||||
Assert.That(read.Name, Is.EqualTo(unityName));
|
||||
Assert.That(read.Name, Is.EqualTo(windbotName));
|
||||
Assert.That(read.Position & 3, Is.EqualTo(unityPos));
|
||||
Assert.That((int)read.Position, Is.EqualTo(windbotPos));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerEnter_EmptyName_ReadsEmpty_WhereYgoSharpReadTwentyNuls()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter("", 2)));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Zeros(40), new byte[] { 2 })));
|
||||
|
||||
var read = StocCodecs.HsPlayerEnter.Read(Reader(bytes));
|
||||
Assert.That(read.Name, Is.EqualTo(""));
|
||||
Assert.That(read.Position, Is.EqualTo(2));
|
||||
|
||||
var legacy = YGOSharp.Network.Utils.BinaryExtensions.ReadUnicode(Reader(bytes), 20);
|
||||
Assert.That(legacy.Length, Is.EqualTo(20));
|
||||
Assert.That(legacy, Is.All.EqualTo('\0'));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerEnter_NameClipsToNineteenAndAFullNameDoesNotThrow()
|
||||
{
|
||||
var longName = new string('x', 25);
|
||||
var bytes = Bytes(w => StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter(longName, 3)));
|
||||
Assert.That(bytes.Length, Is.EqualTo(41));
|
||||
Assert.That(bytes.Skip(38).Take(2), Is.All.EqualTo(0));
|
||||
Assert.That(StocCodecs.HsPlayerEnter.Read(Reader(bytes)).Name, Is.EqualTo(new string('x', 19)));
|
||||
|
||||
var unterminated = Concat(Utf16(new string('y', 20)), new byte[] { 0 });
|
||||
var read = StocCodecs.HsPlayerEnter.Read(Reader(unterminated));
|
||||
Assert.That(read.Name, Is.EqualTo(new string('y', 20)));
|
||||
Assert.That(read.Position, Is.EqualTo(0));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => MDPro3.BinaryExtensions.ReadUnicode(Reader(unterminated), 20));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlayerChange_NibblesRoundTrip()
|
||||
{
|
||||
var ready = Bytes(w => StocCodecs.HsPlayerChange.Write(w, new PlayerChange(2, 0x9)));
|
||||
Assert.That(ready, Is.EqualTo(new byte[] { 0x29 }));
|
||||
|
||||
var read = StocCodecs.HsPlayerChange.Read(Reader(ready));
|
||||
Assert.That(read.Position, Is.EqualTo(2));
|
||||
Assert.That(read.State, Is.EqualTo(0x9));
|
||||
|
||||
var observe = StocCodecs.HsPlayerChange.Read(Reader(new byte[] { 0x38 }));
|
||||
Assert.That(observe.Position, Is.EqualTo(3));
|
||||
Assert.That(observe.State, Is.EqualTo(0x8));
|
||||
|
||||
var move = StocCodecs.HsPlayerChange.Read(Reader(new byte[] { 0x01 }));
|
||||
Assert.That(move.Position, Is.EqualTo(0));
|
||||
Assert.That(move.State, Is.EqualTo(1));
|
||||
|
||||
var leave = Bytes(w => StocCodecs.HsPlayerChange.Write(w, new PlayerChange(1, 0xB)));
|
||||
Assert.That(leave, Is.EqualTo(new byte[] { 0x1B }));
|
||||
}
|
||||
|
||||
[TestCase(0x29, 2, PlayerChangeKind.Ready, 0)]
|
||||
[TestCase(0x38, 3, PlayerChangeKind.Observe, 0)]
|
||||
[TestCase(0x1B, 1, PlayerChangeKind.Leave, 0)]
|
||||
[TestCase(0x1A, 1, PlayerChangeKind.NotReady, 0)]
|
||||
[TestCase(0x10, 1, PlayerChangeKind.MoveTo, 0)]
|
||||
[TestCase(0x03, 0, PlayerChangeKind.MoveTo, 3)]
|
||||
[TestCase(0x2F, 2, PlayerChangeKind.Unknown, 0)]
|
||||
public void PlayerChange_Kind_IsDerivedFromTheStateNibble_AsTheLobbyHandlerDid(int status, int seat, PlayerChangeKind kind, int target)
|
||||
{
|
||||
var read = StocCodecs.HsPlayerChange.Read(Reader(new byte[] { (byte)status }));
|
||||
|
||||
Assert.That(read.Position, Is.EqualTo(seat));
|
||||
Assert.That(read.Kind, Is.EqualTo(kind));
|
||||
Assert.That(read.TargetSeat, Is.EqualTo(target));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WatchChange_GoldenBytes_LittleEndianUInt16()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.HsWatchChange.Write(w, new WatchChange(258)));
|
||||
Assert.That(bytes, Is.EqualTo(new byte[] { 0x02, 0x01 }));
|
||||
Assert.That(StocCodecs.HsWatchChange.Read(Reader(bytes)).Count, Is.EqualTo(258));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeckCount_GoldenBytes_InTheServersOrder()
|
||||
{
|
||||
var bytes = Bytes(w => StocCodecs.DeckCount.Write(w, new DeckCount(40, 15, 10, 41, 14, 9)));
|
||||
|
||||
Assert.That(bytes.Length, Is.EqualTo(12));
|
||||
Assert.That(bytes, Is.EqualTo(Concat(Le16(40), Le16(15), Le16(10), Le16(41), Le16(14), Le16(9))));
|
||||
|
||||
var read = StocCodecs.DeckCount.Read(Reader(bytes));
|
||||
Assert.That(read.Main0, Is.EqualTo(40));
|
||||
Assert.That(read.Extra0, Is.EqualTo(15));
|
||||
Assert.That(read.Side0, Is.EqualTo(10));
|
||||
Assert.That(read.Main1, Is.EqualTo(41));
|
||||
Assert.That(read.Extra1, Is.EqualTo(14));
|
||||
Assert.That(read.Side1, Is.EqualTo(9));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using NUnit.Framework;
|
||||
using YGOLegacy.Protocol.Codecs;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
using YGOLegacy.Protocol.Routing;
|
||||
|
||||
namespace YGOLegacy.Protocol.Tests
|
||||
{
|
||||
public class StocRouterTests
|
||||
{
|
||||
private static BinaryReader Packet(StocMessage id, params byte[] payload)
|
||||
{
|
||||
var bytes = new byte[payload.Length + 1];
|
||||
bytes[0] = (byte)id;
|
||||
Array.Copy(payload, 0, bytes, 1, payload.Length);
|
||||
return new BinaryReader(new MemoryStream(bytes));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MixedBatch_DispatchesInArrivalOrder_WhateverTheRegistrationOrder()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var seen = new List<StocMessage>();
|
||||
router.Register(StocMessage.Chat, r => seen.Add(StocMessage.Chat));
|
||||
router.Register(StocMessage.GameMsg, r => seen.Add(StocMessage.GameMsg));
|
||||
router.Register(StocMessage.HandResult, r => seen.Add(StocMessage.HandResult));
|
||||
|
||||
var arrivals = new[] { StocMessage.HandResult, StocMessage.GameMsg, StocMessage.Chat, StocMessage.GameMsg };
|
||||
foreach (var id in arrivals)
|
||||
{
|
||||
StocMessage read;
|
||||
Assert.That(router.Dispatch(Packet(id), out read), Is.EqualTo(RouteOutcome.Handled));
|
||||
Assert.That(read, Is.EqualTo(id));
|
||||
}
|
||||
|
||||
Assert.That(seen, Is.EqualTo(arrivals));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Handler_GetsTheReaderPositionedAfterTheId()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var result = default(HandResultAnnounce);
|
||||
router.Register(StocMessage.HandResult, r => result = StocCodecs.HandResult.Read(r));
|
||||
|
||||
StocMessage id;
|
||||
var outcome = router.Dispatch(Packet(StocMessage.HandResult, 2, 3), out id);
|
||||
|
||||
Assert.That(outcome, Is.EqualTo(RouteOutcome.Handled));
|
||||
Assert.That(id, Is.EqualTo(StocMessage.HandResult));
|
||||
Assert.That(result.First, Is.EqualTo(2));
|
||||
Assert.That(result.Second, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GameMsg_ReachesItsHandler_WithTheReaderAtTheInnerId()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var inner = -1;
|
||||
var tail = -1L;
|
||||
router.Register(StocMessage.GameMsg, r =>
|
||||
{
|
||||
inner = r.ReadByte();
|
||||
tail = r.BaseStream.Length - r.BaseStream.Position;
|
||||
});
|
||||
|
||||
StocMessage id;
|
||||
var outcome = router.Dispatch(Packet(StocMessage.GameMsg, 0x5A, 1, 2, 3), out id);
|
||||
|
||||
Assert.That(outcome, Is.EqualTo(RouteOutcome.Handled));
|
||||
Assert.That(inner, Is.EqualTo(0x5A));
|
||||
Assert.That(tail, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IgnoredId_ReturnsIgnored_AndCallsNothing()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var unknownCalls = 0;
|
||||
router.OnUnknown = (id, bytes) => unknownCalls++;
|
||||
router.Ignore(StocMessage.FieldFinish);
|
||||
|
||||
StocMessage read;
|
||||
var outcome = router.Dispatch(Packet(StocMessage.FieldFinish, 9, 9), out read);
|
||||
|
||||
Assert.That(outcome, Is.EqualTo(RouteOutcome.Ignored));
|
||||
Assert.That(read, Is.EqualTo(StocMessage.FieldFinish));
|
||||
Assert.That(unknownCalls, Is.EqualTo(0));
|
||||
Assert.That(router.IsRegistered(StocMessage.FieldFinish), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnknownId_ReturnsUnknown_ReportsOncePerId_WithThePayloadLength()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var reports = new List<KeyValuePair<StocMessage, int>>();
|
||||
router.OnUnknown = (id, bytes) => reports.Add(new KeyValuePair<StocMessage, int>(id, bytes));
|
||||
|
||||
StocMessage read;
|
||||
Assert.That(router.Dispatch(Packet(StocMessage.SrvproRoomList, 1, 2, 3), out read), Is.EqualTo(RouteOutcome.Unknown));
|
||||
Assert.That(read, Is.EqualTo(StocMessage.SrvproRoomList));
|
||||
Assert.That(router.Dispatch(Packet(StocMessage.SrvproRoomList, 1), out read), Is.EqualTo(RouteOutcome.Unknown));
|
||||
Assert.That(router.Dispatch(Packet(StocMessage.FieldFinish), out read), Is.EqualTo(RouteOutcome.Unknown));
|
||||
|
||||
Assert.That(reports.Count, Is.EqualTo(2));
|
||||
Assert.That(reports[0].Key, Is.EqualTo(StocMessage.SrvproRoomList));
|
||||
Assert.That(reports[0].Value, Is.EqualTo(3));
|
||||
Assert.That(reports[1].Key, Is.EqualTo(StocMessage.FieldFinish));
|
||||
Assert.That(reports[1].Value, Is.EqualTo(0));
|
||||
Assert.That(router.IsRegistered(StocMessage.SrvproRoomList), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnknownId_WithoutAHook_DoesNotThrow()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
StocMessage read;
|
||||
Assert.That(router.Dispatch(Packet(StocMessage.SrvproRoomList, 1), out read), Is.EqualTo(RouteOutcome.Unknown));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DuplicateRegistration_Throws()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
router.Register(StocMessage.Chat, r => { });
|
||||
router.Ignore(StocMessage.DeckCount);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => router.Register(StocMessage.Chat, r => { }));
|
||||
Assert.Throws<ArgumentException>(() => router.Ignore(StocMessage.Chat));
|
||||
Assert.Throws<ArgumentException>(() => router.Register(StocMessage.DeckCount, r => { }));
|
||||
Assert.Throws<ArgumentException>(() => router.Ignore(StocMessage.DeckCount));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullHandler_Throws()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
Assert.Throws<ArgumentNullException>(() => router.Register(StocMessage.Chat, null));
|
||||
Assert.That(router.IsRegistered(StocMessage.Chat), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EmptyPacket_ReturnsEmpty_WithoutReading()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var calls = 0;
|
||||
router.OnUnknown = (id, bytes) => calls++;
|
||||
router.Register(StocMessage.GameMsg, r => calls++);
|
||||
|
||||
StocMessage read;
|
||||
var outcome = router.Dispatch(new BinaryReader(new MemoryStream(new byte[0])), out read);
|
||||
|
||||
Assert.That(outcome, Is.EqualTo(RouteOutcome.Empty));
|
||||
Assert.That(calls, Is.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HandlerException_PropagatesUnchanged()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
var thrown = new InvalidDataException("bad chat");
|
||||
router.Register(StocMessage.Chat, r => { throw thrown; });
|
||||
|
||||
var read = default(StocMessage);
|
||||
var caught = Assert.Throws<InvalidDataException>(() => router.Dispatch(Packet(StocMessage.Chat, 1), out read));
|
||||
|
||||
Assert.That(caught, Is.SameAs(thrown));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NullReader_Throws()
|
||||
{
|
||||
var router = new StocRouter();
|
||||
StocMessage read;
|
||||
Assert.Throws<ArgumentNullException>(() => router.Dispatch(null, out read));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<LangVersion>9</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="NUnit" Version="3.14.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\YGOLegacy.Engine\YGOLegacy.Engine.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public unsafe delegate IntPtr ScriptReader([MarshalAs(UnmanagedType.LPUTF8Str)] string script_name, int* len);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate uint CardReader(uint code, IntPtr data);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
public delegate uint MessageHandler(IntPtr pduel, uint msg_type);
|
||||
|
||||
public static unsafe class EngineApi
|
||||
{
|
||||
private const string Library = "ygol-engine";
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_script_reader(ScriptReader f);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_card_reader(CardReader f);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_message_handler(MessageHandler f);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel(uint seed);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel_v2(uint[] seed_sequence);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel_ex(uint seed, uint create_flags);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr create_duel_v2_ex(uint[] seed_sequence, uint create_flags);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void start_duel(IntPtr pduel, uint options);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void end_duel(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_player_info(IntPtr pduel, int playerid, int lp, int startcount, int drawcount);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void get_log_message(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_message(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern uint process(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void new_card(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void new_tag_card(IntPtr pduel, uint code, byte owner, byte location);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_card(IntPtr pduel, byte playerid, byte location, byte sequence, uint query_flag, byte[] buf, int use_cache);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_field_count(IntPtr pduel, byte playerid, byte location);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_field_card(IntPtr pduel, byte playerid, byte location, uint query_flag, byte[] buf, int use_cache);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int query_field_info(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_responsei(IntPtr pduel, int value);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_responseb(IntPtr pduel, byte[] buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int preload_script(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string script_name);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr default_script_reader([MarshalAs(UnmanagedType.LPUTF8Str)] string script_name, int* len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_preview_attack(IntPtr pduel, byte playerid, byte location, byte sequence, byte target_location, byte target_sequence, byte[] @out);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_query_tag_cards(IntPtr pduel, byte playerid, byte[] @out);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_query_prompt_context(IntPtr pduel, byte playerid, byte[] @out);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_registry_value(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string key, byte[] out_buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void set_registry_value(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string key, [MarshalAs(UnmanagedType.LPUTF8Str)] string value);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_registry_keys(IntPtr pduel, byte[] out_buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void clear_registry(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int dump_registry(IntPtr pduel, byte[] out_buf);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void load_registry(IntPtr pduel, byte[] in_buf, int in_len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_lua_coverage_dump_size(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string name);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int dump_lua_coverage(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, byte[] out_buf, int out_len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int get_all_lua_coverages_dump_size(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int dump_all_lua_coverages(IntPtr pduel, byte[] out_buf, int out_len);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void clear_lua_coverage(IntPtr pduel, [MarshalAs(UnmanagedType.LPUTF8Str)] string name);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void clear_all_lua_coverages(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_add(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_move(IntPtr pduel, byte playerid, byte location, byte sequence, byte dst_playerid, byte dst_location, byte dst_sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_remove(IntPtr pduel, byte playerid, byte location, byte sequence);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_set_position(IntPtr pduel, byte playerid, byte location, byte sequence, byte position);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_set_lp(IntPtr pduel, byte playerid, int lp);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int ygol_sb_reask(IntPtr pduel);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern int start_server([MarshalAs(UnmanagedType.LPUTF8Str)] string args);
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern void stop_server();
|
||||
|
||||
[DllImport(Library, CallingConvention = CallingConvention.Cdecl)]
|
||||
public static extern IntPtr ygol_engine_version();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
public static partial class EngineBinding
|
||||
{
|
||||
public static string CheckNative()
|
||||
{
|
||||
var native = Marshal.PtrToStringAnsi(EngineApi.ygol_engine_version());
|
||||
if (native == Version) return native;
|
||||
throw new InvalidOperationException(
|
||||
"ygol-engine reports version '" + native + "' but the YGOLegacy.Engine binding is '" + Version
|
||||
+ "'; fetch the engine release whose tag equals the binding version.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
public enum GameMessage : byte
|
||||
{
|
||||
Retry = 1,
|
||||
Hint = 2,
|
||||
Win = 5,
|
||||
UpdateCard = 7,
|
||||
SelectBattlecmd = 10,
|
||||
SelectIdlecmd = 11,
|
||||
SelectEffectyn = 12,
|
||||
SelectYesno = 13,
|
||||
SelectOption = 14,
|
||||
SelectCard = 15,
|
||||
SelectChain = 16,
|
||||
SelectPlace = 18,
|
||||
SelectPosition = 19,
|
||||
SelectTribute = 20,
|
||||
SelectCounter = 22,
|
||||
SelectSum = 23,
|
||||
SelectDisfield = 24,
|
||||
SortCard = 25,
|
||||
SelectUnselectCard = 26,
|
||||
ConfirmDecktop = 30,
|
||||
ConfirmCards = 31,
|
||||
ShuffleDeck = 32,
|
||||
ShuffleHand = 33,
|
||||
SwapGraveDeck = 35,
|
||||
ShuffleSetCard = 36,
|
||||
ReverseDeck = 37,
|
||||
DeckTop = 38,
|
||||
ShuffleExtra = 39,
|
||||
NewTurn = 40,
|
||||
NewPhase = 41,
|
||||
ConfirmExtratop = 42,
|
||||
Move = 50,
|
||||
PosChange = 53,
|
||||
Set = 54,
|
||||
Swap = 55,
|
||||
FieldDisabled = 56,
|
||||
Summoning = 60,
|
||||
Summoned = 61,
|
||||
Spsummoning = 62,
|
||||
Spsummoned = 63,
|
||||
Flipsummoning = 64,
|
||||
Flipsummoned = 65,
|
||||
Chaining = 70,
|
||||
Chained = 71,
|
||||
ChainSolving = 72,
|
||||
ChainSolved = 73,
|
||||
ChainEnd = 74,
|
||||
ChainNegated = 75,
|
||||
ChainDisabled = 76,
|
||||
RandomSelected = 81,
|
||||
BecomeTarget = 83,
|
||||
Draw = 90,
|
||||
Damage = 91,
|
||||
Recover = 92,
|
||||
Equip = 93,
|
||||
Lpupdate = 94,
|
||||
CardTarget = 96,
|
||||
CancelTarget = 97,
|
||||
PayLpcost = 100,
|
||||
AddCounter = 101,
|
||||
RemoveCounter = 102,
|
||||
Attack = 110,
|
||||
Battle = 111,
|
||||
AttackDisabled = 112,
|
||||
DamageStepStart = 113,
|
||||
DamageStepEnd = 114,
|
||||
MissedEffect = 120,
|
||||
TossCoin = 130,
|
||||
TossDice = 131,
|
||||
RockPaperScissors = 132,
|
||||
HandRes = 133,
|
||||
AnnounceRace = 140,
|
||||
AnnounceAttrib = 141,
|
||||
AnnounceCard = 142,
|
||||
AnnounceNumber = 143,
|
||||
CardHint = 160,
|
||||
TagSwap = 161,
|
||||
ReloadField = 162,
|
||||
AiName = 163,
|
||||
ShowHint = 164,
|
||||
PlayerHint = 165,
|
||||
MatchKill = 170,
|
||||
CustomMsg = 180,
|
||||
ResetTime = 221,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
using System;
|
||||
|
||||
namespace YGOLegacy.Engine
|
||||
{
|
||||
public static class MessageScan
|
||||
{
|
||||
private const int LOCATION_DECK = 0x01;
|
||||
private const int LOCATION_HAND = 0x02;
|
||||
private const int LOCATION_GRAVE = 0x10;
|
||||
private const int LOCATION_OVERLAY = 0x80;
|
||||
private const int POS_FACEDOWN = 0xA;
|
||||
private const int QUERY_CODE = 0x1;
|
||||
private const int QUERY_IS_PUBLIC = 0x100000;
|
||||
|
||||
public struct MsgInfo
|
||||
{
|
||||
public int Player;
|
||||
public bool Prompt;
|
||||
public bool ToPlayerOnly;
|
||||
public bool NewTurn;
|
||||
}
|
||||
|
||||
public static string PromptName(int id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case 10: return "SELECT_BATTLECMD";
|
||||
case 11: return "SELECT_IDLECMD";
|
||||
case 12: return "SELECT_EFFECTYN";
|
||||
case 13: return "SELECT_YESNO";
|
||||
case 14: return "SELECT_OPTION";
|
||||
case 15: return "SELECT_CARD";
|
||||
case 16: return "SELECT_CHAIN";
|
||||
case 18: return "SELECT_PLACE";
|
||||
case 19: return "SELECT_POSITION";
|
||||
case 20: return "SELECT_TRIBUTE";
|
||||
case 22: return "SELECT_COUNTER";
|
||||
case 23: return "SELECT_SUM";
|
||||
case 24: return "SELECT_DISFIELD";
|
||||
case 25: return "SORT_CARD";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
public static MsgInfo Scan(byte[] b, ref int pos, int id, int len)
|
||||
{
|
||||
var info = new MsgInfo();
|
||||
int count;
|
||||
switch (id)
|
||||
{
|
||||
case 1: /* RETRY */ break;
|
||||
case 2: /* HINT */
|
||||
{
|
||||
var type = b[pos];
|
||||
info.Player = b[pos + 1];
|
||||
pos += 6;
|
||||
// ygopro's SingleDuel: HINT_EVENT/MESSAGE/SELECTMSG/EFFECT go
|
||||
// to the hinted player only, the rest is public.
|
||||
info.ToPlayerOnly = type == 1 || type == 2 || type == 3 || type == 5;
|
||||
break;
|
||||
}
|
||||
case 3: /* WAITING */ break;
|
||||
case 4: /* START */ pos += 18; break;
|
||||
case 5: /* WIN */ pos += 2; break;
|
||||
case 8: /* REQUEST_DECK */ break;
|
||||
|
||||
case 10: /* SELECT_BATTLECMD */
|
||||
info.Player = b[pos]; pos += 1;
|
||||
count = b[pos++]; pos += count * 11;
|
||||
count = b[pos++]; pos += count * 8;
|
||||
pos += 2;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 11: /* SELECT_IDLECMD */
|
||||
info.Player = b[pos]; pos += 1;
|
||||
for (var k = 0; k < 5; k++) { count = b[pos++]; pos += count * 7; }
|
||||
count = b[pos++]; pos += count * 11;
|
||||
pos += 3;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 12: /* SELECT_EFFECTYN */ info.Player = b[pos]; pos += 13; info.Prompt = true; break;
|
||||
case 13: /* SELECT_YESNO */ info.Player = b[pos]; pos += 5; info.Prompt = true; break;
|
||||
case 14: /* SELECT_OPTION */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 4;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 15: /* SELECT_CARD */
|
||||
case 20: /* SELECT_TRIBUTE */
|
||||
info.Player = b[pos]; pos += 4; count = b[pos++]; pos += count * 8;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 26: /* SELECT_UNSELECT_CARD */
|
||||
info.Player = b[pos]; pos += 5;
|
||||
count = b[pos++]; pos += count * 8;
|
||||
count = b[pos++]; pos += count * 8;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 16: /* SELECT_CHAIN */
|
||||
info.Player = b[pos]; count = b[pos + 1]; pos += 11 + count * 14;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 18: /* SELECT_PLACE */
|
||||
case 19: /* SELECT_POSITION */
|
||||
case 24: /* SELECT_DISFIELD */
|
||||
info.Player = b[pos]; pos += 6; info.Prompt = true; break;
|
||||
|
||||
case 22: /* SELECT_COUNTER */
|
||||
info.Player = b[pos]; pos += 5; count = b[pos++]; pos += count * 9;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 23: /* SELECT_SUM */
|
||||
info.Player = b[pos + 1]; pos += 8;
|
||||
count = b[pos++]; pos += count * 11;
|
||||
count = b[pos++]; pos += count * 11;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 21: /* SORT_CHAIN */
|
||||
case 25: /* SORT_CARD */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 7;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 30: /* CONFIRM_DECKTOP */
|
||||
case 42: /* CONFIRM_EXTRATOP */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 7; break;
|
||||
|
||||
case 31: /* CONFIRM_CARDS */
|
||||
info.Player = b[pos]; pos += 2; count = b[pos++]; pos += count * 7; break;
|
||||
|
||||
case 32: /* SHUFFLE_DECK */
|
||||
case 34: /* REFRESH_DECK */
|
||||
case 35: /* SWAP_GRAVE_DECK*/
|
||||
info.Player = b[pos]; pos += 1; break;
|
||||
|
||||
case 33: /* SHUFFLE_HAND */
|
||||
case 39: /* SHUFFLE_EXTRA */
|
||||
case 90: /* DRAW */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 4; break;
|
||||
|
||||
case 36: /* SHUFFLE_SET_CARD */
|
||||
pos += 1; count = b[pos++]; pos += count * 8; break;
|
||||
|
||||
case 37: /* REVERSE_DECK */ break;
|
||||
case 38: /* DECK_TOP */ info.Player = b[pos]; pos += 6; break;
|
||||
case 40: /* NEW_TURN */ info.NewTurn = true; pos += 1; break;
|
||||
case 41: /* NEW_PHASE */ pos += 2; break;
|
||||
|
||||
case 50: /* MOVE */ pos += 16; break;
|
||||
case 53: /* POS_CHANGE */ pos += 9; break;
|
||||
case 54: /* SET */ pos += 8; break;
|
||||
case 55: /* SWAP */ pos += 16; break;
|
||||
case 56: /* FIELD_DISABLED */ pos += 4; break;
|
||||
|
||||
case 60: /* SUMMONING */
|
||||
case 62: /* SPSUMMONING */
|
||||
case 64: /* FLIPSUMMONING */ pos += 8; break;
|
||||
case 61: /* SUMMONED */
|
||||
case 63: /* SPSUMMONED */
|
||||
case 65: /* FLIPSUMMONED */ break;
|
||||
|
||||
case 70: /* CHAINING */ pos += 16; break;
|
||||
case 71: /* CHAINED */
|
||||
case 72: /* CHAIN_SOLVING */
|
||||
case 73: /* CHAIN_SOLVED */
|
||||
case 75: /* CHAIN_NEGATED */
|
||||
case 76: /* CHAIN_DISABLED*/ pos += 1; break;
|
||||
case 74: /* CHAIN_END */ break;
|
||||
|
||||
case 80: /* CARD_SELECTED */
|
||||
case 81: /* RANDOM_SELECTED */
|
||||
pos += 1; count = b[pos++]; pos += count * 4; break;
|
||||
case 83: /* BECOME_TARGET */
|
||||
count = b[pos++]; pos += count * 4; break;
|
||||
|
||||
case 91: /* DAMAGE */
|
||||
case 92: /* RECOVER */
|
||||
case 94: /* LP_UPDATE */
|
||||
case 100: /* PAY_LPCOST */ pos += 5; break;
|
||||
case 93: /* EQUIP */ pos += 8; break;
|
||||
case 95: /* UNEQUIP */ pos += 4; break;
|
||||
case 96: /* CARD_TARGET */
|
||||
case 97: /* CANCEL_TARGET */ pos += 8; break;
|
||||
case 101: /* ADD_COUNTER */
|
||||
case 102: /* REMOVE_COUNTER */ pos += 7; break;
|
||||
|
||||
case 110: /* ATTACK */ pos += 8; break;
|
||||
case 111: /* BATTLE */ pos += 26; break;
|
||||
case 112: /* ATTACK_DISABLED */
|
||||
case 113: /* DAMAGE_STEP_START */
|
||||
case 114: /* DAMAGE_STEP_END */ break;
|
||||
|
||||
case 120: /* MISSED_EFFECT */ pos += 8; break;
|
||||
case 121: /* BE_CHAIN_TARGET */
|
||||
case 122: /* CREATE_RELATION */
|
||||
case 123: /* RELEASE_RELATION */ break;
|
||||
|
||||
case 130: /* TOSS_COIN */
|
||||
case 131: /* TOSS_DICE */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count; break;
|
||||
|
||||
case 132: /* ROCK_PAPER_SCISSORS */ info.Player = b[pos]; pos += 1; info.Prompt = true; break;
|
||||
case 133: /* HAND_RES */ pos += 2; break;
|
||||
|
||||
case 140: /* ANNOUNCE_RACE */
|
||||
case 141: /* ANNOUNCE_ATTRIB */
|
||||
info.Player = b[pos]; pos += 6; info.Prompt = true; break;
|
||||
case 142: /* ANNOUNCE_CARD */
|
||||
case 143: /* ANNOUNCE_NUMBER */
|
||||
info.Player = b[pos]; pos += 1; count = b[pos++]; pos += count * 4;
|
||||
info.Prompt = true; break;
|
||||
|
||||
case 160: /* CARD_HINT */ pos += 9; break;
|
||||
case 163: /* AI_NAME */
|
||||
case 164: /* SHOW_HINT */
|
||||
{
|
||||
var slen = b[pos] | (b[pos + 1] << 8);
|
||||
pos += 2 + slen + 1; break;
|
||||
}
|
||||
case 165: /* PLAYER_HINT */ pos += 6; break;
|
||||
case 170: /* MATCH_KILL */ pos += 4; break;
|
||||
case 180: /* CUSTOM_MSG */ break;
|
||||
|
||||
case 162: /* RELOAD_FIELD — Debug.ReloadFieldEnd(), so a scripted
|
||||
board (Tools/CardTests) emits it where a duel never does. */
|
||||
{
|
||||
pos += 1; // duel rule
|
||||
for (var side = 0; side < 2; side++)
|
||||
{
|
||||
pos += 4; // life points
|
||||
for (var i = 0; i < 7; i++) if (b[pos++] > 0) pos += 2; // monster zones
|
||||
for (var i = 0; i < 8; i++) if (b[pos++] > 0) pos += 1; // spell/trap zones
|
||||
pos += 6; // deck, hand, grave, banish, extra, extra pendulum counts
|
||||
}
|
||||
// The chain block is written ONCE, after both players. Reading it per
|
||||
// player takes player 1's low LP byte as a chain count and swallows
|
||||
// every message that follows — see the [YGOL] note in CoreWrapper.Analyse.
|
||||
count = b[pos++]; pos += count * 15;
|
||||
break;
|
||||
}
|
||||
|
||||
case 221: /* RESET_TIME */ pos += 3; break;
|
||||
|
||||
default:
|
||||
throw new Exception("unknown core message " + id + " at offset " + (pos - 1) + " of " + len
|
||||
+ " — the host's layout table needs a case for it");
|
||||
}
|
||||
if (pos > len) throw new Exception("core message " + id + " overran its buffer (" + pos + " > " + len + ")");
|
||||
return info;
|
||||
}
|
||||
|
||||
public static byte[] Blank(int id, byte[] msg, MsgInfo info, int recipient)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case 39: // MSG_SHUFFLE_EXTRA: the opponent may not read an extra
|
||||
// deck (RefreshPile hides its codes the same way), so
|
||||
// the new order goes out blank to them.
|
||||
case 33: // MSG_SHUFFLE_HAND: only the owner sees the new order.
|
||||
{
|
||||
if (recipient == info.Player) return msg;
|
||||
var copy = (byte[])msg.Clone();
|
||||
for (var i = 2; i + 4 <= copy.Length; i += 4)
|
||||
copy[i] = copy[i + 1] = copy[i + 2] = copy[i + 3] = 0;
|
||||
return copy;
|
||||
}
|
||||
case 90: // MSG_DRAW: only the drawing player sees what was drawn.
|
||||
{
|
||||
var copy = (byte[])msg.Clone();
|
||||
for (var i = 2; i + 4 <= copy.Length; i += 4)
|
||||
{
|
||||
if (recipient == info.Player)
|
||||
copy[i + 3] &= 0x7f; // strip the "public" bit like Analyse
|
||||
else
|
||||
copy[i] = copy[i + 1] = copy[i + 2] = copy[i + 3] = 0;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
case 50: // MSG_MOVE: a card that lands in a deck/hand (but not a
|
||||
{ // grave or an xyz pile) or lands face-down is hidden —
|
||||
// from the OTHER player only. Its new controller always
|
||||
// sees it: you know the monster you just set. (This is
|
||||
// the one place where ygoserver is per-recipient and
|
||||
// Percy.Ygopro, having a single client, is not.)
|
||||
if (msg.Length < 16) return msg;
|
||||
int cc = msg[8], cl = msg[9], cp = msg[11];
|
||||
if (recipient == cc) return msg;
|
||||
var hidden = ((cl & (LOCATION_GRAVE | LOCATION_OVERLAY)) == 0 && (cl & (LOCATION_DECK | LOCATION_HAND)) != 0)
|
||||
|| (cp & POS_FACEDOWN) != 0;
|
||||
if (!hidden) return msg;
|
||||
var copy = (byte[])msg.Clone();
|
||||
copy[0] = copy[1] = copy[2] = copy[3] = 0;
|
||||
return copy;
|
||||
}
|
||||
case 54: // MSG_SET: the code is never revealed.
|
||||
{
|
||||
if (msg.Length < 4) return msg;
|
||||
var copy = (byte[])msg.Clone();
|
||||
copy[0] = copy[1] = copy[2] = copy[3] = 0;
|
||||
return copy;
|
||||
}
|
||||
default:
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
|
||||
public static void BlankPileCodes(byte[] buf, bool all)
|
||||
{
|
||||
var o = 0;
|
||||
while (o + 8 <= buf.Length)
|
||||
{
|
||||
var recLen = BitConverter.ToInt32(buf, o);
|
||||
if (recLen <= 4 || o + recLen > buf.Length) { o += Math.Max(recLen, 4); continue; }
|
||||
var flag = BitConverter.ToInt32(buf, o + 4);
|
||||
if ((flag & QUERY_CODE) != 0)
|
||||
{
|
||||
var hide = all;
|
||||
if (!hide)
|
||||
{
|
||||
var publicOffset = FieldOffset(buf, o, recLen, flag, QUERY_IS_PUBLIC);
|
||||
hide = publicOffset < 0 || BitConverter.ToInt32(buf, publicOffset) == 0;
|
||||
}
|
||||
if (hide)
|
||||
buf[o + 8] = buf[o + 9] = buf[o + 10] = buf[o + 11] = 0;
|
||||
}
|
||||
o += recLen;
|
||||
}
|
||||
}
|
||||
|
||||
private static int FieldOffset(byte[] buf, int recordStart, int recordLen, int flag, int wanted)
|
||||
{
|
||||
var o = recordStart + 8; // past len + flag
|
||||
var end = recordStart + recordLen;
|
||||
for (var bit = 0x1; bit != 0 && bit <= 0x800000; bit <<= 1)
|
||||
{
|
||||
if ((flag & bit) == 0) continue;
|
||||
if (bit == wanted) return o <= end - 4 ? o : -1;
|
||||
if (o + 4 > end) return -1;
|
||||
switch (bit)
|
||||
{
|
||||
case 0x8000: // TARGET_CARD
|
||||
case 0x10000: // OVERLAY_CARD
|
||||
case 0x20000: // COUNTERS
|
||||
o += 4 + BitConverter.ToInt32(buf, o) * 4;
|
||||
break;
|
||||
case 0x800000: // LINK (count + marker)
|
||||
o += 8;
|
||||
break;
|
||||
default:
|
||||
o += 4;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.IO;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public static class DuelCodecs
|
||||
{
|
||||
public static readonly ResponseCodec Response = new ResponseCodec();
|
||||
public static readonly HandResultCodec HandResult = new HandResultCodec();
|
||||
public static readonly TpResultCodec TpResult = new TpResultCodec();
|
||||
public static readonly EmptyPayloadCodec Surrender = new EmptyPayloadCodec(CtosMessage.Surrender);
|
||||
public static readonly EmptyPayloadCodec TimeConfirm = new EmptyPayloadCodec(CtosMessage.TimeConfirm);
|
||||
}
|
||||
|
||||
public sealed class ResponseCodec : ICtosCodec<Response>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.Response;
|
||||
|
||||
public void Write(BinaryWriter writer, Response payload)
|
||||
{
|
||||
var bytes = payload.Bytes;
|
||||
if (bytes != null && bytes.Length > 0)
|
||||
writer.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, int value)
|
||||
{
|
||||
writer.Write(value);
|
||||
}
|
||||
|
||||
public Response Read(BinaryReader reader)
|
||||
{
|
||||
var remaining = (int)(reader.BaseStream.Length - reader.BaseStream.Position);
|
||||
return new Response(reader.ReadBytes(remaining));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class HandResultCodec : ICtosCodec<HandResult>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.HandResult;
|
||||
|
||||
public void Write(BinaryWriter writer, HandResult payload)
|
||||
{
|
||||
writer.Write(payload.Result);
|
||||
}
|
||||
|
||||
public HandResult Read(BinaryReader reader)
|
||||
{
|
||||
return new HandResult(reader.ReadByte());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TpResultCodec : ICtosCodec<TpResult>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.TpResult;
|
||||
|
||||
public void Write(BinaryWriter writer, TpResult payload)
|
||||
{
|
||||
writer.Write((byte)(payload.GoFirst ? 1 : 0));
|
||||
}
|
||||
|
||||
public TpResult Read(BinaryReader reader)
|
||||
{
|
||||
return new TpResult(reader.ReadByte() != 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,600 @@
|
||||
using System.IO;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public sealed class CapabilityCodec : ICtosCodec<Capability>
|
||||
{
|
||||
public const int Size = 6;
|
||||
public const int StampedSize = Size + StampedCodec.SeatBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.Capability;
|
||||
|
||||
public void Write(BinaryWriter writer, Capability payload)
|
||||
{
|
||||
writer.Write(payload.Protocol);
|
||||
writer.Write(payload.Flags);
|
||||
}
|
||||
|
||||
public Capability Read(BinaryReader reader)
|
||||
{
|
||||
var protocol = reader.ReadUInt16();
|
||||
var flags = reader.ReadUInt32();
|
||||
return new Capability(protocol, flags);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class AppearanceCodec : ICtosCodec<AppearanceState>
|
||||
{
|
||||
public const int Size = AppearanceState.ItemCount * 4
|
||||
+ (AppearanceState.DeckNameChars + AppearanceState.CharacterIdChars + AppearanceState.DeckGroupChars) * 2;
|
||||
public const int StampedSize = Size + StampedCodec.SeatBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.Appearance;
|
||||
|
||||
public void Write(BinaryWriter writer, AppearanceState payload)
|
||||
{
|
||||
for (var i = 0; i < AppearanceState.ItemCount; i++)
|
||||
writer.Write(payload.Items != null && i < payload.Items.Length ? payload.Items[i] : 0);
|
||||
UnicodeCodec.WriteFixed(writer, payload.DeckName, AppearanceState.DeckNameChars);
|
||||
UnicodeCodec.WriteFixed(writer, payload.CharacterId, AppearanceState.CharacterIdChars);
|
||||
UnicodeCodec.WriteFixed(writer, payload.DeckGroup, AppearanceState.DeckGroupChars);
|
||||
}
|
||||
|
||||
public AppearanceState Read(BinaryReader reader)
|
||||
{
|
||||
var items = new int[AppearanceState.ItemCount];
|
||||
for (var i = 0; i < items.Length; i++)
|
||||
items[i] = reader.ReadInt32();
|
||||
var deckName = UnicodeCodec.ReadFixed(reader, AppearanceState.DeckNameChars);
|
||||
var characterId = UnicodeCodec.ReadFixed(reader, AppearanceState.CharacterIdChars);
|
||||
var deckGroup = UnicodeCodec.ReadFixed(reader, AppearanceState.DeckGroupChars);
|
||||
return new AppearanceState(items, deckName, characterId, deckGroup);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DialogueCodec : ICtosCodec<DialogueLine>
|
||||
{
|
||||
public const int Size = 1 + 1 + 2 + 4 + 4 + DialogueLine.KeyChars * 2 * 2;
|
||||
public const int StampedSize = Size + StampedCodec.SeatBytes;
|
||||
private const byte TargetFaceDownFlag = 0x1;
|
||||
|
||||
public CtosMessage Id => CtosMessage.Dialogue;
|
||||
|
||||
public void Write(BinaryWriter writer, DialogueLine payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)(payload.TargetFaceDown ? TargetFaceDownFlag : 0));
|
||||
writer.Write(payload.Index);
|
||||
writer.Write(payload.CardCode);
|
||||
writer.Write(payload.TargetCode);
|
||||
UnicodeCodec.WriteFixed(writer, payload.CorpusKey, DialogueLine.KeyChars);
|
||||
UnicodeCodec.WriteFixed(writer, payload.EventKey, DialogueLine.KeyChars);
|
||||
}
|
||||
|
||||
public DialogueLine Read(BinaryReader reader)
|
||||
{
|
||||
var version = reader.ReadByte();
|
||||
var flags = reader.ReadByte();
|
||||
var index = reader.ReadInt16();
|
||||
var cardCode = reader.ReadUInt32();
|
||||
var targetCode = reader.ReadUInt32();
|
||||
var corpusKey = UnicodeCodec.ReadFixed(reader, DialogueLine.KeyChars);
|
||||
var eventKey = UnicodeCodec.ReadFixed(reader, DialogueLine.KeyChars);
|
||||
return new DialogueLine(version, (flags & TargetFaceDownFlag) != 0, index, cardCode, targetCode, corpusKey, eventKey);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SeatPlanCodec : ICtosCodec<SeatPlan>
|
||||
{
|
||||
public const int Size = SeatPlan.IdBytes + 4 + 2 + 1 + SeatPlan.MaxSeats + SeatPlan.MaxSeats * SeatPlan.IdBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.SeatPlan;
|
||||
|
||||
public void Write(BinaryWriter writer, SeatPlan payload)
|
||||
{
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write(payload.DeadlineMs);
|
||||
writer.Write(payload.Revision);
|
||||
writer.Write(payload.SeatCount);
|
||||
for (var i = 0; i < SeatPlan.MaxSeats; i++)
|
||||
writer.Write((byte)payload.Kind(i));
|
||||
for (var i = 0; i < SeatPlan.MaxSeats; i++)
|
||||
writer.Write(SeatIds.Fixed(payload.Tokens?[i]));
|
||||
}
|
||||
|
||||
public SeatPlan Read(BinaryReader reader)
|
||||
{
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var deadline = reader.ReadUInt32();
|
||||
var revision = reader.ReadUInt16();
|
||||
var count = reader.ReadByte();
|
||||
var kinds = new SeatPlanKind[SeatPlan.MaxSeats];
|
||||
for (var i = 0; i < kinds.Length; i++)
|
||||
kinds[i] = (SeatPlanKind)reader.ReadByte();
|
||||
var tokens = new byte[SeatPlan.MaxSeats][];
|
||||
for (var i = 0; i < tokens.Length; i++)
|
||||
tokens[i] = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
return new SeatPlan(restartId, deadline, revision, count, kinds, tokens);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SeatRequestCodec : ICtosCodec<SeatRequest>
|
||||
{
|
||||
public const int Size = 2 + SeatPlan.IdBytes + 1 + SeatPlan.IdBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.SeatRequest;
|
||||
|
||||
public void Write(BinaryWriter writer, SeatRequest payload)
|
||||
{
|
||||
writer.Write(payload.Protocol);
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write(payload.Seat);
|
||||
writer.Write(SeatIds.Fixed(payload.Token));
|
||||
}
|
||||
|
||||
public SeatRequest Read(BinaryReader reader)
|
||||
{
|
||||
var protocol = reader.ReadUInt16();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var seat = reader.ReadByte();
|
||||
return new SeatRequest(protocol, restartId, seat, reader.ReadBytes(SeatPlan.IdBytes));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SeatSwapCodec : ICtosCodec<SeatSwap>
|
||||
{
|
||||
public const int Size = 2;
|
||||
|
||||
public CtosMessage Id => CtosMessage.SeatSwap;
|
||||
|
||||
public void Write(BinaryWriter writer, SeatSwap payload)
|
||||
{
|
||||
writer.Write(payload.First);
|
||||
writer.Write(payload.Second);
|
||||
}
|
||||
|
||||
public SeatSwap Read(BinaryReader reader) => new SeatSwap(reader.ReadByte(), reader.ReadByte());
|
||||
}
|
||||
|
||||
public sealed class SeatMoveCodec : ICtosCodec<SeatMove>
|
||||
{
|
||||
public const int Size = 2;
|
||||
|
||||
public CtosMessage Id => CtosMessage.SeatMove;
|
||||
|
||||
public void Write(BinaryWriter writer, SeatMove payload)
|
||||
{
|
||||
writer.Write(payload.From);
|
||||
writer.Write(payload.To);
|
||||
}
|
||||
|
||||
public SeatMove Read(BinaryReader reader) => new SeatMove(reader.ReadByte(), reader.ReadByte());
|
||||
}
|
||||
|
||||
public sealed class SeatStateCodec : ICtosCodec<SeatState>
|
||||
{
|
||||
public const int Size = 4;
|
||||
public const int StampedSize = Size + StampedCodec.SeatBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.SeatState;
|
||||
|
||||
public void Write(BinaryWriter writer, SeatState payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)payload.Kind);
|
||||
writer.Write(payload.Value);
|
||||
}
|
||||
|
||||
public SeatState Read(BinaryReader reader)
|
||||
{
|
||||
var version = reader.ReadByte();
|
||||
var kind = (SeatStateKind)reader.ReadByte();
|
||||
return new SeatState(version, kind, reader.ReadUInt16());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ProfileCodec : ICtosCodec<ProfileState>
|
||||
{
|
||||
public const int Size = 1 + 1 + (ProfileState.AvatarIdChars + ProfileState.FrameIdChars) * 2;
|
||||
public const int StampedSize = Size + StampedCodec.SeatBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.Profile;
|
||||
|
||||
public void Write(BinaryWriter writer, ProfileState payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)0);
|
||||
UnicodeCodec.WriteFixed(writer, payload.AvatarId, ProfileState.AvatarIdChars);
|
||||
UnicodeCodec.WriteFixed(writer, payload.FrameId, ProfileState.FrameIdChars);
|
||||
}
|
||||
|
||||
public ProfileState Read(BinaryReader reader)
|
||||
{
|
||||
var version = reader.ReadByte();
|
||||
reader.ReadByte();
|
||||
var avatarId = UnicodeCodec.ReadFixed(reader, ProfileState.AvatarIdChars);
|
||||
var frameId = UnicodeCodec.ReadFixed(reader, ProfileState.FrameIdChars);
|
||||
return new ProfileState(version, avatarId, frameId);
|
||||
}
|
||||
}
|
||||
|
||||
// Version, count, then count x 4 bytes (patch 0023).
|
||||
public sealed class AttackPreviewQueryCodec : ICtosCodec<AttackPreviewQuery>
|
||||
{
|
||||
public const int HeaderSize = 2;
|
||||
|
||||
public CtosMessage Id => CtosMessage.AttackPreview;
|
||||
|
||||
public void Write(BinaryWriter writer, AttackPreviewQuery payload)
|
||||
{
|
||||
var count = payload.Pairs.Length > AttackPreviewQuery.MaxPairs ? AttackPreviewQuery.MaxPairs : payload.Pairs.Length;
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)count);
|
||||
for (var i = 0; i < count; i++)
|
||||
WritePair(writer, payload.Pairs[i]);
|
||||
}
|
||||
|
||||
public AttackPreviewQuery Read(BinaryReader reader)
|
||||
{
|
||||
var version = reader.ReadByte();
|
||||
int count = reader.ReadByte();
|
||||
var pairs = new AttackPreviewPair[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
pairs[i] = ReadPair(reader);
|
||||
return new AttackPreviewQuery(version, pairs);
|
||||
}
|
||||
|
||||
public static void WritePair(BinaryWriter writer, AttackPreviewPair pair)
|
||||
{
|
||||
writer.Write(pair.AttackerLocation);
|
||||
writer.Write(pair.AttackerSequence);
|
||||
writer.Write(pair.TargetLocation);
|
||||
writer.Write(pair.TargetSequence);
|
||||
}
|
||||
|
||||
public static AttackPreviewPair ReadPair(BinaryReader reader)
|
||||
{
|
||||
return new AttackPreviewPair(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RestartPrepareCodec : ICtosCodec<RestartPrepare>
|
||||
{
|
||||
public const int Size = SeatPlan.IdBytes + 4 + 1 + SeatPlan.MaxSeats * SeatPlan.IdBytes + SeatPlan.IdBytes;
|
||||
|
||||
public CtosMessage Id => CtosMessage.RestartPrepare;
|
||||
|
||||
public void Write(BinaryWriter writer, RestartPrepare payload)
|
||||
{
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write(payload.TimeoutMs);
|
||||
writer.Write(payload.SeatCount);
|
||||
for (var i = 0; i < SeatPlan.MaxSeats; i++)
|
||||
writer.Write(SeatIds.Fixed(payload.SeatTokens?[i]));
|
||||
writer.Write(SeatIds.Fixed(payload.ObserverToken));
|
||||
}
|
||||
|
||||
public RestartPrepare Read(BinaryReader reader)
|
||||
{
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var timeout = reader.ReadUInt32();
|
||||
var count = reader.ReadByte();
|
||||
var tokens = new byte[SeatPlan.MaxSeats][];
|
||||
for (var i = 0; i < tokens.Length; i++)
|
||||
tokens[i] = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
return new RestartPrepare(restartId, timeout, count, tokens, reader.ReadBytes(SeatPlan.IdBytes));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RestartAckCodec : ICtosCodec<RestartAck>
|
||||
{
|
||||
public const int Size = SeatPlan.IdBytes + 1;
|
||||
|
||||
public CtosMessage Id => CtosMessage.RestartAck;
|
||||
|
||||
public void Write(BinaryWriter writer, RestartAck payload)
|
||||
{
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write((byte)payload.Phase);
|
||||
}
|
||||
|
||||
public RestartAck Read(BinaryReader reader) => new RestartAck(reader.ReadBytes(SeatPlan.IdBytes), (RestartPhase)reader.ReadByte());
|
||||
}
|
||||
|
||||
public sealed class RestartControlCodec : ICtosCodec<RestartControl>
|
||||
{
|
||||
public const int Size = SeatPlan.IdBytes + 1;
|
||||
|
||||
public CtosMessage Id => CtosMessage.RestartControl;
|
||||
|
||||
public void Write(BinaryWriter writer, RestartControl payload)
|
||||
{
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write((byte)payload.Action);
|
||||
}
|
||||
|
||||
public RestartControl Read(BinaryReader reader) => new RestartControl(reader.ReadBytes(SeatPlan.IdBytes), (RestartPhase)reader.ReadByte());
|
||||
}
|
||||
|
||||
public sealed class SeatResumeCodec : ICtosCodec<SeatResume>
|
||||
{
|
||||
public const int Size = SeatPlan.IdBytes + 2;
|
||||
|
||||
public CtosMessage Id => CtosMessage.SeatResume;
|
||||
|
||||
public void Write(BinaryWriter writer, SeatResume payload)
|
||||
{
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write((byte)payload.Action);
|
||||
writer.Write(payload.Reason);
|
||||
}
|
||||
|
||||
public SeatResume Read(BinaryReader reader)
|
||||
=> new SeatResume(reader.ReadBytes(SeatPlan.IdBytes), (SeatResumeAction)reader.ReadByte(), reader.ReadByte());
|
||||
}
|
||||
|
||||
public sealed class RestartOpenCodec : ICtosCodec<RestartOpen>
|
||||
{
|
||||
public const int Size = SeatPlan.IdBytes * 2;
|
||||
|
||||
public CtosMessage Id => CtosMessage.RestartOpen;
|
||||
|
||||
public void Write(BinaryWriter writer, RestartOpen payload)
|
||||
{
|
||||
writer.Write(SeatIds.Fixed(payload.RestartId));
|
||||
writer.Write(SeatIds.Fixed(payload.ObserverToken));
|
||||
}
|
||||
|
||||
public RestartOpen Read(BinaryReader reader) => new RestartOpen(reader.ReadBytes(SeatPlan.IdBytes), reader.ReadBytes(SeatPlan.IdBytes));
|
||||
}
|
||||
|
||||
// STOC 0x54: uint16 sender (0xFF) + phase, restart id, the receiver's own seat, its token (Prepare only), timeout.
|
||||
public sealed class RoomRestartingCodec : IStocCodec<Stamped<RoomRestarting>>
|
||||
{
|
||||
public const int PayloadSize = 1 + SeatPlan.IdBytes + 1 + SeatPlan.IdBytes + 4;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.RoomRestarting;
|
||||
|
||||
public Stamped<RoomRestarting> Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var seat = reader.ReadUInt16();
|
||||
var phase = (RestartPhase)reader.ReadByte();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var own = reader.ReadByte();
|
||||
var token = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
return new Stamped<RoomRestarting>(seat, new RoomRestarting(phase, restartId, own, token, reader.ReadUInt32()));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<RoomRestarting> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
writer.Write((byte)payload.Payload.Phase);
|
||||
writer.Write(SeatIds.Fixed(payload.Payload.RestartId));
|
||||
writer.Write(payload.Payload.Seat);
|
||||
writer.Write(SeatIds.Fixed(payload.Payload.Token));
|
||||
writer.Write(payload.Payload.TimeoutMs);
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x56, host only: uint16 sender (0xFF) + phase, restart id, acked / expected counts, complete flag, reason.
|
||||
public sealed class RestartStatusCodec : IStocCodec<Stamped<RestartStatus>>
|
||||
{
|
||||
public const int PayloadSize = 1 + SeatPlan.IdBytes + 4;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.RestartStatus;
|
||||
|
||||
public Stamped<RestartStatus> Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var seat = reader.ReadUInt16();
|
||||
var phase = (RestartPhase)reader.ReadByte();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var acked = reader.ReadByte();
|
||||
var expected = reader.ReadByte();
|
||||
var complete = reader.ReadByte() != 0;
|
||||
return new Stamped<RestartStatus>(seat, new RestartStatus(phase, restartId, acked, expected, complete, (RestartReason)reader.ReadByte()));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<RestartStatus> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
writer.Write((byte)payload.Payload.Phase);
|
||||
writer.Write(SeatIds.Fixed(payload.Payload.RestartId));
|
||||
writer.Write(payload.Payload.Acked);
|
||||
writer.Write(payload.Payload.Expected);
|
||||
writer.Write((byte)(payload.Payload.Complete ? 1 : 0));
|
||||
writer.Write((byte)payload.Payload.Reason);
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x57, to the claimant: uint16 sender (0xFF) + restart id, accepted, seat, reason.
|
||||
public sealed class SeatResumeResultCodec : IStocCodec<Stamped<SeatResumeResult>>
|
||||
{
|
||||
public const int PayloadSize = SeatPlan.IdBytes + 3;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.SeatResumeResult;
|
||||
|
||||
public Stamped<SeatResumeResult> Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var seat = reader.ReadUInt16();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var accepted = reader.ReadByte() != 0;
|
||||
var own = reader.ReadByte();
|
||||
return new Stamped<SeatResumeResult>(seat, new SeatResumeResult(restartId, accepted, own, reader.ReadByte()));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<SeatResumeResult> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
writer.Write(SeatIds.Fixed(payload.Payload.RestartId));
|
||||
writer.Write((byte)(payload.Payload.Accepted ? 1 : 0));
|
||||
writer.Write(payload.Payload.Seat);
|
||||
writer.Write(payload.Payload.Reason);
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x58, to the bootstrap host: uint16 sender (0xFF) + restart id, opened.
|
||||
public sealed class RestartOpenedCodec : IStocCodec<Stamped<RestartOpened>>
|
||||
{
|
||||
public const int PayloadSize = SeatPlan.IdBytes + 1;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.RestartOpen;
|
||||
|
||||
public Stamped<RestartOpened> Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var seat = reader.ReadUInt16();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
return new Stamped<RestartOpened>(seat, new RestartOpened(restartId, reader.ReadByte() != 0));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<RestartOpened> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
writer.Write(SeatIds.Fixed(payload.Payload.RestartId));
|
||||
writer.Write((byte)(payload.Payload.Opened ? 1 : 0));
|
||||
}
|
||||
}
|
||||
|
||||
// uint16 sender (0xFF) + version, seat count, occupied per seat (patch 0014).
|
||||
public sealed class MatchOverCodec : IStocCodec<Stamped<MatchOver>>
|
||||
{
|
||||
public const int PayloadSize = 2 + MatchOver.MaxSeats;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.MatchOver;
|
||||
|
||||
public Stamped<MatchOver> Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var seat = reader.ReadUInt16();
|
||||
var version = reader.ReadByte();
|
||||
var seatCount = reader.ReadByte();
|
||||
var occupied = new bool[MatchOver.MaxSeats];
|
||||
for (var i = 0; i < MatchOver.MaxSeats; i++)
|
||||
occupied[i] = reader.ReadByte() != 0;
|
||||
return new Stamped<MatchOver>(seat, new MatchOver(version, seatCount, occupied));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<MatchOver> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
writer.Write(payload.Payload.Version);
|
||||
writer.Write(payload.Payload.SeatCount);
|
||||
for (var i = 0; i < MatchOver.MaxSeats; i++)
|
||||
writer.Write((byte)(payload.Payload.Occupied(i) ? 1 : 0));
|
||||
}
|
||||
}
|
||||
|
||||
// The server's echo: uint16 sender (0xFF) + restart id, revision, seat count and kinds; never tokens.
|
||||
public sealed class SeatPlanStateCodec : IStocCodec<Stamped<SeatPlan>>
|
||||
{
|
||||
public const int PayloadSize = SeatPlan.IdBytes + 2 + 1 + SeatPlan.MaxSeats;
|
||||
public const int Size = StampedCodec.SeatBytes + PayloadSize;
|
||||
|
||||
public StocMessage Id => StocMessage.SeatPlan;
|
||||
|
||||
public Stamped<SeatPlan> Read(BinaryReader reader)
|
||||
{
|
||||
var remaining = StocCodecs.Remaining(reader);
|
||||
if (remaining < Size)
|
||||
throw new EndOfStreamException("STOC " + Id + ": " + remaining + " bytes, expected " + Size);
|
||||
var seat = reader.ReadUInt16();
|
||||
var restartId = reader.ReadBytes(SeatPlan.IdBytes);
|
||||
var revision = reader.ReadUInt16();
|
||||
var count = reader.ReadByte();
|
||||
var kinds = new SeatPlanKind[SeatPlan.MaxSeats];
|
||||
for (var i = 0; i < kinds.Length; i++)
|
||||
kinds[i] = (SeatPlanKind)reader.ReadByte();
|
||||
return new Stamped<SeatPlan>(seat, new SeatPlan(restartId, 0, revision, count, kinds, null));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<SeatPlan> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
writer.Write(SeatIds.Fixed(payload.Payload.RestartId));
|
||||
writer.Write(payload.Payload.Revision);
|
||||
writer.Write(payload.Payload.SeatCount);
|
||||
for (var i = 0; i < SeatPlan.MaxSeats; i++)
|
||||
writer.Write((byte)payload.Payload.Kind(i));
|
||||
}
|
||||
}
|
||||
|
||||
// Version, count, then count x (the 4 request bytes echoed + 24 answer bytes); no sender stamp (patch 0023).
|
||||
public sealed class AttackPreviewResultCodec : IStocCodec<AttackPreviewResult>
|
||||
{
|
||||
public const int HeaderSize = 2;
|
||||
|
||||
public StocMessage Id => StocMessage.AttackPreview;
|
||||
|
||||
public AttackPreviewResult Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, HeaderSize, Id);
|
||||
var version = reader.ReadByte();
|
||||
int count = reader.ReadByte();
|
||||
StocCodecs.Require(reader, count * AttackPreviewEntry.Size, Id);
|
||||
var entries = new AttackPreviewEntry[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var pair = AttackPreviewQueryCodec.ReadPair(reader);
|
||||
entries[i] = new AttackPreviewEntry(pair, reader.ReadBytes(AttackPreviewEntry.AnswerBytes));
|
||||
}
|
||||
return new AttackPreviewResult(version, entries);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, AttackPreviewResult payload)
|
||||
{
|
||||
var count = payload.Entries.Length > AttackPreviewQuery.MaxPairs ? AttackPreviewQuery.MaxPairs : payload.Entries.Length;
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
AttackPreviewQueryCodec.WritePair(writer, payload.Entries[i].Pair);
|
||||
writer.Write(payload.Entries[i].Answer, 0, AttackPreviewEntry.AnswerBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StampedCodec
|
||||
{
|
||||
public const int SeatBytes = 2;
|
||||
}
|
||||
|
||||
// The server prefixes a relayed feature message with the sender's seat (uint16); the payload is the CTOS bytes.
|
||||
public sealed class StampedCodec<T> : IStocCodec<Stamped<T>>
|
||||
{
|
||||
private readonly ICtosCodec<T> _payload;
|
||||
|
||||
public StocMessage Id { get; }
|
||||
public int Size { get; }
|
||||
|
||||
public StampedCodec(StocMessage id, ICtosCodec<T> payload, int payloadSize)
|
||||
{
|
||||
Id = id;
|
||||
_payload = payload;
|
||||
Size = StampedCodec.SeatBytes + payloadSize;
|
||||
}
|
||||
|
||||
public Stamped<T> Read(BinaryReader reader)
|
||||
{
|
||||
var remaining = StocCodecs.Remaining(reader);
|
||||
if (remaining < Size)
|
||||
throw new EndOfStreamException("STOC " + Id + ": " + remaining + " bytes, expected " + Size);
|
||||
var seat = reader.ReadUInt16();
|
||||
return new Stamped<T>(seat, _payload.Read(reader));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<T> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
_payload.Write(writer, payload.Payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public interface ICtosCodec<T>
|
||||
{
|
||||
CtosMessage Id { get; }
|
||||
void Write(BinaryWriter writer, T payload);
|
||||
T Read(BinaryReader reader);
|
||||
}
|
||||
|
||||
public static class CtosPacket
|
||||
{
|
||||
public static BinaryWriter Begin(CtosMessage id)
|
||||
{
|
||||
var writer = new BinaryWriter(new MemoryStream());
|
||||
writer.Write((byte)id);
|
||||
return writer;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class EmptyPayloadCodec : ICtosCodec<NoPayload>
|
||||
{
|
||||
public CtosMessage Id { get; }
|
||||
|
||||
public EmptyPayloadCodec(CtosMessage id)
|
||||
{
|
||||
Id = id;
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer)
|
||||
{
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, NoPayload payload)
|
||||
{
|
||||
}
|
||||
|
||||
public NoPayload Read(BinaryReader reader)
|
||||
{
|
||||
return default(NoPayload);
|
||||
}
|
||||
}
|
||||
|
||||
public static class LobbyCodecs
|
||||
{
|
||||
public const int NameChars = 20;
|
||||
public const int PasswordChars = 20;
|
||||
public const int HostChars = 256;
|
||||
public const int ChatChars = 256;
|
||||
|
||||
public static readonly ExternalAddressCodec ExternalAddress = new ExternalAddressCodec();
|
||||
public static readonly PlayerInfoCodec PlayerInfo = new PlayerInfoCodec();
|
||||
public static readonly JoinGameCodec JoinGame = new JoinGameCodec();
|
||||
public static readonly UpdateDeckCodec UpdateDeck = new UpdateDeckCodec();
|
||||
public static readonly ChatCodec Chat = new ChatCodec();
|
||||
public static readonly KickCodec HsKick = new KickCodec();
|
||||
public static readonly EmptyPayloadCodec LeaveGame = new EmptyPayloadCodec(CtosMessage.LeaveGame);
|
||||
public static readonly EmptyPayloadCodec HsToDuelist = new EmptyPayloadCodec(CtosMessage.HsToDuelist);
|
||||
public static readonly EmptyPayloadCodec HsToObserver = new EmptyPayloadCodec(CtosMessage.HsToObserver);
|
||||
public static readonly EmptyPayloadCodec HsReady = new EmptyPayloadCodec(CtosMessage.HsReady);
|
||||
public static readonly EmptyPayloadCodec HsNotReady = new EmptyPayloadCodec(CtosMessage.HsNotReady);
|
||||
public static readonly EmptyPayloadCodec HsStart = new EmptyPayloadCodec(CtosMessage.HsStart);
|
||||
public static readonly CapabilityCodec Capability = new CapabilityCodec();
|
||||
public static readonly AppearanceCodec Appearance = new AppearanceCodec();
|
||||
public static readonly DialogueCodec Dialogue = new DialogueCodec();
|
||||
public static readonly SeatPlanCodec SeatPlan = new SeatPlanCodec();
|
||||
public static readonly SeatRequestCodec SeatRequest = new SeatRequestCodec();
|
||||
public static readonly SeatSwapCodec SeatSwap = new SeatSwapCodec();
|
||||
public static readonly SeatMoveCodec SeatMove = new SeatMoveCodec();
|
||||
public static readonly RestartPrepareCodec RestartPrepare = new RestartPrepareCodec();
|
||||
public static readonly RestartAckCodec RestartAck = new RestartAckCodec();
|
||||
public static readonly RestartControlCodec RestartControl = new RestartControlCodec();
|
||||
public static readonly SeatResumeCodec SeatResume = new SeatResumeCodec();
|
||||
public static readonly RestartOpenCodec RestartOpen = new RestartOpenCodec();
|
||||
public static readonly SeatStateCodec SeatState = new SeatStateCodec();
|
||||
public static readonly ProfileCodec Profile = new ProfileCodec();
|
||||
public static readonly AttackPreviewQueryCodec AttackPreview = new AttackPreviewQueryCodec();
|
||||
}
|
||||
|
||||
public sealed class ChatCodec : ICtosCodec<Chat>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.Chat;
|
||||
|
||||
public void Write(BinaryWriter writer, Chat payload)
|
||||
{
|
||||
UnicodeCodec.WriteTerminated(writer, payload.Text, LobbyCodecs.ChatChars);
|
||||
}
|
||||
|
||||
public Chat Read(BinaryReader reader)
|
||||
{
|
||||
return new Chat(UnicodeCodec.ReadTerminated(reader, LobbyCodecs.ChatChars));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class KickCodec : ICtosCodec<Kick>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.HsKick;
|
||||
|
||||
public void Write(BinaryWriter writer, Kick payload)
|
||||
{
|
||||
writer.Write(payload.Position);
|
||||
}
|
||||
|
||||
public Kick Read(BinaryReader reader)
|
||||
{
|
||||
return new Kick(reader.ReadByte());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ExternalAddressCodec : ICtosCodec<ExternalAddress>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.ExternalAddress;
|
||||
|
||||
public void Write(BinaryWriter writer, ExternalAddress payload)
|
||||
{
|
||||
writer.Write(0u);
|
||||
UnicodeCodec.WriteTerminated(writer, payload.Host, LobbyCodecs.HostChars);
|
||||
}
|
||||
|
||||
public ExternalAddress Read(BinaryReader reader)
|
||||
{
|
||||
reader.ReadUInt32();
|
||||
return new ExternalAddress(UnicodeCodec.ReadTerminated(reader, LobbyCodecs.HostChars));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PlayerInfoCodec : ICtosCodec<PlayerInfo>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.PlayerInfo;
|
||||
|
||||
public void Write(BinaryWriter writer, PlayerInfo payload)
|
||||
{
|
||||
UnicodeCodec.WriteFixed(writer, payload.Name, LobbyCodecs.NameChars);
|
||||
}
|
||||
|
||||
public PlayerInfo Read(BinaryReader reader)
|
||||
{
|
||||
return new PlayerInfo(UnicodeCodec.ReadFixed(reader, LobbyCodecs.NameChars));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class JoinGameCodec : ICtosCodec<JoinGame>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.JoinGame;
|
||||
|
||||
public void Write(BinaryWriter writer, JoinGame payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
// Struct padding after the uint16 version: both clients have always sent CC CC here.
|
||||
writer.Write((byte)0xCC);
|
||||
writer.Write((byte)0xCC);
|
||||
writer.Write(0u);
|
||||
UnicodeCodec.WriteFixed(writer, payload.Password, LobbyCodecs.PasswordChars);
|
||||
}
|
||||
|
||||
public JoinGame Read(BinaryReader reader)
|
||||
{
|
||||
var version = reader.ReadUInt16();
|
||||
reader.ReadUInt16();
|
||||
reader.ReadUInt32();
|
||||
return new JoinGame(version, UnicodeCodec.ReadFixed(reader, LobbyCodecs.PasswordChars));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class UpdateDeckCodec : ICtosCodec<UpdateDeck>
|
||||
{
|
||||
public CtosMessage Id => CtosMessage.UpdateDeck;
|
||||
|
||||
public void Write(BinaryWriter writer, UpdateDeck payload)
|
||||
{
|
||||
writer.Write(payload.Main.Count + payload.Extra.Count);
|
||||
writer.Write(payload.Side.Count);
|
||||
WriteIds(writer, payload.Main);
|
||||
WriteIds(writer, payload.Extra);
|
||||
WriteIds(writer, payload.Side);
|
||||
}
|
||||
|
||||
// The wire carries one main+extra count, so a read cannot split them again.
|
||||
public UpdateDeck Read(BinaryReader reader)
|
||||
{
|
||||
var mainCount = reader.ReadInt32();
|
||||
var sideCount = reader.ReadInt32();
|
||||
var main = ReadIds(reader, mainCount);
|
||||
var side = ReadIds(reader, sideCount);
|
||||
return new UpdateDeck(main, null, side);
|
||||
}
|
||||
|
||||
private static void WriteIds(BinaryWriter writer, IReadOnlyList<int> ids)
|
||||
{
|
||||
for (var i = 0; i < ids.Count; i++)
|
||||
writer.Write(ids[i]);
|
||||
}
|
||||
|
||||
private static int[] ReadIds(BinaryReader reader, int count)
|
||||
{
|
||||
var ids = new int[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
ids[i] = reader.ReadInt32();
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public interface IStocCodec<T>
|
||||
{
|
||||
StocMessage Id { get; }
|
||||
T Read(BinaryReader reader);
|
||||
void Write(BinaryWriter writer, T payload);
|
||||
}
|
||||
|
||||
public static class StocCodecs
|
||||
{
|
||||
public const int NameChars = 20;
|
||||
public const int ChatChars = 256;
|
||||
|
||||
public static readonly ErrorMsgCodec ErrorMsg = new ErrorMsgCodec();
|
||||
public static readonly HandResultAnnounceCodec HandResult = new HandResultAnnounceCodec();
|
||||
public static readonly HostInfoCodec JoinGame = new HostInfoCodec();
|
||||
public static readonly TypeChangeCodec TypeChange = new TypeChangeCodec();
|
||||
public static readonly TimeLimitCodec TimeLimit = new TimeLimitCodec();
|
||||
public static readonly ServerChatCodec Chat = new ServerChatCodec();
|
||||
public static readonly PlayerEnterCodec HsPlayerEnter = new PlayerEnterCodec();
|
||||
public static readonly PlayerChangeCodec HsPlayerChange = new PlayerChangeCodec();
|
||||
public static readonly WatchChangeCodec HsWatchChange = new WatchChangeCodec();
|
||||
public static readonly DeckCountCodec DeckCount = new DeckCountCodec();
|
||||
public static readonly StampedCodec<Contracts.Capability> Capability = new StampedCodec<Contracts.Capability>(StocMessage.Capability, LobbyCodecs.Capability, CapabilityCodec.Size);
|
||||
public static readonly StampedCodec<AppearanceState> Appearance = new StampedCodec<AppearanceState>(StocMessage.Appearance, LobbyCodecs.Appearance, AppearanceCodec.Size);
|
||||
public static readonly StampedCodec<DialogueLine> Dialogue = new StampedCodec<DialogueLine>(StocMessage.Dialogue, LobbyCodecs.Dialogue, DialogueCodec.Size);
|
||||
public static readonly SetupPairsCodec SetupPairs = new SetupPairsCodec();
|
||||
public static readonly SeatPlanStateCodec SeatPlan = new SeatPlanStateCodec();
|
||||
public static readonly RoomRestartingCodec RoomRestarting = new RoomRestartingCodec();
|
||||
public static readonly RestartStatusCodec RestartStatus = new RestartStatusCodec();
|
||||
public static readonly SeatResumeResultCodec SeatResumeResult = new SeatResumeResultCodec();
|
||||
public static readonly RestartOpenedCodec RestartOpened = new RestartOpenedCodec();
|
||||
public static readonly StampedCodec<SeatState> SeatState = new StampedCodec<SeatState>(StocMessage.SeatState, LobbyCodecs.SeatState, SeatStateCodec.Size);
|
||||
public static readonly MatchOverCodec MatchOver = new MatchOverCodec();
|
||||
public static readonly CoinTossCodec CoinToss = new CoinTossCodec();
|
||||
public static readonly DeckListCodec DeckList = new DeckListCodec();
|
||||
public static readonly StampedCodec<ProfileState> Profile = new StampedCodec<ProfileState>(StocMessage.Profile, LobbyCodecs.Profile, ProfileCodec.Size);
|
||||
public static readonly AttackPreviewResultCodec AttackPreview = new AttackPreviewResultCodec();
|
||||
public static readonly TagPartnerCardsCodec TagPartnerCards = new TagPartnerCardsCodec();
|
||||
public static readonly PromptContextCodec PromptContext = new PromptContextCodec();
|
||||
|
||||
internal static long Remaining(BinaryReader reader)
|
||||
{
|
||||
return reader.BaseStream.Length - reader.BaseStream.Position;
|
||||
}
|
||||
|
||||
internal static void Require(BinaryReader reader, int size, StocMessage id)
|
||||
{
|
||||
var remaining = Remaining(reader);
|
||||
if (remaining < size)
|
||||
throw new EndOfStreamException("STOC " + id + ": " + remaining + " bytes, expected " + size);
|
||||
}
|
||||
|
||||
internal static void SkipPadding(BinaryReader reader, int count)
|
||||
{
|
||||
var available = Remaining(reader);
|
||||
if (available <= 0)
|
||||
return;
|
||||
reader.ReadBytes(count < available ? count : (int)available);
|
||||
}
|
||||
|
||||
internal static void WritePadding(BinaryWriter writer, int count)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
writer.Write((byte)0);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ErrorMsgCodec : IStocCodec<ErrorMsg>
|
||||
{
|
||||
public StocMessage Id => StocMessage.ErrorMsg;
|
||||
|
||||
public ErrorMsg Read(BinaryReader reader)
|
||||
{
|
||||
var msg = reader.ReadByte();
|
||||
StocCodecs.SkipPadding(reader, 3);
|
||||
var code = StocCodecs.Remaining(reader) >= 4 ? reader.ReadInt32() : 0;
|
||||
return new ErrorMsg(msg, code);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, ErrorMsg payload)
|
||||
{
|
||||
writer.Write(payload.Msg);
|
||||
StocCodecs.WritePadding(writer, 3);
|
||||
writer.Write(payload.Code);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class HandResultAnnounceCodec : IStocCodec<HandResultAnnounce>
|
||||
{
|
||||
public StocMessage Id => StocMessage.HandResult;
|
||||
|
||||
public HandResultAnnounce Read(BinaryReader reader)
|
||||
{
|
||||
var first = reader.ReadByte();
|
||||
var second = StocCodecs.Remaining(reader) >= 1 ? reader.ReadByte() : (byte)0;
|
||||
return new HandResultAnnounce(first, second);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, HandResultAnnounce payload)
|
||||
{
|
||||
writer.Write(payload.First);
|
||||
writer.Write(payload.Second);
|
||||
}
|
||||
}
|
||||
|
||||
// Version, chooser seat, face, choose seconds; no sender stamp (patch 0017).
|
||||
public sealed class CoinTossCodec : IStocCodec<CoinTossAnnounce>
|
||||
{
|
||||
public const int Size = 4;
|
||||
|
||||
public StocMessage Id => StocMessage.CoinToss;
|
||||
|
||||
public CoinTossAnnounce Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
return new CoinTossAnnounce(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte());
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, CoinTossAnnounce payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
writer.Write(payload.ChooserSeat);
|
||||
writer.Write(payload.Face);
|
||||
writer.Write(payload.ChooseSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
// Version, side, kind, uint16 count, then count uint32 codes; no sender stamp (patch 0019).
|
||||
public sealed class DeckListCodec : IStocCodec<DeckList>
|
||||
{
|
||||
public const int HeaderSize = 5;
|
||||
|
||||
public StocMessage Id => StocMessage.DeckList;
|
||||
|
||||
public DeckList Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, HeaderSize, Id);
|
||||
var version = reader.ReadByte();
|
||||
var side = reader.ReadByte();
|
||||
var kind = (DeckListKind)reader.ReadByte();
|
||||
int count = reader.ReadUInt16();
|
||||
if (count > DeckList.MaxCards)
|
||||
throw new InvalidDataException("STOC " + Id + ": " + count + " cards, at most " + DeckList.MaxCards);
|
||||
StocCodecs.Require(reader, count * 4, Id);
|
||||
var codes = new int[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
codes[i] = (int)reader.ReadUInt32();
|
||||
return new DeckList(version, side, kind, codes);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, DeckList payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
writer.Write(payload.Side);
|
||||
writer.Write((byte)payload.Kind);
|
||||
writer.Write((ushort)payload.Codes.Length);
|
||||
foreach (var code in payload.Codes)
|
||||
writer.Write((uint)code);
|
||||
}
|
||||
}
|
||||
|
||||
// Side, version, hand count, extra count, pad, uint16 deck count, then the hand, extra and deck codes as uint32; no sender stamp (v1.2.0, TICKET-405).
|
||||
public sealed class TagPartnerCardsCodec : IStocCodec<TagPartnerCards>
|
||||
{
|
||||
public const int HeaderSize = 7;
|
||||
|
||||
public StocMessage Id => StocMessage.TagPartnerCards;
|
||||
|
||||
public TagPartnerCards Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, HeaderSize, Id);
|
||||
var side = reader.ReadByte();
|
||||
var version = reader.ReadByte();
|
||||
int handCount = reader.ReadByte();
|
||||
int extraCount = reader.ReadByte();
|
||||
reader.ReadByte();
|
||||
int deckCount = reader.ReadUInt16();
|
||||
if (deckCount > TagPartnerCards.MaxDeckCards)
|
||||
throw new InvalidDataException("STOC " + Id + ": " + deckCount + " deck cards, at most " + TagPartnerCards.MaxDeckCards);
|
||||
StocCodecs.Require(reader, (handCount + extraCount + deckCount) * 4, Id);
|
||||
var hand = new uint[handCount];
|
||||
for (var i = 0; i < handCount; i++)
|
||||
hand[i] = reader.ReadUInt32();
|
||||
var extra = new uint[extraCount];
|
||||
for (var i = 0; i < extraCount; i++)
|
||||
extra[i] = reader.ReadUInt32();
|
||||
var deck = new int[deckCount];
|
||||
for (var i = 0; i < deckCount; i++)
|
||||
deck[i] = (int)reader.ReadUInt32();
|
||||
return new TagPartnerCards(version, side, hand, extra, deck);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, TagPartnerCards payload)
|
||||
{
|
||||
writer.Write(payload.Side);
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)payload.Hand.Length);
|
||||
writer.Write((byte)payload.Extra.Length);
|
||||
writer.Write((byte)0);
|
||||
writer.Write((ushort)payload.Deck.Length);
|
||||
foreach (var raw in payload.Hand)
|
||||
writer.Write(raw);
|
||||
foreach (var raw in payload.Extra)
|
||||
writer.Write(raw);
|
||||
foreach (var code in payload.Deck)
|
||||
writer.Write((uint)code);
|
||||
}
|
||||
}
|
||||
|
||||
// The 23-byte ygol_query_prompt_context record (version, has effect, uint32 code, controller, location, sequence, position, uint64 description, uint16 effect index, phase, chain link, announce kind) + the prompt's MSG id; no sender stamp (v1.7.0, TICKET-451).
|
||||
public sealed class PromptContextCodec : IStocCodec<PromptContext>
|
||||
{
|
||||
public const int Size = 24;
|
||||
|
||||
public StocMessage Id => StocMessage.PromptContext;
|
||||
|
||||
public PromptContext Read(BinaryReader reader)
|
||||
{
|
||||
StocCodecs.Require(reader, Size, Id);
|
||||
var version = reader.ReadByte();
|
||||
var hasEffect = reader.ReadByte() != 0;
|
||||
var code = reader.ReadUInt32();
|
||||
var controller = reader.ReadByte();
|
||||
var location = reader.ReadByte();
|
||||
var sequence = reader.ReadByte();
|
||||
var position = reader.ReadByte();
|
||||
var description = reader.ReadUInt64();
|
||||
var effectIndex = reader.ReadUInt16();
|
||||
var phase = reader.ReadByte();
|
||||
var chainLink = reader.ReadByte();
|
||||
var announceKind = reader.ReadByte();
|
||||
var prompt = reader.ReadByte();
|
||||
return new PromptContext(version, hasEffect, code, controller, location, sequence, position, description, effectIndex, phase, chainLink, announceKind, prompt);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, PromptContext payload)
|
||||
{
|
||||
writer.Write(payload.Version);
|
||||
writer.Write((byte)(payload.HasEffect ? 1 : 0));
|
||||
writer.Write(payload.Code);
|
||||
writer.Write(payload.Controller);
|
||||
writer.Write(payload.Location);
|
||||
writer.Write(payload.Sequence);
|
||||
writer.Write(payload.Position);
|
||||
writer.Write(payload.Description);
|
||||
writer.Write(payload.EffectIndex);
|
||||
writer.Write(payload.Phase);
|
||||
writer.Write(payload.ChainLink);
|
||||
writer.Write(payload.AnnounceKind);
|
||||
writer.Write(payload.Prompt);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class HostInfoCodec : IStocCodec<HostInfo>
|
||||
{
|
||||
public StocMessage Id => StocMessage.JoinGame;
|
||||
|
||||
public HostInfo Read(BinaryReader reader)
|
||||
{
|
||||
var lflist = reader.ReadUInt32();
|
||||
var rule = reader.ReadByte();
|
||||
var mode = reader.ReadByte();
|
||||
var duelRule = reader.ReadByte();
|
||||
var noCheckDeck = reader.ReadByte() != 0;
|
||||
var noShuffleDeck = reader.ReadByte() != 0;
|
||||
StocCodecs.SkipPadding(reader, 3);
|
||||
var startLp = reader.ReadInt32();
|
||||
var startHand = reader.ReadByte();
|
||||
var drawCount = reader.ReadByte();
|
||||
var timeLimit = reader.ReadUInt16();
|
||||
return new HostInfo(lflist, rule, mode, duelRule, noCheckDeck, noShuffleDeck, startLp, startHand, drawCount, timeLimit);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, HostInfo payload)
|
||||
{
|
||||
writer.Write(payload.Lflist);
|
||||
writer.Write(payload.Rule);
|
||||
writer.Write(payload.Mode);
|
||||
writer.Write(payload.DuelRule);
|
||||
writer.Write((byte)(payload.NoCheckDeck ? 1 : 0));
|
||||
writer.Write((byte)(payload.NoShuffleDeck ? 1 : 0));
|
||||
StocCodecs.WritePadding(writer, 3);
|
||||
writer.Write(payload.StartLp);
|
||||
writer.Write(payload.StartHand);
|
||||
writer.Write(payload.DrawCount);
|
||||
writer.Write(payload.TimeLimit);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TypeChangeCodec : IStocCodec<TypeChange>
|
||||
{
|
||||
public StocMessage Id => StocMessage.TypeChange;
|
||||
|
||||
public TypeChange Read(BinaryReader reader)
|
||||
{
|
||||
var type = reader.ReadByte();
|
||||
return new TypeChange((byte)(type & 0xF), ((type >> 4) & 0xF) != 0);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, TypeChange payload)
|
||||
{
|
||||
writer.Write((byte)((payload.Position & 0xF) | (payload.IsHost ? 0x10 : 0)));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TimeLimitCodec : IStocCodec<TimeLimit>
|
||||
{
|
||||
public StocMessage Id => StocMessage.TimeLimit;
|
||||
|
||||
public TimeLimit Read(BinaryReader reader)
|
||||
{
|
||||
var player = reader.ReadByte();
|
||||
StocCodecs.SkipPadding(reader, 1);
|
||||
var leftTime = StocCodecs.Remaining(reader) >= 2 ? reader.ReadUInt16() : (ushort)0;
|
||||
return new TimeLimit(player, leftTime);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, TimeLimit payload)
|
||||
{
|
||||
writer.Write(payload.Player);
|
||||
StocCodecs.WritePadding(writer, 1);
|
||||
writer.Write(payload.LeftTime);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ServerChatCodec : IStocCodec<ServerChat>
|
||||
{
|
||||
public StocMessage Id => StocMessage.Chat;
|
||||
|
||||
public ServerChat Read(BinaryReader reader)
|
||||
{
|
||||
var player = reader.ReadUInt16();
|
||||
return new ServerChat(player, UnicodeCodec.ReadTerminated(reader, StocCodecs.ChatChars));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, ServerChat payload)
|
||||
{
|
||||
writer.Write(payload.Player);
|
||||
UnicodeCodec.WriteTerminated(writer, payload.Text, StocCodecs.ChatChars);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PlayerEnterCodec : IStocCodec<PlayerEnter>
|
||||
{
|
||||
public StocMessage Id => StocMessage.HsPlayerEnter;
|
||||
|
||||
public PlayerEnter Read(BinaryReader reader)
|
||||
{
|
||||
var name = UnicodeCodec.ReadFixed(reader, StocCodecs.NameChars);
|
||||
var position = StocCodecs.Remaining(reader) >= 1 ? reader.ReadByte() : (byte)0;
|
||||
return new PlayerEnter(name, position);
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, PlayerEnter payload)
|
||||
{
|
||||
UnicodeCodec.WriteFixed(writer, payload.Name, StocCodecs.NameChars);
|
||||
writer.Write(payload.Position);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PlayerChangeCodec : IStocCodec<PlayerChange>
|
||||
{
|
||||
public StocMessage Id => StocMessage.HsPlayerChange;
|
||||
|
||||
public PlayerChange Read(BinaryReader reader)
|
||||
{
|
||||
var status = reader.ReadByte();
|
||||
return new PlayerChange((byte)((status >> 4) & 0xF), (byte)(status & 0xF));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, PlayerChange payload)
|
||||
{
|
||||
writer.Write((byte)((payload.Position << 4) | (payload.State & 0xF)));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class WatchChangeCodec : IStocCodec<WatchChange>
|
||||
{
|
||||
public StocMessage Id => StocMessage.HsWatchChange;
|
||||
|
||||
public WatchChange Read(BinaryReader reader)
|
||||
{
|
||||
return new WatchChange(reader.ReadUInt16());
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, WatchChange payload)
|
||||
{
|
||||
writer.Write(payload.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class DeckCountCodec : IStocCodec<DeckCount>
|
||||
{
|
||||
public StocMessage Id => StocMessage.DeckCount;
|
||||
|
||||
public DeckCount Read(BinaryReader reader)
|
||||
{
|
||||
return new DeckCount(
|
||||
reader.ReadInt16(), reader.ReadInt16(), reader.ReadInt16(),
|
||||
reader.ReadInt16(), reader.ReadInt16(), reader.ReadInt16());
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, DeckCount payload)
|
||||
{
|
||||
writer.Write(payload.Main0);
|
||||
writer.Write(payload.Extra0);
|
||||
writer.Write(payload.Side0);
|
||||
writer.Write(payload.Main1);
|
||||
writer.Write(payload.Extra1);
|
||||
writer.Write(payload.Side1);
|
||||
}
|
||||
}
|
||||
|
||||
// Patch 0009: uint16 count, then per pair uint16 length + the ASCII token "key=value", value verbatim.
|
||||
public sealed class SetupPairsCodec : IStocCodec<Stamped<IReadOnlyList<SetupPair>>>
|
||||
{
|
||||
public const int ReplayFlag = 0x40000000;
|
||||
|
||||
public StocMessage Id => StocMessage.SetupPairs;
|
||||
|
||||
public Stamped<IReadOnlyList<SetupPair>> Read(BinaryReader reader)
|
||||
{
|
||||
var seat = reader.ReadUInt16();
|
||||
return new Stamped<IReadOnlyList<SetupPair>>(seat, ReadBlock(reader));
|
||||
}
|
||||
|
||||
public void Write(BinaryWriter writer, Stamped<IReadOnlyList<SetupPair>> payload)
|
||||
{
|
||||
writer.Write((ushort)payload.Seat);
|
||||
WriteBlock(writer, payload.Payload);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<SetupPair> ReadBlock(BinaryReader reader)
|
||||
{
|
||||
var count = reader.ReadUInt16();
|
||||
var pairs = new List<SetupPair>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var length = reader.ReadUInt16();
|
||||
var bytes = reader.ReadBytes(length);
|
||||
if (bytes.Length < length)
|
||||
throw new EndOfStreamException("setup pair " + i + ": " + bytes.Length + " bytes, expected " + length);
|
||||
pairs.Add(SetupPair.FromToken(Encoding.ASCII.GetString(bytes)));
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
public static void WriteBlock(BinaryWriter writer, IReadOnlyList<SetupPair> pairs)
|
||||
{
|
||||
var count = pairs?.Count ?? 0;
|
||||
writer.Write((ushort)count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var bytes = Encoding.ASCII.GetBytes(pairs[i].Token);
|
||||
writer.Write((ushort)bytes.Length);
|
||||
writer.Write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
// In a replay the block follows a uint32 byte length, at the start of the (decompressed) data.
|
||||
public static IReadOnlyList<SetupPair> ReadReplayBlock(BinaryReader reader)
|
||||
{
|
||||
var length = reader.ReadUInt32();
|
||||
var bytes = reader.ReadBytes(checked((int)length));
|
||||
if (bytes.Length < length)
|
||||
throw new EndOfStreamException("replay setup pairs: " + bytes.Length + " bytes, expected " + length);
|
||||
using var block = new BinaryReader(new MemoryStream(bytes));
|
||||
return ReadBlock(block);
|
||||
}
|
||||
|
||||
public static void WriteReplayBlock(BinaryWriter writer, IReadOnlyList<SetupPair> pairs)
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
using (var block = new BinaryWriter(stream, Encoding.ASCII, true))
|
||||
WriteBlock(block, pairs);
|
||||
writer.Write((uint)stream.Length);
|
||||
writer.Write(stream.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace YGOLegacy.Protocol.Codecs
|
||||
{
|
||||
public static class UnicodeCodec
|
||||
{
|
||||
public static void WriteFixed(BinaryWriter writer, string text, int chars)
|
||||
{
|
||||
if (chars <= 0)
|
||||
return;
|
||||
var buffer = new byte[chars * 2];
|
||||
Encode(Clip(text, chars - 1), buffer);
|
||||
writer.Write(buffer);
|
||||
}
|
||||
|
||||
public static void WriteTerminated(BinaryWriter writer, string text, int maxChars)
|
||||
{
|
||||
if (maxChars <= 0)
|
||||
return;
|
||||
var kept = Clip(text, maxChars - 1);
|
||||
var buffer = new byte[(kept.Length + 1) * 2];
|
||||
Encode(kept, buffer);
|
||||
writer.Write(buffer);
|
||||
}
|
||||
|
||||
public static string ReadFixed(BinaryReader reader, int chars)
|
||||
{
|
||||
if (chars <= 0)
|
||||
return string.Empty;
|
||||
var buffer = reader.ReadBytes(chars * 2);
|
||||
var units = buffer.Length / 2;
|
||||
var text = new char[units];
|
||||
for (var i = 0; i < units; i++)
|
||||
{
|
||||
var c = (char)(buffer[2 * i] | (buffer[2 * i + 1] << 8));
|
||||
if (c == '\0')
|
||||
return new string(text, 0, i);
|
||||
text[i] = c;
|
||||
}
|
||||
return new string(text);
|
||||
}
|
||||
|
||||
public static string ReadTerminated(BinaryReader reader, int maxChars)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
while (text.Length < maxChars)
|
||||
{
|
||||
var pair = reader.ReadBytes(2);
|
||||
if (pair.Length < 2)
|
||||
break;
|
||||
var c = (char)(pair[0] | (pair[1] << 8));
|
||||
if (c == '\0')
|
||||
break;
|
||||
text.Append(c);
|
||||
}
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string Clip(string text, int maxUnits)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text) || maxUnits <= 0)
|
||||
return string.Empty;
|
||||
if (text.Length <= maxUnits)
|
||||
return text;
|
||||
var end = maxUnits;
|
||||
if (char.IsHighSurrogate(text[end - 1]))
|
||||
end--;
|
||||
return text.Substring(0, end);
|
||||
}
|
||||
|
||||
private static void Encode(string text, byte[] buffer)
|
||||
{
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
buffer[2 * i] = (byte)text[i];
|
||||
buffer[2 * i + 1] = (byte)(text[i] >> 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace YGOLegacy.Protocol.Contracts
|
||||
{
|
||||
public readonly struct Response
|
||||
{
|
||||
private static readonly byte[] None = new byte[0];
|
||||
|
||||
public byte[] Bytes { get; }
|
||||
|
||||
public Response(byte[] bytes)
|
||||
{
|
||||
Bytes = bytes ?? None;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct HandResult
|
||||
{
|
||||
public byte Result { get; }
|
||||
|
||||
public HandResult(byte result)
|
||||
{
|
||||
Result = result;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct TpResult
|
||||
{
|
||||
public bool GoFirst { get; }
|
||||
|
||||
public TpResult(bool goFirst)
|
||||
{
|
||||
GoFirst = goFirst;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,715 @@
|
||||
using System;
|
||||
|
||||
namespace YGOLegacy.Protocol.Contracts
|
||||
{
|
||||
public static class FeatureFlags
|
||||
{
|
||||
public const uint Appearance = 0x1;
|
||||
public const uint Dialogue = 0x2;
|
||||
public const uint All = Appearance | Dialogue | SeatPlan | RulesRestart | SeatState | LobbyAfterMatch | CoinToss | DeckList | Profile | AttackPreview | TagTwoFields | TagPartnerCards | TagSharedExtra | PromptContext;
|
||||
// Server-only: the host relays setup pairs (0x43); a client never advertises it.
|
||||
public const uint SetupPairs = 0x4;
|
||||
// Server: chosen seats (0x50-0x53). Client: it renders the seat plan.
|
||||
public const uint SeatPlan = 0x8;
|
||||
// Server: the rules restart (0x54-0x58). Client: it saves its seat on Prepare and rejoins after Commit.
|
||||
public const uint RulesRestart = 0x10;
|
||||
// Server: seat state (0x59) stored per seat and replayed to joiners. Client: it shows what a seat is doing.
|
||||
public const uint SeatState = 0x20;
|
||||
// Server: a match end returns the room to the lobby and sends MatchOver (0x5A). Client: it hands the connection back to the Room.
|
||||
public const uint LobbyAfterMatch = 0x40;
|
||||
// Server: the duel opens with a coin toss (0x5B) and never asks for rock-paper-scissors. Client: it shows the toss.
|
||||
public const uint CoinToss = 0x80;
|
||||
// Server: deck lists (0x5C): the owner's remaining cards sorted, observers' real order and submitted Main Deck when Show all is on. Client: the Deck zone panel shows them.
|
||||
public const uint DeckList = 0x100;
|
||||
// Server: profile (0x5D) stored per seat and replayed to joiners. Client: it shows a human's avatar.
|
||||
public const uint Profile = 0x200;
|
||||
// Server: attack preview (0x5E): the seat whose battle prompt is open asks for its pairs, the host's core answers. Client: it shows the badge.
|
||||
public const uint AttackPreview = 0x400;
|
||||
// Server: Tag on Master Rule 4/5 gives each partner a Field slot (Spell/Trap sequence 5 and 6); a Tag room refuses a joiner without the bit. Client: it shows sequence 6 as the Field Zone and refuses a host without the bit. 0x800 is reserved by proposal 44.
|
||||
public const uint TagTwoFields = 0x1000;
|
||||
// Server: tag partner cards (0x5F): the waiting teammate's hand, Extra Deck and deck go to that side's two seats. Client: the partner view shows them.
|
||||
public const uint TagPartnerCards = 0x2000;
|
||||
// Server: with the setup pair ygol.tag.extra=shared a Tag team has one Extra Deck and its Extra Deck refreshes carry the partner each card came from; a Tag room refuses a joiner without the bit. Client: it reads the value and refuses a host without the bit.
|
||||
public const uint TagSharedExtra = 0x4000;
|
||||
// Server: right before every relayed prompt but rock-paper-scissors, the answering seat gets which card and which effect asks (0x44); never observers, never a replay. Client: it keeps the context on the open prompt.
|
||||
public const uint PromptContext = 0x8000;
|
||||
// Client role, not a feature: set only on the room host's own line, so every peer can badge the host's seat.
|
||||
public const uint RoomHost = 0x80000000;
|
||||
}
|
||||
|
||||
public readonly struct SetupPair
|
||||
{
|
||||
public const int MaxPairs = 64;
|
||||
public const int MaxTokenBytes = 512;
|
||||
|
||||
public string Key { get; }
|
||||
public string Value { get; }
|
||||
|
||||
public SetupPair(string key, string value)
|
||||
{
|
||||
Key = key ?? string.Empty;
|
||||
Value = value ?? string.Empty;
|
||||
}
|
||||
|
||||
public string Token => Key + "=" + Value;
|
||||
|
||||
public static SetupPair FromToken(string token)
|
||||
{
|
||||
var cut = token.IndexOf('=');
|
||||
return cut < 0 ? new SetupPair(token, string.Empty) : new SetupPair(token.Substring(0, cut), token.Substring(cut + 1));
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct Capability
|
||||
{
|
||||
public const ushort ProtocolVersion = 12;
|
||||
public const int ServerSender = 0xFF;
|
||||
|
||||
public ushort Protocol { get; }
|
||||
public uint Flags { get; }
|
||||
|
||||
public Capability(ushort protocol, uint flags)
|
||||
{
|
||||
Protocol = protocol;
|
||||
Flags = flags;
|
||||
}
|
||||
|
||||
public bool Has(uint flag)
|
||||
{
|
||||
return (Flags & flag) == flag;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct AppearanceState
|
||||
{
|
||||
public const int ItemCount = 8;
|
||||
public const int DeckNameChars = 48;
|
||||
public const int CharacterIdChars = 64;
|
||||
public const int DeckGroupChars = 48;
|
||||
|
||||
// Case, Protector, Field, Grave, Stand, Mate, Face, Frame: OnlineAppearanceSync's order.
|
||||
public int[] Items { get; }
|
||||
public string DeckName { get; }
|
||||
public string CharacterId { get; }
|
||||
public string DeckGroup { get; }
|
||||
|
||||
public AppearanceState(int[] items, string deckName, string characterId, string deckGroup)
|
||||
{
|
||||
var copy = new int[ItemCount];
|
||||
if (items != null)
|
||||
Array.Copy(items, copy, Math.Min(items.Length, ItemCount));
|
||||
Items = copy;
|
||||
DeckName = deckName ?? string.Empty;
|
||||
CharacterId = characterId ?? string.Empty;
|
||||
DeckGroup = deckGroup ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
// CTOS/STOC 0x5D (patch 0020): a seated human's avatar id and frame id, as the sender wrote them; a receiver sanitizes both.
|
||||
public readonly struct ProfileState
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int AvatarIdChars = 32;
|
||||
public const int FrameIdChars = 16;
|
||||
|
||||
public byte Version { get; }
|
||||
public string AvatarId { get; }
|
||||
public string FrameId { get; }
|
||||
|
||||
public ProfileState(string avatarId, string frameId) : this(CurrentVersion, avatarId, frameId) { }
|
||||
|
||||
public ProfileState(byte version, string avatarId, string frameId)
|
||||
{
|
||||
Version = version;
|
||||
AvatarId = avatarId ?? string.Empty;
|
||||
FrameId = frameId ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
// One attacker x target pair of CTOS/STOC 0x5E (patch 0023), in the asking seat's own zones; target location 0xFF = direct.
|
||||
public readonly struct AttackPreviewPair
|
||||
{
|
||||
public const byte DirectTarget = 0xFF;
|
||||
public const int Size = 4;
|
||||
|
||||
public byte AttackerLocation { get; }
|
||||
public byte AttackerSequence { get; }
|
||||
public byte TargetLocation { get; }
|
||||
public byte TargetSequence { get; }
|
||||
|
||||
public AttackPreviewPair(byte attackerLocation, byte attackerSequence, byte targetLocation, byte targetSequence)
|
||||
{
|
||||
AttackerLocation = attackerLocation;
|
||||
AttackerSequence = attackerSequence;
|
||||
TargetLocation = targetLocation;
|
||||
TargetSequence = targetSequence;
|
||||
}
|
||||
|
||||
public static AttackPreviewPair Direct(byte attackerLocation, byte attackerSequence)
|
||||
=> new AttackPreviewPair(attackerLocation, attackerSequence, DirectTarget, 0);
|
||||
|
||||
public bool IsDirect => TargetLocation == DirectTarget;
|
||||
}
|
||||
|
||||
// CTOS 0x5E: every pair of one battle prompt, asked once when the prompt opens.
|
||||
public readonly struct AttackPreviewQuery
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int MaxPairs = 255;
|
||||
|
||||
public byte Version { get; }
|
||||
public AttackPreviewPair[] Pairs { get; }
|
||||
|
||||
public AttackPreviewQuery(AttackPreviewPair[] pairs) : this(CurrentVersion, pairs) { }
|
||||
|
||||
public AttackPreviewQuery(byte version, AttackPreviewPair[] pairs)
|
||||
{
|
||||
Version = version;
|
||||
Pairs = pairs ?? Array.Empty<AttackPreviewPair>();
|
||||
}
|
||||
}
|
||||
|
||||
// One answered pair: the request echoed and the 24 bytes ygol_preview_attack wrote, undecoded (the duel's service decodes them).
|
||||
public readonly struct AttackPreviewEntry
|
||||
{
|
||||
public const int AnswerBytes = 24;
|
||||
public const int Size = AttackPreviewPair.Size + AnswerBytes;
|
||||
|
||||
public AttackPreviewPair Pair { get; }
|
||||
public byte[] Answer { get; }
|
||||
|
||||
public AttackPreviewEntry(AttackPreviewPair pair, byte[] answer)
|
||||
{
|
||||
Pair = pair;
|
||||
var copy = new byte[AnswerBytes];
|
||||
if (answer != null)
|
||||
Array.Copy(answer, copy, Math.Min(answer.Length, AnswerBytes));
|
||||
Answer = copy;
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x5E, to the asking seat only, no sender stamp: a refused pair is left out, never answered with zeros.
|
||||
public readonly struct AttackPreviewResult
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
|
||||
public byte Version { get; }
|
||||
public AttackPreviewEntry[] Entries { get; }
|
||||
|
||||
public AttackPreviewResult(AttackPreviewEntry[] entries) : this(CurrentVersion, entries) { }
|
||||
|
||||
public AttackPreviewResult(byte version, AttackPreviewEntry[] entries)
|
||||
{
|
||||
Version = version;
|
||||
Entries = entries ?? Array.Empty<AttackPreviewEntry>();
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct DialogueLine
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int KeyChars = 48;
|
||||
|
||||
public byte Version { get; }
|
||||
public bool TargetFaceDown { get; }
|
||||
public short Index { get; }
|
||||
public uint CardCode { get; }
|
||||
public uint TargetCode { get; }
|
||||
public string CorpusKey { get; }
|
||||
public string EventKey { get; }
|
||||
|
||||
public DialogueLine(byte version, bool targetFaceDown, short index, uint cardCode, uint targetCode,
|
||||
string corpusKey, string eventKey)
|
||||
{
|
||||
Version = version;
|
||||
TargetFaceDown = targetFaceDown;
|
||||
Index = index;
|
||||
CardCode = cardCode;
|
||||
TargetCode = targetCode;
|
||||
CorpusKey = corpusKey ?? string.Empty;
|
||||
EventKey = eventKey ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public enum SeatPlanKind : byte
|
||||
{
|
||||
Open = 0,
|
||||
Cpu = 1,
|
||||
Reserved = 2,
|
||||
}
|
||||
|
||||
public enum SeatStateKind : byte
|
||||
{
|
||||
None = 0,
|
||||
PickingDeck = 1,
|
||||
}
|
||||
|
||||
// What a seated duelist is doing right now; the server keeps one per seat and replays it to joiners after the seat's appearance.
|
||||
public readonly struct SeatState
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
|
||||
public byte Version { get; }
|
||||
public SeatStateKind Kind { get; }
|
||||
// State-specific; 0 for every state today.
|
||||
public ushort Value { get; }
|
||||
|
||||
public SeatState(SeatStateKind kind, ushort value = 0) : this(CurrentVersion, kind, value) { }
|
||||
|
||||
public SeatState(byte version, SeatStateKind kind, ushort value)
|
||||
{
|
||||
Version = version;
|
||||
Kind = kind;
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
// CTOS from the host carries the claim tokens; the server's STOC echo carries neither tokens nor the deadline.
|
||||
public readonly struct SeatPlan
|
||||
{
|
||||
public const int MaxSeats = 4;
|
||||
public const int IdBytes = 16;
|
||||
|
||||
public byte[] RestartId { get; }
|
||||
public uint DeadlineMs { get; }
|
||||
public ushort Revision { get; }
|
||||
public byte SeatCount { get; }
|
||||
public SeatPlanKind[] Kinds { get; }
|
||||
public byte[][] Tokens { get; }
|
||||
|
||||
public SeatPlan(byte[] restartId, uint deadlineMs, ushort revision, byte seatCount, SeatPlanKind[] kinds, byte[][] tokens)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
DeadlineMs = deadlineMs;
|
||||
Revision = revision;
|
||||
SeatCount = seatCount;
|
||||
Kinds = new SeatPlanKind[MaxSeats];
|
||||
if (kinds != null)
|
||||
Array.Copy(kinds, Kinds, Math.Min(kinds.Length, MaxSeats));
|
||||
Tokens = new byte[MaxSeats][];
|
||||
for (var i = 0; i < MaxSeats; i++)
|
||||
Tokens[i] = SeatIds.Fixed(tokens != null && i < tokens.Length ? tokens[i] : null);
|
||||
}
|
||||
|
||||
public SeatPlanKind Kind(int seat) => Kinds != null && seat >= 0 && seat < MaxSeats && seat < SeatCount ? Kinds[seat] : SeatPlanKind.Open;
|
||||
}
|
||||
|
||||
public readonly struct SeatRequest
|
||||
{
|
||||
public const byte Observer = 0xFF;
|
||||
|
||||
public ushort Protocol { get; }
|
||||
public byte[] RestartId { get; }
|
||||
public byte Seat { get; }
|
||||
public byte[] Token { get; }
|
||||
|
||||
public SeatRequest(ushort protocol, byte[] restartId, byte seat, byte[] token)
|
||||
{
|
||||
Protocol = protocol;
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Seat = seat;
|
||||
Token = SeatIds.Fixed(token);
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct SeatSwap
|
||||
{
|
||||
public byte First { get; }
|
||||
public byte Second { get; }
|
||||
|
||||
public SeatSwap(byte first, byte second)
|
||||
{
|
||||
First = first;
|
||||
Second = second;
|
||||
}
|
||||
}
|
||||
|
||||
// From = 0xFF: the sender, as a watcher. To = 0xFF: the watchers.
|
||||
public readonly struct SeatMove
|
||||
{
|
||||
public const byte Watchers = 0xFF;
|
||||
|
||||
public byte From { get; }
|
||||
public byte To { get; }
|
||||
|
||||
public SeatMove(byte from, byte to)
|
||||
{
|
||||
From = from;
|
||||
To = to;
|
||||
}
|
||||
}
|
||||
|
||||
public enum RestartPhase : byte
|
||||
{
|
||||
None = 0,
|
||||
Prepare = 1,
|
||||
Commit = 2,
|
||||
Abort = 3,
|
||||
}
|
||||
|
||||
public enum RestartReason : byte
|
||||
{
|
||||
None = 0,
|
||||
IncompatiblePeer = 1,
|
||||
AckTimeout = 2,
|
||||
NotInLobby = 3,
|
||||
NotHost = 4,
|
||||
Busy = 5,
|
||||
}
|
||||
|
||||
public enum SeatResumeAction : byte
|
||||
{
|
||||
Complete = 1,
|
||||
Release = 2,
|
||||
}
|
||||
|
||||
// Host -> server: one claim token per seat and one for every observer; the server hands each connection only its own.
|
||||
public readonly struct RestartPrepare
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public uint TimeoutMs { get; }
|
||||
public byte SeatCount { get; }
|
||||
public byte[][] SeatTokens { get; }
|
||||
public byte[] ObserverToken { get; }
|
||||
|
||||
public RestartPrepare(byte[] restartId, uint timeoutMs, byte seatCount, byte[][] seatTokens, byte[] observerToken)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
TimeoutMs = timeoutMs;
|
||||
SeatCount = seatCount;
|
||||
SeatTokens = new byte[SeatPlan.MaxSeats][];
|
||||
for (var i = 0; i < SeatPlan.MaxSeats; i++)
|
||||
SeatTokens[i] = SeatIds.Fixed(seatTokens != null && i < seatTokens.Length ? seatTokens[i] : null);
|
||||
ObserverToken = SeatIds.Fixed(observerToken);
|
||||
}
|
||||
}
|
||||
|
||||
// Server -> one connection: its own seat (0xFF = observer) and, in Prepare only, its own token.
|
||||
public readonly struct RoomRestarting
|
||||
{
|
||||
public RestartPhase Phase { get; }
|
||||
public byte[] RestartId { get; }
|
||||
public byte Seat { get; }
|
||||
public byte[] Token { get; }
|
||||
public uint TimeoutMs { get; }
|
||||
|
||||
public RoomRestarting(RestartPhase phase, byte[] restartId, byte seat, byte[] token, uint timeoutMs)
|
||||
{
|
||||
Phase = phase;
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Seat = seat;
|
||||
Token = SeatIds.Fixed(token);
|
||||
TimeoutMs = timeoutMs;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct RestartAck
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public RestartPhase Phase { get; }
|
||||
|
||||
public RestartAck(byte[] restartId, RestartPhase phase)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Phase = phase;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct RestartControl
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public RestartPhase Action { get; }
|
||||
|
||||
public RestartControl(byte[] restartId, RestartPhase action)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Action = action;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct RestartStatus
|
||||
{
|
||||
public RestartPhase Phase { get; }
|
||||
public byte[] RestartId { get; }
|
||||
public byte Acked { get; }
|
||||
public byte Expected { get; }
|
||||
public bool Complete { get; }
|
||||
public RestartReason Reason { get; }
|
||||
|
||||
public RestartStatus(RestartPhase phase, byte[] restartId, byte acked, byte expected, bool complete, RestartReason reason)
|
||||
{
|
||||
Phase = phase;
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Acked = acked;
|
||||
Expected = expected;
|
||||
Complete = complete;
|
||||
Reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct SeatResume
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public SeatResumeAction Action { get; }
|
||||
public byte Reason { get; }
|
||||
|
||||
public SeatResume(byte[] restartId, SeatResumeAction action, byte reason)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Action = action;
|
||||
Reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct SeatResumeResult
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public bool Accepted { get; }
|
||||
public byte Seat { get; }
|
||||
public byte Reason { get; }
|
||||
|
||||
public SeatResumeResult(byte[] restartId, bool accepted, byte seat, byte reason)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Accepted = accepted;
|
||||
Seat = seat;
|
||||
Reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
// Host -> replacement server: the observers' shared claim token, then admission opens.
|
||||
public readonly struct RestartOpen
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public byte[] ObserverToken { get; }
|
||||
|
||||
public RestartOpen(byte[] restartId, byte[] observerToken)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
ObserverToken = SeatIds.Fixed(observerToken);
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct RestartOpened
|
||||
{
|
||||
public byte[] RestartId { get; }
|
||||
public bool Opened { get; }
|
||||
|
||||
public RestartOpened(byte[] restartId, bool opened)
|
||||
{
|
||||
RestartId = SeatIds.Fixed(restartId);
|
||||
Opened = opened;
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x5A, server-stamped: the match ended and the room stayed; the lobby every connection is back in (READY false on every seat).
|
||||
public readonly struct MatchOver
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int MaxSeats = 4;
|
||||
|
||||
public byte Version { get; }
|
||||
public byte SeatCount { get; }
|
||||
private readonly byte occupied0, occupied1, occupied2, occupied3;
|
||||
|
||||
public MatchOver(byte seatCount, bool[] occupied) : this(CurrentVersion, seatCount, occupied) { }
|
||||
|
||||
public MatchOver(byte version, byte seatCount, bool[] occupied)
|
||||
{
|
||||
Version = version;
|
||||
SeatCount = seatCount;
|
||||
occupied0 = (byte)(occupied != null && occupied.Length > 0 && occupied[0] ? 1 : 0);
|
||||
occupied1 = (byte)(occupied != null && occupied.Length > 1 && occupied[1] ? 1 : 0);
|
||||
occupied2 = (byte)(occupied != null && occupied.Length > 2 && occupied[2] ? 1 : 0);
|
||||
occupied3 = (byte)(occupied != null && occupied.Length > 3 && occupied[3] ? 1 : 0);
|
||||
}
|
||||
|
||||
public bool Occupied(int seat) => seat switch { 0 => occupied0 != 0, 1 => occupied1 != 0, 2 => occupied2 != 0, 3 => occupied3 != 0, _ => false };
|
||||
}
|
||||
|
||||
// Sorted: the owner's remaining cards by code. Ordered: the real order, top first. Submitted: the Main Deck in the zone, sorted. 1 and 2 reach observers only.
|
||||
public enum DeckListKind : byte
|
||||
{
|
||||
Sorted = 0,
|
||||
Ordered = 1,
|
||||
Submitted = 2,
|
||||
}
|
||||
|
||||
// STOC 0x5C (patch 0019): one deck's contents for the side that owns it; no sender stamp.
|
||||
public readonly struct DeckList
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int MaxCards = 250;
|
||||
|
||||
public byte Version { get; }
|
||||
public byte Side { get; }
|
||||
public DeckListKind Kind { get; }
|
||||
public int[] Codes { get; }
|
||||
|
||||
public DeckList(byte side, DeckListKind kind, int[] codes) : this(CurrentVersion, side, kind, codes) { }
|
||||
|
||||
public DeckList(byte version, byte side, DeckListKind kind, int[] codes)
|
||||
{
|
||||
Version = version;
|
||||
Side = side;
|
||||
Kind = kind;
|
||||
Codes = codes ?? Array.Empty<int>();
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x5F (v1.2.0, TICKET-405): the waiting tag partner's hand, Extra Deck and deck of one side; to that side's two seats only, no sender stamp.
|
||||
public readonly struct TagPartnerCards
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const int MaxDeckCards = 250;
|
||||
public const uint FaceUpBit = 0x80000000;
|
||||
|
||||
public byte Version { get; }
|
||||
public byte Side { get; }
|
||||
// Raw codes: bit 31 set = face-up (a Pendulum in the Extra Deck), like MSG_TAG_SWAP.
|
||||
public uint[] Hand { get; }
|
||||
public uint[] Extra { get; }
|
||||
// Sorted ascending; the real order never leaves the engine.
|
||||
public int[] Deck { get; }
|
||||
|
||||
public TagPartnerCards(byte side, uint[] hand, uint[] extra, int[] deck) : this(CurrentVersion, side, hand, extra, deck) { }
|
||||
|
||||
public TagPartnerCards(byte version, byte side, uint[] hand, uint[] extra, int[] deck)
|
||||
{
|
||||
Version = version;
|
||||
Side = side;
|
||||
Hand = hand ?? Array.Empty<uint>();
|
||||
Extra = extra ?? Array.Empty<uint>();
|
||||
Deck = deck ?? Array.Empty<int>();
|
||||
}
|
||||
|
||||
public static int CodeOf(uint raw) => (int)(raw & ~FaceUpBit);
|
||||
|
||||
public static bool IsFaceUp(uint raw) => (raw & FaceUpBit) != 0;
|
||||
}
|
||||
|
||||
// STOC 0x44 (v1.7.0, TICKET-451): which card and which effect asks the prompt that follows; to the answering seat only, no sender stamp.
|
||||
public readonly struct PromptContext
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const ushort UnknownIndex = 0xFFFF;
|
||||
public const byte PhaseOther = 0;
|
||||
public const byte PhaseCost = 1;
|
||||
public const byte PhaseTarget = 2;
|
||||
public const byte PhaseOperation = 3;
|
||||
public const byte PhaseAsk = 4;
|
||||
public const byte AnnouncePlain = 0;
|
||||
public const byte AnnounceLevel = 1;
|
||||
public const byte AnnounceDice = 2;
|
||||
|
||||
public byte Version { get; }
|
||||
// False: no effect function runs (battle and idle commands, a plain summon); every other value is zero and EffectIndex is UnknownIndex.
|
||||
public bool HasEffect { get; }
|
||||
// The handler's current code; 0 when the answering player cannot see the card (EffectIndex and Description are then unknown too).
|
||||
public uint Code { get; }
|
||||
public byte Controller { get; }
|
||||
public byte Location { get; }
|
||||
public byte Sequence { get; }
|
||||
public byte Position { get; }
|
||||
// The effect's description (the aux.Stringid value), 0 when it has none.
|
||||
public ulong Description { get; }
|
||||
// The order the card's script registered the effect (the same in every duel); UnknownIndex for an effect the script did not register at load.
|
||||
public ushort EffectIndex { get; }
|
||||
// PhaseCost, PhaseTarget, PhaseOperation: that function of the effect runs; PhaseAsk: the core asks whether to use the effect.
|
||||
public byte Phase { get; }
|
||||
// The chain link the effect is, 0 when it is not on the chain.
|
||||
public byte ChainLink { get; }
|
||||
// MSG_ANNOUNCE_NUMBER only: AnnounceLevel (the script called Duel.AnnounceLevel), AnnounceDice (the asking effect is a visible dice effect); AnnouncePlain everywhere else.
|
||||
public byte AnnounceKind { get; }
|
||||
// The MSG_* id of the prompt this context belongs to.
|
||||
public byte Prompt { get; }
|
||||
|
||||
public PromptContext(bool hasEffect, uint code, byte controller, byte location, byte sequence, byte position, ulong description, ushort effectIndex, byte phase, byte chainLink, byte announceKind, byte prompt)
|
||||
: this(CurrentVersion, hasEffect, code, controller, location, sequence, position, description, effectIndex, phase, chainLink, announceKind, prompt) { }
|
||||
|
||||
public PromptContext(byte version, bool hasEffect, uint code, byte controller, byte location, byte sequence, byte position, ulong description, ushort effectIndex, byte phase, byte chainLink, byte announceKind, byte prompt)
|
||||
{
|
||||
Version = version;
|
||||
HasEffect = hasEffect;
|
||||
Code = code;
|
||||
Controller = controller;
|
||||
Location = location;
|
||||
Sequence = sequence;
|
||||
Position = position;
|
||||
Description = description;
|
||||
EffectIndex = effectIndex;
|
||||
Phase = phase;
|
||||
ChainLink = chainLink;
|
||||
AnnounceKind = announceKind;
|
||||
Prompt = prompt;
|
||||
}
|
||||
|
||||
public static PromptContext None(byte prompt) => new PromptContext(false, 0, 0, 0, 0, 0, 0, UnknownIndex, PhaseOther, 0, AnnouncePlain, prompt);
|
||||
|
||||
public bool IsHidden => HasEffect && Code == 0;
|
||||
}
|
||||
|
||||
public static class SeatIds
|
||||
{
|
||||
public static bool IsZero(byte[] value)
|
||||
{
|
||||
if (value == null)
|
||||
return true;
|
||||
foreach (var b in value)
|
||||
if (b != 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool Same(byte[] a, byte[] b)
|
||||
{
|
||||
var x = Fixed(a);
|
||||
var y = Fixed(b);
|
||||
for (var i = 0; i < x.Length; i++)
|
||||
if (x[i] != y[i])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static byte[] Fixed(byte[] value)
|
||||
{
|
||||
var copy = new byte[SeatPlan.IdBytes];
|
||||
if (value != null)
|
||||
Array.Copy(value, copy, Math.Min(value.Length, SeatPlan.IdBytes));
|
||||
return copy;
|
||||
}
|
||||
|
||||
public static byte[] NewToken()
|
||||
{
|
||||
var token = new byte[SeatPlan.IdBytes];
|
||||
using (var random = System.Security.Cryptography.RandomNumberGenerator.Create())
|
||||
random.GetBytes(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
public static string ToHex(byte[] value) => BitConverter.ToString(Fixed(value)).Replace("-", string.Empty);
|
||||
|
||||
public static byte[] FromHex(string hex)
|
||||
{
|
||||
if (string.IsNullOrEmpty(hex) || hex.Length != SeatPlan.IdBytes * 2)
|
||||
return null;
|
||||
var bytes = new byte[SeatPlan.IdBytes];
|
||||
for (var i = 0; i < bytes.Length; i++)
|
||||
if (!byte.TryParse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber, null, out bytes[i]))
|
||||
return null;
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct Stamped<T>
|
||||
{
|
||||
public int Seat { get; }
|
||||
public T Payload { get; }
|
||||
|
||||
public Stamped(int seat, T payload)
|
||||
{
|
||||
Seat = seat;
|
||||
Payload = payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace YGOLegacy.Protocol.Contracts
|
||||
{
|
||||
public readonly struct ExternalAddress
|
||||
{
|
||||
public string Host { get; }
|
||||
|
||||
public ExternalAddress(string host)
|
||||
{
|
||||
Host = host ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct PlayerInfo
|
||||
{
|
||||
public string Name { get; }
|
||||
|
||||
public PlayerInfo(string name)
|
||||
{
|
||||
Name = name ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct JoinGame
|
||||
{
|
||||
public ushort Version { get; }
|
||||
public string Password { get; }
|
||||
|
||||
public JoinGame(ushort version, string password)
|
||||
{
|
||||
Version = version;
|
||||
Password = password ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct Chat
|
||||
{
|
||||
public string Text { get; }
|
||||
|
||||
public Chat(string text)
|
||||
{
|
||||
Text = text ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct Kick
|
||||
{
|
||||
public byte Position { get; }
|
||||
|
||||
public Kick(byte position)
|
||||
{
|
||||
Position = position;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct NoPayload
|
||||
{
|
||||
}
|
||||
|
||||
public readonly struct UpdateDeck
|
||||
{
|
||||
private static readonly int[] None = new int[0];
|
||||
|
||||
public IReadOnlyList<int> Main { get; }
|
||||
public IReadOnlyList<int> Extra { get; }
|
||||
public IReadOnlyList<int> Side { get; }
|
||||
|
||||
public UpdateDeck(IReadOnlyList<int> main, IReadOnlyList<int> extra, IReadOnlyList<int> side)
|
||||
{
|
||||
Main = main ?? None;
|
||||
Extra = extra ?? None;
|
||||
Side = side ?? None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
namespace YGOLegacy.Protocol.Contracts
|
||||
{
|
||||
public enum CtosMessage
|
||||
{
|
||||
Response = 0x1,
|
||||
UpdateDeck = 0x2,
|
||||
HandResult = 0x3,
|
||||
TpResult = 0x4,
|
||||
PlayerInfo = 0x10,
|
||||
CreateGame = 0x11,
|
||||
JoinGame = 0x12,
|
||||
LeaveGame = 0x13,
|
||||
Surrender = 0x14,
|
||||
TimeConfirm = 0x15,
|
||||
Chat = 0x16,
|
||||
ExternalAddress = 0x17,
|
||||
HsToDuelist = 0x20,
|
||||
HsToObserver = 0x21,
|
||||
HsReady = 0x22,
|
||||
HsNotReady = 0x23,
|
||||
HsKick = 0x24,
|
||||
HsStart = 0x25,
|
||||
RequestField = 0x30,
|
||||
Capability = 0x40,
|
||||
Appearance = 0x41,
|
||||
Dialogue = 0x42,
|
||||
SeatPlan = 0x50,
|
||||
SeatRequest = 0x51,
|
||||
SeatSwap = 0x52,
|
||||
SeatMove = 0x53,
|
||||
RestartPrepare = 0x54,
|
||||
RestartAck = 0x55,
|
||||
RestartControl = 0x56,
|
||||
SeatResume = 0x57,
|
||||
RestartOpen = 0x58,
|
||||
SeatState = 0x59,
|
||||
Profile = 0x5D,
|
||||
AttackPreview = 0x5E
|
||||
}
|
||||
|
||||
public enum StocMessage
|
||||
{
|
||||
GameMsg = 0x1,
|
||||
ErrorMsg = 0x2,
|
||||
SelectHand = 0x3,
|
||||
SelectTp = 0x4,
|
||||
HandResult = 0x5,
|
||||
TpResult = 0x6,
|
||||
ChangeSide = 0x7,
|
||||
WaitingSide = 0x8,
|
||||
DeckCount = 0x9,
|
||||
CreateGame = 0x11,
|
||||
JoinGame = 0x12,
|
||||
TypeChange = 0x13,
|
||||
LeaveGame = 0x14,
|
||||
DuelStart = 0x15,
|
||||
DuelEnd = 0x16,
|
||||
Replay = 0x17,
|
||||
TimeLimit = 0x18,
|
||||
Chat = 0x19,
|
||||
HsPlayerEnter = 0x20,
|
||||
HsPlayerChange = 0x21,
|
||||
HsWatchChange = 0x22,
|
||||
TeammateSurrender = 0x23,
|
||||
FieldFinish = 0x30,
|
||||
SrvproRoomList = 0x31,
|
||||
Capability = 0x40,
|
||||
Appearance = 0x41,
|
||||
Dialogue = 0x42,
|
||||
SetupPairs = 0x43,
|
||||
PromptContext = 0x44,
|
||||
SeatPlan = 0x50,
|
||||
RoomRestarting = 0x54,
|
||||
RestartStatus = 0x56,
|
||||
SeatResumeResult = 0x57,
|
||||
RestartOpen = 0x58,
|
||||
SeatState = 0x59,
|
||||
MatchOver = 0x5A,
|
||||
CoinToss = 0x5B,
|
||||
DeckList = 0x5C,
|
||||
Profile = 0x5D,
|
||||
AttackPreview = 0x5E,
|
||||
TagPartnerCards = 0x5F
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace YGOLegacy.Protocol.Contracts
|
||||
{
|
||||
// Fork replay header flags (contract section (b), Replay). The stock flags stay 0x1 (compressed) and 0x2 (tag).
|
||||
public static class ReplayFlags
|
||||
{
|
||||
// Patch 0009: u32 length + the setup pairs block before the player names.
|
||||
public const int SetupPairs = 0x40000000;
|
||||
// v1.4.0, life points per side: i32 lp[0] + i32 lp[1] (duel player order) after opt.
|
||||
public const int SideLp = 0x20000000;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
namespace YGOLegacy.Protocol.Contracts
|
||||
{
|
||||
public readonly struct ErrorMsg
|
||||
{
|
||||
public byte Msg { get; }
|
||||
public int Code { get; }
|
||||
|
||||
public ErrorMsg(byte msg, int code)
|
||||
{
|
||||
Msg = msg;
|
||||
Code = code;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct HandResultAnnounce
|
||||
{
|
||||
public byte First { get; }
|
||||
public byte Second { get; }
|
||||
|
||||
public HandResultAnnounce(byte first, byte second)
|
||||
{
|
||||
First = first;
|
||||
Second = second;
|
||||
}
|
||||
}
|
||||
|
||||
// STOC 0x5B (patch 0017), to every seat and spectator before SELECT_TP: who chooses the turn order and how the coin landed.
|
||||
public readonly struct CoinTossAnnounce
|
||||
{
|
||||
public const byte CurrentVersion = 1;
|
||||
public const byte Heads = 0;
|
||||
public const byte Tails = 1;
|
||||
// No toss: game 2+ of a match, the loser chooses.
|
||||
public const byte NoFace = 0xFF;
|
||||
|
||||
public byte Version { get; }
|
||||
public byte ChooserSeat { get; }
|
||||
public byte Face { get; }
|
||||
public byte ChooseSeconds { get; }
|
||||
|
||||
public CoinTossAnnounce(byte chooserSeat, byte face, byte chooseSeconds) : this(CurrentVersion, chooserSeat, face, chooseSeconds) { }
|
||||
|
||||
public CoinTossAnnounce(byte version, byte chooserSeat, byte face, byte chooseSeconds)
|
||||
{
|
||||
Version = version;
|
||||
ChooserSeat = chooserSeat;
|
||||
Face = face;
|
||||
ChooseSeconds = chooseSeconds;
|
||||
}
|
||||
|
||||
public bool Tossed => Face != NoFace;
|
||||
}
|
||||
|
||||
public readonly struct HostInfo
|
||||
{
|
||||
public uint Lflist { get; }
|
||||
public byte Rule { get; }
|
||||
public byte Mode { get; }
|
||||
public byte DuelRule { get; }
|
||||
public bool NoCheckDeck { get; }
|
||||
public bool NoShuffleDeck { get; }
|
||||
public int StartLp { get; }
|
||||
public byte StartHand { get; }
|
||||
public byte DrawCount { get; }
|
||||
public ushort TimeLimit { get; }
|
||||
|
||||
public HostInfo(uint lflist, byte rule, byte mode, byte duelRule, bool noCheckDeck, bool noShuffleDeck,
|
||||
int startLp, byte startHand, byte drawCount, ushort timeLimit)
|
||||
{
|
||||
Lflist = lflist;
|
||||
Rule = rule;
|
||||
Mode = mode;
|
||||
DuelRule = duelRule;
|
||||
NoCheckDeck = noCheckDeck;
|
||||
NoShuffleDeck = noShuffleDeck;
|
||||
StartLp = startLp;
|
||||
StartHand = startHand;
|
||||
DrawCount = drawCount;
|
||||
TimeLimit = timeLimit;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct TypeChange
|
||||
{
|
||||
public byte Position { get; }
|
||||
public bool IsHost { get; }
|
||||
|
||||
public TypeChange(byte position, bool isHost)
|
||||
{
|
||||
Position = (byte)(position & 0xF);
|
||||
IsHost = isHost;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct TimeLimit
|
||||
{
|
||||
public byte Player { get; }
|
||||
public ushort LeftTime { get; }
|
||||
|
||||
public TimeLimit(byte player, ushort leftTime)
|
||||
{
|
||||
Player = player;
|
||||
LeftTime = leftTime;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct ServerChat
|
||||
{
|
||||
public ushort Player { get; }
|
||||
public string Text { get; }
|
||||
|
||||
public ServerChat(ushort player, string text)
|
||||
{
|
||||
Player = player;
|
||||
Text = text ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct PlayerEnter
|
||||
{
|
||||
public string Name { get; }
|
||||
public byte Position { get; }
|
||||
|
||||
public PlayerEnter(string name, byte position)
|
||||
{
|
||||
Name = name ?? string.Empty;
|
||||
Position = position;
|
||||
}
|
||||
}
|
||||
|
||||
public enum PlayerChangeKind
|
||||
{
|
||||
MoveTo,
|
||||
Observe,
|
||||
Ready,
|
||||
NotReady,
|
||||
Leave,
|
||||
Unknown
|
||||
}
|
||||
|
||||
public readonly struct PlayerChange
|
||||
{
|
||||
public const byte ObserveState = 0x8;
|
||||
public const byte ReadyState = 0x9;
|
||||
public const byte NotReadyState = 0xA;
|
||||
public const byte LeaveState = 0xB;
|
||||
|
||||
public byte Position { get; }
|
||||
public byte State { get; }
|
||||
public PlayerChangeKind Kind { get; }
|
||||
public byte TargetSeat { get; }
|
||||
|
||||
public PlayerChange(byte position, byte state)
|
||||
{
|
||||
Position = (byte)(position & 0xF);
|
||||
State = (byte)(state & 0xF);
|
||||
Kind = KindOf(State);
|
||||
TargetSeat = Kind == PlayerChangeKind.MoveTo ? State : (byte)0;
|
||||
}
|
||||
|
||||
public static PlayerChangeKind KindOf(byte state)
|
||||
{
|
||||
if (state < ObserveState)
|
||||
return PlayerChangeKind.MoveTo;
|
||||
switch (state)
|
||||
{
|
||||
case ObserveState: return PlayerChangeKind.Observe;
|
||||
case ReadyState: return PlayerChangeKind.Ready;
|
||||
case NotReadyState: return PlayerChangeKind.NotReady;
|
||||
case LeaveState: return PlayerChangeKind.Leave;
|
||||
default: return PlayerChangeKind.Unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct WatchChange
|
||||
{
|
||||
public ushort Count { get; }
|
||||
|
||||
public WatchChange(ushort count)
|
||||
{
|
||||
Count = count;
|
||||
}
|
||||
}
|
||||
|
||||
public readonly struct DeckCount
|
||||
{
|
||||
public short Main0 { get; }
|
||||
public short Extra0 { get; }
|
||||
public short Side0 { get; }
|
||||
public short Main1 { get; }
|
||||
public short Extra1 { get; }
|
||||
public short Side1 { get; }
|
||||
|
||||
public DeckCount(short main0, short extra0, short side0, short main1, short extra1, short side1)
|
||||
{
|
||||
Main0 = main0;
|
||||
Extra0 = extra0;
|
||||
Side0 = side0;
|
||||
Main1 = main1;
|
||||
Extra1 = extra1;
|
||||
Side1 = side1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace YGOLegacy.Protocol.Framing
|
||||
{
|
||||
public static class FrameCodec
|
||||
{
|
||||
public const int HeaderSize = 2;
|
||||
public const int MaxFrame = 0xFFFE;
|
||||
|
||||
public static void Write(BinaryWriter writer, byte id, byte[] payload)
|
||||
{
|
||||
var payloadLength = payload == null ? 0 : payload.Length;
|
||||
WriteHeader(writer, payloadLength + 1);
|
||||
writer.Write(id);
|
||||
if (payloadLength > 0)
|
||||
writer.Write(payload, 0, payloadLength);
|
||||
}
|
||||
|
||||
public static void Write(BinaryWriter writer, byte[] packet)
|
||||
{
|
||||
if (packet == null || packet.Length == 0)
|
||||
throw new ArgumentException("A frame needs at least the id byte", nameof(packet));
|
||||
WriteHeader(writer, packet.Length);
|
||||
writer.Write(packet, 0, packet.Length);
|
||||
}
|
||||
|
||||
public static int ReadLength(byte[] header)
|
||||
{
|
||||
if (header == null || header.Length < HeaderSize)
|
||||
throw new ArgumentException("A frame header is two bytes", nameof(header));
|
||||
return header[0] | (header[1] << 8);
|
||||
}
|
||||
|
||||
private static void WriteHeader(BinaryWriter writer, int length)
|
||||
{
|
||||
if (length > MaxFrame)
|
||||
throw new ArgumentException("Frame of " + length + " bytes exceeds the " + MaxFrame + "-byte ceiling");
|
||||
writer.Write((byte)length);
|
||||
writer.Write((byte)(length >> 8));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class FrameExtractor
|
||||
{
|
||||
private byte[] _buffer = new byte[4096];
|
||||
private int _start;
|
||||
private int _count;
|
||||
|
||||
public int DroppedEmpty { get; private set; }
|
||||
public bool Faulted { get; private set; }
|
||||
public int Buffered => _count;
|
||||
|
||||
public void Feed(byte[] chunk, int count)
|
||||
{
|
||||
if (Faulted || chunk == null || count <= 0)
|
||||
return;
|
||||
if (count > chunk.Length)
|
||||
count = chunk.Length;
|
||||
Reserve(count);
|
||||
Array.Copy(chunk, 0, _buffer, _start + _count, count);
|
||||
_count += count;
|
||||
}
|
||||
|
||||
public bool TryTake(out byte[] packet)
|
||||
{
|
||||
packet = null;
|
||||
while (!Faulted && _count >= FrameCodec.HeaderSize)
|
||||
{
|
||||
var length = _buffer[_start] | (_buffer[_start + 1] << 8);
|
||||
if (length > FrameCodec.MaxFrame)
|
||||
{
|
||||
Faulted = true;
|
||||
return false;
|
||||
}
|
||||
if (length == 0)
|
||||
{
|
||||
Consume(FrameCodec.HeaderSize);
|
||||
DroppedEmpty++;
|
||||
continue;
|
||||
}
|
||||
if (_count < FrameCodec.HeaderSize + length)
|
||||
return false;
|
||||
packet = new byte[length];
|
||||
Array.Copy(_buffer, _start + FrameCodec.HeaderSize, packet, 0, length);
|
||||
Consume(FrameCodec.HeaderSize + length);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Consume(int bytes)
|
||||
{
|
||||
_start += bytes;
|
||||
_count -= bytes;
|
||||
if (_count == 0)
|
||||
_start = 0;
|
||||
}
|
||||
|
||||
private void Reserve(int extra)
|
||||
{
|
||||
if (_start + _count + extra <= _buffer.Length)
|
||||
return;
|
||||
if (_count + extra <= _buffer.Length)
|
||||
{
|
||||
Array.Copy(_buffer, _start, _buffer, 0, _count);
|
||||
_start = 0;
|
||||
return;
|
||||
}
|
||||
var grown = new byte[Math.Max(_buffer.Length * 2, _count + extra)];
|
||||
Array.Copy(_buffer, _start, grown, 0, _count);
|
||||
_buffer = grown;
|
||||
_start = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using YGOLegacy.Protocol.Contracts;
|
||||
|
||||
namespace YGOLegacy.Protocol.Routing
|
||||
{
|
||||
public enum RouteOutcome
|
||||
{
|
||||
Handled,
|
||||
Ignored,
|
||||
Unknown,
|
||||
Empty
|
||||
}
|
||||
|
||||
public sealed class StocRouter
|
||||
{
|
||||
private readonly Dictionary<StocMessage, Action<BinaryReader>> _handlers = new Dictionary<StocMessage, Action<BinaryReader>>();
|
||||
private readonly HashSet<StocMessage> _ignored = new HashSet<StocMessage>();
|
||||
private readonly HashSet<StocMessage> _reported = new HashSet<StocMessage>();
|
||||
|
||||
public Action<StocMessage, int> OnUnknown { get; set; }
|
||||
|
||||
public void Register(StocMessage id, Action<BinaryReader> handler)
|
||||
{
|
||||
if (handler == null)
|
||||
throw new ArgumentNullException(nameof(handler));
|
||||
RequireFree(id);
|
||||
_handlers.Add(id, handler);
|
||||
}
|
||||
|
||||
public void Ignore(StocMessage id)
|
||||
{
|
||||
RequireFree(id);
|
||||
_ignored.Add(id);
|
||||
}
|
||||
|
||||
public bool IsRegistered(StocMessage id)
|
||||
{
|
||||
return _handlers.ContainsKey(id) || _ignored.Contains(id);
|
||||
}
|
||||
|
||||
public RouteOutcome Dispatch(BinaryReader reader, out StocMessage id)
|
||||
{
|
||||
if (reader == null)
|
||||
throw new ArgumentNullException(nameof(reader));
|
||||
id = default(StocMessage);
|
||||
var stream = reader.BaseStream;
|
||||
if (stream.Position >= stream.Length)
|
||||
return RouteOutcome.Empty;
|
||||
id = (StocMessage)reader.ReadByte();
|
||||
Action<BinaryReader> handler;
|
||||
if (_handlers.TryGetValue(id, out handler))
|
||||
{
|
||||
handler(reader);
|
||||
return RouteOutcome.Handled;
|
||||
}
|
||||
if (_ignored.Contains(id))
|
||||
return RouteOutcome.Ignored;
|
||||
if (_reported.Add(id))
|
||||
OnUnknown?.Invoke(id, (int)(stream.Length - stream.Position));
|
||||
return RouteOutcome.Unknown;
|
||||
}
|
||||
|
||||
private void RequireFree(StocMessage id)
|
||||
{
|
||||
if (IsRegistered(id))
|
||||
throw new ArgumentException("STOC " + id + " already has an owner", nameof(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.1</TargetFramework>
|
||||
<LangVersion>9</LangVersion>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>disable</Nullable>
|
||||
<AssemblyName>YGOLegacy.Engine</AssemblyName>
|
||||
<RootNamespace>YGOLegacy.Engine</RootNamespace>
|
||||
<Deterministic>true</Deterministic>
|
||||
<DebugType>portable</DebugType>
|
||||
<EngineVersion Condition="'$(EngineVersion)' == ''">local</EngineVersion>
|
||||
<AssemblyVersion>1.0.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0.0</FileVersion>
|
||||
<InformationalVersion>$(EngineVersion)</InformationalVersion>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<Target Name="GenerateEngineBindingVersion" BeforeTargets="CoreCompile">
|
||||
<PropertyGroup>
|
||||
<EngineBindingVersionFile>$(IntermediateOutputPath)EngineBindingVersion.cs</EngineBindingVersionFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<EngineBindingVersionLine Include="namespace YGOLegacy.Engine" />
|
||||
<EngineBindingVersionLine Include="{" />
|
||||
<EngineBindingVersionLine Include=" public static partial class EngineBinding" />
|
||||
<EngineBindingVersionLine Include=" {" />
|
||||
<EngineBindingVersionLine Include=" public const string Version = "$(EngineVersion)"%3B" />
|
||||
<EngineBindingVersionLine Include=" }" />
|
||||
<EngineBindingVersionLine Include="}" />
|
||||
</ItemGroup>
|
||||
<WriteLinesToFile File="$(EngineBindingVersionFile)" Lines="@(EngineBindingVersionLine)" Overwrite="true" WriteOnlyWhenDifferent="true" />
|
||||
<ItemGroup>
|
||||
<Compile Include="$(EngineBindingVersionFile)" />
|
||||
<FileWrites Include="$(EngineBindingVersionFile)" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
+5
-5
@@ -60,7 +60,7 @@ EOF
|
||||
# defined, no leading underscore: C++ symbols are _Z-mangled; sqlite3_*, lua_*, event_*, ... count,
|
||||
# as they do on Windows), every name declared in contract/ocgapi.h among them, the count exactly
|
||||
# <expected>; then engine.json with protocol and capabilities READ from the server source, never
|
||||
# typed in.
|
||||
# typed in, and binding = the version (the C# binding is released with the engine under one tag).
|
||||
COPY <<'EOF' /export-gate
|
||||
#!/usr/bin/env python3
|
||||
import re, subprocess, sys
|
||||
@@ -86,8 +86,8 @@ capabilities = 0
|
||||
for n in exprs[0].split('|'):
|
||||
if n not in bits: sys.exit('capability %s has no constexpr uint32_t in gframe/network.h' % n)
|
||||
capabilities |= bits[n]
|
||||
open(out + '/engine.json', 'w').write('{\n "version": "%s",\n "exports": %d,\n "protocol": %d,\n "capabilities": %d\n}\n' % (version, len(names), protocol, capabilities))
|
||||
print('engine.json: version %s, exports %d, protocol %d, capabilities 0x%X' % (version, len(names), protocol, capabilities))
|
||||
open(out + '/engine.json', 'w').write('{\n "version": "%s",\n "exports": %d,\n "protocol": %d,\n "capabilities": %d,\n "binding": "%s"\n}\n' % (version, len(names), protocol, capabilities, version))
|
||||
print('engine.json: version %s, exports %d, protocol %d, capabilities 0x%X, binding %s' % (version, len(names), protocol, capabilities, version))
|
||||
EOF
|
||||
|
||||
# --- sources + gates. obj/ bin/ build/ are wiped so a dirty checkout can never hand the build a stale
|
||||
@@ -125,7 +125,7 @@ RUN SERVER_ZIP_SUPPORT=1 SERVER_TAG_SURRENDER_CONFIRM=1 premake5 gmake \
|
||||
&& make -C build config=release -j"$(nproc)" ygopro \
|
||||
&& cp bin/release/ygopro /out/ygoserver
|
||||
RUN file /out/libygol-engine.so /out/ygoserver \
|
||||
&& export-gate nm /out/libygol-engine.so 855 "$VERSION" /out
|
||||
&& export-gate nm /out/libygol-engine.so 857 "$VERSION" /out
|
||||
|
||||
FROM scratch AS linux
|
||||
COPY --from=linux-build /out/ /
|
||||
@@ -140,7 +140,7 @@ RUN YGOL_ENGINE_VERSION=$VERSION premake5 gmake \
|
||||
&& make -C build config=release_android_arm64 -j"$(nproc)" ygoserver \
|
||||
&& mkdir -p /out && cp bin/android_arm64/release/libygol-engine.so /out/
|
||||
RUN file /out/libygol-engine.so \
|
||||
&& export-gate "$NDK_DIR"/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-nm /out/libygol-engine.so 849 "$VERSION" /out
|
||||
&& export-gate "$NDK_DIR"/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-nm /out/libygol-engine.so 851 "$VERSION" /out
|
||||
|
||||
FROM scratch AS android
|
||||
COPY --from=android-build /out/ /
|
||||
+7
-6
@@ -16,11 +16,12 @@
|
||||
verbatim plus the server's YGOSERVER_API lines from gframe\serverapi.h in its
|
||||
marked block; a difference fails the build (the contract is a copy kept honest).
|
||||
After the gate it writes out\win64\engine.json: { version, exports, protocol,
|
||||
capabilities }, protocol and capabilities READ from gframe\network.h and the
|
||||
SendServerCapability line of single_duel.cpp / tag_duel.cpp, never typed in.
|
||||
capabilities, binding }, protocol and capabilities READ from gframe\network.h and
|
||||
the SendServerCapability line of single_duel.cpp / tag_duel.cpp, never typed in;
|
||||
binding is the version of the C# binding released with this engine (the same tag).
|
||||
|
||||
Output: out\win64\ygol-engine.dll (+ .pdb). The export gate is the truth:
|
||||
the script FAILS unless the DLL exports exactly 334 symbols (start_server,
|
||||
the script FAILS unless the DLL exports exactly 336 symbols (start_server,
|
||||
stop_server, ygol_engine_version, and the core C API re-exported, ygol_sb_*
|
||||
and ygol_preview_attack included). The Unity repo's old ygoserver.dll had 327:
|
||||
its own core copy never carried patch 0008's six ygol_sb_* exports.
|
||||
@@ -29,7 +30,7 @@
|
||||
param(
|
||||
[string]$Premake = "C:\premake\premake5.exe",
|
||||
[string]$Version = "local",
|
||||
[int]$ExpectedExports = 334
|
||||
[int]$ExpectedExports = 336
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -138,6 +139,6 @@ Write-Host "Built: $out"
|
||||
Write-Host "exports: $n (expected $ExpectedExports)"
|
||||
if ($n -ne $ExpectedExports) { throw "export count $n != $ExpectedExports; do NOT ship this build" }
|
||||
|
||||
$json = "{`n `"version`": `"$Version`",`n `"exports`": $n,`n `"protocol`": $protocol,`n `"capabilities`": $capabilities`n}`n"
|
||||
$json = "{`n `"version`": `"$Version`",`n `"exports`": $n,`n `"protocol`": $protocol,`n `"capabilities`": $capabilities,`n `"binding`": `"$Version`"`n}`n"
|
||||
[IO.File]::WriteAllText((Join-Path $outDir "engine.json"), $json, (New-Object Text.UTF8Encoding $false))
|
||||
Write-Host "engine.json: version $Version, exports $n, protocol $protocol, capabilities 0x$($capabilities.ToString('X'))"
|
||||
Write-Host "engine.json: version $Version, exports $n, protocol $protocol, capabilities 0x$($capabilities.ToString('X')), binding $Version"
|
||||
+167
-22
@@ -1,8 +1,9 @@
|
||||
# The ygol-engine contract
|
||||
|
||||
This is the one spec every consumer of `ygol-engine` reads instead of the C++. It has four parts:
|
||||
This is the one spec every consumer of `ygol-engine` reads instead of the C++. It has five parts:
|
||||
(a) the C API, (b) the wire protocol the duel server speaks, (c) the engine message stream a duel
|
||||
produces, (d) the setup pairs and the Lua API. A change to any part is a row in `CHANGELOG.md`
|
||||
produces, (d) the setup pairs and the Lua API, (e) the C# binding `YGOLegacy.Engine`. A change to any
|
||||
part is a row in `CHANGELOG.md`
|
||||
(proposal 47, Rule 2). The facts here are read from the source: `core/ocgapi.h`,
|
||||
`server/gframe/serverapi.h`, `server/gframe/network.h`, `server/gframe/netserver.cpp`,
|
||||
`server/gframe/single_duel.cpp` / `tag_duel.cpp`, `core/common.h`. When this file and the source
|
||||
@@ -24,18 +25,20 @@ next to the library (`out/win64/engine.json` on Windows):
|
||||
```json
|
||||
{
|
||||
"version": "v0.0.1",
|
||||
"exports": 334,
|
||||
"protocol": 8,
|
||||
"capabilities": 2047
|
||||
"exports": 336,
|
||||
"protocol": 12,
|
||||
"capabilities": 63487,
|
||||
"binding": "v0.0.1"
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Type | Source |
|
||||
|---|---|---|
|
||||
| `version` | string | The `-Version` the build was given; `local` when none. The same string `ygol_engine_version()` returns. |
|
||||
| `exports` | integer | The library's export count after the gate passed (Windows: 334). |
|
||||
| `protocol` | integer | `FEATURE_PROTOCOL` in `server/gframe/network.h` (8 as of 2026-10-13). |
|
||||
| `capabilities` | integer | The OR of every `FEATURE_*` bit `SendServerCapability` advertises (`single_duel.cpp` and `tag_duel.cpp` must agree), as a decimal integer. 2047 = `0x7FF` = bits `0x1` to `0x400`. |
|
||||
| `exports` | integer | The library's export count after the gate passed (Windows: 336). |
|
||||
| `protocol` | integer | `FEATURE_PROTOCOL` in `server/gframe/network.h` (12 as of 2026-11-08). |
|
||||
| `capabilities` | integer | The OR of every `FEATURE_*` bit `SendServerCapability` advertises (`single_duel.cpp` and `tag_duel.cpp` must agree), as a decimal integer. 63487 = `0xF7FF` = bits `0x1` to `0x400` plus `0x1000` to `0x8000` (`0x800` is reserved by proposal 44). |
|
||||
| `binding` | string | The version of the C# binding released with this engine (section (e)); the same string as `version`. |
|
||||
|
||||
The build reads `protocol` and `capabilities` from the source every time; nothing types them in.
|
||||
|
||||
@@ -49,7 +52,7 @@ the caller's.
|
||||
The library also exports 289 `sqlite3_*` symbols because the server links SQLite with
|
||||
`SQLITE_API=__declspec(dllexport)`. They are NOT part of this contract: nothing of ours calls them
|
||||
through the library, and they are counted by the export gate only so that the number stays exact
|
||||
(Windows: 44 contract exports + 289 SQLite + 1 = 334; the extra 1 is `ygol_engine_version`, see below).
|
||||
(Windows: 46 contract exports + 289 SQLite + 1 = 336; the extra 1 is `ygol_engine_version`, see below).
|
||||
|
||||
### Server exports (`server/gframe/serverapi.h`)
|
||||
|
||||
@@ -70,7 +73,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
|
||||
| 5 | duel rule: `T` (previous master rule), `F` (default), or a numeric `duel_flags` |
|
||||
| 6 | `T` = no deck check |
|
||||
| 7 | `T` = no deck shuffle |
|
||||
| 8 | start LP |
|
||||
| 8 | start LP (seat side A; side B too unless the setup pair `ygol.side.b.lp` names its own) |
|
||||
| 9 | start hand |
|
||||
| 10 | draw count |
|
||||
| 11 | time limit (seconds; 0 = none) |
|
||||
@@ -90,7 +93,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
|
||||
| `create_duel_v2` | `intptr_t create_duel_v2(uint32_t seed_sequence[])` | Upstream (`SEED_COUNT` = 8 words) |
|
||||
| `create_duel_ex` | `intptr_t create_duel_ex(uint_fast32_t seed, uint32_t create_flags)` | Upstream |
|
||||
| `create_duel_v2_ex` | `intptr_t create_duel_v2_ex(uint32_t seed_sequence[], uint32_t create_flags)` | Upstream |
|
||||
| `start_duel` | `void start_duel(intptr_t pduel, uint32_t options)` | Upstream |
|
||||
| `start_duel` | `void start_duel(intptr_t pduel, uint32_t options)` | Upstream. v1.6.0: option `DUEL_TAG_SHARED_EXTRA` `0x200` with `DUEL_TAG_MODE` merges each team's Extra Decks (section (b), behaviour v1.6.0). |
|
||||
| `end_duel` | `void end_duel(intptr_t pduel)` | Upstream |
|
||||
| `set_player_info` | `void set_player_info(intptr_t pduel, int32_t playerid, int32_t lp, int32_t startcount, int32_t drawcount)` | Upstream |
|
||||
| `get_log_message` | `void get_log_message(intptr_t pduel, char* buf)` | Upstream |
|
||||
@@ -107,6 +110,8 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
|
||||
| `preload_script` | `int32_t preload_script(intptr_t pduel, const char* script_name)` | Upstream |
|
||||
| `default_script_reader` | `byte* default_script_reader(const char* script_name, int* len)` | Upstream |
|
||||
| `ygol_preview_attack` | `int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_t location, uint8_t sequence, uint8_t target_location, uint8_t target_sequence, uint8_t* out)` | Patch 0022 (TICKET-374) + 0024 (TICKET-379), 2026-10-13. A read-only dry run of the damage step. Returns 1 answered, 0 refused (bad pointer, no such card, attacker not a face-up monster on `playerid`'s field, target not a monster on the other field); a refusal writes nothing. `target_location` `0xFF` = direct. `out` is 24 bytes: version (1), flags (bit 0 direct, bit 1 unknown, bit 2 attacker destroyed, bit 3 target destroyed, bit 4 pierce, bit 5 illegal), 2 pad bytes, then five `int32`: attacker value, target value, damage to player 0, damage to player 1, reserved 0. A face-down target answers unknown with every number 0. A pair the battle menu (`field::get_attack_target`) would not offer answers illegal alone with every number 0. Call it only while the engine is parked on a prompt; the duel is byte-identical afterwards. |
|
||||
| `ygol_query_tag_cards` | `int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out)` | v1.2.0 (TICKET-405), 2026-10-15. The waiting tag partner's cards of `playerid`'s side, read only. Returns the byte length written, 0 refused (bad pointer, bad player, not a tag duel); a refusal writes nothing. `out`: `u8 version` (1), `u8 hand_count`, `u8 extra_count`, `u8 pad` (0), `u16 deck_count`, then `u32 hand[hand_count]`, `u32 extra[extra_count]` (bit 31 = face-up, as in `MSG_TAG_SWAP`), `u32 deck[deck_count]` sorted ascending (the order stays secret). At most 7 + 4 x (255 + 255 + 250) bytes in practice; size the buffer for your deck limits. The duel is byte-identical afterwards. |
|
||||
| `ygol_query_prompt_context` | `int32_t ygol_query_prompt_context(intptr_t pduel, uint8_t playerid, uint8_t* out)` | v1.7.0 (TICKET-451), 2026-11-08. Which effect asks the prompt the engine is parked on, read only; `playerid` is the answering player. Returns 23 (the bytes written), 0 refused (bad pointer, bad player); a refusal writes nothing. `out` (23 bytes, little-endian): `u8 version` (1), `u8 has_effect`, `u32 code` (the handler's `get_code()` now), `u8 controller`, `u8 location`, `u8 sequence`, `u8 position` (the handler now), `u64 description` (the effect's, 0 when none), `u16 effect_index`, `u8 phase` (1 cost, 2 target, 3 operation, 4 ask), `u8 chain_link` (the newest chain link whose effect it is, 0 when none), `u8 announce_kind` (only while a `MSG_ANNOUNCE_NUMBER` is open: 1 the script called `Duel.AnnounceLevel`, which passes `playerid + 0x10000` to the unit; else 2 when the asking effect has `CATEGORY_DICE` and is visible to `playerid`; else 0; always 0 for any other prompt). The effect is the innermost frame on `core.ygol_running`: a cost / target / operation function running (`field::execute_cost` / `execute_target` / `execute_operation`, the core's only coroutine calls; phases 1 / 2 / 3), or an effect the core itself asks about (phase 4, "ask"): the frame lives while that `MSG_SELECT_EFFECTYN` / `MSG_SELECT_YESNO` is open, at the optional trigger (`processor.cpp`, desc 0), the lone quick trigger (desc 221), the cost-time activation ask (desc 94), the three replacement asks (`operations.cpp`, desc 218 / 220 / 219) and Scrap Chimera's material ask (its own description). Other prompts the core builds itself either list several effects (`MSG_SELECT_CHAIN`, `IDLECMD`, `BATTLECMD`, the `SELECT_OPTION` among replacement effects or activation ways) or ask about no effect (attack, desc 31; the Pendulum / Spell-zone redirect, desc 97; Tribute and material prompts): they push nothing and show whatever runs around them. None running (battle and idle commands, chain prompts, a Summon without an effect) = `has_effect` 0, every other byte 0 but `announce_kind`, and `effect_index` `0xFFFF`. **`effect_index`** is the order the card's script registered the effect while the card loaded (`card::add_effect` under `STATUS_INITIALIZING` stamps `initial_effect.size()`): the same in every duel and on every machine for that card's script; an effect registered at any other time (a clone, a copy, a grant, an effect made during the duel) is `0xFFFF`. **Hidden**: when the handler is not controlled by `playerid` and is not face-up (`is_position(POS_FACEUP)`: a face-down card, the other player's hand, Deck or face-down Extra Deck), `code` is 0, `effect_index` `0xFFFF` and `description` 0; the other fields stay. The duel is byte-identical afterwards. |
|
||||
| `get_registry_value` | `int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf)` | Upstream (koishi) |
|
||||
| `set_registry_value` | `void set_registry_value(intptr_t pduel, const char* key, const char* value)` | Upstream (koishi). The server writes every setup pair here before `special.lua` (patch 0009). |
|
||||
| `get_registry_keys` | `int32_t get_registry_keys(intptr_t pduel, byte* out_buf)` | Upstream (koishi) |
|
||||
@@ -128,7 +133,7 @@ The host string is space-separated tokens, in this order (`server/gframe/gframe.
|
||||
|
||||
Locations the sandbox exports accept: DECK, HAND, MZONE, SZONE, GRAVE, REMOVED, EXTRA.
|
||||
|
||||
Export count on Windows: 3 server + 42 core = 45 contract exports, + 289 `sqlite3_*` = 334. The
|
||||
Export count on Windows: 3 server + 44 core = 47 contract exports, + 289 `sqlite3_*` = 336. The
|
||||
Unity repo's old `ygoserver.dll` had 327: its own core copy never carried patch 0008, and it had no
|
||||
`ygol_engine_version`.
|
||||
|
||||
@@ -161,14 +166,18 @@ the server itself speaks. The STOC form of a relayed message is always the CTOS
|
||||
stamp in front. "Stamp" in the tables below says whether the STOC message carries one.
|
||||
|
||||
**Capability.** The server sends `STOC_CAPABILITY` (stamp `0xFF`) to every connection between
|
||||
`STOC_JOIN_GAME` and `STOC_TYPE_CHANGE`: `protocol` = `FEATURE_PROTOCOL` (8) and `flags` = the OR of
|
||||
the bits below (`0x7FF`). A client sends its own `CTOS_CAPABILITY` after joining. A client refuses a
|
||||
host without bit `0x4` as out of date.
|
||||
`STOC_JOIN_GAME` and `STOC_TYPE_CHANGE`: `protocol` = `FEATURE_PROTOCOL` (12) and `flags` = the OR of
|
||||
the bits below (`0xF7FF`). A client sends its own `CTOS_CAPABILITY` after joining. A client refuses a
|
||||
host without bit `0x4` as out of date, and without bit `0x1000` too (v1.5.0). A Tag room refuses a
|
||||
client whose `CTOS_CAPABILITY` lacks `0x1000` or `0x4000` (v1.6.0): `STOC_ERROR_MSG` `ERRMSG_VERERROR`
|
||||
(code = `FEATURE_PROTOCOL`), then the connection is closed; a Single room keeps it. No room refuses a client
|
||||
without `0x8000` (v1.7.0): it just never gets `STOC_PROMPT_CONTEXT`.
|
||||
|
||||
**Join snapshot.** A joiner gets, per occupied seat, right after that seat's `STOC_HS_PLAYER_ENTER`:
|
||||
the seat's stored capability, appearance (0006), seat state (0013) and profile (0020) when present,
|
||||
then the setup pairs (0009), the seat plan (0011) if one was ever sent, and, during a duel, the field
|
||||
resync (0005) and the deck lists the audience may see (0019).
|
||||
resync (0005), the deck lists the audience may see (0019) and the Tag partner cards: a seated
|
||||
duelist's own side (v1.2.0), both sides for an observer when spectators see all (v1.3.0).
|
||||
|
||||
### Client to server
|
||||
|
||||
@@ -198,6 +207,7 @@ resync (0005) and the deck lists the audience may see (0019).
|
||||
| `0x41` | `STOC_APPEARANCE` | `u16 sender` + `CTOS_Appearance` (354) | Yes | Everyone; stored per seat, replayed to joiners, dropped when the seat empties or moves to the watchers | `0x1` | 1 | 0006 |
|
||||
| `0x42` | `STOC_DIALOGUE` | `u16 sender` + `CTOS_Dialogue` (206) | Yes | Everyone | `0x2` | 1 | 0006 |
|
||||
| `0x43` | `STOC_SETUP_PAIRS` | `u16 0xFF`, `u16 count`, then per pair `u16 length` + `key=value` bytes (no terminator) | Yes (`0xFF`) | Every joiner, in the snapshot | `0x4` | 1 | 0009 |
|
||||
| `0x44` | `STOC_PROMPT_CONTEXT` | The 23 `ygol_query_prompt_context` bytes (section (a)) + `u8 prompt` (the `MSG_*` id of the prompt it belongs to); 24 bytes | No | The seat that answers the prompt (Tag: the team's current hand), and only when its `CTOS_CAPABILITY` had `0x8000`; the packet right before that prompt's `STOC_GAME_MSG`. Sent before every prompt the server relays but `MSG_ROCK_PAPER_SCISSORS`: `MSG_SELECT_BATTLECMD`, `IDLECMD`, `EFFECTYN`, `YESNO`, `OPTION`, `CARD`, `TRIBUTE`, `UNSELECT_CARD`, `CHAIN`, `PLACE`, `DISFIELD`, `POSITION`, `COUNTER`, `SUM`, `MSG_SORT_CARD`, `MSG_ANNOUNCE_RACE`, `ATTRIB`, `CARD`, `NUMBER`. A prompt with no effect running gets `has_effect` 0, so a client never keeps a stale context. Never to observers, the waiting Tag partner or the server-mode recorders, never in a replay; a `MSG_RETRY` re-ask gets none (the context still stands) | `0x8000` | 12 | v1.7.0 |
|
||||
| `0x50` | `STOC_SEAT_PLAN` | `u16 0xFF` + `STOC_SeatPlan` (23): `u8 restart_id[16]`, `u16 revision`, `u8 seat_count`, `u8 kind[4]` (25 total; no token on the wire) | Yes (`0xFF`) | Everyone after a plan, swap or move; joiners in the snapshot | `0x8` | 2 | 0011 |
|
||||
| `0x54` | `STOC_ROOM_RESTARTING` | `u16 0xFF` + `STOC_RoomRestarting` (38): `u8 phase` (1 Prepare, 2 Commit, 3 Abort), `u8 restart_id[16]`, `u8 seat`, `u8 token[16]`, `u32 timeout_ms` | Yes (`0xFF`) | Each participant, with ITS OWN seat and token only | `0x10` | 2 | 0012 |
|
||||
| `0x56` | `STOC_RESTART_STATUS` | `u16 0xFF` + `STOC_RestartStatus` (21): `u8 phase`, `u8 restart_id[16]`, `u8 acked`, `u8 expected`, `u8 complete`, `u8 reason` (0 none, 1 incompatible, 2 ack timeout, 3 not lobby, 4 not host, 5 busy, 6 bad request) | Yes (`0xFF`) | The host only | `0x10` | 2 | 0012 |
|
||||
@@ -209,6 +219,7 @@ resync (0005) and the deck lists the audience may see (0019).
|
||||
| `0x5C` | `STOC_DECK_LIST` | `STOC_DeckList` (5): `u8 version` (1), `u8 side`, `u8 kind`, `u16 count`, then `u32 codes[count]` | No | Kind 0 (the deck's remaining cards, SORTED) to its owner (both teammates in Tag); kind 1 (real order, top first) and kind 2 (the submitted Main Deck of the duelist whose deck is in the zone, sorted) to observers only when spectators see all. Sent when a list differs from the last one that audience got; in the late-watcher snapshot | `0x100` | 6 | 0019 |
|
||||
| `0x5D` | `STOC_PROFILE` | `u16 sender` + `CTOS_Profile` (100) | Yes | Everyone; stored per seat, in the snapshot after APPEARANCE, swapped with the seat, kept across the 0014 lobby reset, cleared when the seat empties | `0x200` | 7 | 0020 |
|
||||
| `0x5E` | `STOC_ATTACK_PREVIEW` | `u8 version` (1), `u8 count`, then per pair the 4 ask bytes echoed + the 24-byte `ygol_preview_attack` answer | No | The asker only. Only attackers the open prompt listed; a pair the engine refuses is left out (the count shrinks); a valid ask whose every pair is left out still gets count 0 | `0x400` | 8 | 0023 |
|
||||
| `0x5F` | `STOC_TAG_PARTNER_CARDS` | `u8 side` + the `ygol_query_tag_cards` bytes (7 + 4 x the three counts) | No | The two seats of `side`, never the other team. Sent after `start_duel` (the waiting members' opening hands), after every `MSG_TAG_SWAP` for the side that swapped (the member that just left is the waiting one), and to a seated duelist in its field resync (`CTOS_REQUEST_FIELD`, after the `MSG_RELOAD_FIELD`). **v1.3.0 (TICKET-412): when spectators see all (no `ygol.room.spectatorview=hidden`), every observer gets the same bytes for BOTH sides at the start and after every swap, and an observer's field resync and a late watcher's snapshot carry both sides (after the deck lists); with the pair, an observer never gets one.** **v1.4.2 (TICKET-424): after every engine batch (beside the deck lists, not when the duel ended), a side whose bytes differ from the last ones broadcast for it is sent again to the same receivers (an effect that moves a waiting member's card mid-turn); every broadcast records its bytes, so a swap is never sent twice; a resync to one player does not record.** Tag rooms only; a Single / Match room never sends it | `0x2000` | 9 | v1.2.0, v1.3.0, v1.4.2 |
|
||||
|
||||
### Capability bits and protocol numbers
|
||||
|
||||
@@ -225,6 +236,13 @@ resync (0005) and the deck lists the audience may see (0019).
|
||||
| `0x100` | `FEATURE_DECK_LIST` | 6 | 0019 | Deck lists |
|
||||
| `0x200` | `FEATURE_PROFILE` | 7 | 0020 | Profile |
|
||||
| `0x400` | `FEATURE_ATTACK_PREVIEW` | 8 | 0023 | Attack preview over the wire |
|
||||
| `0x800` | reserved | - | - | Proposal 44 (agreed, not shipped) |
|
||||
| `0x1000` | `FEATURE_TAG_TWO_FIELDS` | 10 | v1.5.0 | Tag two Field slots: Spell/Trap sequence 6 is a team's second Field Zone (no message); a Tag room refuses a joiner without it |
|
||||
| `0x2000` | `FEATURE_TAG_PARTNER_CARDS` | 9 | v1.2.0 | Tag partner cards (`STOC_TAG_PARTNER_CARDS`, `ygol_query_tag_cards`) |
|
||||
| `0x4000` | `FEATURE_TAG_SHARED_EXTRA` | 11 | v1.6.0 | Tag shared Extra Deck: the setup pair `ygol.tag.extra=shared`, `QUERY_TAG_MEMBER` on Extra Deck refreshes; a Tag room refuses a joiner without it |
|
||||
| v1.7.1 | A card read with a `rule_code` (a distant cdb alias) is a member of its OWN setcodes as well as those of the card it names: `Card.IsSetCard`, `Card.IsPreviousSetCard` and `Card.IsSummonSetCard` check `data.setcode` while the card bears its own `rule_code` (`card::check_code_setcode`). A card renamed by `EFFECT_CHANGE_CODE` answers from the new name only, as stock. No new message, no capability bit. |
|
||||
| v1.7.2 | In Tag on Master Rule 4/5 a Field Spell that lands while the playing partner's Field slot is taken and the other partner's is free takes the free slot (`field::get_fzone_landing`); with both taken it replaces the playing partner's. Before, only a card that changed control took the free slot, so a partner who played the team's two Fields one after the other lost the first. No new export, message or bit; protocol 12. |
|
||||
| `0x8000` | `FEATURE_PROMPT_CONTEXT` | 12 | v1.7.0 | Prompt context (`STOC_PROMPT_CONTEXT`, `ygol_query_prompt_context`): which card and which effect asks; no room refuses a joiner without it |
|
||||
|
||||
`FEATURE_PROTOCOL` is bumped by every patch that adds a message a client must understand; the join
|
||||
list hides hosts older than the client's number. Rule 4 (proposal 47): one feature, one door. Never
|
||||
@@ -240,6 +258,11 @@ carry a new feature inside another feature's message.
|
||||
| 0016 | Tag: team B is loaded as seat 2 main deck + seat 3 tag deck, the prompt owner starts at seat 2; with core patch 0015 the turn order is seat 0, 2, 1, 3. |
|
||||
| 0018 | Spectators see all: every observer gets the UNMASKED stream (both hands, draws, set cards, extra, banished, the 0005 snapshot) unless the setup pair `ygol.room.spectatorview=hidden` is present, which restores the stock masked stream byte for byte. Duelists' streams never change. |
|
||||
| 0021 | START ends a rules-restart reservation window and stops the lobby clock, so an untimed duel no longer ends at once on "time limit up". |
|
||||
| v1.1.1 | Tag: no Battle Phase on turns 1, 2 and 3 (1A, 2A, 1B); the fourth duelist (2B) is the first who can battle. `MSG_SELECT_IDLECMD` carries `to_bp` = 0 on those turns and `Duel.IsAbleToEnterBP` answers false. Single duels: turn 1 only, as stock. |
|
||||
| v1.3.0 | Tag partner cards reach observers: when spectators see all, `STOC_TAG_PARTNER_CARDS` goes to every observer for both sides at every send point, plus both sides in an observer's resync and the late-watcher snapshot. Same id, same payload, no new capability bit (TICKET-412). |
|
||||
| v1.4.0 | Life points per side: with the setup pair `ygol.side.b.lp=<n>` (section (d)) seat side B (seat 1; Tag seats 2 and 3) starts at `n` LP and side A at slot 8; without it both sides start at slot 8, as before. `set_player_info` gets each duel player its own LP, and `MSG_START` (the start and the late-watcher snapshot) carries `lp[0]`, `lp[1]` in duel player order: the side that goes first is player 0, so the two values swap when side B won the toss. `STOC_JOIN_GAME`'s `start_lp` stays side A's. Single, Match (every duel) and Tag; no new message, no capability bit. |
|
||||
| v1.5.0 | Tag two Field slots (proposal 45, TICKET-384; core `field::has_two_fields` = `DUEL_TAG_MODE` on Master Rule 4 or 5): a team has a Field slot per partner, Spell/Trap sequence 5 for the partner who plays the team's first turn and 6 for the other (`player_info::tag_partner` flips in `tag_swap`). A Field Spell that lands (activated, Set, `Duel.MoveToField` to `LOCATION_FZONE`) goes to the playing partner's slot and replaces only the card there; while that slot is taken and the other is free it takes the free one (since v1.7.2; before, only a card that changed control did). A Set opens only the landing slot's bit in `MSG_SELECT_PLACE`. `LOCATION_FZONE` covers both slots (`Card.IsLocation`, `Duel.GetMatchingGroup` and the other filters, `Duel.IsEnvironment`, `Duel.CheckLocation(p, LOCATION_FZONE, 0/1)`), `Duel.GetFieldCard(p, LOCATION_FZONE, 0)` is the playing partner's field, else the other one, and sequence 1 the remaining one; `Duel.GetFieldCard(p, LOCATION_SZONE, 6)` works. The second field reaches a client as `MSG_MOVE` to Spell/Trap sequence 6 and in `MSG_RELOAD_FIELD`'s sixth Spell/Trap entry: no new message. Singles, Match and Master Rule 3 (where slot 6 is a Pendulum Zone) are unchanged. Scripts that name Spell/Trap sequence 5 by number see one field (the TICKET-384 closing note lists them). Capability `0x1000`, protocol 9 -> 10. |
|
||||
| v1.6.0 | Tag shared Extra Deck (proposal 53, TICKET-433): with the setup pair `ygol.tag.extra=shared` (section (d)) `TagDuel` sets the duel option `DUEL_TAG_SHARED_EXTRA` `0x200`. `start_duel` moves each team's `tag_list_extra` into `list_extra` (the first partner's cards first) and renumbers the sequences, so either partner can Summon any of the cards; `tag_swap` leaves the Extra Deck alone, `MSG_TAG_SWAP` keeps its layout and sends the one list, and `ygol_query_tag_cards` / `0x5F` report an Extra count of 0. The opening `MSG_START` carries the sum of both partners' Extra Decks, and the opening Extra Deck refreshes run after `start_duel`. The core has one `owner` per team, so each card has `card::tag_member`, set once when it is loaded (0 `new_card`, 1 `new_tag_card`), and `RefreshExtra` adds `QUERY_TAG_MEMBER` to its flag in such a duel (section (c), Query records). Replays need no format change: `opt` holds the option and every reader passes `opt` to `start_duel`; a reader that writes its own `MSG_START` before `start_duel` must add the partner's Extra count. An older engine ignores the option and plays such a replay wrongly. Without the pair every stream is unchanged. Capability `0x4000`, protocol 10 -> 11. |
|
||||
|
||||
### Replay
|
||||
|
||||
@@ -248,15 +271,21 @@ carries, before the player names, `u32 length` + the setup pairs block (`u16 cou
|
||||
`u16 length` + `key=value`). Limits: `SETUP_PAIRS_MAX` 64 pairs, `SETUP_PAIR_MAX_LEN` 512 bytes per
|
||||
pair.
|
||||
|
||||
v1.4.0 adds the replay flag `REPLAY_YGOL_SIDE_LP` = `0x20000000`, set only when the two duel players
|
||||
start with different LP (`ygol.side.b.lp`). When set, `i32 lp[0]` + `i32 lp[1]` (duel player order)
|
||||
follow the stock `opt` field, before the decks; a reader without the flag keeps the stock layout and
|
||||
gives both players the header's `start_lp`.
|
||||
|
||||
## (c) Engine message stream
|
||||
|
||||
`process` + `get_message` hand the consumer a buffer of messages; each is `u8 id` + payload. The
|
||||
server relays them to clients inside `STOC_GAME_MSG` (`0x1`), masking the other side's hidden cards.
|
||||
The table is the one the Unity bot host reads (`LocalDuelHost.Scan`,
|
||||
`Assets/YGOLegacy/Scripts/Core/Bot/LocalDuelHost.cs`); the ids are `MSG_*` in `core/common.h`.
|
||||
The table is the one `MessageScan.Scan` in the C# binding reads (section (e)); the ids are `MSG_*` in
|
||||
`core/common.h`, the enum `GameMessage`.
|
||||
`n` = a count byte read at that point; "prompt" = the engine waits for `set_responsei` /
|
||||
`set_responseb` from `player`. **The fork adds NO message id and changes NO layout**; the only
|
||||
fork-related rows are marked.
|
||||
fork-related rows are marked. The prompt context (v1.7.0) is read beside the stream through
|
||||
`ygol_query_prompt_context` while the engine is parked on a prompt; no message carries it.
|
||||
|
||||
| Id | Name | Payload length rule | Prompt |
|
||||
|---|---|---|---|
|
||||
@@ -347,7 +376,7 @@ fork-related rows are marked.
|
||||
| 142 | `MSG_ANNOUNCE_CARD` | `u8 player`; `n` x 4 | yes |
|
||||
| 143 | `MSG_ANNOUNCE_NUMBER` | `u8 player`; `n` x 4 | yes |
|
||||
| 160 | `MSG_CARD_HINT` | 9 | - |
|
||||
| 161 | `MSG_TAG_SWAP` | `u8 player`, `u8 main count`, `u8 extra count`, `u8 extra pendulum count`, `u8 hand count`, `u32 top code`, then `u32` x hand, `u32` x extra. Not in `Scan` (the bot host never runs Tag). **Fork (core patch 0015): never emitted on a team's first turn; the first swap comes on turn 3 or later.** | - |
|
||||
| 161 | `MSG_TAG_SWAP` | `u8 player`, `u8 main count`, `u8 extra count`, `u8 extra pendulum count`, `u8 hand count`, `u32 top code`, then `u32` x hand, `u32` x extra. Not in `Scan` (the bot host never runs Tag). **Fork (core patch 0015): never emitted on a team's first turn; the first swap comes on turn 3 or later. v1.2.0: the server follows every swap with `STOC_TAG_PARTNER_CARDS` to the swapping side's two seats; v1.3.0: and to every observer when spectators see all. v1.4.1 (TICKET-415): a card an effect moves out of the waiting member's hand, deck or Extra Deck (one it kept across the swap, e.g. Time Fusion's Fusion) leaves that list, so the next swap lists one card fewer; its `MSG_MOVE` `from` sequence counts into the waiting list, not the active one.** | - |
|
||||
| 162 | `MSG_RELOAD_FIELD` | `u8 duel rule`; per player: `u32 lp`, 7 monster zones (`u8 present`, +2 when present), 8 spell zones (`u8 present`, +1 when present), 6 count bytes; then ONE chain block `n` x 15 after both players. Produced by `query_field_info` and `Debug.ReloadFieldEnd()`; the server sends it as the 0005 field resync | - |
|
||||
| 163 | `MSG_AI_NAME` | `u16 len` + bytes + 1 | - |
|
||||
| 164 | `MSG_SHOW_HINT` | `u16 len` + bytes + 1 | - |
|
||||
@@ -359,6 +388,21 @@ fork-related rows are marked.
|
||||
Ids 6, 7 and 34 are server-side (`network.h`); the core's `common.h` lists the rest. Any other id is
|
||||
an error for the consumer.
|
||||
|
||||
### Query records
|
||||
|
||||
`query_card`, `query_field_card` and the query buffer of `MSG_UPDATE_DATA` / `MSG_UPDATE_CARD` hold one
|
||||
record per card: `i32 length`, `u32 flag`, then one value per set `QUERY_*` bit in bit order, the bits
|
||||
in `core/common.h`. The fork adds one bit:
|
||||
|
||||
| Bit | Name | Value | Since |
|
||||
|---|---|---|---|
|
||||
| `0x1000000` | `QUERY_TAG_MEMBER` | `u32`, written LAST, after `QUERY_LINK`: the partner who brought the card, 0 from `new_card`, 1 from `new_tag_card`. It never changes when the card moves. The core writes it for any caller that sets the bit; the server sets it only on `RefreshExtra` in a duel with `ygol.tag.extra=shared` | v1.6.0 |
|
||||
|
||||
**Bit `0x100000` stays unused.** Old flags set it with no value after it: `RefreshSingle`'s default
|
||||
`0xf81fff`, the hand refresh `0x181fff` and YGOSharp's `0xFFFFFF` mask, and saved `.yrp3d` replays are
|
||||
recorded streams of them. A value for that bit would shift every later field of those records, with no
|
||||
error.
|
||||
|
||||
## (d) Setup pairs and the Lua API
|
||||
|
||||
### Setup pairs (patch 0009, TICKET-258; ADR 0004 in the Unity repo)
|
||||
@@ -370,12 +414,14 @@ never interprets a pair: it stores the ordered list (max 64 pairs, 512 bytes eac
|
||||
`0x40000000`) and sends them to every joiner as `STOC_SETUP_PAIRS` (`0x43`). Values that need `,`,
|
||||
`=`, `%` or a space are percent-encoded by the client (`MatchSetup.cs`).
|
||||
|
||||
Two pairs ARE read by the server itself:
|
||||
Four pairs ARE read by the server itself:
|
||||
|
||||
| Key | Value | Read by |
|
||||
|---|---|---|
|
||||
| `ygol.room.watchers` | `0` = no observers: every observer join and HsToObserver is refused | 0012 |
|
||||
| `ygol.room.spectatorview` | `hidden` = the stock masked observer stream; absent = spectators see all | 0018, 0019 |
|
||||
| `ygol.side.b.lp` | a positive integer: seat side B's start LP (seat 1; Tag seats 2 and 3); side A keeps slot 8. Absent, `0`, negative or not a number = both sides at slot 8 | v1.4.0 |
|
||||
| `ygol.tag.extra` | `shared` = a Tag team has one Extra Deck (option `0x200`, section (b) v1.6.0); anything else or absent = separate Extra Decks. A Single or Match room ignores it | v1.6.0 |
|
||||
|
||||
Keys the Unity client sends today (`Assets/YGOLegacy/Scripts/Core/Duel/MatchSetup.cs`,
|
||||
`SetupPairKeys`); the rules Lua reads them from the registry:
|
||||
@@ -396,4 +442,103 @@ into `contract/lua-reference/`: `api-card.md`, `api-duel.md`, `api-effect.md`, `
|
||||
the core sets). A name that is not there is not in the core; the card scripts' `library/` defines the
|
||||
rest. Regenerate with `python contract/lua-reference/generate.py` after any core change to those
|
||||
files and commit the result with it. The fork's core patches add no Lua function (0001 adds the
|
||||
setcode `0xFDF`, `SETCODE_FACEDOWN_TOKEN`, as a cdb convention, not an API).
|
||||
setcode `0xFDF`, `SETCODE_FACEDOWN_TOKEN`, as a cdb convention, not an API). v1.5.0 gives two
|
||||
existing calls a second answer in Tag on Master Rule 4/5: `Duel.GetFieldCard(p, LOCATION_FZONE, 1)`
|
||||
is the other partner's field and `Duel.CheckLocation(p, LOCATION_FZONE, 1)` asks about its slot
|
||||
(both say nothing elsewhere, as before).
|
||||
|
||||
## (e) C# binding
|
||||
|
||||
The managed side of the engine ships in the same release as the native libraries: the asset
|
||||
`ygol-engine-binding.zip` holds `YGOLegacy.Engine.dll` and `YGOLegacy.Engine.pdb`, built from
|
||||
`binding/YGOLegacy.Engine/` (`netstandard2.1`, LangVersion 9, unsafe allowed, no package and no Unity
|
||||
reference) and tested by `binding/YGOLegacy.Engine.Tests/` (`net8.0`, NUnit) in the release workflow's
|
||||
`windows` job. Unity, the Tools and the server repo's card-tester consume this DLL instead of their own
|
||||
copies of the sources.
|
||||
|
||||
Namespaces:
|
||||
|
||||
| Namespace | What |
|
||||
|---|---|
|
||||
| `YGOLegacy.Protocol.{Contracts, Codecs, Framing, Routing}` | Section (b) in C#: the message ids and payload records, the CTOS / STOC codecs, the frame codec and the STOC router. Unchanged from the Unity repo (TICKET-397); v1.2.0 adds `StocMessage.TagPartnerCards`, `FeatureFlags.TagPartnerCards`, the `TagPartnerCards` record and `StocCodecs.TagPartnerCards`, and `Capability.ProtocolVersion` is 9; v1.4.0 adds `ReplayFlags` (`SetupPairs` = `0x40000000`, `SideLp` = `0x20000000`); v1.5.0 adds `FeatureFlags.TagTwoFields` (`0x1000`, in `All`) and `Capability.ProtocolVersion` is 10; v1.6.0 adds `FeatureFlags.TagSharedExtra` (`0x4000`, in `All`) and `Capability.ProtocolVersion` is 11; v1.7.0 adds `StocMessage.PromptContext` (`0x44`), `FeatureFlags.PromptContext` (`0x8000`, in `All`), the `PromptContext` record (`HasEffect`, `Code`, `Controller`, `Location`, `Sequence`, `Position`, `Description`, `EffectIndex`, `Phase`, `ChainLink`, `AnnounceKind`, `Prompt`, `IsHidden`, `None(prompt)`, `UnknownIndex` `0xFFFF`, `PhaseCost` / `PhaseTarget` / `PhaseOperation` / `PhaseAsk` 1 / 2 / 3 / 4, `AnnouncePlain` / `AnnounceLevel` / `AnnounceDice` 0 / 1 / 2) and `StocCodecs.PromptContext` (`PromptContextCodec`, 24 bytes), and `Capability.ProtocolVersion` is 12. |
|
||||
| `YGOLegacy.Engine` | The four types below (TICKET-398). |
|
||||
|
||||
| Type | What |
|
||||
|---|---|
|
||||
| `EngineApi` | `public static unsafe class`: one `DllImport("ygol-engine", Cdecl)` extern per export of section (a), C names kept, no overloads; the delegates `ScriptReader`, `CardReader`, `MessageHandler` (`UnmanagedFunctionPointer(Cdecl)`) beside it. `[MonoPInvokeCallback]` belongs on the consumer's callback methods (IL2CPP), not here. |
|
||||
| `MessageScan` | `public static class`: the section (c) layout scanner, moved from the Unity bot host (`LocalDuelHost`) with its bodies unchanged. `MsgInfo` (player, prompt, to-player-only, new-turn), `Scan(byte[] b, ref int pos, int id, int len)` (advances `pos` past one message and says who may see it; throws on an unknown id or an overrun), `Blank(id, msg, info, recipient)` (hidden-information blanking per recipient for `MSG_SHUFFLE_HAND`, `MSG_SHUFFLE_EXTRA`, `MSG_DRAW`, `MSG_MOVE`, `MSG_SET`), `BlankPileCodes(buf, all)` (zeroes the `QUERY_CODE` field of query records) and `PromptName(id)`. |
|
||||
| `GameMessage` | `public enum GameMessage : byte`: one member per `#define MSG_<NAME> <n>` in `core/common.h` (84), member = PascalCase of `<NAME>` (`MSG_SELECT_BATTLECMD` -> `SelectBattlecmd`), value = `<n>`. `GameMessageParityTests` parses the header and fails on a missing, extra or renumbered id. The commented-out defines (`MSG_WAITING`, `MSG_START`, `MSG_UPDATE_DATA`, ...) are not members. |
|
||||
| `EngineBinding` | `public const string Version` (the tag the DLL was built for, `local` when none; generated at build from the `EngineVersion` property) and `public static string CheckNative()`: returns `ygol_engine_version()` when it equals `Version`, else throws `InvalidOperationException` naming both strings. |
|
||||
|
||||
### `EngineApi` externs
|
||||
|
||||
Every row is one export of section (a) with its managed signature. A `string` parameter is
|
||||
`[MarshalAs(UnmanagedType.LPUTF8Str)]`.
|
||||
|
||||
| Export | Managed signature |
|
||||
|---|---|
|
||||
| `set_script_reader` | `void set_script_reader(ScriptReader f)` |
|
||||
| `set_card_reader` | `void set_card_reader(CardReader f)` |
|
||||
| `set_message_handler` | `void set_message_handler(MessageHandler f)` |
|
||||
| `create_duel` | `IntPtr create_duel(uint seed)` |
|
||||
| `create_duel_v2` | `IntPtr create_duel_v2(uint[] seed_sequence)` |
|
||||
| `create_duel_ex` | `IntPtr create_duel_ex(uint seed, uint create_flags)` |
|
||||
| `create_duel_v2_ex` | `IntPtr create_duel_v2_ex(uint[] seed_sequence, uint create_flags)` |
|
||||
| `start_duel` | `void start_duel(IntPtr pduel, uint options)` |
|
||||
| `end_duel` | `void end_duel(IntPtr pduel)` |
|
||||
| `set_player_info` | `void set_player_info(IntPtr pduel, int playerid, int lp, int startcount, int drawcount)` |
|
||||
| `get_log_message` | `void get_log_message(IntPtr pduel, byte[] buf)` |
|
||||
| `get_message` | `int get_message(IntPtr pduel, byte[] buf)` |
|
||||
| `process` | `uint process(IntPtr pduel)` |
|
||||
| `new_card` | `void new_card(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position)` |
|
||||
| `new_tag_card` | `void new_tag_card(IntPtr pduel, uint code, byte owner, byte location)` |
|
||||
| `query_card` | `int query_card(IntPtr pduel, byte playerid, byte location, byte sequence, uint query_flag, byte[] buf, int use_cache)` |
|
||||
| `query_field_count` | `int query_field_count(IntPtr pduel, byte playerid, byte location)` |
|
||||
| `query_field_card` | `int query_field_card(IntPtr pduel, byte playerid, byte location, uint query_flag, byte[] buf, int use_cache)` |
|
||||
| `query_field_info` | `int query_field_info(IntPtr pduel, byte[] buf)` |
|
||||
| `set_responsei` | `void set_responsei(IntPtr pduel, int value)` |
|
||||
| `set_responseb` | `void set_responseb(IntPtr pduel, byte[] buf)` |
|
||||
| `preload_script` | `int preload_script(IntPtr pduel, string script_name)` |
|
||||
| `default_script_reader` | `IntPtr default_script_reader(string script_name, int* len)` |
|
||||
| `ygol_preview_attack` | `int ygol_preview_attack(IntPtr pduel, byte playerid, byte location, byte sequence, byte target_location, byte target_sequence, byte[] @out)` |
|
||||
| `ygol_query_tag_cards` | `int ygol_query_tag_cards(IntPtr pduel, byte playerid, byte[] @out)` |
|
||||
| `ygol_query_prompt_context` | `int ygol_query_prompt_context(IntPtr pduel, byte playerid, byte[] @out)` |
|
||||
| `get_registry_value` | `int get_registry_value(IntPtr pduel, string key, byte[] out_buf)` |
|
||||
| `set_registry_value` | `void set_registry_value(IntPtr pduel, string key, string value)` |
|
||||
| `get_registry_keys` | `int get_registry_keys(IntPtr pduel, byte[] out_buf)` |
|
||||
| `clear_registry` | `void clear_registry(IntPtr pduel)` |
|
||||
| `dump_registry` | `int dump_registry(IntPtr pduel, byte[] out_buf)` |
|
||||
| `load_registry` | `void load_registry(IntPtr pduel, byte[] in_buf, int in_len)` |
|
||||
| `get_lua_coverage_dump_size` | `int get_lua_coverage_dump_size(IntPtr pduel, string name)` |
|
||||
| `dump_lua_coverage` | `int dump_lua_coverage(IntPtr pduel, string name, byte[] out_buf, int out_len)` |
|
||||
| `get_all_lua_coverages_dump_size` | `int get_all_lua_coverages_dump_size(IntPtr pduel)` |
|
||||
| `dump_all_lua_coverages` | `int dump_all_lua_coverages(IntPtr pduel, byte[] out_buf, int out_len)` |
|
||||
| `clear_lua_coverage` | `void clear_lua_coverage(IntPtr pduel, string name)` |
|
||||
| `clear_all_lua_coverages` | `void clear_all_lua_coverages(IntPtr pduel)` |
|
||||
| `ygol_sb_add` | `int ygol_sb_add(IntPtr pduel, uint code, byte owner, byte playerid, byte location, byte sequence, byte position)` |
|
||||
| `ygol_sb_move` | `int ygol_sb_move(IntPtr pduel, byte playerid, byte location, byte sequence, byte dst_playerid, byte dst_location, byte dst_sequence, byte position)` |
|
||||
| `ygol_sb_remove` | `int ygol_sb_remove(IntPtr pduel, byte playerid, byte location, byte sequence)` |
|
||||
| `ygol_sb_set_position` | `int ygol_sb_set_position(IntPtr pduel, byte playerid, byte location, byte sequence, byte position)` |
|
||||
| `ygol_sb_set_lp` | `int ygol_sb_set_lp(IntPtr pduel, byte playerid, int lp)` |
|
||||
| `ygol_sb_reask` | `int ygol_sb_reask(IntPtr pduel)` |
|
||||
| `start_server` | `int start_server(string args)` |
|
||||
| `stop_server` | `void stop_server()` |
|
||||
| `ygol_engine_version` | `IntPtr ygol_engine_version()` |
|
||||
|
||||
Delegates: `IntPtr ScriptReader(string script_name, int* len)`, `uint CardReader(uint code, IntPtr data)`
|
||||
(`data` is the `card_data*` the core wants filled), `uint MessageHandler(IntPtr pduel, uint msg_type)`.
|
||||
|
||||
**Type rule** (the header has no wide string, so `CharSet.Unicode` appears nowhere): `intptr_t` ->
|
||||
`IntPtr`; `int32_t` / `int` -> `int`; `uint32_t` -> `uint`; `uint8_t` -> `byte`; `uint_fast32_t` ->
|
||||
`uint` (32-bit on MSVC x64, 64-bit on glibc x64; the register is zero-extended); `byte*`, `char* buf`,
|
||||
`uint8_t* out`, `const byte*` -> `byte[]`; `uint32_t seed_sequence[]` -> `uint[]`; `const char*` in ->
|
||||
`string` with `LPUTF8Str`; `const char*` out (`ygol_engine_version`) and `byte*` out
|
||||
(`default_script_reader`) -> `IntPtr`; `int*` -> `int*`; `card_data*` -> `IntPtr`; function pointers ->
|
||||
the delegates. `EngineApiParityTests` parses `contract/ocgapi.h` and fails when a header export has no
|
||||
extern of that name or an extern has no header line.
|
||||
|
||||
**Version rule.** The binding's version is the engine tag: `EngineBinding.Version` = `engine.json`'s
|
||||
`binding` = `engine.json`'s `version` = `ygol_engine_version()`, all the same string for one release. A
|
||||
consumer calls `EngineBinding.CheckNative()` once at start and treats the exception as "fetch the engine
|
||||
release whose tag equals the binding version". The native libraries and the binding are released
|
||||
together even when only one of them changed.
|
||||
@@ -83,6 +83,23 @@ OCGCORE_API byte* default_script_reader(const char* script_name, int* len);
|
||||
// the duel is byte-identical afterwards (proposal 43).
|
||||
OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_t location, uint8_t sequence, uint8_t target_location, uint8_t target_sequence, uint8_t* out);
|
||||
|
||||
// [YGOL] v1.2.0 (tag partner cards, TICKET-405): the waiting tag partner's cards of playerid's side, read
|
||||
// only. out: version (1), hand count, extra count, one pad byte, uint16 deck count, then the uint32 hand
|
||||
// codes, the uint32 extra codes (bit 31 = face-up, like MSG_TAG_SWAP) and the uint32 deck codes sorted
|
||||
// ascending (the order stays secret). Returns the byte length, 0 refused (bad pointer, bad player, not a
|
||||
// tag duel); a refusal writes nothing. The duel is byte-identical afterwards (proposal 33 Rule 11).
|
||||
OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out);
|
||||
|
||||
// [YGOL] v1.7.0 (prompt context, TICKET-451): which effect asks the prompt the engine is parked on, read only.
|
||||
// playerid = the answering player. out (23 bytes): version (1), has_effect, uint32 code (the handler's current
|
||||
// code), controller, location, sequence, position, uint64 description, uint16 effect_index (the order the
|
||||
// card's script registered the effect in initial_effect; 0xffff unknown), phase (1 cost, 2 target, 3 operation, 4 the core asks whether to use the effect),
|
||||
// chain link (0 none), announce kind (MSG_ANNOUNCE_NUMBER only: 1 Duel.AnnounceLevel, 2 the effect has
|
||||
// CATEGORY_DICE and is visible, else 0). has_effect 0 = no effect runs: every other byte 0 but announce kind, effect_index 0xffff. A
|
||||
// handler playerid does not control and that is not face-up writes code 0, effect_index 0xffff, description 0.
|
||||
// Returns 23, 0 refused (bad pointer, bad player); a refusal writes nothing.
|
||||
OCGCORE_API int32_t ygol_query_prompt_context(intptr_t pduel, uint8_t playerid, uint8_t* out);
|
||||
|
||||
// koishi specific
|
||||
OCGCORE_API int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf);
|
||||
OCGCORE_API void set_registry_value(intptr_t pduel, const char* key, const char* value);
|
||||
|
||||
+1448
-10
File diff suppressed because it is too large.
Load diff
+24
-22
@@ -67,7 +67,8 @@ uint32_t card::get_summon_info() {
|
||||
}
|
||||
|
||||
bool card_state::is_location(uint32_t loc) const {
|
||||
if((loc & LOCATION_FZONE) && location == LOCATION_SZONE && sequence == 5)
|
||||
// [YGOL] proposal 45: slot 6 is the second Field slot in Tag (Master Rule 4/5); a Master Rule 3 Pendulum Zone card there has pzone set
|
||||
if((loc & LOCATION_FZONE) && location == LOCATION_SZONE && (sequence == 5 || (sequence == 6 && !pzone)))
|
||||
return true;
|
||||
if((loc & LOCATION_PZONE) && location == LOCATION_SZONE && pzone)
|
||||
return true;
|
||||
@@ -178,6 +179,13 @@ bool card::check_card_setcode(uint32_t code, uint32_t value) {
|
||||
::read_card(code, &dat);
|
||||
return dat.is_setcode(value);
|
||||
}
|
||||
bool card::check_code_setcode(uint32_t code, uint32_t value) const {
|
||||
if (code == data.code)
|
||||
return data.is_setcode(value);
|
||||
if (data.rule_code && code == data.rule_code && data.is_setcode(value))
|
||||
return true;
|
||||
return check_card_setcode(code, value);
|
||||
}
|
||||
void card::attacker_map::addcard(card* pcard) {
|
||||
auto fid = pcard ? pcard->fieldid_r : 0;
|
||||
auto pr = emplace(fid, mapped_type(pcard, 0));
|
||||
@@ -430,6 +438,9 @@ int32_t card::get_infos(byte* buf, uint32_t query_flag, int32_t use_cache) {
|
||||
query_flag &= ~QUERY_LINK;
|
||||
}
|
||||
}
|
||||
if(query_flag & QUERY_TAG_MEMBER) {
|
||||
buffer_write<uint32_t>(p, tag_member);
|
||||
}
|
||||
byte* finalize = buf;
|
||||
buffer_write<int32_t>(finalize, (int32_t)(p - buf));
|
||||
buffer_write<uint32_t>(finalize, query_flag);
|
||||
@@ -507,15 +518,8 @@ uint32_t card::get_another_code() {
|
||||
}
|
||||
int32_t card::is_set_card(uint32_t set_code) {
|
||||
uint32_t code1 = get_code();
|
||||
card_data dat1;
|
||||
if (code1 == data.code) {
|
||||
if (data.is_setcode(set_code))
|
||||
return TRUE;
|
||||
}
|
||||
else {
|
||||
if (check_card_setcode(code1, set_code))
|
||||
return TRUE;
|
||||
}
|
||||
if (check_code_setcode(code1, set_code))
|
||||
return TRUE;
|
||||
uint32_t code2 = get_another_code();
|
||||
if (code2 && check_card_setcode(code2, set_code))
|
||||
return TRUE;
|
||||
@@ -540,14 +544,8 @@ int32_t card::is_origin_set_card(uint32_t set_code) {
|
||||
}
|
||||
int32_t card::is_pre_set_card(uint32_t set_code) {
|
||||
uint32_t code = previous.code;
|
||||
if (code == data.code) {
|
||||
if (data.is_setcode(set_code))
|
||||
return TRUE;
|
||||
}
|
||||
else {
|
||||
if (check_card_setcode(code, set_code))
|
||||
return TRUE;
|
||||
}
|
||||
if (check_code_setcode(code, set_code))
|
||||
return TRUE;
|
||||
uint32_t code2 = previous.code2;
|
||||
if (code2 && check_card_setcode(code2, set_code))
|
||||
return TRUE;
|
||||
@@ -594,7 +592,7 @@ int32_t card::is_link_set_card(uint32_t set_code) {
|
||||
}
|
||||
int32_t card::is_special_summon_set_card(uint32_t set_code) {
|
||||
uint32_t code = spsummon.code;
|
||||
if (check_card_setcode(code, set_code))
|
||||
if (check_code_setcode(code, set_code))
|
||||
return TRUE;
|
||||
uint32_t code2 = spsummon.code2;
|
||||
if (code2 && check_card_setcode(code2, set_code))
|
||||
@@ -1954,10 +1952,14 @@ int32_t card::add_effect(effect* peffect) {
|
||||
return 0;
|
||||
peffect->id = pduel->game_field->infos.field_id++;
|
||||
peffect->card_type = data.type;
|
||||
if (get_status(STATUS_INITIALIZING))
|
||||
if (get_status(STATUS_INITIALIZING)) {
|
||||
peffect->flag[0] |= EFFECT_FLAG_INITIAL;
|
||||
else if (get_status(STATUS_COPYING_EFFECT))
|
||||
peffect->flag[0] |= EFFECT_FLAG_COPY;
|
||||
peffect->ygol_script_index = (uint16_t)initial_effect.size(); // [YGOL] v1.7.0 prompt context: the script's registration order
|
||||
} else {
|
||||
peffect->ygol_script_index = 0xffff;
|
||||
if (get_status(STATUS_COPYING_EFFECT))
|
||||
peffect->flag[0] |= EFFECT_FLAG_COPY;
|
||||
}
|
||||
if (get_status(STATUS_COPYING_EFFECT)) {
|
||||
peffect->copy_id = pduel->game_field->infos.copy_id;
|
||||
peffect->reset_flag |= pduel->game_field->core.copy_reset;
|
||||
|
||||
@@ -164,6 +164,7 @@ public:
|
||||
card_state spsummon;
|
||||
query_cache q_cache;
|
||||
uint8_t owner{ PLAYER_NONE };
|
||||
uint8_t tag_member{ 0 }; // [YGOL] proposal 53: the partner who brought it, 0 from new_card, 1 from new_tag_card
|
||||
uint8_t summon_player{ PLAYER_NONE };
|
||||
uint32_t summon_info{};
|
||||
uint32_t status{};
|
||||
@@ -228,6 +229,7 @@ public:
|
||||
~card() = default;
|
||||
static bool card_operation_sort(card* c1, card* c2);
|
||||
static bool check_card_setcode(uint32_t code, uint32_t value);
|
||||
bool check_code_setcode(uint32_t code, uint32_t value) const;
|
||||
bool is_extra_deck_monster() const { return !!(data.type & TYPES_EXTRA_DECK); }
|
||||
|
||||
int32_t get_infos(byte* buf, uint32_t query_flag, int32_t use_cache = TRUE);
|
||||
|
||||
@@ -271,6 +271,7 @@ enum LuaParamType : int32_t {
|
||||
#define QUERY_LSCALE 0x200000
|
||||
#define QUERY_RSCALE 0x400000
|
||||
#define QUERY_LINK 0x800000
|
||||
#define QUERY_TAG_MEMBER 0x1000000 // [YGOL] proposal 53. Never 0x100000: old flags (0xf81fff, 0x181fff, 0xFFFFFF) set it with no value
|
||||
|
||||
//Link markers
|
||||
#define LINK_MARKER_BOTTOM_LEFT 0x001
|
||||
@@ -452,6 +453,7 @@ enum LuaParamType : int32_t {
|
||||
#define DUEL_SIMPLE_AI 0x40
|
||||
#define DUEL_RETURN_DECK_TOP 0x80
|
||||
#define DUEL_REVEAL_DECK_SEQ 0x100
|
||||
#define DUEL_TAG_SHARED_EXTRA 0x200 // [YGOL] proposal 53: one Extra Deck per Tag team
|
||||
|
||||
//Activity
|
||||
#define ACTIVITY_SUMMON 1
|
||||
|
||||
@@ -65,6 +65,7 @@ public:
|
||||
int32_t operation{ 0 };
|
||||
uint8_t cost_checked{ FALSE };
|
||||
uint8_t is_granted{ 0 };
|
||||
uint16_t ygol_script_index{ 0xffff }; // [YGOL] v1.7.0 prompt context: registration order in the card's initial_effect, 0xffff = not from it
|
||||
|
||||
effect_set required_handorset_effects;
|
||||
LuaParamType object_type{ PARAM_TYPE_INT };
|
||||
|
||||
+122
-35
@@ -205,6 +205,16 @@ void field::remove_card(card* pcard) {
|
||||
if (!check_playerid(pcard->current.controler) || pcard->current.location == 0)
|
||||
return;
|
||||
uint8_t playerid = pcard->current.controler;
|
||||
if(card_vector* tag_list = tag_list_holding(pcard)) { // [YGOL] TICKET-415, see tag_list_holding
|
||||
tag_list->erase(std::find(tag_list->begin(), tag_list->end(), pcard));
|
||||
uint8_t seq = 0;
|
||||
for(auto& tcard : *tag_list)
|
||||
tcard->current.sequence = seq++;
|
||||
if(pcard->current.location == LOCATION_HAND)
|
||||
pcard->set_status(STATUS_TO_HAND_WITHOUT_CONFIRM, FALSE);
|
||||
else if(pcard->current.location == LOCATION_EXTRA && (pcard->data.type & TYPE_PENDULUM) && (pcard->current.position & POS_FACEUP))
|
||||
--player[playerid].tag_extra_p_count;
|
||||
} else
|
||||
switch (pcard->current.location) {
|
||||
case LOCATION_MZONE:
|
||||
player[playerid].list_mzone[pcard->current.sequence] = 0;
|
||||
@@ -259,7 +269,7 @@ void field::move_card(uint8_t playerid, card* pcard, uint8_t location, uint8_t s
|
||||
pcard->sendto_param.position = POS_FACEDOWN_DEFENSE;
|
||||
}
|
||||
if (pcard->current.location) {
|
||||
if (pcard->current.location == location && pcard->current.pzone == !!pzone) {
|
||||
if (pcard->current.location == location && pcard->current.pzone == !!pzone && !tag_list_holding(pcard)) { // [YGOL] TICKET-415
|
||||
if (pcard->current.location == LOCATION_DECK) {
|
||||
if(preplayer == playerid) {
|
||||
pduel->write_buffer8(MSG_MOVE);
|
||||
@@ -293,7 +303,7 @@ void field::move_card(uint8_t playerid, card* pcard, uint8_t location, uint8_t s
|
||||
if(sequence >= (int32_t)player[playerid].list_mzone.size() || player[playerid].list_mzone[sequence])
|
||||
return;
|
||||
} else {
|
||||
if(sequence >= player[playerid].szone_size || player[playerid].list_szone[sequence])
|
||||
if(sequence >= get_szone_size(playerid) || player[playerid].list_szone[sequence])
|
||||
return;
|
||||
}
|
||||
if(preplayer == playerid) {
|
||||
@@ -559,18 +569,23 @@ card* field::get_field_card(uint8_t playerid, uint32_t general_location, uint8_t
|
||||
break;
|
||||
}
|
||||
case LOCATION_SZONE: {
|
||||
if(sequence < player[playerid].szone_size)
|
||||
if(sequence < get_szone_size(playerid))
|
||||
return player[playerid].list_szone[sequence];
|
||||
else
|
||||
return nullptr;
|
||||
break;
|
||||
}
|
||||
case LOCATION_FZONE: {
|
||||
if(sequence == 0)
|
||||
return player[playerid].list_szone[5];
|
||||
else
|
||||
// [YGOL] proposal 45 Rule 3: 0 = the playing partner's field, else the other one; 1 = the remaining one
|
||||
if(sequence > 1 || (sequence == 1 && !has_two_fields()))
|
||||
return nullptr;
|
||||
break;
|
||||
card* first = player[playerid].list_szone[get_fzone_sequence(playerid, 0)];
|
||||
card* second = has_two_fields() ? player[playerid].list_szone[get_fzone_sequence(playerid, 1)] : nullptr;
|
||||
if(!first) {
|
||||
first = second;
|
||||
second = nullptr;
|
||||
}
|
||||
return sequence == 0 ? first : second;
|
||||
}
|
||||
case LOCATION_PZONE: {
|
||||
if(sequence == 0 || sequence == 1) {
|
||||
@@ -598,14 +613,14 @@ int32_t field::is_location_useable(uint8_t playerid, uint32_t general_location,
|
||||
return FALSE;
|
||||
}
|
||||
} else if (general_location == LOCATION_SZONE) {
|
||||
if (sequence >= player[playerid].szone_size)
|
||||
if (sequence >= get_szone_size(playerid))
|
||||
return FALSE;
|
||||
if(flag & (0x100U << sequence))
|
||||
return FALSE;
|
||||
} else if (general_location == LOCATION_FZONE) {
|
||||
if (sequence >= 1)
|
||||
if (sequence >= (has_two_fields() ? 2 : 1))
|
||||
return FALSE;
|
||||
if(flag & (0x100U << (5 + sequence)))
|
||||
if(flag & (0x100U << get_fzone_sequence(playerid, sequence)))
|
||||
return FALSE;
|
||||
} else if (general_location == LOCATION_PZONE) {
|
||||
if (sequence >= 2)
|
||||
@@ -615,6 +630,39 @@ int32_t field::is_location_useable(uint8_t playerid, uint32_t general_location,
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
// [YGOL] proposal 45: in Tag on Master Rule 4/5 a team has a Field slot per partner: Spell/Trap sequence 5 for the
|
||||
// partner who plays the team's first turn, 6 for the other (slot 6 is free there: Master Rule 3 alone uses it as a
|
||||
// Pendulum Zone). LOCATION_FZONE covers both; Singles, Match and Master Rule 3 keep the one slot.
|
||||
bool field::has_two_fields() const {
|
||||
return (core.duel_options & DUEL_TAG_MODE) && core.duel_rule >= NEW_MASTER_RULE;
|
||||
}
|
||||
int32_t field::get_szone_size(uint8_t playerid) const {
|
||||
return has_two_fields() ? 7 : player[playerid].szone_size;
|
||||
}
|
||||
// fseq 0 = the playing partner's slot, 1 = the other partner's
|
||||
uint8_t field::get_fzone_sequence(uint8_t playerid, uint8_t fseq) const {
|
||||
if(!has_two_fields())
|
||||
return 5;
|
||||
return (player[playerid].tag_partner ^ fseq) ? 6 : 5;
|
||||
}
|
||||
// a zone flag that names the Field Zone (callers pass 1 << 5 for "the Field Zone" and the engine picks the slot)
|
||||
bool field::is_fzone_zone(uint32_t zone) const {
|
||||
return zone == (0x1U << 5) || (has_two_fields() && zone == (0x1U << 6));
|
||||
}
|
||||
// the slot a Field Spell lands in for playerid: the playing partner's, which it replaces; when the playing partner's
|
||||
// slot is taken and the other is free, it takes the free one
|
||||
uint8_t field::get_fzone_landing(card* pcard, uint8_t playerid) const {
|
||||
if(!has_two_fields())
|
||||
return 5;
|
||||
if(pcard->current.location == LOCATION_SZONE && pcard->current.controler == playerid
|
||||
&& (pcard->current.sequence == 5 || pcard->current.sequence == 6))
|
||||
return pcard->current.sequence;
|
||||
uint8_t mine = get_fzone_sequence(playerid, 0);
|
||||
uint8_t other = get_fzone_sequence(playerid, 1);
|
||||
if(player[playerid].list_szone[mine] && !player[playerid].list_szone[other])
|
||||
return other;
|
||||
return mine;
|
||||
}
|
||||
/**
|
||||
* Return usable count in `zone` when `uplayer` moves `pcard` to the MZONE or SZONE(0~4) of `playerid` (can be negative).
|
||||
* For LOCATION_MZONE, "usable" means not used, not disabled, satisfying EFFECT_MUST_USE_MZONE, satisfying EFFECT_MAX_MZONE.
|
||||
@@ -1140,12 +1188,38 @@ void field::refresh_player_info(uint8_t playerid) {
|
||||
if (player[playerid].list_mzone[i])
|
||||
used_flag |= 0x1U << i;
|
||||
}
|
||||
for (int32_t i = 0; i < player[playerid].szone_size; ++i) {
|
||||
for (int32_t i = 0; i < get_szone_size(playerid); ++i) {
|
||||
if (player[playerid].list_szone[i])
|
||||
used_flag |= 0x100U << i;
|
||||
}
|
||||
player[playerid].used_location = used_flag;
|
||||
}
|
||||
// [YGOL] TICKET-415: the lists of the waiting tag partner (tag_list_main / tag_list_hand / tag_list_extra)
|
||||
// hold cards that still say LOCATION_DECK / HAND / EXTRA with a sequence into THAT list. An effect that
|
||||
// kept a card across the tag swap moves it later (Time Fusion: the Fusion picked from the Extra Deck at
|
||||
// activation, Summoned at the team's next Standby Phase, when the partner's Extra Deck is the active one);
|
||||
// remove_card then erased the ACTIVE list at the card's sequence: past the end of a shorter list (an
|
||||
// empty Extra Deck: the owner's crash) or the wrong card. Such a card leaves the list that holds it.
|
||||
card_vector* field::tag_list_holding(card* pcard) {
|
||||
if(!(core.duel_options & DUEL_TAG_MODE) || !check_playerid(pcard->current.controler))
|
||||
return nullptr;
|
||||
auto& p = player[pcard->current.controler];
|
||||
card_vector* tag_list = nullptr;
|
||||
switch(pcard->current.location) {
|
||||
case LOCATION_DECK:
|
||||
tag_list = &p.tag_list_main;
|
||||
break;
|
||||
case LOCATION_HAND:
|
||||
tag_list = &p.tag_list_hand;
|
||||
break;
|
||||
case LOCATION_EXTRA:
|
||||
tag_list = &p.tag_list_extra;
|
||||
break;
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
return std::find(tag_list->begin(), tag_list->end(), pcard) != tag_list->end() ? tag_list : nullptr;
|
||||
}
|
||||
void field::tag_swap(uint8_t playerid) {
|
||||
//main
|
||||
for(auto& pcard : player[playerid].list_main) {
|
||||
@@ -1168,16 +1242,19 @@ void field::tag_swap(uint8_t playerid) {
|
||||
pcard->enable_field_effect(true);
|
||||
}
|
||||
//extra
|
||||
for(auto& pcard : player[playerid].list_extra) {
|
||||
pcard->enable_field_effect(false);
|
||||
pcard->cancel_field_effect();
|
||||
}
|
||||
std::swap(player[playerid].list_extra, player[playerid].tag_list_extra);
|
||||
std::swap(player[playerid].extra_p_count, player[playerid].tag_extra_p_count);
|
||||
for(auto& pcard : player[playerid].list_extra) {
|
||||
pcard->apply_field_effect();
|
||||
pcard->enable_field_effect(true);
|
||||
if(!(core.duel_options & DUEL_TAG_SHARED_EXTRA)) { // [YGOL] proposal 53: a shared Extra Deck stays live for both partners
|
||||
for(auto& pcard : player[playerid].list_extra) {
|
||||
pcard->enable_field_effect(false);
|
||||
pcard->cancel_field_effect();
|
||||
}
|
||||
std::swap(player[playerid].list_extra, player[playerid].tag_list_extra);
|
||||
std::swap(player[playerid].extra_p_count, player[playerid].tag_extra_p_count);
|
||||
for(auto& pcard : player[playerid].list_extra) {
|
||||
pcard->apply_field_effect();
|
||||
pcard->enable_field_effect(true);
|
||||
}
|
||||
}
|
||||
player[playerid].tag_partner ^= 1; // [YGOL] proposal 45: the other partner's Field slot is the live one now
|
||||
pduel->write_buffer8(MSG_TAG_SWAP);
|
||||
pduel->write_buffer8(playerid);
|
||||
pduel->write_buffer8((uint8_t)player[playerid].list_main.size());
|
||||
@@ -1529,18 +1606,20 @@ int32_t field::filter_matching_card(lua_State* L, int32_t findex, uint8_t self,
|
||||
}
|
||||
}
|
||||
if(location & LOCATION_FZONE) {
|
||||
card* pcard = player[self].list_szone[5];
|
||||
if(pcard && !pcard->is_treated_as_not_on_field()
|
||||
&& pcard != pexception && !(pexgroup && pexgroup->has_card(pcard))
|
||||
&& pduel->lua->check_filter(L, pcard, findex, extraargs)
|
||||
&& (!is_target || pcard->is_capable_be_effect_target(core.reason_effect, core.reason_player))) {
|
||||
if(pret) {
|
||||
*pret = pcard;
|
||||
return TRUE;
|
||||
for(uint8_t fseq = 0, fzones = has_two_fields() ? 2 : 1; fseq < fzones; ++fseq) { // [YGOL] proposal 45: both Field slots
|
||||
card* pcard = player[self].list_szone[get_fzone_sequence(self, fseq)];
|
||||
if(pcard && !pcard->is_treated_as_not_on_field()
|
||||
&& pcard != pexception && !(pexgroup && pexgroup->has_card(pcard))
|
||||
&& pduel->lua->check_filter(L, pcard, findex, extraargs)
|
||||
&& (!is_target || pcard->is_capable_be_effect_target(core.reason_effect, core.reason_player))) {
|
||||
if(pret) {
|
||||
*pret = pcard;
|
||||
return TRUE;
|
||||
}
|
||||
result.insert(pcard);
|
||||
if (fcount && (int32_t)result.size() >= fcount)
|
||||
return TRUE;
|
||||
}
|
||||
result.insert(pcard);
|
||||
if (fcount && (int32_t)result.size() >= fcount)
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(location & LOCATION_PZONE) {
|
||||
@@ -1664,9 +1743,11 @@ int32_t field::filter_field_card(uint8_t self, uint32_t location1, uint32_t loca
|
||||
}
|
||||
}
|
||||
if(location & LOCATION_FZONE) {
|
||||
card* pcard = player[self].list_szone[5];
|
||||
if(pcard) {
|
||||
result.insert(pcard);
|
||||
for(uint8_t fseq = 0, fzones = has_two_fields() ? 2 : 1; fseq < fzones; ++fseq) { // [YGOL] proposal 45: both Field slots
|
||||
card* pcard = player[self].list_szone[get_fzone_sequence(self, fseq)];
|
||||
if(pcard) {
|
||||
result.insert(pcard);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(location & LOCATION_PZONE) {
|
||||
@@ -3704,8 +3785,14 @@ int32_t field::check_spself_from_hand_trigger(const chain& ch) const {
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
// [YGOL] Tag: the first three duelists (1A, 2A, 1B) have no Battle Phase; the fourth is the first who can battle.
|
||||
int32_t field::is_opening_turn_without_bp() {
|
||||
if(core.duel_options & DUEL_ATTACK_FIRST_TURN)
|
||||
return FALSE;
|
||||
return infos.turn_id <= ((core.duel_options & DUEL_TAG_MODE) ? 3 : 1);
|
||||
}
|
||||
int32_t field::is_able_to_enter_bp() {
|
||||
return ((core.duel_options & DUEL_ATTACK_FIRST_TURN) || infos.turn_id != 1)
|
||||
return !is_opening_turn_without_bp()
|
||||
&& infos.phase < PHASE_BATTLE_START
|
||||
&& !is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP);
|
||||
}
|
||||
@@ -87,6 +87,7 @@ struct player_info {
|
||||
uint32_t extra_p_count{ 0 };
|
||||
uint32_t tag_extra_p_count{ 0 };
|
||||
int32_t szone_size{ 6 };
|
||||
uint8_t tag_partner{ 0 }; // [YGOL] proposal 45: 0 = the partner who plays the team's first turn (Field slot 5), 1 = the other (slot 6); flips in tag_swap
|
||||
card_vector list_mzone;
|
||||
card_vector list_szone;
|
||||
card_vector list_main;
|
||||
@@ -341,6 +342,16 @@ struct processor {
|
||||
uint8_t selfdes_disabled{ FALSE };
|
||||
uint8_t overdraw[2]{};
|
||||
int32_t check_level{ 0 };
|
||||
// [YGOL] v1.7.0 prompt context: the effect functions running now (cost / target / operation), innermost last
|
||||
struct ygol_running_effect {
|
||||
card* handler{ nullptr };
|
||||
uint32_t description{ 0 };
|
||||
uint16_t script_index{ 0xffff };
|
||||
uint8_t phase{ 0 };
|
||||
uint8_t chain_link{ 0 };
|
||||
uint64_t category{ 0 };
|
||||
};
|
||||
std::vector<ygol_running_effect> ygol_running;
|
||||
uint8_t shuffle_check_disabled{ FALSE };
|
||||
uint8_t shuffle_hand_check[2]{};
|
||||
uint8_t shuffle_deck_check[2]{};
|
||||
@@ -402,6 +413,12 @@ public:
|
||||
const card_vector* get_field_vector(uint8_t playerid, uint8_t location) const;
|
||||
card* get_field_card(uint8_t playerid, uint32_t general_location, uint8_t sequence) const;
|
||||
int32_t is_location_useable(uint8_t playerid, uint32_t general_location, uint8_t sequence) const;
|
||||
// [YGOL] proposal 45: Tag on Master Rule 4/5 gives each partner a Field slot (Spell/Trap sequence 5 and 6)
|
||||
bool has_two_fields() const;
|
||||
int32_t get_szone_size(uint8_t playerid) const;
|
||||
uint8_t get_fzone_sequence(uint8_t playerid, uint8_t fseq) const;
|
||||
uint8_t get_fzone_landing(card* pcard, uint8_t playerid) const;
|
||||
bool is_fzone_zone(uint32_t zone) const;
|
||||
int32_t get_useable_count(card* pcard, uint8_t playerid, uint8_t location, uint8_t uplayer, uint32_t reason, uint32_t zone = 0xff, uint32_t* list = nullptr);
|
||||
int32_t get_useable_count_fromex(card* pcard, uint8_t playerid, uint8_t uplayer, uint32_t zone = 0xff, uint32_t* list = nullptr);
|
||||
int32_t get_spsummonable_count(card* pcard, uint8_t playerid, uint32_t zone = 0xff, uint32_t* list = nullptr);
|
||||
@@ -424,6 +441,7 @@ public:
|
||||
void swap_deck_and_grave(uint8_t playerid);
|
||||
void reverse_deck(uint8_t playerid);
|
||||
void refresh_player_info(uint8_t playerid);
|
||||
card_vector* tag_list_holding(card* pcard); // [YGOL] TICKET-415
|
||||
void tag_swap(uint8_t playerid);
|
||||
|
||||
void add_effect(effect* peffect, uint8_t owner_player = PLAYER_NONE);
|
||||
@@ -531,6 +549,7 @@ public:
|
||||
int32_t check_trigger_effect(const chain& ch) const;
|
||||
int32_t check_spself_from_hand_trigger(const chain& ch) const;
|
||||
int32_t is_able_to_enter_bp();
|
||||
int32_t is_opening_turn_without_bp();
|
||||
|
||||
void add_process(uint16_t type, uint16_t step, effect* peffect, group* target, int32_t arg1, int32_t arg2, int32_t arg3 = 0, int32_t arg4 = 0, void* ptr1 = nullptr, void* ptr2 = nullptr);
|
||||
uint32_t process();
|
||||
@@ -855,4 +874,12 @@ public:
|
||||
//#define PROCESSOR_SWAP_CONTROL_S 145
|
||||
//#define PROCESSOR_MOVETOFIELD_S 161
|
||||
|
||||
// [YGOL] v1.7.0 prompt context (processor.cpp): phases 1 cost, 2 target, 3 operation, 4 the core asks whether to use the effect
|
||||
constexpr uint8_t YGOL_PHASE_COST = 1;
|
||||
constexpr uint8_t YGOL_PHASE_TARGET = 2;
|
||||
constexpr uint8_t YGOL_PHASE_OPERATION = 3;
|
||||
constexpr uint8_t YGOL_PHASE_ASK = 4;
|
||||
void ygol_push_running(field* pfield, effect* peffect, uint8_t phase);
|
||||
void ygol_pop_running(field* pfield);
|
||||
|
||||
#endif /* FIELD_H_ */
|
||||
+10
-11
@@ -1575,17 +1575,16 @@ int32_t scriptlib::duel_is_environment(lua_State *L) {
|
||||
duel* pduel = interpreter::get_duel_info(L);
|
||||
int32_t ret = 0, fc = 0;
|
||||
if(loc & (LOCATION_FZONE + LOCATION_SZONE)) {
|
||||
card* pcard = pduel->game_field->player[0].list_szone[5];
|
||||
if(pcard && pcard->is_position(POS_FACEUP)) {
|
||||
fc = 1;
|
||||
if(code == pcard->get_code() && (playerid == 0 || playerid == PLAYER_ALL))
|
||||
ret = 1;
|
||||
}
|
||||
pcard = pduel->game_field->player[1].list_szone[5];
|
||||
if(pcard && pcard->is_position(POS_FACEUP)) {
|
||||
fc = 1;
|
||||
if(code == pcard->get_code() && (playerid == 1 || playerid == PLAYER_ALL))
|
||||
ret = 1;
|
||||
field* pfield = pduel->game_field;
|
||||
for(uint8_t p = 0; p < 2; ++p) {
|
||||
for(uint8_t fseq = 0, fzones = pfield->has_two_fields() ? 2 : 1; fseq < fzones; ++fseq) { // [YGOL] proposal 45: both Field slots
|
||||
card* pcard = pfield->player[p].list_szone[pfield->get_fzone_sequence(p, fseq)];
|
||||
if(pcard && pcard->is_position(POS_FACEUP)) {
|
||||
fc = 1;
|
||||
if(code == pcard->get_code() && (playerid == p || playerid == PLAYER_ALL))
|
||||
ret = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!ret && (loc & LOCATION_SZONE)) {
|
||||
|
||||
@@ -109,6 +109,18 @@ OCGCORE_API void start_duel(intptr_t pduel, uint32_t options) {
|
||||
pd->game_field->core.shuffle_hand_check[1] = FALSE;
|
||||
pd->game_field->core.shuffle_deck_check[0] = FALSE;
|
||||
pd->game_field->core.shuffle_deck_check[1] = FALSE;
|
||||
if((options & DUEL_TAG_MODE) && (options & DUEL_TAG_SHARED_EXTRA)) { // [YGOL] proposal 53: the team has one live Extra Deck
|
||||
for(uint8_t p = 0; p < 2; ++p) {
|
||||
auto& team = pd->game_field->player[p];
|
||||
for(auto& pcard : team.tag_list_extra) {
|
||||
team.list_extra.push_back(pcard);
|
||||
pcard->apply_field_effect();
|
||||
pcard->enable_field_effect(true);
|
||||
}
|
||||
team.tag_list_extra.clear();
|
||||
pd->game_field->reset_sequence(p, LOCATION_EXTRA);
|
||||
}
|
||||
}
|
||||
if(pd->game_field->player[0].start_count > 0)
|
||||
pd->game_field->draw(0, REASON_RULE, PLAYER_NONE, 0, pd->game_field->player[0].start_count);
|
||||
if(pd->game_field->player[1].start_count > 0)
|
||||
@@ -198,6 +210,7 @@ OCGCORE_API void new_tag_card(intptr_t pduel, uint32_t code, uint8_t owner, uint
|
||||
if(owner > 1 || !(location & (LOCATION_DECK | LOCATION_EXTRA)))
|
||||
return;
|
||||
card* pcard = ptduel->new_card(code);
|
||||
pcard->tag_member = 1; // [YGOL] proposal 53
|
||||
switch(location) {
|
||||
case LOCATION_DECK:
|
||||
ptduel->game_field->player[owner].tag_list_main.push_back(pcard);
|
||||
@@ -441,6 +454,78 @@ OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_
|
||||
buffer_write<int32_t>(ptr, 0);
|
||||
return 1;
|
||||
}
|
||||
// [YGOL] v1.2.0 (tag partner cards) -- see ocgapi.h. Reads the three tag_list_* vectors the core keeps for the
|
||||
// waiting member; nothing is moved, nothing is written to the duel.
|
||||
OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out) {
|
||||
duel* pd = (duel*)pduel;
|
||||
if(!pd || !out || !duel_set.count(pd) || !pd->game_field)
|
||||
return 0;
|
||||
if(!check_playerid(playerid) || !(pd->game_field->core.duel_options & DUEL_TAG_MODE))
|
||||
return 0;
|
||||
const auto& p = pd->game_field->player[playerid];
|
||||
std::vector<uint32_t> deck;
|
||||
deck.reserve(p.tag_list_main.size());
|
||||
for(auto& pcard : p.tag_list_main)
|
||||
deck.push_back(pcard->data.code);
|
||||
std::sort(deck.begin(), deck.end());
|
||||
byte* ptr = out;
|
||||
buffer_write<uint8_t>(ptr, 1);
|
||||
buffer_write<uint8_t>(ptr, (uint8_t)p.tag_list_hand.size());
|
||||
buffer_write<uint8_t>(ptr, (uint8_t)p.tag_list_extra.size());
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint16_t>(ptr, (uint16_t)deck.size());
|
||||
for(auto& pcard : p.tag_list_hand)
|
||||
buffer_write<uint32_t>(ptr, pcard->data.code | (pcard->is_position(POS_FACEUP) ? 0x80000000 : 0));
|
||||
for(auto& pcard : p.tag_list_extra)
|
||||
buffer_write<uint32_t>(ptr, pcard->data.code | (pcard->is_position(POS_FACEUP) ? 0x80000000 : 0));
|
||||
for(auto code : deck)
|
||||
buffer_write<uint32_t>(ptr, code);
|
||||
return (int32_t)(ptr - out);
|
||||
}
|
||||
// [YGOL] v1.7.0 (prompt context) -- see ocgapi.h. Reads field::core.ygol_running, the cost / target / operation
|
||||
// functions running now (processor.cpp); the innermost one is the effect that asks.
|
||||
OCGCORE_API int32_t ygol_query_prompt_context(intptr_t pduel, uint8_t playerid, uint8_t* out) {
|
||||
duel* pd = (duel*)pduel;
|
||||
if(!pd || !out || !duel_set.count(pd) || !pd->game_field || !check_playerid(playerid))
|
||||
return 0;
|
||||
const auto& running = pd->game_field->core.ygol_running;
|
||||
card* handler = running.empty() ? nullptr : running.back().handler;
|
||||
if(handler && !pd->cards.count(handler))
|
||||
handler = nullptr;
|
||||
const auto& units = pd->game_field->core.units;
|
||||
const bool announce = !units.empty() && units.front().type == PROCESSOR_ANNOUNCE_NUMBER;
|
||||
const bool announce_level = announce && (units.front().arg1 >> 16) == 1; // Duel.AnnounceLevel passes playerid + 0x10000
|
||||
byte* ptr = out;
|
||||
buffer_write<uint8_t>(ptr, 1);
|
||||
if(!handler) {
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint32_t>(ptr, 0);
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint64_t>(ptr, 0);
|
||||
buffer_write<uint16_t>(ptr, 0xffff);
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint8_t>(ptr, 0);
|
||||
buffer_write<uint8_t>(ptr, announce_level ? 1 : 0);
|
||||
return (int32_t)(ptr - out);
|
||||
}
|
||||
const auto& top = running.back();
|
||||
const bool visible = handler->current.controler == playerid || handler->is_position(POS_FACEUP);
|
||||
buffer_write<uint8_t>(ptr, 1);
|
||||
buffer_write<uint32_t>(ptr, visible ? handler->get_code() : 0);
|
||||
buffer_write<uint8_t>(ptr, handler->current.controler);
|
||||
buffer_write<uint8_t>(ptr, handler->current.location);
|
||||
buffer_write<uint8_t>(ptr, handler->current.sequence);
|
||||
buffer_write<uint8_t>(ptr, handler->current.position);
|
||||
buffer_write<uint64_t>(ptr, visible ? top.description : 0);
|
||||
buffer_write<uint16_t>(ptr, visible ? top.script_index : 0xffff);
|
||||
buffer_write<uint8_t>(ptr, top.phase);
|
||||
buffer_write<uint8_t>(ptr, top.chain_link);
|
||||
buffer_write<uint8_t>(ptr, announce_level ? 1 : (announce && visible && (top.category & CATEGORY_DICE)) ? 2 : 0);
|
||||
return (int32_t)(ptr - out);
|
||||
}
|
||||
OCGCORE_API int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf) {
|
||||
if (!pduel || !key || !out_buf) return -1;
|
||||
|
||||
|
||||
@@ -80,6 +80,23 @@ OCGCORE_API byte* default_script_reader(const char* script_name, int* len);
|
||||
// the duel is byte-identical afterwards (proposal 43).
|
||||
OCGCORE_API int32_t ygol_preview_attack(intptr_t pduel, uint8_t playerid, uint8_t location, uint8_t sequence, uint8_t target_location, uint8_t target_sequence, uint8_t* out);
|
||||
|
||||
// [YGOL] v1.2.0 (tag partner cards, TICKET-405): the waiting tag partner's cards of playerid's side, read
|
||||
// only. out: version (1), hand count, extra count, one pad byte, uint16 deck count, then the uint32 hand
|
||||
// codes, the uint32 extra codes (bit 31 = face-up, like MSG_TAG_SWAP) and the uint32 deck codes sorted
|
||||
// ascending (the order stays secret). Returns the byte length, 0 refused (bad pointer, bad player, not a
|
||||
// tag duel); a refusal writes nothing. The duel is byte-identical afterwards (proposal 33 Rule 11).
|
||||
OCGCORE_API int32_t ygol_query_tag_cards(intptr_t pduel, uint8_t playerid, uint8_t* out);
|
||||
|
||||
// [YGOL] v1.7.0 (prompt context, TICKET-451): which effect asks the prompt the engine is parked on, read only.
|
||||
// playerid = the answering player. out (23 bytes): version (1), has_effect, uint32 code (the handler's current
|
||||
// code), controller, location, sequence, position, uint64 description, uint16 effect_index (the order the
|
||||
// card's script registered the effect in initial_effect; 0xffff unknown), phase (1 cost, 2 target, 3 operation, 4 the core asks whether to use the effect),
|
||||
// chain link (0 none), announce kind (MSG_ANNOUNCE_NUMBER only: 1 Duel.AnnounceLevel, 2 the effect has
|
||||
// CATEGORY_DICE and is visible, else 0). has_effect 0 = no effect runs: every other byte 0 but announce kind, effect_index 0xffff. A
|
||||
// handler playerid does not control and that is not face-up writes code 0, effect_index 0xffff, description 0.
|
||||
// Returns 23, 0 refused (bad pointer, bad player); a refusal writes nothing.
|
||||
OCGCORE_API int32_t ygol_query_prompt_context(intptr_t pduel, uint8_t playerid, uint8_t* out);
|
||||
|
||||
// koishi specific
|
||||
OCGCORE_API int32_t get_registry_value(intptr_t pduel, const char* key, byte* out_buf);
|
||||
OCGCORE_API void set_registry_value(intptr_t pduel, const char* key, const char* value);
|
||||
|
||||
+15
-12
@@ -665,7 +665,7 @@ int32_t field::pay_lp_cost(uint32_t step, uint8_t playerid, uint32_t cost, uint3
|
||||
if(core.select_options.size() == 1)
|
||||
returns.ivalue[0] = 0;
|
||||
else if(core.select_effects[0] == 0 && core.select_effects.size() == 2)
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_effects[1]->handler, playerid, 218);
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_effects[1], (group*)core.select_effects[1]->handler, playerid, 218); // [YGOL] v1.7.0 prompt context
|
||||
else
|
||||
add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, playerid, 0);
|
||||
return FALSE;
|
||||
@@ -729,7 +729,7 @@ int32_t field::remove_counter(uint16_t step, uint32_t reason, card* pcard, uint8
|
||||
if(core.select_options.size() == 1)
|
||||
returns.ivalue[0] = 0;
|
||||
else if(core.select_effects[0] == nullptr && core.select_effects.size() == 2)
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_effects[1]->handler, rplayer, 220);
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_effects[1], (group*)core.select_effects[1]->handler, rplayer, 220); // [YGOL] v1.7.0 prompt context
|
||||
else
|
||||
add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, rplayer, 0);
|
||||
return FALSE;
|
||||
@@ -825,7 +825,7 @@ int32_t field::remove_overlay_card(uint16_t step, uint32_t reason, card* pcard,
|
||||
if(core.select_options.size() == 1)
|
||||
returns.ivalue[0] = 0;
|
||||
else if(core.select_effects[0] == 0 && core.select_effects.size() == 2)
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_effects[1]->handler, rplayer, 219);
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_effects[1], (group*)core.select_effects[1]->handler, rplayer, 219); // [YGOL] v1.7.0 prompt context
|
||||
else
|
||||
add_process(PROCESSOR_SELECT_OPTION, 0, 0, 0, rplayer, 0);
|
||||
return FALSE;
|
||||
@@ -2459,7 +2459,7 @@ int32_t field::sset(uint16_t step, uint8_t setplayer, uint8_t toplayer, card * t
|
||||
return TRUE;
|
||||
uint32_t flag = 0;
|
||||
if(target->data.type & TYPE_FIELD) {
|
||||
flag = ~(0x1U << 13);
|
||||
flag = ~(0x1U << (8 + get_fzone_landing(target, toplayer))); // [YGOL] proposal 45: the partner's Field slot
|
||||
} else {
|
||||
get_useable_count(target, setplayer, LOCATION_SZONE, toplayer, LOCATION_REASON_TOFIELD, zone ? zone : 0xff, &flag);
|
||||
flag = ((flag & 0xff) << 8) | 0xffff00ff;
|
||||
@@ -2567,7 +2567,7 @@ int32_t field::sset_g(uint16_t step, uint8_t setplayer, uint8_t toplayer, group*
|
||||
card_set* set_cards = (card_set*)ptarget;
|
||||
card* target = *set_cards->begin();
|
||||
if(target->data.type & TYPE_FIELD) {
|
||||
returns.bvalue[2] = 5;
|
||||
returns.bvalue[2] = get_fzone_landing(target, toplayer); // [YGOL] proposal 45
|
||||
return FALSE;
|
||||
}
|
||||
uint32_t flag;
|
||||
@@ -2606,7 +2606,7 @@ int32_t field::sset_g(uint16_t step, uint8_t setplayer, uint8_t toplayer, group*
|
||||
target->enable_field_effect(false);
|
||||
uint32_t zone;
|
||||
if(target->data.type & TYPE_FIELD) {
|
||||
zone = 0x1U << 5;
|
||||
zone = 0x1U << get_fzone_landing(target, toplayer); // [YGOL] proposal 45
|
||||
} else {
|
||||
for(int32_t i = 0; i < 7; i++) {
|
||||
zone = 0x1U << i;
|
||||
@@ -2676,6 +2676,8 @@ int32_t field::sset_g(uint16_t step, uint8_t setplayer, uint8_t toplayer, group*
|
||||
uint8_t ct = (uint8_t)core.operated_set.size();
|
||||
if(core.set_group_used_zones & (0x1U << 5))
|
||||
--ct;
|
||||
if(core.set_group_used_zones & (0x1U << 6)) // [YGOL] proposal 45: the second Field slot
|
||||
--ct;
|
||||
if(ct <= 1)
|
||||
return FALSE;
|
||||
pduel->write_buffer8(MSG_SHUFFLE_SET_CARD);
|
||||
@@ -4602,9 +4604,10 @@ int32_t field::move_to_field(uint16_t step, card* target, uint32_t enable, uint3
|
||||
returns.ivalue[0] = FALSE;
|
||||
if((ret == RETURN_TEMP_REMOVE_TO_FIELD) && (!(target->current.reason & REASON_TEMPORARY) || (target->current.reason_effect->owner != core.reason_effect->owner)))
|
||||
return TRUE;
|
||||
if(location == LOCATION_SZONE && zone == 0x1U << 5 && (target->data.type & TYPE_FIELD) && (target->data.type & TYPE_SPELL)) {
|
||||
card* pcard = get_field_card(playerid, LOCATION_SZONE, 5);
|
||||
if(pcard) {
|
||||
if(location == LOCATION_SZONE && is_fzone_zone(zone) && (target->data.type & TYPE_FIELD) && (target->data.type & TYPE_SPELL)) {
|
||||
// [YGOL] proposal 45: the card replaces only the Field slot it lands in
|
||||
card* pcard = get_field_card(playerid, LOCATION_SZONE, get_fzone_landing(target, playerid));
|
||||
if(pcard && pcard != target) {
|
||||
if(core.duel_rule >= 3)
|
||||
send_to(pcard, 0, REASON_RULE, pcard->current.controler, PLAYER_NONE, LOCATION_GRAVE, 0, 0);
|
||||
else
|
||||
@@ -4683,8 +4686,8 @@ int32_t field::move_to_field(uint16_t step, card* target, uint32_t enable, uint3
|
||||
}
|
||||
case 1: {
|
||||
uint32_t seq = returns.bvalue[2];
|
||||
if(location == LOCATION_SZONE && zone == 0x1U << 5 && (target->data.type & TYPE_FIELD) && (target->data.type & TYPE_SPELL))
|
||||
seq = 5;
|
||||
if(location == LOCATION_SZONE && is_fzone_zone(zone) && (target->data.type & TYPE_FIELD) && (target->data.type & TYPE_SPELL))
|
||||
seq = get_fzone_landing(target, playerid); // [YGOL] proposal 45
|
||||
if(ret != RETURN_TEMP_REMOVE_TO_FIELD) {
|
||||
if(location != target->current.location) {
|
||||
uint32_t resetflag = 0;
|
||||
@@ -5626,7 +5629,7 @@ int32_t field::select_synchro_material(int16_t step, uint8_t playerid, card* pca
|
||||
}
|
||||
if(mfiltered && check_with_sum_limit_m(nsyn_filtered, lv, 0, min, max, 0xffff, mcount)) {
|
||||
if(mremoved && check_with_sum_limit_m(nsyn_removed, lv, 0, min, max, 0xffff, mcount)) {
|
||||
add_process(PROCESSOR_SELECT_YESNO, 0, 0, 0, playerid, peffect->description);
|
||||
add_process(PROCESSOR_SELECT_YESNO, 0, peffect, 0, playerid, peffect->description); // [YGOL] v1.7.0 prompt context
|
||||
core.units.begin()->step = 9;
|
||||
return FALSE;
|
||||
} else
|
||||
|
||||
+41
-4
@@ -84,7 +84,11 @@ uint32_t field::process() {
|
||||
}
|
||||
}
|
||||
case PROCESSOR_SELECT_EFFECTYN: {
|
||||
if (it->step == 0 && it->peffect)
|
||||
ygol_push_running(this, it->peffect, YGOL_PHASE_ASK); // [YGOL] v1.7.0 prompt context: the core asks whether to use this effect
|
||||
if (select_effect_yes_no(it->step, it->arg1, it->arg2, (card*)it->ptarget)) {
|
||||
if (it->peffect)
|
||||
ygol_pop_running(this);
|
||||
core.units.pop_front();
|
||||
return pduel->buffer_size();
|
||||
} else {
|
||||
@@ -93,7 +97,11 @@ uint32_t field::process() {
|
||||
}
|
||||
}
|
||||
case PROCESSOR_SELECT_YESNO: {
|
||||
if (it->step == 0 && it->peffect)
|
||||
ygol_push_running(this, it->peffect, YGOL_PHASE_ASK); // [YGOL] v1.7.0 prompt context
|
||||
if (select_yes_no(it->step, it->arg1, it->arg2)) {
|
||||
if (it->peffect)
|
||||
ygol_pop_running(this);
|
||||
core.units.pop_front();
|
||||
return pduel->buffer_size();
|
||||
} else {
|
||||
@@ -727,6 +735,29 @@ uint32_t field::process() {
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(pop)
|
||||
#endif
|
||||
// [YGOL] v1.7.0 prompt context: remember which effect function runs, so ygol_query_prompt_context can name it at a prompt
|
||||
void ygol_push_running(field* pfield, effect* peffect, uint8_t phase) {
|
||||
processor::ygol_running_effect running;
|
||||
running.handler = peffect->get_handler();
|
||||
if(!running.handler)
|
||||
running.handler = peffect->owner;
|
||||
running.description = peffect->description;
|
||||
running.script_index = peffect->ygol_script_index;
|
||||
running.phase = phase;
|
||||
running.category = peffect->category;
|
||||
auto& chain = pfield->core.current_chain;
|
||||
for(auto it = chain.rbegin(); it != chain.rend(); ++it) {
|
||||
if(it->triggering_effect == peffect) {
|
||||
running.chain_link = it->chain_count;
|
||||
break;
|
||||
}
|
||||
}
|
||||
pfield->core.ygol_running.push_back(running);
|
||||
}
|
||||
void ygol_pop_running(field* pfield) {
|
||||
if(!pfield->core.ygol_running.empty())
|
||||
pfield->core.ygol_running.pop_back();
|
||||
}
|
||||
int32_t field::execute_cost(uint16_t step, effect * triggering_effect, uint8_t triggering_player) {
|
||||
if(!triggering_effect->cost) {
|
||||
core.solving_event.splice(core.solving_event.begin(), core.sub_solving_event);
|
||||
@@ -754,6 +785,7 @@ int32_t field::execute_cost(uint16_t step, effect * triggering_effect, uint8_t t
|
||||
core.units.begin()->arg2 = core.shuffle_check_disabled;
|
||||
core.shuffle_check_disabled = FALSE;
|
||||
++core.check_level;
|
||||
ygol_push_running(this, triggering_effect, YGOL_PHASE_COST);
|
||||
}
|
||||
core.reason_effect = triggering_effect;
|
||||
core.reason_player = triggering_player;
|
||||
@@ -765,6 +797,7 @@ int32_t field::execute_cost(uint16_t step, effect * triggering_effect, uint8_t t
|
||||
core.reason_effect = 0;
|
||||
core.reason_player = PLAYER_NONE;
|
||||
--core.check_level;
|
||||
ygol_pop_running(this);
|
||||
if(core.check_level == 0) {
|
||||
if(core.shuffle_hand_check[0])
|
||||
shuffle(0, LOCATION_HAND);
|
||||
@@ -806,6 +839,7 @@ int32_t field::execute_operation(uint16_t step, effect * triggering_effect, uint
|
||||
core.units.begin()->arg2 = core.shuffle_check_disabled;
|
||||
core.shuffle_check_disabled = FALSE;
|
||||
++core.check_level;
|
||||
ygol_push_running(this, triggering_effect, YGOL_PHASE_OPERATION);
|
||||
}
|
||||
core.reason_effect = triggering_effect;
|
||||
core.reason_player = triggering_player;
|
||||
@@ -817,6 +851,7 @@ int32_t field::execute_operation(uint16_t step, effect * triggering_effect, uint
|
||||
core.reason_effect = 0;
|
||||
core.reason_player = PLAYER_NONE;
|
||||
--core.check_level;
|
||||
ygol_pop_running(this);
|
||||
if(core.check_level == 0) {
|
||||
if(core.shuffle_hand_check[0])
|
||||
shuffle(0, LOCATION_HAND);
|
||||
@@ -863,6 +898,7 @@ int32_t field::execute_target(uint16_t step, effect * triggering_effect, uint8_t
|
||||
core.units.begin()->arg2 = core.shuffle_check_disabled;
|
||||
core.shuffle_check_disabled = FALSE;
|
||||
++core.check_level;
|
||||
ygol_push_running(this, triggering_effect, YGOL_PHASE_TARGET);
|
||||
}
|
||||
core.reason_effect = triggering_effect;
|
||||
core.reason_player = triggering_player;
|
||||
@@ -874,6 +910,7 @@ int32_t field::execute_target(uint16_t step, effect * triggering_effect, uint8_t
|
||||
core.reason_effect = 0;
|
||||
core.reason_player = PLAYER_NONE;
|
||||
--core.check_level;
|
||||
ygol_pop_running(this);
|
||||
if(core.check_level == 0) {
|
||||
if(core.shuffle_hand_check[0])
|
||||
shuffle(0, LOCATION_HAND);
|
||||
@@ -1153,7 +1190,7 @@ int32_t field::process_phase_event(int16_t step, int32_t phase) {
|
||||
else
|
||||
pduel->write_buffer32(26);
|
||||
if(tf_count == 0 && to_count == 1 && fc_count == 0 && cn_count == 0) {
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_chains[0].triggering_effect->get_handler(), check_player, 0);
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_chains[0].triggering_effect, (group*)core.select_chains[0].triggering_effect->get_handler(), check_player, 0); // [YGOL] v1.7.0 prompt context: the asked effect rides in peffect
|
||||
return FALSE;
|
||||
} else {
|
||||
add_process(PROCESSOR_SELECT_CHAIN, 0, 0, 0, check_player, core.spe_effect[check_player]);
|
||||
@@ -1404,7 +1441,7 @@ int32_t field::process_point_event(int16_t step, int32_t skip_trigger, int32_t s
|
||||
core.units.begin()->step = 5;
|
||||
return FALSE;
|
||||
} else if(core.select_chains.size() == 1 && !core.current_chain.size()) {
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)core.select_chains[0].triggering_effect->get_handler(), core.current_player, 221);
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, core.select_chains[0].triggering_effect, (group*)core.select_chains[0].triggering_effect->get_handler(), core.current_player, 221); // [YGOL] v1.7.0 prompt context
|
||||
return FALSE;
|
||||
} else {
|
||||
add_process(PROCESSOR_SELECT_CHAIN, 0, 0, 0, core.current_player, 0x7f);
|
||||
@@ -2078,7 +2115,7 @@ int32_t field::process_idle_command(uint16_t step) {
|
||||
chain newchain;
|
||||
core.to_bp = TRUE;
|
||||
core.to_ep = TRUE;
|
||||
if((!(core.duel_options & DUEL_ATTACK_FIRST_TURN) && infos.turn_id == 1) || infos.phase == PHASE_MAIN2 || is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP))
|
||||
if(is_opening_turn_without_bp() || infos.phase == PHASE_MAIN2 || is_player_affected_by_effect(infos.turn_player, EFFECT_CANNOT_BP))
|
||||
core.to_bp = FALSE;
|
||||
if(infos.phase == PHASE_MAIN1) {
|
||||
for(auto& pcard : player[infos.turn_player].list_mzone) {
|
||||
@@ -4225,7 +4262,7 @@ int32_t field::add_chain(uint16_t step) {
|
||||
returns.ivalue[0] = TRUE;
|
||||
return FALSE;
|
||||
}
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, 0, (group*)peffect->get_handler(), playerid, 94);
|
||||
add_process(PROCESSOR_SELECT_EFFECTYN, 0, peffect, (group*)peffect->get_handler(), playerid, 94); // [YGOL] v1.7.0 prompt context
|
||||
} else
|
||||
returns.ivalue[0] = FALSE;
|
||||
return FALSE;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <algorithm> // [YGOL] std::find (attack preview); MSVC includes it transitively, GCC does not
|
||||
#include <cstdlib> // [YGOL] std::strtol (life points per side)
|
||||
#include <event2/event.h>
|
||||
#include <event2/listener.h>
|
||||
#include <event2/bufferevent.h>
|
||||
@@ -786,6 +787,25 @@ bool SpectatorsSeeAll() { // YGOL spectators see all
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
int32_t SideBStartLp(int32_t fallback) { // YGOL life points per side
|
||||
static const char key[] = "ygol.side.b.lp=";
|
||||
constexpr size_t key_len = sizeof(key) - 1;
|
||||
for(const auto& pair : setup_pairs) {
|
||||
if(pair.compare(0, key_len, key) != 0)
|
||||
continue;
|
||||
char* end = nullptr;
|
||||
const long value = std::strtol(pair.c_str() + key_len, &end, 10);
|
||||
if(end && *end == '\0' && value > 0 && value <= 0x7FFFFFFFL)
|
||||
return (int32_t)value;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
bool TagSharedExtra() { // YGOL tag shared extra
|
||||
for(const auto& pair : setup_pairs)
|
||||
if(pair == "ygol.tag.extra=shared")
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
size_t WriteSetupPairsBlock(unsigned char* dst) {
|
||||
auto pdst = dst;
|
||||
BufferIO::Write<uint16_t>(pdst, (uint16_t)setup_pairs.size());
|
||||
|
||||
+21
-1
@@ -224,7 +224,7 @@ static_assert(sizeof(CTOS_Appearance) == 352, "size mismatch: CTOS_Appearance");
|
||||
check_trivially_copyable(CTOS_Dialogue);
|
||||
static_assert(sizeof(CTOS_Dialogue) == 204, "size mismatch: CTOS_Dialogue");
|
||||
constexpr int SIZE_STOC_FEATURE = sizeof(uint16_t) + sizeof(CTOS_Appearance);
|
||||
constexpr uint16_t FEATURE_PROTOCOL = 8; // YGOL host seats: 1 -> 2; YGOL seat state: 2 -> 3; YGOL lobby after match: 3 -> 4; YGOL coin toss: 4 -> 5; YGOL deck lists: 5 -> 6; YGOL profile: 6 -> 7; YGOL attack preview: 7 -> 8
|
||||
constexpr uint16_t FEATURE_PROTOCOL = 12; // YGOL host seats: 1 -> 2; YGOL seat state: 2 -> 3; YGOL lobby after match: 3 -> 4; YGOL coin toss: 4 -> 5; YGOL deck lists: 5 -> 6; YGOL profile: 6 -> 7; YGOL attack preview: 7 -> 8; YGOL tag partner cards: 8 -> 9; YGOL tag two fields: 9 -> 10; YGOL tag shared extra: 10 -> 11; YGOL prompt context: 11 -> 12
|
||||
constexpr uint32_t FEATURE_APPEARANCE = 0x1;
|
||||
constexpr uint32_t FEATURE_DIALOGUE = 0x2;
|
||||
constexpr uint16_t FEATURE_SENDER_SERVER = 0xff;
|
||||
@@ -234,6 +234,8 @@ constexpr size_t SETUP_PAIRS_MAX = 64;
|
||||
constexpr size_t SETUP_PAIR_MAX_LEN = 512;
|
||||
constexpr size_t SETUP_PAIRS_BLOCK_MAX = sizeof(uint16_t) + SETUP_PAIRS_MAX * (sizeof(uint16_t) + SETUP_PAIR_MAX_LEN);
|
||||
constexpr uint32_t REPLAY_YGOL_SETUP_PAIRS = 0x40000000; // replay flag: uint32_t length + the block, before the names
|
||||
// YGOL life points per side: the setup pair ygol.side.b.lp gives seat side B (seat 1; Tag seats 2 and 3) its own start LP
|
||||
constexpr uint32_t REPLAY_YGOL_SIDE_LP = 0x20000000; // replay flag: int32_t lp[0], int32_t lp[1] in duel player order, after opt
|
||||
extern std::vector<std::string> setup_pairs;
|
||||
bool IsSetupPairToken(const char* token);
|
||||
bool AddSetupPair(const char* token);
|
||||
@@ -462,6 +464,20 @@ constexpr uint8_t ATTACK_PREVIEW_VERSION = 1;
|
||||
constexpr uint8_t ATTACK_PREVIEW_DIRECT = 0xFF;
|
||||
constexpr int ATTACK_PREVIEW_MAX_PAIRS = 64;
|
||||
constexpr int ATTACK_PREVIEW_ANSWER_SIZE = 24; // the ygol_preview_attack answer, echoed after the pair
|
||||
// YGOL tag two fields (proposal 45): in Tag on Master Rule 4/5 each partner has a Field slot (Spell/Trap sequence 5 and 6, the core's
|
||||
// field::has_two_fields); no message, the second field reaches a client as sequence 6. A Tag room refuses a joiner without the bit
|
||||
// (ERRMSG_VERERROR), a Single room does not care; 0x800 is reserved by proposal 44
|
||||
constexpr uint32_t FEATURE_TAG_TWO_FIELDS = 0x1000;
|
||||
// YGOL tag partner cards: the waiting teammate's hand, Extra Deck and deck (ygol_query_tag_cards), sent to that side's two seats only
|
||||
constexpr uint32_t FEATURE_TAG_PARTNER_CARDS = 0x2000;
|
||||
// YGOL tag shared extra (proposal 53): with the setup pair ygol.tag.extra=shared a Tag team has one Extra Deck (option DUEL_TAG_SHARED_EXTRA)
|
||||
// and its Extra Deck refreshes carry QUERY_TAG_MEMBER; a Tag room refuses a joiner without the bit (ERRMSG_VERERROR)
|
||||
constexpr uint32_t FEATURE_TAG_SHARED_EXTRA = 0x4000;
|
||||
// YGOL prompt context (proposal 55): which card and which effect asks (ygol_query_prompt_context), sent to the answering seat right
|
||||
// before every relayed prompt but rock-paper-scissors; never to observers, never in a replay; a room does not refuse a joiner without it
|
||||
constexpr uint32_t FEATURE_PROMPT_CONTEXT = 0x8000;
|
||||
constexpr int PROMPT_CONTEXT_RECORD_SIZE = 23; // the ygol_query_prompt_context answer; the message adds the prompt's MSG id after it
|
||||
constexpr uint8_t TAG_PARTNER_CARDS_VERSION = 1;
|
||||
// the one-use bootstrap secret of a replacement server: a host-string token parsed apart from the ygol.* pairs, never stored anywhere else
|
||||
extern uint8_t bootstrap_secret[16];
|
||||
extern bool bootstrap_closed;
|
||||
@@ -469,6 +485,8 @@ bool IsBootstrapToken(const char* token);
|
||||
void SetBootstrapSecret(const char* token);
|
||||
bool WatchersAllowed();
|
||||
bool SpectatorsSeeAll(); // YGOL spectators see all
|
||||
int32_t SideBStartLp(int32_t fallback); // YGOL life points per side: ygol.side.b.lp, else fallback
|
||||
bool TagSharedExtra(); // YGOL tag shared extra: ygol.tag.extra=shared
|
||||
inline bool IsZeroId(const uint8_t* id) {
|
||||
for(int i = 0; i < 16; ++i)
|
||||
if(id[i])
|
||||
@@ -654,6 +672,7 @@ inline bool IsFeatureMessage(unsigned char pktType) {
|
||||
#define STOC_APPEARANCE 0x41 // uint16_t + CTOS_Appearance
|
||||
#define STOC_DIALOGUE 0x42 // uint16_t + CTOS_Dialogue
|
||||
#define STOC_SETUP_PAIRS 0x43 // uint16_t (0xff) + uint16_t count, then per pair uint16_t length + "key=value"
|
||||
#define STOC_PROMPT_CONTEXT 0x44 // the 23-byte ygol_query_prompt_context record + uint8_t prompt MSG id, no sender stamp, to the answering seat only (YGOL prompt context)
|
||||
#define STOC_SEAT_PLAN 0x50 // uint16_t (0xff) + STOC_SeatPlan (YGOL host seats)
|
||||
// YGOL rules restart: uint16_t (0xff) + the struct
|
||||
#define STOC_ROOM_RESTARTING 0x54 // STOC_RoomRestarting, to each participant with its own seat and token
|
||||
@@ -666,6 +685,7 @@ inline bool IsFeatureMessage(unsigned char pktType) {
|
||||
#define STOC_DECK_LIST 0x5C // STOC_DeckList + uint32_t codes[count], no sender stamp (YGOL deck lists)
|
||||
#define STOC_PROFILE 0x5D // uint16_t + CTOS_Profile (YGOL profile)
|
||||
#define STOC_ATTACK_PREVIEW 0x5E // uint8_t version, uint8_t count, count x (CTOS_AttackPreviewPair + 24-byte answer), no sender stamp, to the asker only (YGOL attack preview)
|
||||
#define STOC_TAG_PARTNER_CARDS 0x5F // uint8_t side + the ygol_query_tag_cards bytes, no sender stamp, to that side's two seats only (YGOL tag partner cards)
|
||||
|
||||
// STOC_GAME_MSG header
|
||||
#define MSG_WAITING 3
|
||||
|
||||
@@ -95,10 +95,21 @@ void SingleDuel::AttackPreview(DuelPlayer* dp, unsigned char* pdata, int len) {
|
||||
return;
|
||||
NetServer::AnswerAttackPreview(dp, pduel, (uint8_t)last_response, preview_attackers, pdata, len);
|
||||
}
|
||||
// YGOL prompt context: STOC_PROMPT_CONTEXT 0x44 = the ygol_query_prompt_context record + the prompt's MSG id, to the seat that answers
|
||||
// the prompt (only when it advertised the bit), right before that prompt; never to observers or the recorders, never in a replay
|
||||
static void SendPromptContext(intptr_t pduel, DuelPlayer* dp, int player, unsigned char msg) {
|
||||
if(!pduel || !dp || !dp->has_capability || !(dp->capability.flags & FEATURE_PROMPT_CONTEXT))
|
||||
return;
|
||||
unsigned char buf[PROMPT_CONTEXT_RECORD_SIZE + 1];
|
||||
if(ygol_query_prompt_context(pduel, (uint8_t)player, buf) != PROMPT_CONTEXT_RECORD_SIZE)
|
||||
return;
|
||||
buf[PROMPT_CONTEXT_RECORD_SIZE] = msg;
|
||||
NetServer::SendBufferToPlayer(dp, STOC_PROMPT_CONTEXT, buf, sizeof buf);
|
||||
}
|
||||
void SingleDuel::SendServerCapability(DuelPlayer* dp) {
|
||||
CTOS_Capability cap;
|
||||
cap.protocol = FEATURE_PROTOCOL;
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW | FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_PARTNER_CARDS | FEATURE_TAG_SHARED_EXTRA | FEATURE_PROMPT_CONTEXT; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag two fields + tag partner cards + tag shared extra + prompt context
|
||||
unsigned char buf[SIZE_STOC_FEATURE];
|
||||
const auto size = NetServer::CreateStampedPacket((unsigned char*)&cap, sizeof cap, buf, FEATURE_SENDER_SERVER);
|
||||
NetServer::SendBufferToPlayer(dp, STOC_CAPABILITY, buf, size);
|
||||
@@ -1222,6 +1233,9 @@ void SingleDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
swapped = true;
|
||||
}
|
||||
dp->state = CTOS_RESPONSE;
|
||||
const int32_t side_b_lp = SideBStartLp(host_info.start_lp); // YGOL life points per side: seat side B keeps its LP through the swap
|
||||
player_lp[0] = swapped ? side_b_lp : host_info.start_lp;
|
||||
player_lp[1] = swapped ? host_info.start_lp : side_b_lp;
|
||||
std::random_device rd;
|
||||
ExtendedReplayHeader rh;
|
||||
rh.base.id = REPLAY_ID_YRP2;
|
||||
@@ -1238,6 +1252,8 @@ void SingleDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
mtrandom rnd(rh.seed_sequence, SEED_COUNT);
|
||||
if(!setup_pairs.empty()) // YGOL setup pairs
|
||||
rh.base.flag |= REPLAY_YGOL_SETUP_PAIRS;
|
||||
if(player_lp[0] != player_lp[1]) // YGOL life points per side
|
||||
rh.base.flag |= REPLAY_YGOL_SIDE_LP;
|
||||
last_replay.BeginRecord();
|
||||
last_replay.WriteHeader(rh);
|
||||
if(!setup_pairs.empty()) {
|
||||
@@ -1285,8 +1301,8 @@ void SingleDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
const auto eq = pair.find('=');
|
||||
set_registry_value(pduel, pair.substr(0, eq).c_str(), pair.c_str() + eq + 1);
|
||||
}
|
||||
set_player_info(pduel, 0, host_info.start_lp, host_info.start_hand, host_info.draw_count);
|
||||
set_player_info(pduel, 1, host_info.start_lp, host_info.start_hand, host_info.draw_count);
|
||||
set_player_info(pduel, 0, player_lp[0], host_info.start_hand, host_info.draw_count); // YGOL life points per side
|
||||
set_player_info(pduel, 1, player_lp[1], host_info.start_hand, host_info.draw_count);
|
||||
preload_script(pduel, "./script/patches/entry.lua");
|
||||
preload_script(pduel, "./script/special.lua");
|
||||
preload_script(pduel, "./script/init.lua");
|
||||
@@ -1298,6 +1314,10 @@ void SingleDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
last_replay.WriteInt32(host_info.start_hand, false);
|
||||
last_replay.WriteInt32(host_info.draw_count, false);
|
||||
last_replay.WriteInt32(opt, false);
|
||||
if(player_lp[0] != player_lp[1]) { // YGOL life points per side: REPLAY_YGOL_SIDE_LP
|
||||
last_replay.WriteInt32(player_lp[0], false);
|
||||
last_replay.WriteInt32(player_lp[1], false);
|
||||
}
|
||||
last_replay.Flush();
|
||||
auto load = [&](const std::vector<const CardDataC*>& deck_container, uint8_t p, uint8_t location) {
|
||||
last_replay.WriteInt32(deck_container.size(), false);
|
||||
@@ -1334,8 +1354,8 @@ void SingleDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
BufferIO::Write<uint8_t>(pbuf, MSG_START);
|
||||
BufferIO::Write<uint8_t>(pbuf, 0);
|
||||
BufferIO::Write<uint8_t>(pbuf, host_info.duel_rule);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[0]); // YGOL life points per side
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[1]);
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_DECK));
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_EXTRA));
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_DECK));
|
||||
@@ -1611,6 +1631,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
RefreshHand(0);
|
||||
RefreshHand(1);
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1635,6 +1656,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
RefreshHand(0);
|
||||
RefreshHand(1);
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1642,6 +1664,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 12;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1649,6 +1672,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 4;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1657,6 +1681,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 4;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1676,6 +1701,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
|
||||
}
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1704,6 +1730,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
|
||||
}
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1712,6 +1739,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 9 + count * 14;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1720,6 +1748,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1727,6 +1756,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1736,6 +1766,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 9;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1748,6 +1779,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 11;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1756,6 +1788,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 7;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2536,6 +2569,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2543,6 +2577,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2552,6 +2587,7 @@ int SingleDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 4 * count;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, players[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(players[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2700,8 +2736,8 @@ void SingleDuel::RequestField(DuelPlayer* dp) {
|
||||
BufferIO::Write<uint8_t>(pbuf, MSG_START);
|
||||
BufferIO::Write<uint8_t>(pbuf, watcher ? ((players[0] == pplayer[0]) ? 0x10 : 0x11) : player); // [YGOL] late watcher: the observer byte lobby watchers get
|
||||
BufferIO::Write<uint8_t>(pbuf, host_info.duel_rule);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[0]); // YGOL life points per side
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[1]);
|
||||
BufferIO::Write<uint16_t>(pbuf, 0);
|
||||
BufferIO::Write<uint16_t>(pbuf, 0);
|
||||
BufferIO::Write<uint16_t>(pbuf, 0);
|
||||
|
||||
@@ -147,6 +147,7 @@ protected:
|
||||
bool ygol_started{};
|
||||
DuelPlayer* players[2]{};
|
||||
DuelPlayer* pplayer[2]{};
|
||||
int32_t player_lp[2]{}; // YGOL life points per side: start LP in duel player order, set at every duel start
|
||||
bool ready[2]{};
|
||||
Deck pdeck[2];
|
||||
int deck_error[2]{};
|
||||
|
||||
+123
-13
@@ -50,6 +50,16 @@ void TagDuel::BroadcastFeature(unsigned char proto, unsigned char* pdata, int le
|
||||
void TagDuel::Capability(DuelPlayer* dp, unsigned char* pdata, int len) {
|
||||
std::memcpy(&dp->capability, pdata, sizeof dp->capability);
|
||||
dp->has_capability = true;
|
||||
// YGOL tag two fields: a client without the bit shows the second Field slot as a Pendulum Zone, so a Tag room refuses it as out of date
|
||||
// YGOL tag shared extra: a client without the bit misreads a shared Extra Deck refresh, the same refusal
|
||||
if((dp->capability.flags & (FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_SHARED_EXTRA)) != (FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_SHARED_EXTRA)) {
|
||||
STOC_ErrorMsg scem;
|
||||
scem.msg = ERRMSG_VERERROR;
|
||||
scem.code = FEATURE_PROTOCOL;
|
||||
NetServer::SendPacketToPlayer(dp, STOC_ERROR_MSG, scem);
|
||||
NetServer::DisconnectAfterFlush(dp);
|
||||
return;
|
||||
}
|
||||
BroadcastFeature(STOC_CAPABILITY, pdata, len, dp->type);
|
||||
}
|
||||
void TagDuel::Appearance(DuelPlayer* dp, unsigned char* pdata, int len) {
|
||||
@@ -93,10 +103,21 @@ void TagDuel::AttackPreview(DuelPlayer* dp, unsigned char* pdata, int len) {
|
||||
return;
|
||||
NetServer::AnswerAttackPreview(dp, pduel, (uint8_t)last_response, preview_attackers, pdata, len);
|
||||
}
|
||||
// YGOL prompt context: STOC_PROMPT_CONTEXT 0x44 = the ygol_query_prompt_context record + the prompt's MSG id, to the seat that answers
|
||||
// the prompt (only when it advertised the bit), right before that prompt; never to observers or the recorders, never in a replay
|
||||
static void SendPromptContext(intptr_t pduel, DuelPlayer* dp, int player, unsigned char msg) {
|
||||
if(!pduel || !dp || !dp->has_capability || !(dp->capability.flags & FEATURE_PROMPT_CONTEXT))
|
||||
return;
|
||||
unsigned char buf[PROMPT_CONTEXT_RECORD_SIZE + 1];
|
||||
if(ygol_query_prompt_context(pduel, (uint8_t)player, buf) != PROMPT_CONTEXT_RECORD_SIZE)
|
||||
return;
|
||||
buf[PROMPT_CONTEXT_RECORD_SIZE] = msg;
|
||||
NetServer::SendBufferToPlayer(dp, STOC_PROMPT_CONTEXT, buf, sizeof buf);
|
||||
}
|
||||
void TagDuel::SendServerCapability(DuelPlayer* dp) {
|
||||
CTOS_Capability cap;
|
||||
cap.protocol = FEATURE_PROTOCOL;
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview
|
||||
cap.flags = FEATURE_APPEARANCE | FEATURE_DIALOGUE | FEATURE_SETUP_PAIRS | FEATURE_SEAT_PLAN | FEATURE_RULES_RESTART | FEATURE_SEAT_STATE | FEATURE_LOBBY_AFTER_MATCH | FEATURE_COIN_TOSS | FEATURE_DECK_LIST | FEATURE_PROFILE | FEATURE_ATTACK_PREVIEW | FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_PARTNER_CARDS | FEATURE_TAG_SHARED_EXTRA | FEATURE_PROMPT_CONTEXT; // YGOL setup pairs + host seats + rules restart + seat state + lobby after match + coin toss + deck lists + profile + attack preview + tag two fields + tag partner cards + tag shared extra + prompt context
|
||||
unsigned char buf[SIZE_STOC_FEATURE];
|
||||
const auto size = NetServer::CreateStampedPacket((unsigned char*)&cap, sizeof cap, buf, FEATURE_SENDER_SERVER);
|
||||
NetServer::SendBufferToPlayer(dp, STOC_CAPABILITY, buf, size);
|
||||
@@ -1214,6 +1235,9 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
std::swap(pdeck[1], pdeck[3]);
|
||||
swapped = true;
|
||||
}
|
||||
const int32_t side_b_lp = SideBStartLp(host_info.start_lp); // YGOL life points per side: seat side B keeps its LP through the swap
|
||||
player_lp[0] = swapped ? side_b_lp : host_info.start_lp;
|
||||
player_lp[1] = swapped ? host_info.start_lp : side_b_lp;
|
||||
turn_count = 0;
|
||||
cur_player[0] = players[0];
|
||||
cur_player[1] = players[2]; // YGOL first seat holds the hand: the engine skips the swap on a team's first turn
|
||||
@@ -1234,6 +1258,8 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
mtrandom rnd(rh.seed_sequence, SEED_COUNT);
|
||||
if(!setup_pairs.empty()) // YGOL setup pairs
|
||||
rh.base.flag |= REPLAY_YGOL_SETUP_PAIRS;
|
||||
if(player_lp[0] != player_lp[1]) // YGOL life points per side
|
||||
rh.base.flag |= REPLAY_YGOL_SIDE_LP;
|
||||
last_replay.BeginRecord();
|
||||
last_replay.WriteHeader(rh);
|
||||
if(!setup_pairs.empty()) {
|
||||
@@ -1282,8 +1308,8 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
const auto eq = pair.find('=');
|
||||
set_registry_value(pduel, pair.substr(0, eq).c_str(), pair.c_str() + eq + 1);
|
||||
}
|
||||
set_player_info(pduel, 0, host_info.start_lp, host_info.start_hand, host_info.draw_count);
|
||||
set_player_info(pduel, 1, host_info.start_lp, host_info.start_hand, host_info.draw_count);
|
||||
set_player_info(pduel, 0, player_lp[0], host_info.start_hand, host_info.draw_count); // YGOL life points per side
|
||||
set_player_info(pduel, 1, player_lp[1], host_info.start_hand, host_info.draw_count);
|
||||
preload_script(pduel, "./script/patches/entry.lua");
|
||||
preload_script(pduel, "./script/special.lua");
|
||||
preload_script(pduel, "./script/init.lua");
|
||||
@@ -1292,10 +1318,17 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
if(host_info.no_shuffle_deck)
|
||||
opt |= DUEL_PSEUDO_SHUFFLE;
|
||||
opt |= DUEL_TAG_MODE;
|
||||
const bool shared_extra = TagSharedExtra(); // YGOL tag shared extra
|
||||
if(shared_extra)
|
||||
opt |= DUEL_TAG_SHARED_EXTRA;
|
||||
last_replay.WriteInt32(host_info.start_lp, false);
|
||||
last_replay.WriteInt32(host_info.start_hand, false);
|
||||
last_replay.WriteInt32(host_info.draw_count, false);
|
||||
last_replay.WriteInt32(opt, false);
|
||||
if(player_lp[0] != player_lp[1]) { // YGOL life points per side: REPLAY_YGOL_SIDE_LP
|
||||
last_replay.WriteInt32(player_lp[0], false);
|
||||
last_replay.WriteInt32(player_lp[1], false);
|
||||
}
|
||||
last_replay.Flush();
|
||||
auto load_single = [&](const std::vector<const CardDataC*>& deck_container, uint8_t p, uint8_t location) {
|
||||
last_replay.WriteInt32(deck_container.size(), false);
|
||||
@@ -1304,7 +1337,10 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
last_replay.WriteInt32((*cit)->code, false);
|
||||
}
|
||||
};
|
||||
uint16_t merged_extra[2]{}; // YGOL tag shared extra: what start_duel adds to each team's Extra Deck
|
||||
auto load_tag = [&](const std::vector<const CardDataC*>& deck_container, uint8_t p, uint8_t location) {
|
||||
if(shared_extra && location == LOCATION_EXTRA)
|
||||
merged_extra[p] = (uint16_t)deck_container.size();
|
||||
last_replay.WriteInt32(deck_container.size(), false);
|
||||
for (auto cit = deck_container.rbegin(); cit != deck_container.rend(); ++cit) {
|
||||
new_tag_card(pduel, (*cit)->code, p, location);
|
||||
@@ -1347,12 +1383,12 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
BufferIO::Write<uint8_t>(pbuf, MSG_START);
|
||||
BufferIO::Write<uint8_t>(pbuf, 0);
|
||||
BufferIO::Write<uint8_t>(pbuf, host_info.duel_rule);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[0]); // YGOL life points per side
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[1]);
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_DECK));
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_EXTRA));
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 0, LOCATION_EXTRA) + merged_extra[0]);
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_DECK));
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_EXTRA));
|
||||
BufferIO::Write<uint16_t>(pbuf, query_field_count(pduel, 1, LOCATION_EXTRA) + merged_extra[1]);
|
||||
NetServer::SendBufferToPlayer(players[0], STOC_GAME_MSG, startbuf, 19);
|
||||
NetServer::ReSendToPlayer(players[1]);
|
||||
startbuf[1] = 1;
|
||||
@@ -1372,9 +1408,18 @@ void TagDuel::TPResult(DuelPlayer* dp, unsigned char tp) {
|
||||
phase = 1;
|
||||
deck_reversed = false;
|
||||
#endif
|
||||
RefreshExtra(0);
|
||||
RefreshExtra(1);
|
||||
if(!shared_extra) {
|
||||
RefreshExtra(0);
|
||||
RefreshExtra(1);
|
||||
}
|
||||
start_duel(pduel, opt);
|
||||
if(shared_extra) { // YGOL tag shared extra: start_duel merged the lists
|
||||
RefreshExtra(0);
|
||||
RefreshExtra(1);
|
||||
}
|
||||
tag_cards_known[0] = tag_cards_known[1] = false;
|
||||
SendTagPartnerCards(0); // YGOL tag partner cards: the waiting members' opening hands
|
||||
SendTagPartnerCards(1);
|
||||
if(host_info.time_limit) {
|
||||
time_elapsed = 0;
|
||||
#ifdef YGOPRO_SERVER_MODE
|
||||
@@ -1409,8 +1454,10 @@ void TagDuel::Process() {
|
||||
stop = Analyze(engineBuffer.data(), engLen);
|
||||
}
|
||||
}
|
||||
if(stop != 2) // YGOL deck lists: after every engine batch, before a prompt waits
|
||||
if(stop != 2) { // YGOL deck lists + tag partner cards: after every engine batch, before a prompt waits
|
||||
FlushDeckLists();
|
||||
FlushTagPartnerCards();
|
||||
}
|
||||
if(stop == 2)
|
||||
DuelEndProc();
|
||||
}
|
||||
@@ -1573,6 +1620,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
RefreshHand(0);
|
||||
RefreshHand(1);
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1597,6 +1645,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
RefreshHand(0);
|
||||
RefreshHand(1);
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1604,6 +1653,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 12;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1611,6 +1661,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 4;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1619,6 +1670,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 4;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1638,6 +1690,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
|
||||
}
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1666,6 +1719,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
if (c != player) BufferIO::Write<int32_t>(pbufw, 0);
|
||||
}
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1674,6 +1728,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 9 + count * 14;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1682,6 +1737,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1689,6 +1745,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1698,6 +1755,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 9;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1710,6 +1768,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 11;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -1718,6 +1777,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += count * 7;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2631,6 +2691,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2638,6 +2699,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
player = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 5;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2647,6 +2709,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
count = BufferIO::Read<uint8_t>(pbuf);
|
||||
pbuf += 4 * count;
|
||||
WaitforResponse(player);
|
||||
SendPromptContext(pduel, cur_player[player], player, engType);
|
||||
NetServer::SendBufferToPlayer(cur_player[player], STOC_GAME_MSG, offset, pbuf - offset);
|
||||
return 1;
|
||||
}
|
||||
@@ -2722,6 +2785,7 @@ int TagDuel::Analyze(unsigned char* msgbuffer, unsigned int len) {
|
||||
RefreshSzone(1, 0x681fff, 0);
|
||||
RefreshHand(0, 0x781fff, 0);
|
||||
RefreshHand(1, 0x781fff, 0);
|
||||
SendTagPartnerCards(player); // YGOL tag partner cards: the member that just left is the waiting one now
|
||||
break;
|
||||
}
|
||||
case MSG_MATCH_KILL: {
|
||||
@@ -2849,8 +2913,8 @@ void TagDuel::RequestField(DuelPlayer* dp) {
|
||||
BufferIO::Write<uint8_t>(pbuf, MSG_START);
|
||||
BufferIO::Write<uint8_t>(pbuf, watcher ? ((players[0] == pplayer[0]) ? 0x10 : 0x11) : player); // [YGOL] late watcher: the observer byte lobby watchers get
|
||||
BufferIO::Write<uint8_t>(pbuf, host_info.duel_rule);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, host_info.start_lp);
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[0]); // YGOL life points per side
|
||||
BufferIO::Write<int32_t>(pbuf, player_lp[1]);
|
||||
BufferIO::Write<uint16_t>(pbuf, 0);
|
||||
BufferIO::Write<uint16_t>(pbuf, 0);
|
||||
BufferIO::Write<uint16_t>(pbuf, 0);
|
||||
@@ -2892,17 +2956,21 @@ void TagDuel::RequestField(DuelPlayer* dp) {
|
||||
|
||||
// YGOL deck lists: the snapshot carries the lists this connection may see
|
||||
if(watcher) {
|
||||
if(SpectatorsSeeAll())
|
||||
if(SpectatorsSeeAll()) {
|
||||
for(int i = 0; i < 2; ++i)
|
||||
for(uint8_t kind = DECK_LIST_ORDERED; kind <= DECK_LIST_SUBMITTED; ++kind) {
|
||||
std::vector<uint32_t> codes;
|
||||
if(BuildDeckList(i, kind, codes))
|
||||
SendDeckList(dp, i, kind, codes);
|
||||
}
|
||||
SendTagPartnerCards(0, dp); // YGOL tag partner cards: a watcher that sees all gets both sides (TICKET-412)
|
||||
SendTagPartnerCards(1, dp);
|
||||
}
|
||||
} else {
|
||||
std::vector<uint32_t> codes;
|
||||
if(BuildDeckList(player, DECK_LIST_SORTED, codes))
|
||||
SendDeckList(dp, player, DECK_LIST_SORTED, codes);
|
||||
SendTagPartnerCards(player, dp); // YGOL tag partner cards: a seat's field resync carries its side's waiting cards
|
||||
}
|
||||
|
||||
uint8_t query_buffer[SIZE_QUERY_BUFFER];
|
||||
@@ -3032,6 +3100,46 @@ void TagDuel::FlushDeckLists() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// YGOL tag partner cards: STOC_TAG_PARTNER_CARDS 0x5F = uint8_t side + the ygol_query_tag_cards bytes, to that side's two
|
||||
// seats (never the other team) and, when spectators see all, to every observer: after start_duel, after every
|
||||
// MSG_TAG_SWAP, after any engine batch that changed the side's bytes (TICKET-424), in a seat's field resync (its side)
|
||||
// and in an observer's resync / late-watcher snapshot (both sides). A broadcast records the bytes it sent; a send to
|
||||
// one player (a resync) does not, so it never hides a change the others have not had.
|
||||
void TagDuel::SendTagPartnerCards(int side, DuelPlayer* dp) {
|
||||
if(!pduel)
|
||||
return;
|
||||
unsigned char buf[1 + 6 + (2 * UINT8_MAX + MAINC_MAX) * sizeof(uint32_t)];
|
||||
buf[0] = (uint8_t)side;
|
||||
const int len = ygol_query_tag_cards(pduel, (uint8_t)side, buf + 1);
|
||||
if(len <= 0)
|
||||
return;
|
||||
if(dp) {
|
||||
NetServer::SendBufferToPlayer(dp, STOC_TAG_PARTNER_CARDS, buf, 1 + len);
|
||||
return;
|
||||
}
|
||||
tag_cards_sent[side].assign(buf + 1, buf + 1 + len);
|
||||
tag_cards_known[side] = true;
|
||||
for(int seat = side * 2; seat < side * 2 + 2; ++seat)
|
||||
if(players[seat])
|
||||
NetServer::SendBufferToPlayer(players[seat], STOC_TAG_PARTNER_CARDS, buf, 1 + len);
|
||||
if(SpectatorsSeeAll()) // YGOL spectators see all: every observer gets both sides (TICKET-412)
|
||||
for(auto oit = observers.begin(); oit != observers.end(); ++oit)
|
||||
NetServer::SendBufferToPlayer(*oit, STOC_TAG_PARTNER_CARDS, buf, 1 + len);
|
||||
}
|
||||
void TagDuel::FlushTagPartnerCards() {
|
||||
if(!pduel)
|
||||
return;
|
||||
unsigned char buf[1 + 6 + (2 * UINT8_MAX + MAINC_MAX) * sizeof(uint32_t)];
|
||||
for(int side = 0; side < 2; ++side) {
|
||||
const int len = ygol_query_tag_cards(pduel, (uint8_t)side, buf);
|
||||
if(len <= 0)
|
||||
continue;
|
||||
if(tag_cards_known[side] && tag_cards_sent[side].size() == (size_t)len
|
||||
&& std::equal(tag_cards_sent[side].begin(), tag_cards_sent[side].end(), buf))
|
||||
continue;
|
||||
SendTagPartnerCards(side);
|
||||
}
|
||||
}
|
||||
void TagDuel::TimeConfirm(DuelPlayer* dp) {
|
||||
if(host_info.time_limit == 0)
|
||||
return;
|
||||
@@ -3306,6 +3414,8 @@ void TagDuel::RefreshExtra(int player, int flag, int use_cache, DuelPlayer* dp)
|
||||
void TagDuel::RefreshExtra(int player, int flag, int use_cache)
|
||||
#endif //YGOPRO_SERVER_MODE
|
||||
{
|
||||
if(TagSharedExtra()) // YGOL tag shared extra
|
||||
flag |= QUERY_TAG_MEMBER;
|
||||
std::array<unsigned char, SIZE_QUERY_BUFFER> query_buffer;
|
||||
auto qbuf = query_buffer.data();
|
||||
auto len = WriteUpdateData(player, LOCATION_EXTRA, flag, qbuf, use_cache);
|
||||
|
||||
@@ -99,6 +99,10 @@ protected:
|
||||
bool has_profile[4]{};
|
||||
CTOS_Profile profile[4]{};
|
||||
std::vector<uint16_t> preview_attackers; // YGOL attack preview: location << 8 | sequence of every attacker the open battle prompt lists
|
||||
void SendTagPartnerCards(int side, DuelPlayer* dp = nullptr); // YGOL tag partner cards: STOC 0x5F to the side's two seats (+ every observer when they see all), or to dp alone
|
||||
void FlushTagPartnerCards(); // YGOL tag partner cards: after every engine batch, a side whose bytes changed since its last broadcast sends again (TICKET-424)
|
||||
std::vector<unsigned char> tag_cards_sent[2];
|
||||
bool tag_cards_known[2]{};
|
||||
// YGOL coin toss
|
||||
void BeginChoose(int chooser, uint8_t face);
|
||||
int choose_seat{};
|
||||
@@ -150,6 +154,7 @@ protected:
|
||||
bool ygol_started{};
|
||||
DuelPlayer* players[4]{};
|
||||
DuelPlayer* pplayer[4]{};
|
||||
int32_t player_lp[2]{}; // YGOL life points per side: start LP in duel player order, set at every duel start
|
||||
DuelPlayer* cur_player[2]{};
|
||||
std::set<DuelPlayer*> observers;
|
||||
#ifdef YGOPRO_SERVER_MODE
|
||||
|
||||
Reference in new issue
Block a user