Documentation
¶
Overview ¶
Package wire defines the YAML wire message schema format for pkg/online/netplay and game protocols, integer-only quantization helpers, bit-packing primitives, and deterministic zero-allocation Go and TypeScript codec generators.
Schema files declare fixed-width integers (with explicit big- or little-endian byte order), varints, zigzag signed varints, booleans, raw float32 values, integer-quantized qfloat and fixed-point numbers, length-prefixed or trailing bytes and strings, fixed and variable arrays, enums, MSB-first bit-packed fields, presence-bitmask groups with optional delta diff/apply generation, and tag- or nibble-discriminated unions.
Run game wire (directly or through go generate) to produce deterministic Go codecs (AppendX / DecodeX) and dependency-free TypeScript codecs (encodeX / decodeX, plus diffX / applyX for delta masks) that fill caller-owned storage without per-packet heap allocations.
Index ¶
- Constants
- Variables
- func AppendChannel(dst []byte, v Channel) []byte
- func AppendChecksumMsg(dst []byte, m *ChecksumMsg) []byte
- func AppendEntityRecord(dst []byte, m *EntityRecord) []byte
- func AppendHandshakeHello(dst []byte, m *HandshakeHello) []byte
- func AppendHandshakeMessage(dst []byte, m *HandshakeMessage) []byte
- func AppendHandshakeReject(dst []byte, m *HandshakeReject) []byte
- func AppendHandshakeWelcome(dst []byte, m *HandshakeWelcome) []byte
- func AppendInputBundle(dst []byte, m *InputBundle) []byte
- func AppendInputFrame(dst []byte, m *InputFrame) []byte
- func AppendJoinState(dst []byte, m *JoinState) []byte
- func AppendJoinStatePart(dst []byte, m *JoinStatePart) []byte
- func AppendMatchMember(dst []byte, m *MatchMember) []byte
- func AppendMemberChange(dst []byte, m *MemberChange) []byte
- func AppendMemberChangeKind(dst []byte, v MemberChangeKind) []byte
- func AppendMembershipMessage(dst []byte, m *MembershipMessage) []byte
- func AppendRelayAck(dst []byte, m *RelayAck) []byte
- func AppendRelayBody(dst []byte, m *RelayBody) []byte
- func AppendRelayFrame(dst []byte, m *RelayFrame) []byte
- func AppendRelayMembers(dst []byte, m *RelayMembers) []byte
- func AppendRelayReliable(dst []byte, m *RelayReliable) []byte
- func AppendRelayUnreliable(dst []byte, m *RelayUnreliable) []byte
- func AppendReplicationMessage(dst []byte, m *ReplicationMessage) []byte
- func AppendResyncRequest(dst []byte, m *ResyncRequest) []byte
- func AppendRollbackMessage(dst []byte, m *RollbackMessage) []byte
- func AppendSingleInput(dst []byte, m *SingleInput) []byte
- func AppendSnapshotAck(dst []byte, m *SnapshotAck) []byte
- func AppendSnapshotDelta(dst []byte, m *SnapshotDelta) []byte
- func AppendSnapshotFull(dst []byte, m *SnapshotFull) []byte
- func AppendSnapshotFullPart(dst []byte, m *SnapshotFullPart) []byte
- func AppendTransportFrame(dst []byte, m *TransportFrame) []byte
- func AppendUDPDatagramType(dst []byte, v UDPDatagramType) []byte
- func AppendUDPPeerFrame(dst []byte, m *UDPPeerFrame) []byte
- func AppendUDPSealedDatagram(dst []byte, m *UDPSealedDatagram) []byte
- func ApplyEntityRecord(dst, delta *EntityRecord)
- func BuiltinFiles() ([]string, error)
- func DecodeChannel(src []byte, v *Channel) (int, error)
- func DecodeChecksumMsg(src []byte, m *ChecksumMsg) (int, error)
- func DecodeEntityRecord(src []byte, m *EntityRecord) (int, error)
- func DecodeHandshakeHello(src []byte, m *HandshakeHello) (int, error)
- func DecodeHandshakeMessage(src []byte, m *HandshakeMessage) (int, error)
- func DecodeHandshakeReject(src []byte, m *HandshakeReject) (int, error)
- func DecodeHandshakeWelcome(src []byte, m *HandshakeWelcome) (int, error)
- func DecodeInputBundle(src []byte, m *InputBundle) (int, error)
- func DecodeInputFrame(src []byte, m *InputFrame) (int, error)
- func DecodeJoinState(src []byte, m *JoinState) (int, error)
- func DecodeJoinStatePart(src []byte, m *JoinStatePart) (int, error)
- func DecodeMatchMember(src []byte, m *MatchMember) (int, error)
- func DecodeMemberChange(src []byte, m *MemberChange) (int, error)
- func DecodeMemberChangeKind(src []byte, v *MemberChangeKind) (int, error)
- func DecodeMembershipMessage(src []byte, m *MembershipMessage) (int, error)
- func DecodeRelayAck(src []byte, m *RelayAck) (int, error)
- func DecodeRelayBody(src []byte, m *RelayBody) (int, error)
- func DecodeRelayFrame(src []byte, m *RelayFrame) (int, error)
- func DecodeRelayMembers(src []byte, m *RelayMembers) (int, error)
- func DecodeRelayReliable(src []byte, m *RelayReliable) (int, error)
- func DecodeRelayUnreliable(src []byte, m *RelayUnreliable) (int, error)
- func DecodeReplicationMessage(src []byte, m *ReplicationMessage) (int, error)
- func DecodeResyncRequest(src []byte, m *ResyncRequest) (int, error)
- func DecodeRollbackMessage(src []byte, m *RollbackMessage) (int, error)
- func DecodeSingleInput(src []byte, m *SingleInput) (int, error)
- func DecodeSnapshotAck(src []byte, m *SnapshotAck) (int, error)
- func DecodeSnapshotDelta(src []byte, m *SnapshotDelta) (int, error)
- func DecodeSnapshotFull(src []byte, m *SnapshotFull) (int, error)
- func DecodeSnapshotFullPart(src []byte, m *SnapshotFullPart) (int, error)
- func DecodeTransportFrame(src []byte, m *TransportFrame) (int, error)
- func DecodeUDPDatagramType(src []byte, v *UDPDatagramType) (int, error)
- func DecodeUDPPeerFrame(src []byte, m *UDPPeerFrame) (int, error)
- func DecodeUDPSealedDatagram(src []byte, m *UDPSealedDatagram) (int, error)
- func DequantizeFixed(q, scale int64) float64
- func DequantizeFixedUint(q uint64, scale int64) float64
- func DequantizeFloat(q uint32, minVal, maxVal float32, bits int) float32
- func DiffEntityRecord(base, cur *EntityRecord) uint8
- func Encode(s *Schema) ([]byte, error)
- func FrameMessageType(frame DecodedFrame) string
- func GenerateGo(schema *Schema, opts GenerateOptions) ([]byte, error)
- func GenerateTS(schema *Schema, opts TSGenerateOptions) ([]byte, error)
- func GenerateTSIndex(schemaFileNames []string) []byte
- func GenerateTSRuntime() []byte
- func QuantizeFixed(v float64, scale, minInt, maxInt int64) int64
- func QuantizeFixedUint(v float64, scale int64, maxUint uint64) uint64
- func QuantizeFloat(v, minVal, maxVal float32, bits int) uint32
- func TSOutputFileName(schemaBaseName string) string
- func Validate(s *Schema) error
- func ValidateAll(schemas []*Schema) error
- type ArraySpec
- type BitReader
- type BitWriter
- type ByteOrder
- type CaptureStats
- type Channel
- type ChecksumMsg
- type DecodedEnum
- type DecodedField
- type DecodedFrame
- type DecodedLayer
- type DecodedMask
- type DecodedObject
- type DecodedPayload
- type DecodedUnion
- type Discriminator
- type EntityRecord
- type Enum
- type EnumValue
- type Field
- type FixedSpec
- type GenerateOptions
- type HandshakeHello
- type HandshakeMessage
- type HandshakeReject
- type HandshakeWelcome
- type InputBundle
- type InputFrame
- type InspectOptions
- type Inspector
- func (ins *Inspector) ComputeStats(frames []DecodedFrame) CaptureStats
- func (ins *Inspector) DecodeRawFrameText(text string) ([]byte, error)
- func (ins *Inspector) InspectCaptureRecord(index int, t int64, dir string, peer uint32, ch uint8, seq uint32, ...) DecodedFrame
- func (ins *Inspector) InspectRawFrame(index int, raw []byte) DecodedFrame
- func (ins *Inspector) ReencodeLayers(layers []DecodedLayer) ([]byte, error)
- func (ins *Inspector) ReencodePayload(frame DecodedFrame) ([]byte, error)
- func (ins *Inspector) Registry() *Registry
- type JoinState
- type JoinStatePart
- type MaskSpec
- type MatchMember
- type MemberChange
- type MemberChangeKind
- type MembershipMessage
- type Message
- type NamedSchema
- type PeerStats
- type QFloatSpec
- type Registry
- func (r *Registry) CustomMessages() []string
- func (r *Registry) CustomUnions() []string
- func (r *Registry) DecodeMessage(name string, src []byte) (DecodedObject, int, error)
- func (r *Registry) DecodeUnion(name string, src []byte) (DecodedUnion, int, error)
- func (r *Registry) EncodeMessage(name string, obj DecodedObject) ([]byte, error)
- func (r *Registry) EncodeUnion(du DecodedUnion) ([]byte, error)
- type RelayAck
- type RelayBody
- type RelayFrame
- type RelayMembers
- type RelayReliable
- type RelayUnreliable
- type ReplicationMessage
- type ResyncRequest
- type RollbackMessage
- type Schema
- type SingleInput
- type SnapshotAck
- type SnapshotDelta
- type SnapshotFull
- type SnapshotFullPart
- type TSGenerateOptions
- type TransportFrame
- type TypeStats
- type UDPDatagramType
- type UDPPeerFrame
- type UDPSealedDatagram
- type Union
- type UnionCase
- type WireBytes
Examples ¶
Constants ¶
const ( // Client hello (0xA1). HandshakeMessageTagHello uint8 = 161 // Server welcome (0xA2). HandshakeMessageTagWelcome uint8 = 162 // Server rejection (0xA3). HandshakeMessageTagReject uint8 = 163 )
const ( // Join or leave announcement (tag 13). MembershipMessageTagChange uint8 = 13 // Join state fragment (tag 14). MembershipMessageTagJoinStatePart uint8 = 14 )
const ( // Unreliable peer datagram (0x01). RelayBodyTagUnreliable uint8 = 1 // Reliable ordered peer segment (0x02). RelayBodyTagReliable uint8 = 2 // Cumulative + 64-bit SACK acknowledgment (0x03). RelayBodyTagAck uint8 = 3 )
const ( EntityRecordFieldKind uint8 = 1 << 0 EntityRecordFieldX uint8 = 1 << 1 EntityRecordFieldY uint8 = 1 << 2 EntityRecordFieldVX uint8 = 1 << 3 EntityRecordFieldVY uint8 = 1 << 4 EntityRecordFieldRotation uint8 = 1 << 5 EntityRecordFieldFlags uint8 = 1 << 6 EntityRecordFieldProps uint8 = 1 << 7 EntityRecordMaskValid uint8 = 0xff )
const ( ReplicationMessageVersion uint8 = 2 // Full snapshot (type 1). ReplicationMessageTagFull uint8 = 1 // Delta snapshot (type 2). ReplicationMessageTagDelta uint8 = 2 // Snapshot acknowledgment (type 3). ReplicationMessageTagAck uint8 = 3 // Full snapshot resync request (type 4). ReplicationMessageTagResync uint8 = 4 // Split full snapshot part (type 5). ReplicationMessageTagFullPart uint8 = 5 )
const ( // Single input sample (tag 10). RollbackMessageTagSingleInput uint8 = 10 // Redundant input bundle (tag 11). RollbackMessageTagInputBundle uint8 = 11 // Periodic desync checksum (tag 12). RollbackMessageTagChecksum uint8 = 12 )
const CurrentVersion = 1
CurrentVersion is the wire schema YAML format version this package reads and writes.
const DefaultRuntimeImport = "github.com/nsgo-dev/game/pkg/online/netplay/wire"
DefaultRuntimeImport is the Go import path used by generated codecs outside pkg/online/netplay/wire.
const DefaultTSRuntimeImport = "./runtime.ts"
DefaultTSRuntimeImport is the ES module specifier imported by generated TypeScript codecs when EmbedRuntime is false.
const (
HandshakeHelloVersion uint8 = 1
)
const (
HandshakeRejectVersion uint8 = 1
)
const (
HandshakeWelcomeVersion uint8 = 1
)
const (
RelayFrameVersion uint8 = 1
)
const (
RelayMembersKind uint8 = 1
)
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL
SchemaComment is the yaml-language-server header line Encode writes at the top of a wire schema file.
const SchemaURL = "https://game.nsgo.dev/schemas/wire.v1.json"
SchemaURL is where the JSON Schema of version 1 wire schema files (*.wire.yaml) is published.
Variables ¶
var ( // ErrShortBuffer is returned when the input slice ends before a message or field is complete. ErrShortBuffer = errors.New("wire: short buffer") // ErrOverflow is returned when a varint overflows 64 bits or exceeds the field's declared bit width. ErrOverflow = errors.New("wire: integer overflow") // ErrInvalidBool is returned when a boolean byte on the wire is neither 0 nor 1. ErrInvalidBool = errors.New("wire: invalid boolean value") // ErrInvalidEnum is returned when a decoded enum integer does not match any declared enum value. ErrInvalidEnum = errors.New("wire: unknown enum value") // ErrInvalidTag is returned when a union discriminator does not match any declared case tag. ErrInvalidTag = errors.New("wire: unknown message tag") // ErrInvalidVersion is returned when a nibble-split discriminator carries an unexpected high-bit version value. ErrInvalidVersion = errors.New("wire: unexpected protocol version") // ErrInvalidConst is returned when a constant wire field does not match its declared value. ErrInvalidConst = errors.New("wire: unexpected constant field value") // ErrInvalidMask is returned when a presence bitmask sets bits beyond the mask group's declared fields. ErrInvalidMask = errors.New("wire: unknown presence mask bit") // ErrNonZeroPadding is returned when trailing padding bits in a bit-packed byte are non-zero. ErrNonZeroPadding = errors.New("wire: non-zero bit padding") // ErrLimitExceeded is returned when a variable-length bytes, string, or array field exceeds its schema maxLength. ErrLimitExceeded = errors.New("wire: length limit exceeded") )
var BuiltinFS embed.FS
BuiltinFS embeds the canonical YAML wire schemas describing every pkg/net wire format (transport, UDP sealed datagrams, handshake, relay, replication v2, lockstep/rollback, and membership).
Functions ¶
func AppendChannel ¶
AppendChannel appends v to dst in wire format.
func AppendChecksumMsg ¶
func AppendChecksumMsg(dst []byte, m *ChecksumMsg) []byte
AppendChecksumMsg encodes m onto dst in wire format without allocating when dst has capacity.
func AppendEntityRecord ¶
func AppendEntityRecord(dst []byte, m *EntityRecord) []byte
AppendEntityRecord encodes m onto dst in wire format without allocating when dst has capacity.
func AppendHandshakeHello ¶
func AppendHandshakeHello(dst []byte, m *HandshakeHello) []byte
AppendHandshakeHello encodes m onto dst in wire format without allocating when dst has capacity.
func AppendHandshakeMessage ¶
func AppendHandshakeMessage(dst []byte, m *HandshakeMessage) []byte
AppendHandshakeMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.
func AppendHandshakeReject ¶
func AppendHandshakeReject(dst []byte, m *HandshakeReject) []byte
AppendHandshakeReject encodes m onto dst in wire format without allocating when dst has capacity.
func AppendHandshakeWelcome ¶
func AppendHandshakeWelcome(dst []byte, m *HandshakeWelcome) []byte
AppendHandshakeWelcome encodes m onto dst in wire format without allocating when dst has capacity.
func AppendInputBundle ¶
func AppendInputBundle(dst []byte, m *InputBundle) []byte
AppendInputBundle encodes m onto dst in wire format without allocating when dst has capacity.
func AppendInputFrame ¶
func AppendInputFrame(dst []byte, m *InputFrame) []byte
AppendInputFrame encodes m onto dst in wire format without allocating when dst has capacity.
func AppendJoinState ¶
AppendJoinState encodes m onto dst in wire format without allocating when dst has capacity.
func AppendJoinStatePart ¶
func AppendJoinStatePart(dst []byte, m *JoinStatePart) []byte
AppendJoinStatePart encodes m onto dst in wire format without allocating when dst has capacity.
func AppendMatchMember ¶
func AppendMatchMember(dst []byte, m *MatchMember) []byte
AppendMatchMember encodes m onto dst in wire format without allocating when dst has capacity.
func AppendMemberChange ¶
func AppendMemberChange(dst []byte, m *MemberChange) []byte
AppendMemberChange encodes m onto dst in wire format without allocating when dst has capacity.
func AppendMemberChangeKind ¶
func AppendMemberChangeKind(dst []byte, v MemberChangeKind) []byte
AppendMemberChangeKind appends v to dst in wire format.
func AppendMembershipMessage ¶
func AppendMembershipMessage(dst []byte, m *MembershipMessage) []byte
AppendMembershipMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.
func AppendRelayAck ¶
AppendRelayAck encodes m onto dst in wire format without allocating when dst has capacity.
func AppendRelayBody ¶
AppendRelayBody encodes the active case of m onto dst in wire format without allocating when dst has capacity.
func AppendRelayFrame ¶
func AppendRelayFrame(dst []byte, m *RelayFrame) []byte
AppendRelayFrame encodes m onto dst in wire format without allocating when dst has capacity.
func AppendRelayMembers ¶
func AppendRelayMembers(dst []byte, m *RelayMembers) []byte
AppendRelayMembers encodes m onto dst in wire format without allocating when dst has capacity.
func AppendRelayReliable ¶
func AppendRelayReliable(dst []byte, m *RelayReliable) []byte
AppendRelayReliable encodes m onto dst in wire format without allocating when dst has capacity.
func AppendRelayUnreliable ¶
func AppendRelayUnreliable(dst []byte, m *RelayUnreliable) []byte
AppendRelayUnreliable encodes m onto dst in wire format without allocating when dst has capacity.
func AppendReplicationMessage ¶
func AppendReplicationMessage(dst []byte, m *ReplicationMessage) []byte
AppendReplicationMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.
func AppendResyncRequest ¶
func AppendResyncRequest(dst []byte, m *ResyncRequest) []byte
AppendResyncRequest encodes m onto dst in wire format without allocating when dst has capacity.
func AppendRollbackMessage ¶
func AppendRollbackMessage(dst []byte, m *RollbackMessage) []byte
AppendRollbackMessage encodes the active case of m onto dst in wire format without allocating when dst has capacity.
func AppendSingleInput ¶
func AppendSingleInput(dst []byte, m *SingleInput) []byte
AppendSingleInput encodes m onto dst in wire format without allocating when dst has capacity.
func AppendSnapshotAck ¶
func AppendSnapshotAck(dst []byte, m *SnapshotAck) []byte
AppendSnapshotAck encodes m onto dst in wire format without allocating when dst has capacity.
func AppendSnapshotDelta ¶
func AppendSnapshotDelta(dst []byte, m *SnapshotDelta) []byte
AppendSnapshotDelta encodes m onto dst in wire format without allocating when dst has capacity.
func AppendSnapshotFull ¶
func AppendSnapshotFull(dst []byte, m *SnapshotFull) []byte
AppendSnapshotFull encodes m onto dst in wire format without allocating when dst has capacity.
func AppendSnapshotFullPart ¶
func AppendSnapshotFullPart(dst []byte, m *SnapshotFullPart) []byte
AppendSnapshotFullPart encodes m onto dst in wire format without allocating when dst has capacity.
func AppendTransportFrame ¶
func AppendTransportFrame(dst []byte, m *TransportFrame) []byte
AppendTransportFrame encodes m onto dst in wire format without allocating when dst has capacity.
func AppendUDPDatagramType ¶
func AppendUDPDatagramType(dst []byte, v UDPDatagramType) []byte
AppendUDPDatagramType appends v to dst in wire format.
func AppendUDPPeerFrame ¶
func AppendUDPPeerFrame(dst []byte, m *UDPPeerFrame) []byte
AppendUDPPeerFrame encodes m onto dst in wire format without allocating when dst has capacity.
func AppendUDPSealedDatagram ¶
func AppendUDPSealedDatagram(dst []byte, m *UDPSealedDatagram) []byte
AppendUDPSealedDatagram encodes m onto dst in wire format without allocating when dst has capacity.
func ApplyEntityRecord ¶
func ApplyEntityRecord(dst, delta *EntityRecord)
ApplyEntityRecord copies every masked field present in delta into dst, reusing dst slice capacities.
func BuiltinFiles ¶
BuiltinFiles returns the sorted file names of the embedded pkg/net wire schemas.
func DecodeChannel ¶
DecodeChannel decodes one Channel from src into v, validating that it is a declared enum value.
func DecodeChecksumMsg ¶
func DecodeChecksumMsg(src []byte, m *ChecksumMsg) (int, error)
DecodeChecksumMsg decodes one ChecksumMsg from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeEntityRecord ¶
func DecodeEntityRecord(src []byte, m *EntityRecord) (int, error)
DecodeEntityRecord decodes one EntityRecord from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeHandshakeHello ¶
func DecodeHandshakeHello(src []byte, m *HandshakeHello) (int, error)
DecodeHandshakeHello decodes one HandshakeHello from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeHandshakeMessage ¶
func DecodeHandshakeMessage(src []byte, m *HandshakeMessage) (int, error)
DecodeHandshakeMessage decodes one HandshakeMessage from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeHandshakeReject ¶
func DecodeHandshakeReject(src []byte, m *HandshakeReject) (int, error)
DecodeHandshakeReject decodes one HandshakeReject from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeHandshakeWelcome ¶
func DecodeHandshakeWelcome(src []byte, m *HandshakeWelcome) (int, error)
DecodeHandshakeWelcome decodes one HandshakeWelcome from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeInputBundle ¶
func DecodeInputBundle(src []byte, m *InputBundle) (int, error)
DecodeInputBundle decodes one InputBundle from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeInputFrame ¶
func DecodeInputFrame(src []byte, m *InputFrame) (int, error)
DecodeInputFrame decodes one InputFrame from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeJoinState ¶
DecodeJoinState decodes one JoinState from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeJoinStatePart ¶
func DecodeJoinStatePart(src []byte, m *JoinStatePart) (int, error)
DecodeJoinStatePart decodes one JoinStatePart from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeMatchMember ¶
func DecodeMatchMember(src []byte, m *MatchMember) (int, error)
DecodeMatchMember decodes one MatchMember from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeMemberChange ¶
func DecodeMemberChange(src []byte, m *MemberChange) (int, error)
DecodeMemberChange decodes one MemberChange from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeMemberChangeKind ¶
func DecodeMemberChangeKind(src []byte, v *MemberChangeKind) (int, error)
DecodeMemberChangeKind decodes one MemberChangeKind from src into v, validating that it is a declared enum value.
func DecodeMembershipMessage ¶
func DecodeMembershipMessage(src []byte, m *MembershipMessage) (int, error)
DecodeMembershipMessage decodes one MembershipMessage from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRelayAck ¶
DecodeRelayAck decodes one RelayAck from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRelayBody ¶
DecodeRelayBody decodes one RelayBody from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRelayFrame ¶
func DecodeRelayFrame(src []byte, m *RelayFrame) (int, error)
DecodeRelayFrame decodes one RelayFrame from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRelayMembers ¶
func DecodeRelayMembers(src []byte, m *RelayMembers) (int, error)
DecodeRelayMembers decodes one RelayMembers from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRelayReliable ¶
func DecodeRelayReliable(src []byte, m *RelayReliable) (int, error)
DecodeRelayReliable decodes one RelayReliable from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRelayUnreliable ¶
func DecodeRelayUnreliable(src []byte, m *RelayUnreliable) (int, error)
DecodeRelayUnreliable decodes one RelayUnreliable from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeReplicationMessage ¶
func DecodeReplicationMessage(src []byte, m *ReplicationMessage) (int, error)
DecodeReplicationMessage decodes one ReplicationMessage from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeResyncRequest ¶
func DecodeResyncRequest(src []byte, m *ResyncRequest) (int, error)
DecodeResyncRequest decodes one ResyncRequest from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeRollbackMessage ¶
func DecodeRollbackMessage(src []byte, m *RollbackMessage) (int, error)
DecodeRollbackMessage decodes one RollbackMessage from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeSingleInput ¶
func DecodeSingleInput(src []byte, m *SingleInput) (int, error)
DecodeSingleInput decodes one SingleInput from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeSnapshotAck ¶
func DecodeSnapshotAck(src []byte, m *SnapshotAck) (int, error)
DecodeSnapshotAck decodes one SnapshotAck from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeSnapshotDelta ¶
func DecodeSnapshotDelta(src []byte, m *SnapshotDelta) (int, error)
DecodeSnapshotDelta decodes one SnapshotDelta from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeSnapshotFull ¶
func DecodeSnapshotFull(src []byte, m *SnapshotFull) (int, error)
DecodeSnapshotFull decodes one SnapshotFull from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeSnapshotFullPart ¶
func DecodeSnapshotFullPart(src []byte, m *SnapshotFullPart) (int, error)
DecodeSnapshotFullPart decodes one SnapshotFullPart from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeTransportFrame ¶
func DecodeTransportFrame(src []byte, m *TransportFrame) (int, error)
DecodeTransportFrame decodes one TransportFrame from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeUDPDatagramType ¶
func DecodeUDPDatagramType(src []byte, v *UDPDatagramType) (int, error)
DecodeUDPDatagramType decodes one UDPDatagramType from src into v, validating that it is a declared enum value.
func DecodeUDPPeerFrame ¶
func DecodeUDPPeerFrame(src []byte, m *UDPPeerFrame) (int, error)
DecodeUDPPeerFrame decodes one UDPPeerFrame from src into caller-owned storage m without heap allocations once slices have capacity.
func DecodeUDPSealedDatagram ¶
func DecodeUDPSealedDatagram(src []byte, m *UDPSealedDatagram) (int, error)
DecodeUDPSealedDatagram decodes one UDPSealedDatagram from src into caller-owned storage m without heap allocations once slices have capacity.
func DequantizeFixed ¶
DequantizeFixed converts a signed fixed-point integer q back to float64 (q / scale) using integer arithmetic only.
func DequantizeFixedUint ¶
DequantizeFixedUint converts an unsigned fixed-point integer q back to float64 (q / scale) using integer arithmetic only.
func DequantizeFloat ¶
DequantizeFloat reconstructs a float32 from an unsigned quantized integer q in [0, (1<<bits)-1] over [minVal, maxVal] using integer arithmetic only, guaranteeing bit-identical results across architectures.
q == 0 returns minVal exactly and q >= (1<<bits)-1 returns maxVal exactly.
func DiffEntityRecord ¶
func DiffEntityRecord(base, cur *EntityRecord) uint8
DiffEntityRecord returns the presence mask of fields in cur that differ from base, comparing float bit patterns and byte slices directly.
Example ¶
Generated codecs encode into caller-owned slices with AppendX and decode into caller-owned structs with DecodeX, while DiffX and ApplyX compute and apply presence-bitmask deltas.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)
func main() {
base := wire.EntityRecord{ID: 7, Kind: 1, X: 10, Y: 20}
cur := base
cur.X = 14.5
cur.Props = []byte{0x01, 0x02}
cur.FieldsMask = wire.DiffEntityRecord(&base, &cur)
buf := wire.AppendEntityRecord(make([]byte, 0, 64), &cur)
var decoded wire.EntityRecord
n, err := wire.DecodeEntityRecord(buf, &decoded)
if err != nil {
panic(err)
}
wire.ApplyEntityRecord(&base, &decoded)
fmt.Printf("bytes=%d mask=0x%02x x=%.1f y=%.1f props=%x\n", n, decoded.FieldsMask, base.X, base.Y, base.Props)
}
Output: bytes=9 mask=0x82 x=14.5 y=20.0 props=0102
func Encode ¶
Encode validates s and writes it as canonical, deterministic 2-space YAML prefixed with SchemaComment.
func FrameMessageType ¶
func FrameMessageType(frame DecodedFrame) string
FrameMessageType returns a stable, human-readable message type name for frame (such as "replication.delta", "rollback.single_input", "relay.members", or "raw").
func GenerateGo ¶
func GenerateGo(schema *Schema, opts GenerateOptions) ([]byte, error)
GenerateGo generates deterministic, formatted, zero-allocation Go codec source for schema.
Example ¶
Parse reads a *.wire.yaml schema strictly and GenerateGo writes deterministic Go codecs for it.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)
func main() {
const src = `version: 1
package: demo
messages:
- name: Ping
fields:
- name: seq
type: uvarint
bits: 32
`
s, err := wire.Parse([]byte(src))
if err != nil {
panic(err)
}
code, err := wire.GenerateGo(s, wire.GenerateOptions{SourceName: "ping.wire.yaml"})
if err != nil {
panic(err)
}
fmt.Println(len(code) > 0, s.Messages[0].Name)
}
Output: true Ping
func GenerateTS ¶
func GenerateTS(schema *Schema, opts TSGenerateOptions) ([]byte, error)
GenerateTS generates deterministic, dependency-free TypeScript codec source for schema.
Example ¶
GenerateTS produces deterministic, dependency-free TypeScript codecs (encodeX, decodeX, plus diffX/applyX for delta masks) from a parsed wire schema.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)
func main() {
const src = `version: 1
package: demo
messages:
- name: Ping
fields:
- name: seq
type: uvarint
bits: 32
- name: stamp
type: u64
`
s, err := wire.Parse([]byte(src))
if err != nil {
panic(err)
}
code, err := wire.GenerateTS(s, wire.TSGenerateOptions{SourceName: "ping.wire.yaml"})
if err != nil {
panic(err)
}
fmt.Println(len(code) > 0, s.Messages[0].Name)
}
Output: true Ping
func GenerateTSIndex ¶
GenerateTSIndex generates a deterministic barrel index.ts re-exporting runtime.ts and each generated schema module.
func GenerateTSRuntime ¶
func GenerateTSRuntime() []byte
GenerateTSRuntime returns the deterministic, zero-dependency TypeScript runtime module shared by codecs generated with GenerateTS.
func QuantizeFixed ¶
QuantizeFixed converts v into a signed fixed-point integer round(v * scale), clamped to [minInt, maxInt], using integer arithmetic only. Halfway ties round away from zero.
func QuantizeFixedUint ¶
QuantizeFixedUint converts v into an unsigned fixed-point integer round(v * scale), clamped to [0, maxUint], using integer arithmetic only. Halfway ties round up.
func QuantizeFloat ¶
QuantizeFloat quantizes v from [minVal, maxVal] into an unsigned integer in [0, (1<<bits)-1] using integer arithmetic only, so every CPU architecture (amd64, arm64, wasm) and cross-language implementation produces identical bytes.
Values at or below minVal (and NaN) quantize to 0; values at or above maxVal quantize to (1<<bits)-1. Halfway ties round up.
Example ¶
QuantizeFloat and DequantizeFloat map float32 values into compact integer bit widths using integer arithmetic only, producing bit-identical bytes on amd64, arm64, and wasm.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)
func main() {
q := wire.QuantizeFloat(0.25, 0, 1, 8)
v := wire.DequantizeFloat(q, 0, 1, 8)
fmt.Printf("q=%d v=%.4f\n", q, v)
}
Output: q=64 v=0.2510
func TSOutputFileName ¶
TSOutputFileName returns the generated TypeScript file name for a *.wire.yaml schema file name (for example "replication.wire.yaml" -> "replication_wire.ts").
func Validate ¶
Validate checks a single Schema document. When s.Imports is empty, every enum and message reference must resolve within s; when s.Imports is non-empty, cross-file references are verified by ValidateAll or GenerateGo.
func ValidateAll ¶
ValidateAll checks a linked set of schemas (such as a directory of *.wire.yaml files in one package), ensuring unique top-level type names across files and that every cross-file type reference resolves.
Types ¶
type ArraySpec ¶
type ArraySpec struct {
// Count fixes the array length to a compile-time constant [Count]T; omit or set 0 for a variable-length slice.
Count int `yaml:"count,omitempty" schema:"minimum=0"`
// Length sets the element-count prefix for variable-length arrays ("uvarint", "u8", "u16", or "u32"; defaults to "uvarint").
Length string `yaml:"length,omitempty" schema:"enum=uvarint|u8|u16|u32"`
// Order overrides the byte order for a multi-byte Length prefix (and as default for elements when OfOrder is omitted).
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// Of is the element wire type: a primitive ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "uvarint", "svarint", "bool", "f32") or the name of a declared Enum or Message.
Of string `yaml:"of" schema:"required,minLength=1"`
// OfOrder overrides the byte order of multi-byte primitive elements ("be" or "le").
OfOrder ByteOrder `yaml:"ofOrder,omitempty" schema:"enum=be|le"`
// OfBits sets the Go integer bit width (8, 16, 32, or 64) when Of is "uvarint" or "svarint".
OfBits int `yaml:"ofBits,omitempty" schema:"minimum=1,maximum=64"`
// MaxLength bounds the decoded element count of variable-length arrays (0 means unbounded).
MaxLength int `yaml:"maxLength,omitempty" schema:"minimum=0"`
}
ArraySpec configures a fixed-count ([N]T) or length-prefixed ([]T) array field.
type BitReader ¶
BitReader reads MSB-first bit-packed values from a byte slice without heap allocations.
type BitWriter ¶
type BitWriter struct {
Dst []byte
// contains filtered or unexported fields
}
BitWriter appends MSB-first bit-packed values to a caller-owned byte slice without heap allocations.
type CaptureStats ¶
type CaptureStats struct {
TotalPackets int `yaml:"total_packets" json:"total_packets"`
TotalBytes int64 `yaml:"total_bytes" json:"total_bytes"`
SendPackets int `yaml:"send_packets" json:"send_packets"`
SendBytes int64 `yaml:"send_bytes" json:"send_bytes"`
RecvPackets int `yaml:"recv_packets" json:"recv_packets"`
RecvBytes int64 `yaml:"recv_bytes" json:"recv_bytes"`
DurationNS int64 `yaml:"duration_ns" json:"duration_ns"`
DeltaCount int `yaml:"delta_count" json:"delta_count"`
DeltaBytes int64 `yaml:"delta_bytes" json:"delta_bytes"`
MeanDeltaBytes float64 `yaml:"mean_delta_bytes" json:"mean_delta_bytes"`
ByType []TypeStats `yaml:"by_type" json:"by_type"`
ByPeer []PeerStats `yaml:"by_peer" json:"by_peer"`
}
CaptureStats summarizes traffic decoded from a capture stream.
type ChecksumMsg ¶
ChecksumMsg carries a peer's 64-bit simulation state checksum for tick following tag 12.
type DecodedEnum ¶
DecodedEnum holds a validated wire enum value together with its declared schema member name. It marshals as Name in both YAML and JSON while retaining Value for lossless re-encoding.
func (DecodedEnum) MarshalJSON ¶
func (e DecodedEnum) MarshalJSON() ([]byte, error)
MarshalJSON encodes DecodedEnum as its member name.
func (DecodedEnum) MarshalYAML ¶
func (e DecodedEnum) MarshalYAML() (any, error)
MarshalYAML encodes DecodedEnum as its member name.
type DecodedField ¶
DecodedField is one decoded wire field in exact schema declaration order.
type DecodedFrame ¶
type DecodedFrame struct {
// Index is the 0-based frame index in the input stream.
Index int `yaml:"index" json:"index"`
// T is the capture timestamp in nanoseconds (nil for raw stdin frames).
T *int64 `yaml:"t,omitempty" json:"t,omitempty"`
// Dir is "send" or "recv" (empty for raw stdin frames).
Dir string `yaml:"dir,omitempty" json:"dir,omitempty"`
// Peer is the remote peer ID (nil for raw stdin frames).
Peer *uint32 `yaml:"peer,omitempty" json:"peer,omitempty"`
// Size is the payload size in bytes.
Size int `yaml:"size" json:"size"`
// Layers lists the decoded protocol layers from outermost to innermost.
Layers []DecodedLayer `yaml:"layers" json:"layers"`
}
DecodedFrame is one fully decoded packet from a capture stream or raw frame input.
type DecodedLayer ¶
type DecodedLayer struct {
// Layer names the protocol layer ("transport", "udp_sealed", "relay", "replication", "rollback", "membership", "handshake", a custom schema package, or "raw").
Layer string `yaml:"layer" json:"layer"`
// Union names the discriminated wire union when this layer was selected by a union discriminator.
Union string `yaml:"union,omitempty" json:"union,omitempty"`
// Version is the nibble discriminator high value when a nibble union matched (for example 2 for ReplicationMessage).
Version *uint8 `yaml:"version,omitempty" json:"version,omitempty"`
// Case is the matched union case name (for example "full", "delta", "single_input", "reliable").
Case string `yaml:"case,omitempty" json:"case,omitempty"`
// Tag is the union discriminator tag value when Union is set.
Tag *uint64 `yaml:"tag,omitempty" json:"tag,omitempty"`
// Message is the wire message name decoded at this layer.
Message string `yaml:"message,omitempty" json:"message,omitempty"`
// Fields holds the decoded fields of Message in exact wire order. Trailing payload bytes peeled into the next layer are omitted here; ReencodeLayers restores them from the inner layer.
Fields DecodedObject `yaml:"fields,omitempty" json:"fields,omitempty"`
// Raw holds raw undecoded bytes when Layer is "raw".
Raw WireBytes `yaml:"raw,omitempty" json:"raw,omitempty"`
// Resolved holds the full resulting entity states after applying a SnapshotDelta to its tracked peer baseline when ResolveDeltas is enabled.
Resolved []DecodedObject `yaml:"resolved,omitempty" json:"resolved,omitempty"`
// BaselineMissing is true when ResolveDeltas was enabled on a SnapshotDelta whose baseline_tick had not been captured yet.
BaselineMissing bool `yaml:"baseline_missing,omitempty" json:"baseline_missing,omitempty"`
// PayloadField records which trailing bytes field of Message was peeled off into the next layer so ReencodeLayers can reconstruct exact wire bytes.
PayloadField string `yaml:"-" json:"-"`
}
DecodedLayer is one protocol layer decoded from a packet using the wire schemas.
type DecodedMask ¶
type DecodedMask struct {
Mask uint64
Fields DecodedObject
}
DecodedMask holds a presence-bitmask group's raw bitmask and present fields in bit order.
func (DecodedMask) MarshalJSON ¶
func (m DecodedMask) MarshalJSON() ([]byte, error)
MarshalJSON encodes DecodedMask as a JSON object with "mask" followed by its present fields.
func (DecodedMask) MarshalYAML ¶
func (m DecodedMask) MarshalYAML() (any, error)
MarshalYAML encodes DecodedMask as a YAML mapping with "mask" followed by its present fields.
type DecodedObject ¶
type DecodedObject []DecodedField
DecodedObject is an ordered list of decoded wire fields that marshals as a YAML mapping or JSON object in wire field order.
func (DecodedObject) Get ¶
func (o DecodedObject) Get(name string) (any, bool)
Get returns the value of the named field and whether it was present.
func (DecodedObject) MarshalJSON ¶
func (o DecodedObject) MarshalJSON() ([]byte, error)
MarshalJSON encodes DecodedObject as an ordered JSON object.
func (DecodedObject) MarshalYAML ¶
func (o DecodedObject) MarshalYAML() (any, error)
MarshalYAML encodes DecodedObject as an ordered YAML mapping.
func (*DecodedObject) Set ¶
func (o *DecodedObject) Set(name string, value any)
Set updates an existing field's value in place or appends a new field.
func (DecodedObject) Without ¶
func (o DecodedObject) Without(name string) DecodedObject
Without returns a shallow copy of o omitting the named field.
type DecodedPayload ¶
type DecodedPayload struct {
Schema string `yaml:"schema" json:"schema"`
Union string `yaml:"union,omitempty" json:"union,omitempty"`
Case string `yaml:"case,omitempty" json:"case,omitempty"`
Tag *uint64 `yaml:"tag,omitempty" json:"tag,omitempty"`
Version *uint8 `yaml:"version,omitempty" json:"version,omitempty"`
Message string `yaml:"message" json:"message"`
Fields DecodedObject `yaml:"fields,omitempty" json:"fields,omitempty"`
}
DecodedPayload holds a nested bytes field (such as EntityRecord.props) that was further decoded using a custom wire schema.
type DecodedUnion ¶
type DecodedUnion struct {
Schema string
Union string
HasHigh bool
HighName string
HighValue uint8
Case string
Tag uint64
Message string
Fields DecodedObject
}
DecodedUnion holds a dynamically decoded union envelope and its selected member message.
type Discriminator ¶
type Discriminator struct {
// Type selects the discriminator wire encoding: "u8", "u16", "uvarint", or "nibble" (a 1-byte high/low bit split).
Type string `yaml:"type" schema:"required,enum=u8|u16|uvarint|nibble"`
// Order overrides the byte order when Type is "u16" ("be" or "le").
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// HighBits is the width in bits (1..7) of the high field when Type is "nibble" (defaults to 4).
HighBits int `yaml:"highBits,omitempty" schema:"minimum=1,maximum=7"`
// HighName is the Go field name for the high bits when Type is "nibble" (defaults to "version").
HighName string `yaml:"highName,omitempty"`
// HighValue is the expected constant value of the high bits when Type is "nibble" (for example, 2 for replication v2).
HighValue uint8 `yaml:"highValue,omitempty"`
// LowName is the logical name of the low tag bits when Type is "nibble" (defaults to "type").
LowName string `yaml:"lowName,omitempty"`
}
Discriminator configures the leading tag encoding of a Union.
type EntityRecord ¶
type EntityRecord struct {
ID uint32
FieldsMask uint8
Kind uint16
X float32
Y float32
VX float32
VY float32
Rotation float32
Flags uint32
Props []byte
}
EntityRecord encodes one entity ID and its presence-masked ComponentState fields in replication v2.
type Enum ¶
type Enum struct {
// Name is the Go type name of the enum, in PascalCase.
Name string `yaml:"name" schema:"required,minLength=1"`
// Doc is an optional comment emitted on the generated Go type.
Doc string `yaml:"doc,omitempty"`
// Type is the underlying integer wire type ("u8", "u16", "u32", "u64", or "uvarint").
Type string `yaml:"type" schema:"required,enum=u8|u16|u32|u64|uvarint"`
// Order overrides the schema byte order for multi-byte enum types ("be" or "le").
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// Values lists the enum's named members and their wire integers.
Values []EnumValue `yaml:"values" schema:"required,minItems=1"`
}
Enum defines a named integer enumeration on the wire.
type EnumValue ¶
type EnumValue struct {
// Name is the member name, appended to the enum type name to form the Go constant.
Name string `yaml:"name" schema:"required,minLength=1"`
// Value is the unsigned wire integer value of the member.
Value uint64 `yaml:"value"`
// Doc is an optional comment emitted on the generated Go constant.
Doc string `yaml:"doc,omitempty"`
}
EnumValue is one named member of an Enum.
type Field ¶
type Field struct {
// Name is the field name (snake_case or lowerCamelCase); codegen converts it to an exported Go field name.
Name string `yaml:"name" schema:"required,minLength=1"`
// Doc is an optional comment emitted on the generated Go struct field.
Doc string `yaml:"doc,omitempty"`
// Type is a built-in wire type ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "uvarint", "svarint", "bool", "f32", "qfloat", "fixed", "bytes", "string", "array", "bits", "mask") or the name of a declared Enum or Message.
Type string `yaml:"type" schema:"required,minLength=1"`
// Order overrides the message/schema byte order for multi-byte primitives, length prefixes, or mask integers ("be" or "le").
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// Bits specifies the bit width for "bits" fields (1..64) or the Go integer width (8, 16, 32, or 64) for "uvarint"/"svarint" fields.
Bits int `yaml:"bits,omitempty" schema:"minimum=1,maximum=64"`
// Const fixes an unsigned integer, bits, or enum wire field to a single constant value written on encode and verified on decode.
Const *uint64 `yaml:"const,omitempty"`
// QFloat configures an integer-quantized float32 field when Type is "qfloat".
QFloat *QFloatSpec `yaml:"qfloat,omitempty"`
// Fixed configures an integer-scaled fixed-point float64 field when Type is "fixed".
Fixed *FixedSpec `yaml:"fixed,omitempty"`
// Length configures the length encoding for "bytes" and "string" fields ("uvarint", "u8", "u16", "u32", or "rest"; defaults to "uvarint").
Length string `yaml:"length,omitempty" schema:"enum=uvarint|u8|u16|u32|rest"`
// MaxLength bounds the decoded byte length of variable-length "bytes" and "string" fields (0 means unbounded).
MaxLength int `yaml:"maxLength,omitempty" schema:"minimum=0"`
// Array configures a fixed-size or length-prefixed array field when Type is "array".
Array *ArraySpec `yaml:"array,omitempty"`
// Mask configures a presence-bitmask group of optional fields when Type is "mask".
Mask *MaskSpec `yaml:"mask,omitempty"`
}
Field defines one field of a Message or MaskSpec.
type FixedSpec ¶
type FixedSpec struct {
// Scale is the positive integer scale factor (wire integer equals round(value * Scale)).
Scale int64 `yaml:"scale" schema:"required,minimum=1"`
// Type is the underlying integer wire type ("i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "uvarint", or "svarint").
Type string `yaml:"type" schema:"required,enum=i8|i16|i32|i64|u8|u16|u32|u64|uvarint|svarint"`
// Order overrides the byte order for multi-byte integer wire types ("be" or "le").
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
}
FixedSpec configures a fixed-point number stored as an integer scaled by Scale.
type GenerateOptions ¶
type GenerateOptions struct {
// Package overrides schema.Package when non-empty.
Package string
// SourceName is the schema file name shown in the generated header comment.
SourceName string
// Self omits the runtime package import and references runtime helpers unqualified, for files generated inside pkg/net/wire itself.
Self bool
// RuntimeImport overrides DefaultRuntimeImport when Self is false.
RuntimeImport string
// ExtraSchemas supplies sibling schemas in the same package whose enums and messages schema references via imports.
ExtraSchemas []*Schema
}
GenerateOptions configures Go codec generation in GenerateGo.
type HandshakeHello ¶
type HandshakeHello struct {
Nonce [16]uint8
ResumePeer uint32
ResumeSecret [16]uint8
Token []byte
}
HandshakeHello is the client-to-server version 1 connection handshake body following tag 0xA1.
type HandshakeMessage ¶
type HandshakeMessage struct {
Tag uint8
Hello HandshakeHello
Welcome HandshakeWelcome
Reject HandshakeReject
}
HandshakeMessage is a tag-discriminated version 1 connection handshake message.
type HandshakeReject ¶
HandshakeReject is the server-to-client version 1 rejection body following tag 0xA3.
type HandshakeWelcome ¶
type HandshakeWelcome struct {
Nonce [16]uint8
Peer uint32
Server uint32
Resumed bool
Secret [16]uint8
Key [32]uint8
}
HandshakeWelcome is the server-to-client version 1 acceptance body following tag 0xA2.
type InputBundle ¶
type InputBundle struct {
Inputs []InputFrame
}
InputBundle carries a 1-byte counted list of redundant InputFrames following tag 11.
type InputFrame ¶
InputFrame is a 20-byte deterministic per-tick player input sample exchanged by lockstep and rollback sessions.
type InspectOptions ¶
type InspectOptions struct {
// ResolveDeltas tracks per-peer replication baselines across a capture so SnapshotDelta layers include full resolved entity states.
ResolveDeltas bool
}
InspectOptions configures schema-driven packet inspection.
type Inspector ¶
type Inspector struct {
// contains filtered or unexported fields
}
Inspector decodes captured packets and raw wire frames layer by layer using a Registry of built-in and optional custom wire schemas, and re-encodes decoded frames back to exact wire bytes.
func NewInspector ¶
func NewInspector(reg *Registry, opts InspectOptions) (*Inspector, error)
NewInspector returns a schema-driven Inspector. When reg is nil, NewRegistry() is called to load the built-in pkg/online/netplay schemas.
Example ¶
NewInspector decodes a captured packet layer by layer using the built-in wire schemas and re-encodes it back to the exact original bytes.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/online/netplay/wire"
)
func main() {
ins, err := wire.NewInspector(nil, wire.InspectOptions{})
if err != nil {
panic(err)
}
payload := wire.AppendReplicationMessage(nil, &wire.ReplicationMessage{
Tag: wire.ReplicationMessageTagAck,
Ack: wire.SnapshotAck{Epoch: 1, Tick: 42},
})
frame := ins.InspectCaptureRecord(0, 0, "send", 1, uint8(wire.ChannelUnreliable), 1, payload)
reencoded, err := ins.ReencodePayload(frame)
if err != nil {
panic(err)
}
fmt.Println(wire.FrameMessageType(frame), len(frame.Layers), len(reencoded) == len(payload))
}
Output: replication.ack 2 true
func (*Inspector) ComputeStats ¶
func (ins *Inspector) ComputeStats(frames []DecodedFrame) CaptureStats
ComputeStats aggregates message-type counts, per-peer counts, and mean delta size across frames.
func (*Inspector) DecodeRawFrameText ¶
DecodeRawFrameText parses a standalone hex (optional 0x prefix, optional spaces) or base64 (standard or URL, padded or unpadded) frame string into raw bytes.
func (*Inspector) InspectCaptureRecord ¶
func (ins *Inspector) InspectCaptureRecord(index int, t int64, dir string, peer uint32, ch uint8, seq uint32, payload []byte) DecodedFrame
InspectCaptureRecord decodes one captured transport packet into a layered DecodedFrame. The transport layer is populated from ch and seq using transport.wire.yaml, and payload is decoded layer by layer using the wire discriminators.
func (*Inspector) InspectRawFrame ¶
func (ins *Inspector) InspectRawFrame(index int, raw []byte) DecodedFrame
InspectRawFrame decodes a standalone raw wire frame (such as hex or base64 read from stdin) into a layered DecodedFrame.
func (*Inspector) ReencodeLayers ¶
func (ins *Inspector) ReencodeLayers(layers []DecodedLayer) ([]byte, error)
ReencodeLayers re-encodes a stack of decoded layers from innermost to outermost back into wire bytes using the wire schemas.
func (*Inspector) ReencodePayload ¶
func (ins *Inspector) ReencodePayload(frame DecodedFrame) ([]byte, error)
ReencodePayload re-encodes the transport payload of a capture-decoded DecodedFrame (skipping the synthetic outer transport layer when present). For frames decoded via InspectRawFrame, it re-encodes all layers from outermost to innermost.
type JoinState ¶
type JoinState struct {
Tick uint32
Members []MatchMember
Inputs []InputFrame
State []byte
}
JoinState is the reassembled blob sent by the host to a joining peer at its join tick.
type JoinStatePart ¶
JoinStatePart is one fragment of a serialized JoinState following tag 14.
type MaskSpec ¶
type MaskSpec struct {
// Type is the mask integer wire type ("u8", "u16", "u32", or "u64"; defaults to "u8").
Type string `yaml:"type,omitempty" schema:"enum=u8|u16|u32|u64"`
// Order overrides the byte order for multi-byte mask types ("be" or "le").
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// Delta, when true, generates Diff<Message>(base, cur) and Apply<Message>(dst, delta) helpers comparing float bit patterns and byte slices directly.
Delta bool `yaml:"delta,omitempty"`
// Fields lists the gated fields in bit order (index i corresponds to bit 1<<i).
Fields []Field `yaml:"fields" schema:"required,minItems=1"`
}
MaskSpec configures a presence-bitmask group that gates its fields in bit order (bit 0, bit 1, ...).
type MatchMember ¶
MatchMember is a 13-byte record describing one peer's active tick window inside an assembled JoinState.
type MemberChange ¶
type MemberChange struct {
Kind MemberChangeKind
Peer uint32
Tick uint32
Inputs []InputFrame
}
MemberChange is a host-issued membership announcement following tag 13.
type MemberChangeKind ¶
type MemberChangeKind uint8
MemberChangeKind identifies whether a membership announcement adds or removes a peer.
const ( // Peer joins at tick. MemberChangeKindJoin MemberChangeKind = 1 // Peer leaves at tick with declared inputs. MemberChangeKindLeave MemberChangeKind = 2 )
func (MemberChangeKind) Valid ¶
func (v MemberChangeKind) Valid() bool
Valid reports whether v is a declared MemberChangeKind value.
type MembershipMessage ¶
type MembershipMessage struct {
Tag uint8
Change MemberChange
JoinStatePart JoinStatePart
}
MembershipMessage is a tag-discriminated mid-match membership control packet.
type Message ¶
type Message struct {
// Name is the Go struct name of the message, in PascalCase.
Name string `yaml:"name" schema:"required,minLength=1"`
// Doc is an optional comment emitted on the generated Go struct.
Doc string `yaml:"doc,omitempty"`
// Order overrides the schema default byte order for fields of this message ("be" or "le").
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// Fields lists the wire fields in exact on-the-wire order.
Fields []Field `yaml:"fields,omitempty"`
}
Message defines one binary wire message struct and its ordered sequence of fields.
type NamedSchema ¶
NamedSchema pairs a parsed wire Schema with its schema file name (for example "transport.wire.yaml") so cross-file TypeScript imports resolve to sibling generated modules.
type PeerStats ¶
type PeerStats struct {
Peer uint32 `yaml:"peer" json:"peer"`
Packets int `yaml:"packets" json:"packets"`
Bytes int64 `yaml:"bytes" json:"bytes"`
SendPackets int `yaml:"send_packets" json:"send_packets"`
SendBytes int64 `yaml:"send_bytes" json:"send_bytes"`
RecvPackets int `yaml:"recv_packets" json:"recv_packets"`
RecvBytes int64 `yaml:"recv_bytes" json:"recv_bytes"`
}
PeerStats aggregates packet and byte totals for one peer ID.
type QFloatSpec ¶
type QFloatSpec struct {
// Min is the finite lower bound mapped to 0.
Min float64 `yaml:"min"`
// Max is the finite upper bound mapped to (1<<Bits)-1; it must be strictly greater than Min.
Max float64 `yaml:"max"`
// Bits is the quantized bit width, from 1 to 32.
Bits int `yaml:"bits" schema:"required,minimum=1,maximum=32"`
}
QFloatSpec configures integer-only quantization of a float32 across [Min, Max] into Bits unsigned bits.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry indexes built-in and optional custom wire schemas for schema-driven dynamic decoding and re-encoding.
func NewRegistry ¶
NewRegistry builds a Registry loaded with all built-in pkg/online/netplay wire schemas plus any caller-supplied custom schemas.
func (*Registry) CustomMessages ¶
CustomMessages returns the sorted names of messages declared in custom schemas.
func (*Registry) CustomUnions ¶
CustomUnions returns the sorted names of unions declared in custom schemas.
func (*Registry) DecodeMessage ¶
DecodeMessage dynamically decodes one named Message from src using its schema definition.
func (*Registry) DecodeUnion ¶
DecodeUnion dynamically decodes one named Union from src using its discriminator and matched case message.
func (*Registry) EncodeMessage ¶
func (r *Registry) EncodeMessage(name string, obj DecodedObject) ([]byte, error)
EncodeMessage dynamically encodes obj back into wire bytes according to the named Message's schema definition.
func (*Registry) EncodeUnion ¶
func (r *Registry) EncodeUnion(du DecodedUnion) ([]byte, error)
EncodeUnion dynamically encodes du back into wire bytes according to its Union's discriminator and selected case message.
type RelayBody ¶
type RelayBody struct {
Tag uint8
Unreliable RelayUnreliable
Reliable RelayReliable
Ack RelayAck
}
RelayBody is the tag-discriminated end-to-end body carried inside a peer-addressed RelayFrame.
type RelayFrame ¶
RelayFrame is the version 1 outer frame exchanged between a RelayTransport and a Relay server.
type RelayMembers ¶
RelayMembers is the control body (when RelayFrame.Peer is 0) announcing the sorted members of a relay session.
type RelayReliable ¶
RelayReliable is a peer-to-peer reliable body following tag 0x02.
type RelayUnreliable ¶
RelayUnreliable is a peer-to-peer unreliable body following tag 0x01.
type ReplicationMessage ¶
type ReplicationMessage struct {
Tag uint8
Version uint8
Full SnapshotFull
Delta SnapshotDelta
Ack SnapshotAck
Resync ResyncRequest
FullPart SnapshotFullPart
}
ReplicationMessage is a version 2 replication packet whose leading byte packs protocol version (high nibble = 2) and message type (low nibble = 1..5).
type ResyncRequest ¶
type ResyncRequest struct {
Epoch uint32
}
ResyncRequest asks the server for a full replication v2 snapshot in epoch.
type RollbackMessage ¶
type RollbackMessage struct {
Tag uint8
SingleInput SingleInput
InputBundle InputBundle
Checksum ChecksumMsg
}
RollbackMessage is a tag-discriminated lockstep or rollback input/checksum packet.
type Schema ¶
type Schema struct {
// Version is the schema format version; it must equal CurrentVersion (1).
Version int `yaml:"version" schema:"required"`
// Package is the Go package name emitted by game wire when -pkg is not specified.
Package string `yaml:"package" schema:"required,minLength=1"`
// Order is the default byte order for multi-byte fields in this file ("be" or "le"; defaults to "be" when omitted).
Order ByteOrder `yaml:"order,omitempty" schema:"enum=be|le"`
// Imports lists relative paths to sibling *.wire.yaml files in the same package whose enums and messages this schema references.
Imports []string `yaml:"imports,omitempty"`
// Enums declares named integer enumerations validated on decode.
Enums []Enum `yaml:"enums,omitempty"`
// Messages declares binary wire message layouts.
Messages []Message `yaml:"messages,omitempty"`
// Unions declares tag- or nibble-discriminated message envelopes.
Unions []Union `yaml:"unions,omitempty"`
}
Schema is the root of a versioned *.wire.yaml document describing binary wire enums, messages, and discriminated unions.
func LoadBuiltins ¶
LoadBuiltins parses and validates all embedded pkg/net wire schemas in sorted file order.
func LoadSchemaPath ¶
LoadSchemaPath loads one *.wire.yaml file or every *.wire.yaml file directly under a directory in sorted lexical order.
type SingleInput ¶
type SingleInput struct {
Input InputFrame
}
SingleInput carries one InputFrame following tag 10.
type SnapshotAck ¶
SnapshotAck acknowledges receipt of a replication v2 snapshot tick for epoch.
type SnapshotDelta ¶
type SnapshotDelta struct {
Epoch uint32
Tick uint32
BaselineTick uint32
Despawns []uint32
Updates []EntityRecord
}
SnapshotDelta is a delta replication v2 world snapshot relative to baseline_tick.
type SnapshotFull ¶
type SnapshotFull struct {
Epoch uint32
Tick uint32
Entities []EntityRecord
}
SnapshotFull is a full replication v2 world snapshot following the nibble header byte.
type SnapshotFullPart ¶
type SnapshotFullPart struct {
Epoch uint32
Tick uint32
Index uint32
Total uint32
Entities []EntityRecord
}
SnapshotFullPart carries one fragment of a split full replication v2 snapshot.
type TSGenerateOptions ¶
type TSGenerateOptions struct {
// SourceName is the schema file name shown in the generated header comment.
SourceName string
// RuntimeImport overrides DefaultTSRuntimeImport when EmbedRuntime is false.
RuntimeImport string
// EmbedRuntime embeds the shared runtime directly into the generated module instead of importing RuntimeImport.
EmbedRuntime bool
// ExtraSchemas supplies sibling schemas referenced via imports, paired with their schema file names.
ExtraSchemas []NamedSchema
}
TSGenerateOptions configures TypeScript codec generation in GenerateTS.
type TransportFrame ¶
TransportFrame is the 5-byte channel and sequence header followed by raw payload bytes used by pkg/net transports.
type TypeStats ¶
type TypeStats struct {
Type string `yaml:"type" json:"type"`
Packets int `yaml:"packets" json:"packets"`
Bytes int64 `yaml:"bytes" json:"bytes"`
}
TypeStats aggregates packet and byte totals for one decoded message type.
type UDPDatagramType ¶
type UDPDatagramType uint8
UDPDatagramType identifies the direction and purpose of a sealed UDP session datagram.
const ( // Client-to-server application datagram (0xB1). UDPDatagramTypeData UDPDatagramType = 177 // Server-to-client application datagram (0xB2). UDPDatagramTypeServerData UDPDatagramType = 178 // Client-to-server keepalive ping (0xB3). UDPDatagramTypePing UDPDatagramType = 179 // Server-to-client keepalive reply (0xB4). UDPDatagramTypePong UDPDatagramType = 180 // Client-to-server session goodbye (0xB5). UDPDatagramTypeBye UDPDatagramType = 181 // UDPTransport pre-shared key peer datagram (0xB6). UDPDatagramTypePeerData UDPDatagramType = 182 // Server-to-client session removal whose payload is the reason (0xB7). UDPDatagramTypeKick UDPDatagramType = 183 )
func (UDPDatagramType) Valid ¶
func (v UDPDatagramType) Valid() bool
Valid reports whether v is a declared UDPDatagramType value.
type UDPPeerFrame ¶
UDPPeerFrame is the 9-byte peer-to-peer UDP datagram header (sender PeerID plus TransportFrame) used by UDPTransport.
type UDPSealedDatagram ¶
type UDPSealedDatagram struct {
Type UDPDatagramType
Peer uint32
Seq uint32
Channel Channel
// ChaCha20-Poly1305 ciphertext followed by the 16-byte Poly1305 authentication tag.
Sealed []byte
}
UDPSealedDatagram is a ChaCha20-Poly1305 AEAD UDP datagram with a 10-byte cleartext header (type, peer, seq, channel) authenticated as associated data followed by ciphertext and a 16-byte Poly1305 tag.
type Union ¶
type Union struct {
// Name is the Go struct name of the union envelope, in PascalCase.
Name string `yaml:"name" schema:"required,minLength=1"`
// Doc is an optional comment emitted on the generated Go struct.
Doc string `yaml:"doc,omitempty"`
// Discriminator configures how the leading tag (and optional nibble-split version) is encoded on the wire.
Discriminator Discriminator `yaml:"discriminator" schema:"required"`
// Cases maps discriminator tags to member messages.
Cases []UnionCase `yaml:"cases" schema:"required,minItems=1"`
}
Union defines a discriminated message envelope selecting one of Cases by a leading tag or nibble-split header byte.
type UnionCase ¶
type UnionCase struct {
// Name is the Go field name inside the union struct (defaults to Message when omitted).
Name string `yaml:"name,omitempty"`
// Tag is the discriminator tag value selecting this case.
Tag uint64 `yaml:"tag"`
// Message is the name of the Message encoded after the discriminator.
Message string `yaml:"message" schema:"required,minLength=1"`
// Doc is an optional comment emitted on the generated tag constant.
Doc string `yaml:"doc,omitempty"`
}
UnionCase binds one discriminator tag value to a Message inside a Union.
type WireBytes ¶
type WireBytes []byte
WireBytes holds raw wire bytes in a dynamically decoded message. It marshals as a standard base64 string in both YAML and JSON.
func (WireBytes) MarshalJSON ¶
MarshalJSON encodes WireBytes as a standard base64 JSON string.
func (WireBytes) MarshalYAML ¶
MarshalYAML encodes WireBytes as a standard base64 string.