1use crate::*;
2use boxcars;
3use std::collections::HashMap;
4
5pub mod actor_state;
6pub use actor_state::*;
7
8pub(crate) fn attribute_type_name(attribute: &boxcars::Attribute) -> &'static str {
9 match attribute {
10 boxcars::Attribute::Boolean(_) => "Boolean",
11 boxcars::Attribute::Byte(_) => "Byte",
12 boxcars::Attribute::AppliedDamage(_) => "AppliedDamage",
13 boxcars::Attribute::DamageState(_) => "DamageState",
14 boxcars::Attribute::CamSettings(_) => "CamSettings",
15 boxcars::Attribute::ClubColors(_) => "ClubColors",
16 boxcars::Attribute::Demolish(_) => "Demolish",
17 boxcars::Attribute::DemolishExtended(_) => "DemolishExtended",
18 boxcars::Attribute::DemolishFx(_) => "DemolishFx",
19 boxcars::Attribute::Enum(_) => "Enum",
20 boxcars::Attribute::Explosion(_) => "Explosion",
21 boxcars::Attribute::ExtendedExplosion(_) => "ExtendedExplosion",
22 boxcars::Attribute::FlaggedByte(_, _) => "FlaggedByte",
23 boxcars::Attribute::ActiveActor(_) => "ActiveActor",
24 boxcars::Attribute::Float(_) => "Float",
25 boxcars::Attribute::GameMode(_, _) => "GameMode",
26 boxcars::Attribute::Int(_) => "Int",
27 boxcars::Attribute::Int64(_) => "Int64",
28 boxcars::Attribute::Loadout(_) => "Loadout",
29 boxcars::Attribute::TeamLoadout(_) => "TeamLoadout",
30 boxcars::Attribute::Location(_) => "Location",
31 boxcars::Attribute::MusicStinger(_) => "MusicStinger",
32 boxcars::Attribute::PlayerHistoryKey(_) => "PlayerHistoryKey",
33 boxcars::Attribute::Pickup(_) => "Pickup",
34 boxcars::Attribute::PickupNew(_) => "PickupNew",
35 boxcars::Attribute::QWord(_) => "QWord",
36 boxcars::Attribute::Welded(_) => "Welded",
37 boxcars::Attribute::Title(_, _, _, _, _, _, _, _) => "Title",
38 boxcars::Attribute::TeamPaint(_) => "TeamPaint",
39 boxcars::Attribute::RigidBody(_) => "RigidBody",
40 boxcars::Attribute::String(_) => "String",
41 boxcars::Attribute::UniqueId(_) => "UniqueId",
42 boxcars::Attribute::Reservation(_) => "Reservation",
43 boxcars::Attribute::PartyLeader(_) => "PartyLeader",
44 boxcars::Attribute::PrivateMatch(_) => "PrivateMatch",
45 boxcars::Attribute::LoadoutOnline(_) => "LoadoutOnline",
46 boxcars::Attribute::LoadoutsOnline(_) => "LoadoutsOnline",
47 boxcars::Attribute::StatEvent(_) => "StatEvent",
48 boxcars::Attribute::Rotation(_) => "Rotation",
49 boxcars::Attribute::RepStatTitle(_) => "RepStatTitle",
50 boxcars::Attribute::PickupInfo(_) => "PickupInfo",
51 boxcars::Attribute::Impulse(_) => "Impulse",
52 boxcars::Attribute::ReplicatedBoost(_) => "ReplicatedBoost",
53 boxcars::Attribute::LogoData(_) => "LogoData",
54 }
55}
56
57#[macro_export]
69macro_rules! attribute_match {
70 ($value:expr, $type:path $(,)?) => {{
71 let attribute = $value;
72 if let $type(value) = attribute {
73 Ok(value)
74 } else {
75 SubtrActorError::new_result(SubtrActorErrorVariant::UnexpectedAttributeType {
76 expected_type: stringify!($type),
77 actual_type: attribute_type_name(&attribute),
78 })
79 }
80 }};
81}
82
83#[macro_export]
92macro_rules! get_attribute_errors_expected {
93 ($self:ident, $map:expr, $prop:expr, $type:path) => {
94 $self
95 .get_attribute($map, $prop)
96 .and_then(|found| attribute_match!(found, $type))
97 };
98}
99
100macro_rules! get_attribute_and_updated {
113 ($self:ident, $map:expr, $prop:expr, $type:path) => {
114 $self
115 .get_attribute_and_updated($map, $prop)
116 .and_then(|(found, updated)| attribute_match!(found, $type).map(|v| (v, updated)))
117 };
118}
119
120macro_rules! get_actor_attribute_matching {
129 ($self:ident, $actor:expr, $prop:expr, $type:path) => {
130 $self
131 .get_actor_attribute($actor, $prop)
132 .and_then(|found| attribute_match!(found, $type))
133 };
134}
135
136macro_rules! get_derived_attribute {
145 ($map:expr, $key:expr, $type:path) => {
146 $map.get($key)
147 .ok_or_else(|| {
148 SubtrActorError::new(SubtrActorErrorVariant::DerivedKeyValueNotFound {
149 name: $key.to_string(),
150 })
151 })
152 .and_then(|found| attribute_match!(&found.0, $type))
153 };
154}
155
156fn get_actor_id_from_active_actor<T>(
157 _: T,
158 active_actor: &boxcars::ActiveActor,
159) -> boxcars::ActorId {
160 active_actor.actor
161}
162
163fn use_update_actor<T>(id: boxcars::ActorId, _: T) -> boxcars::ActorId {
164 id
165}
166
167#[derive(Clone, Copy, Default)]
168struct CachedObjectIds {
169 player_type: Option<boxcars::ObjectId>,
170 car_type: Option<boxcars::ObjectId>,
171 boost_type: Option<boxcars::ObjectId>,
172 dodge_type: Option<boxcars::ObjectId>,
173 jump_type: Option<boxcars::ObjectId>,
174 double_jump_type: Option<boxcars::ObjectId>,
175 unique_id: Option<boxcars::ObjectId>,
176 team: Option<boxcars::ObjectId>,
177 player_replication: Option<boxcars::ObjectId>,
178 vehicle: Option<boxcars::ObjectId>,
179 boost_replicated: Option<boxcars::ObjectId>,
180 boost_amount: Option<boxcars::ObjectId>,
181 component_active: Option<boxcars::ObjectId>,
182 seconds_remaining: Option<boxcars::ObjectId>,
183 replicated_state_name: Option<boxcars::ObjectId>,
184 replicated_game_state_time_remaining: Option<boxcars::ObjectId>,
185 ball_has_been_hit: Option<boxcars::ObjectId>,
186 ball_hit_team_num: Option<boxcars::ObjectId>,
187 dodges_refreshed_counter: Option<boxcars::ObjectId>,
188}
189
190impl CachedObjectIds {
191 fn from_name_map(name_to_object_id: &HashMap<String, boxcars::ObjectId>) -> Self {
192 let cached = |name| name_to_object_id.get(name).copied();
193 Self {
194 player_type: cached(PLAYER_TYPE),
195 car_type: cached(CAR_TYPE),
196 boost_type: cached(BOOST_TYPE),
197 dodge_type: cached(DODGE_TYPE),
198 jump_type: cached(JUMP_TYPE),
199 double_jump_type: cached(DOUBLE_JUMP_TYPE),
200 unique_id: cached(UNIQUE_ID_KEY),
201 team: cached(TEAM_KEY),
202 player_replication: cached(PLAYER_REPLICATION_KEY),
203 vehicle: cached(VEHICLE_KEY),
204 boost_replicated: cached(BOOST_REPLICATED_KEY),
205 boost_amount: cached(BOOST_AMOUNT_KEY),
206 component_active: cached(COMPONENT_ACTIVE_KEY),
207 seconds_remaining: cached(SECONDS_REMAINING_KEY),
208 replicated_state_name: cached(REPLICATED_STATE_NAME_KEY),
209 replicated_game_state_time_remaining: cached(REPLICATED_GAME_STATE_TIME_REMAINING_KEY),
210 ball_has_been_hit: cached(BALL_HAS_BEEN_HIT_KEY),
211 ball_hit_team_num: cached(BALL_HIT_TEAM_NUM_KEY),
212 dodges_refreshed_counter: cached(DODGES_REFRESHED_COUNTER_KEY),
213 }
214 }
215}
216
217mod bootstrap;
218mod debug;
219mod queries;
220mod updaters;
221
222pub struct ReplayProcessor<'a> {
254 pub replay: &'a boxcars::Replay,
256 spatial_normalization_factor: f32,
257 rigid_body_velocity_normalization_factor: f32,
258 uses_legacy_rigid_body_rotation: bool,
259 cached_object_ids: CachedObjectIds,
260 is_boost_pad_object: Vec<bool>,
261 pub actor_state: ActorStateModeler,
263 pub object_id_to_name: HashMap<boxcars::ObjectId, String>,
265 pub name_to_object_id: HashMap<String, boxcars::ObjectId>,
267 pub ball_actor_id: Option<boxcars::ActorId>,
269 pub team_zero: Vec<PlayerId>,
271 pub team_one: Vec<PlayerId>,
273 pub player_to_actor_id: HashMap<PlayerId, boxcars::ActorId>,
275 pub player_to_car: HashMap<boxcars::ActorId, boxcars::ActorId>,
277 pub player_to_team: HashMap<boxcars::ActorId, boxcars::ActorId>,
279 pub car_to_player: HashMap<boxcars::ActorId, boxcars::ActorId>,
281 pub car_to_boost: HashMap<boxcars::ActorId, boxcars::ActorId>,
283 pub car_to_jump: HashMap<boxcars::ActorId, boxcars::ActorId>,
285 pub car_to_double_jump: HashMap<boxcars::ActorId, boxcars::ActorId>,
287 pub car_to_dodge: HashMap<boxcars::ActorId, boxcars::ActorId>,
289 pub boost_pad_events: Vec<BoostPadEvent>,
291 current_frame_boost_pad_events: Vec<BoostPadEvent>,
292 pub touch_events: Vec<TouchEvent>,
294 current_frame_touch_events: Vec<TouchEvent>,
295 pub dodge_refreshed_events: Vec<DodgeRefreshedEvent>,
297 current_frame_dodge_refreshed_events: Vec<DodgeRefreshedEvent>,
298 dodge_refreshed_counters: HashMap<PlayerId, i32>,
299 pub goal_events: Vec<GoalEvent>,
301 current_frame_goal_events: Vec<GoalEvent>,
302 pub player_stat_events: Vec<PlayerStatEvent>,
304 current_frame_player_stat_events: Vec<PlayerStatEvent>,
305 player_stat_counters: HashMap<(PlayerId, PlayerStatEventKind), i32>,
306 pub demolishes: Vec<DemolishInfo>,
308 known_demolishes: Vec<(DemolishAttribute, usize)>,
309 demolish_format: Option<DemolishFormat>,
310 kickoff_phase_active_last_frame: bool,
311}
312
313impl<'a> ReplayProcessor<'a> {
314 const LEGACY_RIGID_BODY_NET_VERSION_CUTOFF: i32 = 5;
315 const LEGACY_RIGID_BODY_ROTATION_NET_VERSION_CUTOFF: i32 = 7;
316 const LEGACY_RIGID_BODY_LOCATION_FACTOR: f32 = 100.0;
317 const LEGACY_RIGID_BODY_VELOCITY_FACTOR: f32 = 10.0;
318
319 fn uses_legacy_rigid_body_vector_scale(net_version: Option<i32>) -> bool {
320 net_version.is_none_or(|version| version < Self::LEGACY_RIGID_BODY_NET_VERSION_CUTOFF)
321 }
322
323 fn uses_legacy_rigid_body_rotation_for_net_version(net_version: Option<i32>) -> bool {
324 net_version
325 .is_none_or(|version| version < Self::LEGACY_RIGID_BODY_ROTATION_NET_VERSION_CUTOFF)
326 }
327
328 fn rigid_body_location_normalization_factor_for_net_version(net_version: Option<i32>) -> f32 {
329 if Self::uses_legacy_rigid_body_vector_scale(net_version) {
330 Self::LEGACY_RIGID_BODY_LOCATION_FACTOR
331 } else {
332 1.0
333 }
334 }
335
336 fn rigid_body_velocity_normalization_factor_for_net_version(net_version: Option<i32>) -> f32 {
337 if Self::uses_legacy_rigid_body_vector_scale(net_version) {
338 Self::LEGACY_RIGID_BODY_VELOCITY_FACTOR
339 } else {
340 1.0
341 }
342 }
343
344 pub fn new(replay: &'a boxcars::Replay) -> SubtrActorResult<Self> {
358 let mut object_id_to_name = HashMap::new();
359 let mut name_to_object_id = HashMap::new();
360 let spatial_normalization_factor =
361 Self::rigid_body_location_normalization_factor_for_net_version(replay.net_version);
362 let rigid_body_velocity_normalization_factor =
363 Self::rigid_body_velocity_normalization_factor_for_net_version(replay.net_version);
364 let uses_legacy_rigid_body_rotation =
365 Self::uses_legacy_rigid_body_rotation_for_net_version(replay.net_version);
366 for (id, name) in replay.objects.iter().enumerate() {
367 let object_id = boxcars::ObjectId(id as i32);
368 object_id_to_name.insert(object_id, name.clone());
369 name_to_object_id.insert(name.clone(), object_id);
370 }
371 let cached_object_ids = CachedObjectIds::from_name_map(&name_to_object_id);
372 let mut processor = Self {
373 actor_state: ActorStateModeler::new(),
374 replay,
375 spatial_normalization_factor,
376 rigid_body_velocity_normalization_factor,
377 uses_legacy_rigid_body_rotation,
378 cached_object_ids,
379 is_boost_pad_object: replay
380 .objects
381 .iter()
382 .map(|name| name.contains("VehiclePickup_Boost_TA"))
383 .collect(),
384 object_id_to_name,
385 name_to_object_id,
386 team_zero: Vec::new(),
387 team_one: Vec::new(),
388 ball_actor_id: None,
389 player_to_car: HashMap::new(),
390 player_to_team: HashMap::new(),
391 player_to_actor_id: HashMap::new(),
392 car_to_player: HashMap::new(),
393 car_to_boost: HashMap::new(),
394 car_to_jump: HashMap::new(),
395 car_to_double_jump: HashMap::new(),
396 car_to_dodge: HashMap::new(),
397 boost_pad_events: Vec::new(),
398 current_frame_boost_pad_events: Vec::new(),
399 touch_events: Vec::new(),
400 current_frame_touch_events: Vec::new(),
401 dodge_refreshed_events: Vec::new(),
402 current_frame_dodge_refreshed_events: Vec::new(),
403 dodge_refreshed_counters: HashMap::new(),
404 goal_events: Vec::new(),
405 current_frame_goal_events: Vec::new(),
406 player_stat_events: Vec::new(),
407 current_frame_player_stat_events: Vec::new(),
408 player_stat_counters: HashMap::new(),
409 demolishes: Vec::new(),
410 known_demolishes: Vec::new(),
411 demolish_format: None,
412 kickoff_phase_active_last_frame: false,
413 };
414 processor
415 .set_player_order_from_headers()
416 .or_else(|_| processor.set_player_order_from_frames())?;
417
418 Ok(processor)
419 }
420
421 pub fn spatial_normalization_factor(&self) -> f32 {
423 self.spatial_normalization_factor
424 }
425
426 pub fn rigid_body_velocity_normalization_factor(&self) -> f32 {
428 self.rigid_body_velocity_normalization_factor
429 }
430
431 fn normalize_vector_by_factor(
432 &self,
433 vector: boxcars::Vector3f,
434 factor: f32,
435 ) -> boxcars::Vector3f {
436 if (factor - 1.0).abs() < f32::EPSILON {
437 vector
438 } else {
439 boxcars::Vector3f {
440 x: vector.x * factor,
441 y: vector.y * factor,
442 z: vector.z * factor,
443 }
444 }
445 }
446
447 fn normalize_vector(&self, vector: boxcars::Vector3f) -> boxcars::Vector3f {
448 self.normalize_vector_by_factor(vector, self.spatial_normalization_factor)
449 }
450
451 fn normalize_rigid_body_velocity(&self, vector: boxcars::Vector3f) -> boxcars::Vector3f {
452 self.normalize_vector_by_factor(vector, self.rigid_body_velocity_normalization_factor)
453 }
454
455 fn normalize_optional_rigid_body_velocity(
456 &self,
457 vector: Option<boxcars::Vector3f>,
458 ) -> Option<boxcars::Vector3f> {
459 vector.map(|value| self.normalize_rigid_body_velocity(value))
460 }
461
462 fn normalize_rigid_body_rotation(&self, rotation: boxcars::Quaternion) -> boxcars::Quaternion {
463 if !self.uses_legacy_rigid_body_rotation {
464 return rotation;
465 }
466
467 let normalized = glam::Quat::from_euler(
471 glam::EulerRot::ZYX,
472 rotation.y * std::f32::consts::PI,
473 rotation.x * std::f32::consts::PI,
474 -rotation.z * std::f32::consts::PI,
475 );
476 boxcars::Quaternion {
477 x: normalized.x,
478 y: normalized.y,
479 z: normalized.z,
480 w: normalized.w,
481 }
482 }
483
484 fn normalize_rigid_body(&self, rigid_body: &boxcars::RigidBody) -> boxcars::RigidBody {
485 if (self.spatial_normalization_factor - 1.0).abs() < f32::EPSILON
486 && (self.rigid_body_velocity_normalization_factor - 1.0).abs() < f32::EPSILON
487 && !self.uses_legacy_rigid_body_rotation
488 {
489 *rigid_body
490 } else {
491 boxcars::RigidBody {
492 sleeping: rigid_body.sleeping,
493 location: self.normalize_vector(rigid_body.location),
494 rotation: self.normalize_rigid_body_rotation(rigid_body.rotation),
495 linear_velocity: self
496 .normalize_optional_rigid_body_velocity(rigid_body.linear_velocity),
497 angular_velocity: self
498 .normalize_optional_rigid_body_velocity(rigid_body.angular_velocity),
499 }
500 }
501 }
502
503 fn required_cached_object_id(
504 &self,
505 object_id: Option<boxcars::ObjectId>,
506 name: &'static str,
507 ) -> SubtrActorResult<boxcars::ObjectId> {
508 object_id
509 .ok_or_else(|| SubtrActorError::new(SubtrActorErrorVariant::ObjectIdNotFound { name }))
510 }
511
512 pub fn process<H: Collector>(&mut self, handler: &mut H) -> SubtrActorResult<()> {
534 let mut target_time = TimeAdvance::NextFrame;
537 for (index, frame) in self
538 .replay
539 .network_frames
540 .as_ref()
541 .ok_or(SubtrActorError::new(
542 SubtrActorErrorVariant::NoNetworkFrames,
543 ))?
544 .frames
545 .iter()
546 .enumerate()
547 {
548 self.actor_state.process_frame(frame, index)?;
550 self.update_mappings(frame)?;
551 self.update_ball_id(frame)?;
552 self.update_boost_amounts(frame, index)?;
553 self.update_boost_pad_events(frame, index)?;
554 self.update_touch_events(frame, index)?;
555 self.update_dodge_refreshed_events(frame, index)?;
556 self.update_goal_events(frame, index)?;
557 self.update_player_stat_events(frame, index)?;
558 self.update_demolishes(frame, index)?;
559
560 let mut current_time = match &target_time {
563 TimeAdvance::Time(t) => *t,
564 TimeAdvance::NextFrame => frame.time,
565 };
566
567 while current_time <= frame.time {
568 target_time = handler.process_frame(self, frame, index, current_time)?;
571 if let TimeAdvance::Time(new_target) = target_time {
577 current_time = new_target;
578 } else {
579 break;
580 }
581 }
582 }
583 handler.finish_replay(self)?;
584 Ok(())
585 }
586
587 pub fn process_all(&mut self, collectors: &mut [&mut dyn Collector]) -> SubtrActorResult<()> {
596 for (index, frame) in self
597 .replay
598 .network_frames
599 .as_ref()
600 .ok_or(SubtrActorError::new(
601 SubtrActorErrorVariant::NoNetworkFrames,
602 ))?
603 .frames
604 .iter()
605 .enumerate()
606 {
607 self.actor_state.process_frame(frame, index)?;
608 self.update_mappings(frame)?;
609 self.update_ball_id(frame)?;
610 self.update_boost_amounts(frame, index)?;
611 self.update_boost_pad_events(frame, index)?;
612 self.update_touch_events(frame, index)?;
613 self.update_dodge_refreshed_events(frame, index)?;
614 self.update_goal_events(frame, index)?;
615 self.update_player_stat_events(frame, index)?;
616 self.update_demolishes(frame, index)?;
617
618 for collector in collectors.iter_mut() {
619 collector.process_frame(self, frame, index, frame.time)?;
620 }
621 }
622 for collector in collectors.iter_mut() {
623 collector.finish_replay(self)?;
624 }
625 Ok(())
626 }
627
628 pub fn reset(&mut self) {
630 self.ball_actor_id = None;
631 self.player_to_car = HashMap::new();
632 self.player_to_team = HashMap::new();
633 self.player_to_actor_id = HashMap::new();
634 self.car_to_player = HashMap::new();
635 self.car_to_boost = HashMap::new();
636 self.car_to_jump = HashMap::new();
637 self.car_to_double_jump = HashMap::new();
638 self.car_to_dodge = HashMap::new();
639 self.actor_state = ActorStateModeler::new();
640 self.boost_pad_events = Vec::new();
641 self.current_frame_boost_pad_events = Vec::new();
642 self.touch_events = Vec::new();
643 self.current_frame_touch_events = Vec::new();
644 self.dodge_refreshed_events = Vec::new();
645 self.current_frame_dodge_refreshed_events = Vec::new();
646 self.dodge_refreshed_counters = HashMap::new();
647 self.goal_events = Vec::new();
648 self.current_frame_goal_events = Vec::new();
649 self.player_stat_events = Vec::new();
650 self.current_frame_player_stat_events = Vec::new();
651 self.player_stat_counters = HashMap::new();
652 self.demolishes = Vec::new();
653 self.known_demolishes = Vec::new();
654 self.demolish_format = None;
655 self.kickoff_phase_active_last_frame = false;
656 }
657}
658
659#[cfg(test)]
660mod tests {
661 use super::ReplayProcessor;
662
663 #[test]
664 fn rigid_body_normalization_factors_split_at_expected_legacy_boundary() {
665 assert_eq!(
666 ReplayProcessor::rigid_body_location_normalization_factor_for_net_version(None),
667 100.0
668 );
669 assert_eq!(
670 ReplayProcessor::rigid_body_velocity_normalization_factor_for_net_version(None),
671 10.0
672 );
673 assert_eq!(
674 ReplayProcessor::rigid_body_location_normalization_factor_for_net_version(Some(2)),
675 100.0
676 );
677 assert_eq!(
678 ReplayProcessor::rigid_body_velocity_normalization_factor_for_net_version(Some(2)),
679 10.0
680 );
681 assert!(ReplayProcessor::uses_legacy_rigid_body_rotation_for_net_version(Some(2)));
682 assert_eq!(
683 ReplayProcessor::rigid_body_location_normalization_factor_for_net_version(Some(5)),
684 1.0
685 );
686 assert_eq!(
687 ReplayProcessor::rigid_body_velocity_normalization_factor_for_net_version(Some(5)),
688 1.0
689 );
690 assert!(ReplayProcessor::uses_legacy_rigid_body_rotation_for_net_version(Some(5)));
691 assert_eq!(
692 ReplayProcessor::rigid_body_location_normalization_factor_for_net_version(Some(10)),
693 1.0
694 );
695 assert_eq!(
696 ReplayProcessor::rigid_body_velocity_normalization_factor_for_net_version(Some(10)),
697 1.0
698 );
699 assert!(!ReplayProcessor::uses_legacy_rigid_body_rotation_for_net_version(Some(7)));
700 assert!(!ReplayProcessor::uses_legacy_rigid_body_rotation_for_net_version(Some(10)));
701 }
702}