mirror of
https://codeberg.org/demostf/parser.git
synced 2026-11-30 02:30:46 +01:00
Compare commits
11 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
471f89a155 |
|||
|
f914f1b747 |
|||
|
3cc6951766 |
|||
|
2bb0a60171 |
|||
|
9b0e19a7e7 |
|||
|
1f7a80468e |
|||
|
541e175cdd |
|||
|
329293b547 |
|||
|
7a0646edcc |
|||
|
573f48db58 |
|||
|
7b480bc844 |
16 changed files with 276 additions and 122 deletions
|
|
@ -1,41 +0,0 @@
|
|||
name: Release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
matrix:
|
||||
runs-on: nix
|
||||
outputs:
|
||||
cross-matrix: ${{ steps.set-matrix.outputs.cross-matrix }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- id: set-matrix
|
||||
run: |
|
||||
echo "cross-matrix={\"include\":$(nix eval --json '.#lib.crossMatrix')}" | tee -a $GITHUB_OUTPUT
|
||||
|
||||
build:
|
||||
runs-on: nix
|
||||
needs: [matrix]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{fromJson(needs.matrix.outputs.cross-matrix)}}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: https://codeberg.org/icewind/attic-action@v1
|
||||
with:
|
||||
name: link
|
||||
instance: https://cache.icewind.link
|
||||
authToken: "${{ secrets.ATTIC_TOKEN }}"
|
||||
- run: nix build .#${{ matrix.target }}
|
||||
- name: Upload binary to release
|
||||
uses: https://github.com/svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: result/bin/parse_demo${{ matrix.binary-suffix }}
|
||||
asset_name: parser-${{ matrix.target }}${{ matrix.binary-suffix }}
|
||||
tag: ${{ github.ref }}
|
||||
14
CHANGELOG.md
14
CHANGELOG.md
|
|
@ -1,3 +1,17 @@
|
|||
## Unreleased
|
||||
|
||||
- `SetConVar` message now uses `Cow` instead of `String`.
|
||||
- Add `Message::Disconnect` and `MessageType::Disconnect`. These never appears
|
||||
in demos, but are used in the network protocol.
|
||||
- `Message::encode` now write the message type by itself, instead of requiring
|
||||
the caller to do so beforehand.
|
||||
- `SignOnStateMessage::count` has been changed from an `u32` to an `i32`.
|
||||
|
||||
## 0.7.2
|
||||
|
||||
- Compress string tables, this fixes playback of encoded demos with large string
|
||||
tables.
|
||||
|
||||
## 0.7.1
|
||||
|
||||
- Add functionality for re-encoding baselines
|
||||
|
|
|
|||
12
Cargo.lock
generated
12
Cargo.lock
generated
|
|
@ -151,6 +151,15 @@ version = "1.1.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32b13ea120a812beba79e34316b3942a857c86ec1593cb34f27bb28272ce2cca"
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "2.1.1"
|
||||
|
|
@ -959,12 +968,13 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "tf-demo-parser"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
dependencies = [
|
||||
"Inflector",
|
||||
"better-panic",
|
||||
"bitbuffer",
|
||||
"const-fnv1a-hash",
|
||||
"crc32fast",
|
||||
"enumflags2",
|
||||
"fnv",
|
||||
"gungraun",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "tf-demo-parser"
|
||||
version = "0.7.1"
|
||||
version = "0.8.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91.0"
|
||||
description = "parser for tf2 demo files"
|
||||
|
|
@ -17,6 +17,10 @@ path = "src/lib.rs"
|
|||
name = "parse_demo"
|
||||
path = "src/bin/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "crc"
|
||||
path = "src/bin/crc.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "reencode_demo"
|
||||
path = "src/bin/reencode.rs"
|
||||
|
|
@ -52,6 +56,7 @@ name = "parse"
|
|||
better-panic = { version = "0.3.0", optional = true }
|
||||
bitbuffer = { version = "0.11.3", features = ["serde"] }
|
||||
const-fnv1a-hash = "1.1.0"
|
||||
crc32fast = "1.5.4"
|
||||
enumflags2 = { version = "0.7.12", features = ["serde"] }
|
||||
fnv = "1.0.7"
|
||||
itertools = "0.15.0"
|
||||
|
|
|
|||
35
src/bin/crc.rs
Normal file
35
src/bin/crc.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
use std::env;
|
||||
use std::fs;
|
||||
|
||||
use bitbuffer::BitRead;
|
||||
use main_error::MainError;
|
||||
use tf_demo_parser::demo::header::Header;
|
||||
use tf_demo_parser::demo::packet::Packet;
|
||||
use tf_demo_parser::demo::parser::RawPacketStream;
|
||||
pub use tf_demo_parser::{Demo, DemoParser, Parse, ParseError, ParserState, Stream};
|
||||
|
||||
fn main() -> Result<(), MainError> {
|
||||
#[cfg(feature = "better-panic")]
|
||||
better_panic::install();
|
||||
|
||||
let args: Vec<_> = env::args().collect();
|
||||
if args.len() < 2 {
|
||||
println!("1 argument required");
|
||||
return Ok(());
|
||||
}
|
||||
let path = args[1].clone();
|
||||
let file = fs::read(path)?;
|
||||
let demo = Demo::new(&file);
|
||||
|
||||
let mut stream = demo.get_stream();
|
||||
let header = Header::read(&mut stream)?;
|
||||
let mut packets = RawPacketStream::new(stream.clone());
|
||||
let state = ParserState::new(header.protocol, |_| false, false);
|
||||
while let Some(packet) = packets.next(&state)? {
|
||||
if let Packet::DataTables(tables) = packet {
|
||||
println!("{:08X}", tables.data_tables_crc32());
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(ParseError::InvalidDemo("No datatables in demo").into())
|
||||
}
|
||||
|
|
@ -55,7 +55,7 @@ fn main() -> Result<(), MainError> {
|
|||
println!("{header:?}");
|
||||
|
||||
let table_header = "Player | Points | Kills | Deaths | Assists | Destruction | Captures | Defenses | Domination | Revenge | Ubers | Headshots | Teleports | Healing | Backstabs | Bonus | Support | Damage Dealt";
|
||||
let divider = "---------------------------------|------------|------------|------------|------------|-------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|-------------";
|
||||
let divider = "---------------------------------|------------|------------|------------|------------|-------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|-------------";
|
||||
println!("{table_header}");
|
||||
println!("{divider}");
|
||||
|
||||
|
|
@ -74,7 +74,6 @@ fn main() -> Result<(), MainError> {
|
|||
println!(
|
||||
"{}{:32} | {:10} | {:10} | {:10} | {:10} | {:11} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:10} | {:12}{}",
|
||||
color_code_start,
|
||||
|
||||
player_name,
|
||||
s.points,
|
||||
s.kills,
|
||||
|
|
@ -93,7 +92,6 @@ fn main() -> Result<(), MainError> {
|
|||
s.bonus_points,
|
||||
s.support,
|
||||
s.damage_dealt,
|
||||
|
||||
color_code_end,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,46 +1,59 @@
|
|||
pub fn decompress(input: &[u8], output: &mut Vec<u8>) {
|
||||
decompress_(input, output);
|
||||
use bitbuffer::{BitRead, LittleEndian};
|
||||
|
||||
use crate::{ParseError, Stream};
|
||||
|
||||
const LZSS_ERROR: ParseError = ParseError::InvalidDemo("invalid LZSS encoding");
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CopyInfo {
|
||||
offset: u16,
|
||||
count: u8,
|
||||
}
|
||||
|
||||
/// inner fn that returns an option so we can use ? for short circuiting return
|
||||
fn decompress_(input: &[u8], output: &mut Vec<u8>) -> Option<()> {
|
||||
let mut len_bytes = [0; 4];
|
||||
len_bytes.copy_from_slice(input.get(0..4)?);
|
||||
let target_len = u32::from_le_bytes(len_bytes) as usize;
|
||||
// can't derive this, since it uses big-endian encoding for the `offset`
|
||||
impl BitRead<'_, LittleEndian> for CopyInfo {
|
||||
fn read(stream: &mut Stream) -> bitbuffer::Result<Self> {
|
||||
let bytes: [u8; 2] = stream.read()?;
|
||||
|
||||
let mut read_pos = 4;
|
||||
let mut read_byte = move || {
|
||||
let byte = *input.get(read_pos)?;
|
||||
read_pos += 1;
|
||||
Some(byte)
|
||||
};
|
||||
Ok(CopyInfo {
|
||||
offset: (bytes[0] as u16) << 4 | (bytes[1] as u16 >> 4),
|
||||
count: (bytes[1] & 0x0F) + 1,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
let mut cmd_byte = read_byte()?;
|
||||
pub fn decompress(input: &mut Stream, output: &mut Vec<u8>) -> Result<(), ParseError> {
|
||||
let target_len = input.read::<u32>()? as usize;
|
||||
|
||||
while output.len() < target_len {
|
||||
let mut cmd_byte: u8 = input.read()?;
|
||||
|
||||
for _ in 0..8 {
|
||||
if cmd_byte & 0x01 == 0x01 {
|
||||
let pos = (read_byte()? as usize) << 4;
|
||||
let mixed = read_byte()? as usize;
|
||||
let pos = pos | (mixed >> 4);
|
||||
let count = (mixed & 0x0F) + 1;
|
||||
if count == 1 {
|
||||
return None;
|
||||
let info: CopyInfo = input.read()?;
|
||||
|
||||
if info.count == 1 {
|
||||
break;
|
||||
}
|
||||
|
||||
if output.len() + count > target_len {
|
||||
return None;
|
||||
if output.len() + info.count as usize > target_len {
|
||||
return Err(LZSS_ERROR);
|
||||
}
|
||||
|
||||
let start = output.len() - pos - 1;
|
||||
let start = output
|
||||
.len()
|
||||
.checked_sub(info.offset as usize + 1)
|
||||
.ok_or(LZSS_ERROR)?;
|
||||
// can't do extend_from_within since it start + count can be larger than output.len
|
||||
for i in 0..count {
|
||||
output.push(*output.get(start + i)?);
|
||||
for i in 0..info.count {
|
||||
output.push(*output.get(start + i as usize).ok_or(LZSS_ERROR)?);
|
||||
}
|
||||
} else {
|
||||
output.push(read_byte()?);
|
||||
output.push(input.read()?);
|
||||
}
|
||||
cmd_byte >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ pub struct StringCmdMessage {
|
|||
}
|
||||
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
#[derive(BitRead, Debug, PartialEq, Serialize, Deserialize, Clone)]
|
||||
#[derive(BitRead, Debug, PartialEq, Serialize, Deserialize, Clone, Copy)]
|
||||
#[cfg_attr(feature = "write", derive(BitWrite))]
|
||||
#[discriminant_bits = 8]
|
||||
pub enum SignOnState {
|
||||
|
|
@ -51,7 +51,7 @@ pub enum SignOnState {
|
|||
#[cfg_attr(feature = "write", derive(BitWrite))]
|
||||
pub struct SignOnStateMessage {
|
||||
pub state: SignOnState,
|
||||
pub count: u32,
|
||||
pub count: i32,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ pub mod voice;
|
|||
#[discriminant_bits = 6]
|
||||
pub enum MessageType {
|
||||
Empty = 0,
|
||||
Disconnect = 1,
|
||||
File = 2,
|
||||
NetTick = 3,
|
||||
StringCmd = 4,
|
||||
|
|
@ -48,16 +49,20 @@ pub enum MessageType {
|
|||
SignOnState = 6,
|
||||
Print = 7,
|
||||
ServerInfo = 8,
|
||||
// SendTable = 9,
|
||||
ClassInfo = 10,
|
||||
SetPause = 11,
|
||||
CreateStringTable = 12,
|
||||
UpdateStringTable = 13,
|
||||
VoiceInit = 14,
|
||||
VoiceData = 15,
|
||||
// Hltv = 16,
|
||||
ParseSounds = 17,
|
||||
SetView = 18,
|
||||
FixAngle = 19,
|
||||
// CrosshairAngle = 20,
|
||||
BspDecal = 21,
|
||||
// TerrainMod = 22,
|
||||
UserMessage = 23,
|
||||
EntityMessage = 24,
|
||||
GameEvent = 25,
|
||||
|
|
@ -76,10 +81,11 @@ pub enum MessageType {
|
|||
#[serde(tag = "type")]
|
||||
pub enum Message<'a> {
|
||||
Empty,
|
||||
Disconnect(String),
|
||||
File(FileMessage),
|
||||
NetTick(NetTickMessage),
|
||||
StringCmd(StringCmdMessage),
|
||||
SetConVar(SetConVarMessage),
|
||||
SetConVar(SetConVarMessage<'a>),
|
||||
SignOnState(SignOnStateMessage),
|
||||
Print(PrintMessage),
|
||||
ServerInfo(Box<ServerInfoMessage>),
|
||||
|
|
@ -116,6 +122,7 @@ impl<'a> Message<'a> {
|
|||
pub fn get_message_type(&self) -> MessageType {
|
||||
match self {
|
||||
Message::Empty => MessageType::Empty,
|
||||
Message::Disconnect(_) => MessageType::Disconnect,
|
||||
Message::File(_) => MessageType::File,
|
||||
Message::NetTick(_) => MessageType::NetTick,
|
||||
Message::StringCmd(_) => MessageType::StringCmd,
|
||||
|
|
@ -153,6 +160,7 @@ impl<'a> Message<'a> {
|
|||
) -> Result<Self> {
|
||||
Ok(match message_type {
|
||||
MessageType::Empty => Message::Empty,
|
||||
MessageType::Disconnect => Message::Disconnect(String::read(stream)?),
|
||||
MessageType::File => Message::File(FileMessage::parse(stream, state)?),
|
||||
MessageType::NetTick => Message::NetTick(NetTickMessage::parse(stream, state)?),
|
||||
MessageType::StringCmd => Message::StringCmd(StringCmdMessage::parse(stream, state)?),
|
||||
|
|
@ -212,6 +220,7 @@ impl<'a> Message<'a> {
|
|||
) -> Result<()> {
|
||||
match message_type {
|
||||
MessageType::Empty => Ok(()),
|
||||
MessageType::Disconnect => String::parse_skip(stream, state),
|
||||
MessageType::File => FileMessage::parse_skip(stream, state),
|
||||
MessageType::NetTick => NetTickMessage::parse_skip(stream, state),
|
||||
MessageType::StringCmd => StringCmdMessage::parse_skip(stream, state),
|
||||
|
|
@ -246,8 +255,10 @@ impl<'a> Message<'a> {
|
|||
#[cfg(feature = "write")]
|
||||
impl Encode for Message<'_> {
|
||||
fn encode(&self, stream: &mut BitWriteStream<LittleEndian>, state: &ParserState) -> Result<()> {
|
||||
self.get_message_type().write(stream)?;
|
||||
match self {
|
||||
Message::Empty => Ok(()),
|
||||
Message::Disconnect(reason) => reason.encode(stream, state),
|
||||
Message::File(message) => message.encode(stream, state),
|
||||
Message::NetTick(message) => message.encode(stream, state),
|
||||
Message::StringCmd(message) => message.encode(stream, state),
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
use std::borrow::Cow;
|
||||
|
||||
use bitbuffer::{BitRead, BitReadStream, Endianness};
|
||||
#[cfg(feature = "write")]
|
||||
use bitbuffer::{BitWrite, BitWriteStream};
|
||||
|
|
@ -8,33 +10,33 @@ use crate::ReadResult;
|
|||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
|
||||
#[cfg_attr(feature = "write", derive(BitWrite))]
|
||||
pub struct ConVar {
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
pub struct ConVar<'a> {
|
||||
pub key: Cow<'a, str>,
|
||||
pub value: Cow<'a, str>,
|
||||
}
|
||||
|
||||
impl<E: Endianness> BitRead<'_, E> for ConVar {
|
||||
fn read(stream: &mut BitReadStream<'_, E>) -> ReadResult<Self> {
|
||||
impl<'a, E: Endianness> BitRead<'a, E> for ConVar<'a> {
|
||||
fn read(stream: &mut BitReadStream<'a, E>) -> ReadResult<Self> {
|
||||
let key = stream
|
||||
.read()
|
||||
.unwrap_or_else(|_| "Malformed cvar name".to_string());
|
||||
.unwrap_or_else(|_| "Malformed cvar name".into());
|
||||
let value = stream
|
||||
.read()
|
||||
.unwrap_or_else(|_| "Malformed cvar value".to_string());
|
||||
.unwrap_or_else(|_| "Malformed cvar value".into());
|
||||
Ok(ConVar { key, value })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
#[derive(Debug, BitRead, PartialEq, Serialize, Deserialize, Clone)]
|
||||
pub struct SetConVarMessage {
|
||||
pub struct SetConVarMessage<'a> {
|
||||
pub length: u8,
|
||||
#[size = "length"]
|
||||
pub vars: Vec<ConVar>,
|
||||
pub vars: Vec<ConVar<'a>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "write")]
|
||||
impl<E: Endianness> BitWrite<E> for SetConVarMessage {
|
||||
impl<E: Endianness> BitWrite<E> for SetConVarMessage<'_> {
|
||||
fn write(&self, stream: &mut BitWriteStream<E>) -> ReadResult<()> {
|
||||
self.length.write(stream)?;
|
||||
self.vars.write(stream)
|
||||
|
|
@ -51,12 +53,12 @@ fn test_set_con_var_roundtrip() {
|
|||
length: 2,
|
||||
vars: vec![
|
||||
ConVar {
|
||||
key: "foo1".to_string(),
|
||||
value: "bar1".to_string(),
|
||||
key: "foo1".into(),
|
||||
value: "bar1".into(),
|
||||
},
|
||||
ConVar {
|
||||
key: "foo2".to_string(),
|
||||
value: "bar2".to_string(),
|
||||
key: "foo2".into(),
|
||||
value: "bar2".into(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ use bitbuffer::{BitError, BitWrite, BitWriteSized, BitWriteStream};
|
|||
use bitbuffer::{BitReadBuffer, BitReadStream, LittleEndian};
|
||||
use num_traits::{PrimInt, Unsigned};
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(feature = "write")]
|
||||
use snap::raw::Encoder;
|
||||
use snap::raw::{decompress_len, Decoder};
|
||||
|
||||
use crate::demo::lzss::decompress;
|
||||
|
|
@ -99,9 +101,10 @@ impl<'a> Parse<'a> for CreateStringTableMessage<'a> {
|
|||
table_data = BitReadStream::new(buffer);
|
||||
}
|
||||
b"LZSS" => {
|
||||
let compressed_data = table_data.read_bytes(compressed_size as usize - 4)?;
|
||||
let mut compressed_data =
|
||||
table_data.read_bits((compressed_size as usize - 4) * 8)?;
|
||||
let mut decompressed_data = Vec::with_capacity(decompressed_size as usize);
|
||||
decompress(&compressed_data, &mut decompressed_data);
|
||||
decompress(&mut compressed_data, &mut decompressed_data)?;
|
||||
|
||||
if decompressed_data.len() != decompressed_size as usize {
|
||||
return Err(ParseError::UnexpectedDecompressedSize {
|
||||
|
|
@ -180,14 +183,26 @@ impl Encode for CreateStringTableMessage<'_> {
|
|||
fixed_size.write(stream)?;
|
||||
}
|
||||
|
||||
// no compression for now
|
||||
false.write(stream)?;
|
||||
|
||||
let start = stream.bit_len();
|
||||
let mut uncompressed = Vec::with_capacity(1024);
|
||||
let mut uncompressed_stream = BitWriteStream::new(&mut uncompressed, LittleEndian);
|
||||
|
||||
let table_meta = table.get_table_meta();
|
||||
|
||||
write_string_table_update(&table.entries, stream, &table_meta)?;
|
||||
write_string_table_update(&table.entries, &mut uncompressed_stream, &table_meta)?;
|
||||
|
||||
let mut encoder = Encoder::new();
|
||||
let compressed = encoder
|
||||
.compress_vec(&uncompressed)
|
||||
.map_err(ParseError::from)?;
|
||||
|
||||
// compressed flag is not included in size
|
||||
true.write(stream)?;
|
||||
let start = stream.bit_len();
|
||||
|
||||
(uncompressed.len() as u32).write(stream)?;
|
||||
(compressed.len() as u32 + 4).write(stream)?; // +4 for the magic bytes
|
||||
b"SNAP".write(stream)?;
|
||||
compressed.write(stream)?;
|
||||
|
||||
let end = stream.bit_len();
|
||||
Ok(encode_length((end - start) as u32))
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ use crate::{Parse, ParseError, ParserState, Result, Stream};
|
|||
use bitbuffer::{BitRead, BitReadStream, Endianness};
|
||||
#[cfg(feature = "write")]
|
||||
use bitbuffer::{BitWrite, BitWriteSized, BitWriteStream, LittleEndian};
|
||||
use crc32fast::Hasher;
|
||||
use parse_display::{Display, FromStr};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
|
|
@ -170,6 +171,22 @@ pub struct ParseSendTable {
|
|||
pub needs_decoder: bool,
|
||||
}
|
||||
|
||||
impl ParseSendTable {
|
||||
fn crc32(&self, hasher: &mut Hasher) {
|
||||
hasher.update(self.name.as_bytes());
|
||||
let prop_count: u32 = self
|
||||
.props
|
||||
.iter()
|
||||
.map(|p| if p.array_property.is_some() { 2 } else { 1 })
|
||||
.sum();
|
||||
|
||||
hasher.update(&prop_count.to_le_bytes());
|
||||
for prop in &self.props {
|
||||
prop.crc32(hasher);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse<'_> for ParseSendTable {
|
||||
fn parse(stream: &mut Stream, _state: &ParserState) -> Result<Self> {
|
||||
let needs_decoder = stream.read()?;
|
||||
|
|
@ -186,11 +203,10 @@ impl Parse<'_> for ParseSendTable {
|
|||
return Err(MalformedSendPropDefinitionError::ArrayChangesOften.into());
|
||||
}
|
||||
array_element_prop = Some(prop);
|
||||
} else if let Some(array_element) = array_element_prop {
|
||||
} else if let Some(array_element) = array_element_prop.take() {
|
||||
if prop.prop_type != SendPropType::Array {
|
||||
return Err(MalformedSendPropDefinitionError::UntypedArray.into());
|
||||
}
|
||||
array_element_prop = None;
|
||||
props.push(prop.with_array_property(array_element));
|
||||
} else {
|
||||
props.push(prop);
|
||||
|
|
@ -359,9 +375,10 @@ impl ParseSendTable {
|
|||
prop.name.as_str(),
|
||||
))
|
||||
} else if let Some(table) = prop.get_data_table(tables)
|
||||
&& !processed_tables.contains(&&table.name) {
|
||||
table.build_excludes(tables, processed_tables, excludes);
|
||||
}
|
||||
&& !processed_tables.contains(&&table.name)
|
||||
{
|
||||
table.build_excludes(tables, processed_tables, excludes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -438,6 +455,28 @@ pub struct DataTablePacket {
|
|||
pub server_classes: Vec<ServerClass>,
|
||||
}
|
||||
|
||||
impl DataTablePacket {
|
||||
/// calculate the crc32 hash of the data tables
|
||||
///
|
||||
/// The tf2 network protocol requires the crc32 of the datatables in order to ensure that the client and server use the same sendtables.
|
||||
pub fn data_tables_crc32(&self) -> u32 {
|
||||
let mut hasher = Hasher::new();
|
||||
for class in &self.server_classes {
|
||||
// unlike how they are stored in the demo, the in-engine tables that the CRC is compared against, are stored in server-class order.
|
||||
// in the demo, they are stored leaf-first, then any referenced table
|
||||
if let Some(table) = self
|
||||
.tables
|
||||
.iter()
|
||||
.find(|table| class.data_table == table.name)
|
||||
{
|
||||
table.crc32(&mut hasher);
|
||||
}
|
||||
}
|
||||
|
||||
hasher.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse<'_> for DataTablePacket {
|
||||
fn parse(stream: &mut Stream, state: &ParserState) -> Result<Self> {
|
||||
let tick = stream.read()?;
|
||||
|
|
|
|||
|
|
@ -107,7 +107,6 @@ impl Encode for MessagePacket<'_> {
|
|||
self.meta.write(stream)?;
|
||||
stream.reserve_byte_length(32, |stream| {
|
||||
for message in self.messages.iter() {
|
||||
message.get_message_type().write(stream)?;
|
||||
message.encode(stream, state)?;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -323,11 +323,12 @@ impl ParserState {
|
|||
|
||||
pub fn handle_string_entry(&mut self, table: &str, _index: usize, entry: &StringTableEntry) {
|
||||
if table == "instancebaseline"
|
||||
&& let (Some(extra), Ok(class_id)) = (&entry.extra_data, entry.text().parse()) {
|
||||
let baseline = StaticBaseline::new(class_id, extra.data.to_owned());
|
||||
self.static_baselines.insert(class_id, baseline);
|
||||
self.parsed_static_baselines.borrow_mut().remove(&class_id);
|
||||
}
|
||||
&& let (Some(extra), Ok(class_id)) = (&entry.extra_data, entry.text().parse())
|
||||
{
|
||||
let baseline = StaticBaseline::new(class_id, extra.data.to_owned());
|
||||
self.static_baselines.insert(class_id, baseline);
|
||||
self.parsed_static_baselines.borrow_mut().remove(&class_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn index_for_prop(&self, class: ClassId, prop: SendPropIdentifier) -> Option<u32> {
|
||||
|
|
@ -507,9 +508,6 @@ fn test_static_baseline_reencode() {
|
|||
assert_ne!(misread, props);
|
||||
}
|
||||
|
||||
let fixed = StaticBaseline::new(
|
||||
ClassId::from(0u16),
|
||||
baseline.reencode(&from, &to).unwrap(),
|
||||
);
|
||||
let fixed = StaticBaseline::new(ClassId::from(0u16), baseline.reencode(&from, &to).unwrap());
|
||||
assert_eq!(fixed.parse(&to).unwrap(), props);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use crate::{ParseError, ReadResult, Result, Stream};
|
|||
use bitbuffer::{BitRead, BitReadStream, Endianness, LittleEndian};
|
||||
#[cfg(feature = "write")]
|
||||
use bitbuffer::{BitWrite, BitWriteSized, BitWriteStream};
|
||||
use crc32fast::Hasher;
|
||||
use enumflags2::{bitflags, BitFlags};
|
||||
#[cfg(feature = "write")]
|
||||
use num_traits::Signed;
|
||||
|
|
@ -187,7 +188,8 @@ impl RawSendPropDefinition {
|
|||
let prop_type = SendPropType::read(stream)?;
|
||||
let name: SendPropName = stream.read()?;
|
||||
let identifier = SendPropIdentifier::new(owner_table.as_str(), name.as_str());
|
||||
let flags = SendPropFlags::read(stream)?;
|
||||
let flags = SendPropFlags::read(stream)?.with_non_networked_flags(&name);
|
||||
|
||||
let mut table_name = None;
|
||||
let mut element_count = None;
|
||||
let mut low_value = None;
|
||||
|
|
@ -240,6 +242,28 @@ impl RawSendPropDefinition {
|
|||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn crc32(&self, hasher: &mut Hasher) {
|
||||
if let Some(array_prop) = &self.array_property {
|
||||
array_prop.crc32(hasher);
|
||||
}
|
||||
|
||||
hasher.update(&(self.prop_type as u8 as u32).to_le_bytes());
|
||||
hasher.update(self.name.as_bytes());
|
||||
hasher.update(&self.flags.bits().to_le_bytes());
|
||||
|
||||
if let Some(table_name) = &self.table_name {
|
||||
// datatable and exclude props
|
||||
hasher.update(table_name.as_bytes());
|
||||
} else if let Some(count) = self.element_count {
|
||||
// array prop
|
||||
hasher.update(&(count as u32).to_le_bytes());
|
||||
} else {
|
||||
hasher.update(&self.low_value.unwrap_or_default().to_le_bytes());
|
||||
hasher.update(&self.high_value.unwrap_or_default().to_le_bytes());
|
||||
hasher.update(&self.original_bit_count.unwrap_or_default().to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "write")]
|
||||
|
|
@ -271,6 +295,7 @@ impl BitWrite<LittleEndian> for RawSendPropDefinition {
|
|||
#[derive(BitRead, Copy, Clone, PartialEq, Debug, Display, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "write", derive(BitWrite))]
|
||||
#[discriminant_bits = 5]
|
||||
#[repr(u8)]
|
||||
pub enum SendPropType {
|
||||
Int = 0,
|
||||
Float = 1,
|
||||
|
|
@ -284,7 +309,7 @@ pub enum SendPropType {
|
|||
|
||||
#[bitflags]
|
||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||
#[repr(u16)]
|
||||
#[repr(u32)]
|
||||
pub enum SendPropFlag {
|
||||
// Unsigned integer data.
|
||||
Unsigned = 1,
|
||||
|
|
@ -324,9 +349,32 @@ pub enum SendPropFlag {
|
|||
// SPROP_COORD_MP, but coordinates are rounded to integral boundaries
|
||||
// overloaded as both "Normal" and "VarInt"
|
||||
CoordMPIntegral = 32768,
|
||||
// This property is not networked, "m_flAnimTime" and "m_flSimulationTime" are the only props that have it
|
||||
EncodedAgainstTickCount = 65536,
|
||||
NormalVarInt = 32,
|
||||
}
|
||||
|
||||
impl SendPropFlags {
|
||||
pub fn with_non_networked_flags(self, name: &SendPropName) -> SendPropFlags {
|
||||
const AGAINST_TICKCOUNT_PROPS: &[&str] = &["m_flSimulationTime", "m_flAnimTime"];
|
||||
if AGAINST_TICKCOUNT_PROPS.contains(&name.as_str())
|
||||
&& self.contains(SendPropFlag::ChangesOften)
|
||||
{
|
||||
SendPropFlags(self.0 | SendPropFlag::EncodedAgainstTickCount)
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bits(&self) -> u32 {
|
||||
self.0.bits()
|
||||
}
|
||||
|
||||
pub fn networked_bits(&self) -> u16 {
|
||||
(self.0.bits() & 0xFFFF) as u16
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Default, Serialize, Deserialize)]
|
||||
pub struct SendPropFlags(BitFlags<SendPropFlag>);
|
||||
|
||||
|
|
@ -370,7 +418,9 @@ impl SendPropFlags {
|
|||
impl BitRead<'_, LittleEndian> for SendPropFlags {
|
||||
fn read(stream: &mut Stream) -> ReadResult<Self> {
|
||||
// since all 16 bits worth of flags are used there are no invalid flags
|
||||
Ok(SendPropFlags(BitFlags::from_bits_truncate(stream.read()?)))
|
||||
Ok(SendPropFlags(BitFlags::from_bits_truncate(
|
||||
stream.read::<u16>()? as u32,
|
||||
)))
|
||||
}
|
||||
|
||||
fn bit_size() -> Option<usize> {
|
||||
|
|
@ -381,7 +431,7 @@ impl BitRead<'_, LittleEndian> for SendPropFlags {
|
|||
#[cfg(feature = "write")]
|
||||
impl BitWrite<LittleEndian> for SendPropFlags {
|
||||
fn write(&self, stream: &mut BitWriteStream<LittleEndian>) -> ReadResult<()> {
|
||||
self.0.bits().write(stream)
|
||||
self.networked_bits().write(stream)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -69,19 +69,25 @@ fn message_reencode(
|
|||
let mut write = BitWriteStream::new(&mut out, LittleEndian);
|
||||
parsed.encode(&mut write, state).unwrap();
|
||||
write.bit_len()
|
||||
};
|
||||
} - 6; // 6 for the message type
|
||||
out.push(0);
|
||||
|
||||
let mut re_stream = BitReadStream::new(BitReadBuffer::new(&out, LittleEndian));
|
||||
let re_parsed = Message::from_type(ty, &mut re_stream, state).unwrap();
|
||||
let re_parsed = Message::parse(&mut re_stream, state).unwrap();
|
||||
assert_eq!(ty, re_parsed.get_message_type());
|
||||
|
||||
assert_eq!(parsed, re_parsed);
|
||||
assert_eq!(written_bits, stream.pos());
|
||||
|
||||
assert_eq!(data.len(), out.len());
|
||||
// cut of the message type
|
||||
let mut out_stream = BitReadStream::<LittleEndian>::from(out.as_slice());
|
||||
out_stream.skip_bits(6).unwrap();
|
||||
let out_body = out_stream.read_bytes(data.len()).unwrap();
|
||||
|
||||
if data.len() > 16 {
|
||||
pretty_assertions::assert_eq!(&data[0..data.len() - 8], &out[0..out.len() - 8]);
|
||||
pretty_assertions::assert_eq!(&data[data.len() - 8..], &out[out.len() - 8..]);
|
||||
pretty_assertions::assert_eq!(&data[0..8], &out_body[0..8]);
|
||||
pretty_assertions::assert_eq!(&data[8..], &out_body[8..]);
|
||||
} else {
|
||||
pretty_assertions::assert_eq!(data, out);
|
||||
pretty_assertions::assert_eq!(data.as_slice(), out_body.as_ref());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue