more weapons

This commit is contained in:
Robin Appelman 2026-11-12 22:42:00 +01:00
commit 371fe4079d
Signed by: robin
SSH key fingerprint: SHA256:kifqgrqnut7q1YUIrI0AdMNC23qiKAS/T9uGFmIYvbE
3 changed files with 347 additions and 1 deletions

165
examples/weapons.rs Normal file
View file

@ -0,0 +1,165 @@
use ahash::AHashSet;
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use main_error::MainError;
use rayon::prelude::*;
use std::env::args;
use std::ffi::OsStr;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::channel;
use std::thread::spawn;
use std::time::{Duration, Instant};
use tf_log_parser::event::ShotFiredEvent;
use tf_log_parser::module::GlobalData;
use tf_log_parser::{
parse_with_handler, EventMeta, GameEvent, RawEventType, SubjectId, SubjectMap,
};
use walkdir::WalkDir;
#[derive(Default)]
struct WeaponsHandler {
weapons: AHashSet<String>,
}
impl GlobalData for WeaponsHandler {
type Output = AHashSet<String>;
fn does_handle(ty: RawEventType) -> bool {
matches!(ty, RawEventType::ShotFired)
}
fn handle_event(&mut self, _meta: &EventMeta, _subject: SubjectId, event: &GameEvent) {
if let GameEvent::ShotFired(ShotFiredEvent {
weapon: Some(weapon),
..
}) = event
{
if !self.weapons.contains(*weapon) {
self.weapons.insert((*weapon).into());
}
}
}
fn finish(self, _subjects: &SubjectMap) -> Self::Output {
self.weapons
}
}
fn main() -> Result<(), MainError> {
let mut args = args().skip(1);
let path = args.next().expect("No input path provided");
let out_path = args.next().expect("No output path provided");
let parse_time = AtomicUsize::default();
let read_time = AtomicUsize::default();
let count = AtomicUsize::default();
let start = Instant::now();
let style = ProgressStyle::with_template(
"[{elapsed_precise}] {wide_bar:.cyan/blue} {per_sec:!} {pos:>7}/{len:7} [{eta}]",
)
.unwrap();
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(Duration::from_millis(120));
pb.set_style(
ProgressStyle::with_template("[{elapsed_precise}] {spinner:.blue} {msg}")
.unwrap()
.tick_strings(&[
"▹▹▹▹▹",
"▸▹▹▹▹",
"▹▸▹▹▹",
"▹▹▸▹▹",
"▹▹▹▸▹",
"▹▹▹▹▸",
"▪▪▪▪▪",
]),
);
pb.set_message("Collecting paths...");
let paths: Vec<_> = WalkDir::new(path)
.into_iter()
.flatten()
.filter(|entry| entry.path().extension() == Some(OsStr::new("log")))
.collect();
pb.finish_with_message("Done");
let bar = ProgressBar::new(paths.len() as u64);
bar.set_style(style);
let (tx, rx) = channel::<AHashSet<String>>();
let count_handle = spawn(move || {
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(&out_path)
.unwrap();
let mut weapons = AHashSet::new();
while let Ok(log_weapons) = rx.recv() {
for weapon in log_weapons {
if !weapons.contains(&weapon) {
writeln!(&mut file, "{weapon}").unwrap();
weapons.insert(weapon);
}
}
}
weapons.len()
});
paths.into_par_iter().progress_with(bar).for_each(|entry| {
let path = entry.path();
if path.extension() == Some(OsStr::new("log")) {
// let _ = print!("{} - ", path.display());
let read_start = Instant::now();
let input = match fs::read(path) {
Ok(input) => input,
Err(_e) => {
// println!("failed to read file: {}", e);
return;
}
};
let input = String::from_utf8_lossy(&input);
read_time.fetch_add(read_start.elapsed().as_micros() as usize, Ordering::Relaxed);
let parse_start = Instant::now();
let Ok((log_weapons, _)) = parse_with_handler::<WeaponsHandler>(&input) else {
return;
};
parse_time.fetch_add(
parse_start.elapsed().as_micros() as usize,
Ordering::Relaxed,
);
count.fetch_add(1, Ordering::Relaxed);
tx.send(log_weapons).unwrap();
}
});
drop(tx);
let total = start.elapsed();
let read_time = read_time.load(Ordering::Relaxed);
let parse_time = parse_time.load(Ordering::Relaxed);
let weapon_count = count_handle.join().unwrap();
println!(
"Parsed {} in {:01}s, spend {:01}s reading files, in {:01}s of real time, found {} unique weapon names",
count.load(Ordering::Relaxed),
micros_as_sec(parse_time),
micros_as_sec(read_time),
micros_as_sec(total.as_micros() as usize),
weapon_count,
);
Ok(())
}
fn micros_as_sec(micros: usize) -> f32 {
micros as f32 / 1_000_000.0
}