Files
yugioh-legacy-engine/binding/YGOLegacy.Engine/Protocol/Codecs/StocCodecs.cs
T
donnyandClaude Fable 5.1 7ec61d18e6
Release / windows (push) Successful in 33s
Release / android (push) Successful in 41s
Release / linux (push) Successful in 1m8s
Release / release (push) Skipped
Release / attach-windows (push) Skipped
binding: YGOLegacy.Engine carries the wire protocol; CI builds, tests and ships ygol-engine-binding.zip (TICKET-397)
binding/YGOLegacy.Engine (netstandard2.1, LangVersion 9, unsafe, no package, no Unity
reference) holds the Unity repo's Assets/YGOLegacy/Scripts/Protocol/ as
Protocol/{Contracts,Codecs,Framing,Routing}: 12 files copied byte-identical (LF), namespaces
YGOLegacy.Protocol.* unchanged. EngineVersion (default local) is stamped as the informational
version, so the DLL's ProductVersion is the tag it was built for.

binding/YGOLegacy.Engine.Tests (net8.0, NUnit 3.14) holds the six fixtures. 114 tests pass,
the Unity Edit Mode count. Two deviations from "as-is", lead-approved 2026-10-15:
LegacyReaders.cs is a frozen test-only copy of the legacy MDPro3 / YGOSharp readers and enums
the parity tests compare against (they live only in the Unity repo), and FrameCodecTests.cs
line 35 casts (short) instead of (byte): BitConverter.GetBytes((byte)) is ambiguous on
net8.0 (the Half overload), same bytes written.

The windows job builds and tests the binding after the native gates (both with
-p:EngineVersion so the test's project reference does not restamp the DLL as local), checks
the ProductVersion and stages ygol-engine-binding.zip (YGOLegacy.Engine.dll + .pdb) beside
ygol-engine-win64.zip; attach-windows attaches both. engine.json gains "binding": "<version>"
on every platform (windows.ps1 and the Dockerfile's export-gate, the only writers) and the
release job's agreement check includes it. README gains the Binding section and the asset row;
.gitignore ignores binding/**/bin and obj.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DJUFwdiGCHipsxLkgxssSR
2026-10-15 16:14:17 -07:00

394 lines
15 KiB
C#

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();
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);
}
}
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());
}
}
}