1
0
Fork 0
mirror of https://codeberg.org/demostf/parser.git synced 2026-11-30 10:40:50 +01:00

implement calculating datatable crc

This commit is contained in:
Robin Appelman 2026-11-07 16:54:25 +01:00
commit f914f1b747
Signed by: robin
SSH key fingerprint: SHA256:kifqgrqnut7q1YUIrI0AdMNC23qiKAS/T9uGFmIYvbE
6 changed files with 151 additions and 12 deletions

12
Cargo.lock generated
View file

@ -151,6 +151,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32b13ea120a812beba79e34316b3942a857c86ec1593cb34f27bb28272ce2cca" 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]] [[package]]
name = "derive_more" name = "derive_more"
version = "2.1.1" version = "2.1.1"
@ -959,12 +968,13 @@ dependencies = [
[[package]] [[package]]
name = "tf-demo-parser" name = "tf-demo-parser"
version = "0.7.2" version = "0.8.0"
dependencies = [ dependencies = [
"Inflector", "Inflector",
"better-panic", "better-panic",
"bitbuffer", "bitbuffer",
"const-fnv1a-hash", "const-fnv1a-hash",
"crc32fast",
"enumflags2", "enumflags2",
"fnv", "fnv",
"gungraun", "gungraun",

View file

@ -1,6 +1,6 @@
[package] [package]
name = "tf-demo-parser" name = "tf-demo-parser"
version = "0.7.2" version = "0.8.0"
edition = "2024" edition = "2024"
rust-version = "1.91.0" rust-version = "1.91.0"
description = "parser for tf2 demo files" description = "parser for tf2 demo files"
@ -17,6 +17,10 @@ path = "src/lib.rs"
name = "parse_demo" name = "parse_demo"
path = "src/bin/main.rs" path = "src/bin/main.rs"
[[bin]]
name = "crc"
path = "src/bin/crc.rs"
[[bin]] [[bin]]
name = "reencode_demo" name = "reencode_demo"
path = "src/bin/reencode.rs" path = "src/bin/reencode.rs"
@ -52,6 +56,7 @@ name = "parse"
better-panic = { version = "0.3.0", optional = true } better-panic = { version = "0.3.0", optional = true }
bitbuffer = { version = "0.11.3", features = ["serde"] } bitbuffer = { version = "0.11.3", features = ["serde"] }
const-fnv1a-hash = "1.1.0" const-fnv1a-hash = "1.1.0"
crc32fast = "1.5.4"
enumflags2 = { version = "0.7.12", features = ["serde"] } enumflags2 = { version = "0.7.12", features = ["serde"] }
fnv = "1.0.7" fnv = "1.0.7"
itertools = "0.15.0" itertools = "0.15.0"

35
src/bin/crc.rs Normal file
View 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())
}

View file

@ -32,7 +32,7 @@ pub struct StringCmdMessage {
} }
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[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))] #[cfg_attr(feature = "write", derive(BitWrite))]
#[discriminant_bits = 8] #[discriminant_bits = 8]
pub enum SignOnState { pub enum SignOnState {

View file

@ -7,6 +7,7 @@ use crate::{Parse, ParseError, ParserState, Result, Stream};
use bitbuffer::{BitRead, BitReadStream, Endianness}; use bitbuffer::{BitRead, BitReadStream, Endianness};
#[cfg(feature = "write")] #[cfg(feature = "write")]
use bitbuffer::{BitWrite, BitWriteSized, BitWriteStream, LittleEndian}; use bitbuffer::{BitWrite, BitWriteSized, BitWriteStream, LittleEndian};
use crc32fast::Hasher;
use parse_display::{Display, FromStr}; use parse_display::{Display, FromStr};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::borrow::Cow; use std::borrow::Cow;
@ -170,6 +171,22 @@ pub struct ParseSendTable {
pub needs_decoder: bool, 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 { impl Parse<'_> for ParseSendTable {
fn parse(stream: &mut Stream, _state: &ParserState) -> Result<Self> { fn parse(stream: &mut Stream, _state: &ParserState) -> Result<Self> {
let needs_decoder = stream.read()?; let needs_decoder = stream.read()?;
@ -186,11 +203,10 @@ impl Parse<'_> for ParseSendTable {
return Err(MalformedSendPropDefinitionError::ArrayChangesOften.into()); return Err(MalformedSendPropDefinitionError::ArrayChangesOften.into());
} }
array_element_prop = Some(prop); 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 { if prop.prop_type != SendPropType::Array {
return Err(MalformedSendPropDefinitionError::UntypedArray.into()); return Err(MalformedSendPropDefinitionError::UntypedArray.into());
} }
array_element_prop = None;
props.push(prop.with_array_property(array_element)); props.push(prop.with_array_property(array_element));
} else { } else {
props.push(prop); props.push(prop);
@ -359,7 +375,8 @@ impl ParseSendTable {
prop.name.as_str(), prop.name.as_str(),
)) ))
} else if let Some(table) = prop.get_data_table(tables) } else if let Some(table) = prop.get_data_table(tables)
&& !processed_tables.contains(&&table.name) { && !processed_tables.contains(&&table.name)
{
table.build_excludes(tables, processed_tables, excludes); table.build_excludes(tables, processed_tables, excludes);
} }
} }
@ -438,6 +455,28 @@ pub struct DataTablePacket {
pub server_classes: Vec<ServerClass>, 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 { impl Parse<'_> for DataTablePacket {
fn parse(stream: &mut Stream, state: &ParserState) -> Result<Self> { fn parse(stream: &mut Stream, state: &ParserState) -> Result<Self> {
let tick = stream.read()?; let tick = stream.read()?;

View file

@ -9,6 +9,7 @@ use crate::{ParseError, ReadResult, Result, Stream};
use bitbuffer::{BitRead, BitReadStream, Endianness, LittleEndian}; use bitbuffer::{BitRead, BitReadStream, Endianness, LittleEndian};
#[cfg(feature = "write")] #[cfg(feature = "write")]
use bitbuffer::{BitWrite, BitWriteSized, BitWriteStream}; use bitbuffer::{BitWrite, BitWriteSized, BitWriteStream};
use crc32fast::Hasher;
use enumflags2::{bitflags, BitFlags}; use enumflags2::{bitflags, BitFlags};
#[cfg(feature = "write")] #[cfg(feature = "write")]
use num_traits::Signed; use num_traits::Signed;
@ -187,7 +188,8 @@ impl RawSendPropDefinition {
let prop_type = SendPropType::read(stream)?; let prop_type = SendPropType::read(stream)?;
let name: SendPropName = stream.read()?; let name: SendPropName = stream.read()?;
let identifier = SendPropIdentifier::new(owner_table.as_str(), name.as_str()); 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 table_name = None;
let mut element_count = None; let mut element_count = None;
let mut low_value = None; let mut low_value = None;
@ -240,6 +242,28 @@ impl RawSendPropDefinition {
None 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")] #[cfg(feature = "write")]
@ -271,6 +295,7 @@ impl BitWrite<LittleEndian> for RawSendPropDefinition {
#[derive(BitRead, Copy, Clone, PartialEq, Debug, Display, Serialize, Deserialize)] #[derive(BitRead, Copy, Clone, PartialEq, Debug, Display, Serialize, Deserialize)]
#[cfg_attr(feature = "write", derive(BitWrite))] #[cfg_attr(feature = "write", derive(BitWrite))]
#[discriminant_bits = 5] #[discriminant_bits = 5]
#[repr(u8)]
pub enum SendPropType { pub enum SendPropType {
Int = 0, Int = 0,
Float = 1, Float = 1,
@ -284,7 +309,7 @@ pub enum SendPropType {
#[bitflags] #[bitflags]
#[derive(Copy, Clone, PartialEq, Debug)] #[derive(Copy, Clone, PartialEq, Debug)]
#[repr(u16)] #[repr(u32)]
pub enum SendPropFlag { pub enum SendPropFlag {
// Unsigned integer data. // Unsigned integer data.
Unsigned = 1, Unsigned = 1,
@ -324,9 +349,32 @@ pub enum SendPropFlag {
// SPROP_COORD_MP, but coordinates are rounded to integral boundaries // SPROP_COORD_MP, but coordinates are rounded to integral boundaries
// overloaded as both "Normal" and "VarInt" // overloaded as both "Normal" and "VarInt"
CoordMPIntegral = 32768, CoordMPIntegral = 32768,
// This property is not networked, "m_flAnimTime" and "m_flSimulationTime" are the only props that have it
EncodedAgainstTickCount = 65536,
NormalVarInt = 32, NormalVarInt = 32,
} }
impl SendPropFlags {
pub fn with_non_networked_flags(self, name: &SendPropName) -> SendPropFlags {
const AGAINST_TICKCOUNT_PROPS: &[&'static 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)] #[derive(Debug, Copy, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SendPropFlags(BitFlags<SendPropFlag>); pub struct SendPropFlags(BitFlags<SendPropFlag>);
@ -370,7 +418,9 @@ impl SendPropFlags {
impl BitRead<'_, LittleEndian> for SendPropFlags { impl BitRead<'_, LittleEndian> for SendPropFlags {
fn read(stream: &mut Stream) -> ReadResult<Self> { fn read(stream: &mut Stream) -> ReadResult<Self> {
// since all 16 bits worth of flags are used there are no invalid flags // 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> { fn bit_size() -> Option<usize> {
@ -381,7 +431,7 @@ impl BitRead<'_, LittleEndian> for SendPropFlags {
#[cfg(feature = "write")] #[cfg(feature = "write")]
impl BitWrite<LittleEndian> for SendPropFlags { impl BitWrite<LittleEndian> for SendPropFlags {
fn write(&self, stream: &mut BitWriteStream<LittleEndian>) -> ReadResult<()> { fn write(&self, stream: &mut BitWriteStream<LittleEndian>) -> ReadResult<()> {
self.0.bits().write(stream) self.networked_bits().write(stream)
} }
} }