format.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. use std::collections::HashSet;
  2. use std::path::{Path, PathBuf};
  3. use serde::{Deserialize, Serialize};
  4. use crate::net::handshake::HandshakeMapSource;
  5. use crate::net::protocol::{
  6. NetCombatFx, NetDestructionEvent, NetPlayerRoster, NetSoldierState, NetSoundFx, NetTracer,
  7. NetVehicleState,
  8. };
  9. use crate::replay::cinematic::CinematicTimeline;
  10. use crate::sim::session::PlayerId;
  11. use crate::world::{Faction, VehicleKind};
  12. pub const REPLAY_SCHEMA_VERSION: u32 = 1;
  13. pub const REPLAYS_DIR: &str = "replays";
  14. #[derive(Clone, Debug, Serialize, Deserialize)]
  15. pub struct ReplayWeatherSnapshot {
  16. pub sun_elevation_deg: f32,
  17. pub sun_azimuth_deg: f32,
  18. pub cloud_coverage: f32,
  19. pub cloud_seed_offset: [f32; 2],
  20. pub cloud_seed_angle: f32,
  21. pub wetness: f32,
  22. }
  23. impl Default for ReplayWeatherSnapshot {
  24. fn default() -> Self {
  25. Self {
  26. sun_elevation_deg: 24.0,
  27. sun_azimuth_deg: 218.0,
  28. cloud_coverage: 0.54,
  29. cloud_seed_offset: [137.4, -84.2],
  30. cloud_seed_angle: 0.63,
  31. wetness: 0.78,
  32. }
  33. }
  34. }
  35. #[derive(Clone, Debug, Serialize, Deserialize)]
  36. pub struct ReplayHeader {
  37. pub schema_version: u32,
  38. pub title: String,
  39. pub recorded_unix_secs: u64,
  40. pub map_label: String,
  41. pub map_source: HandshakeMapSource,
  42. pub sample_hz: f32,
  43. pub duration_secs: f32,
  44. pub server_name: Option<String>,
  45. pub is_multiplayer: bool,
  46. pub weather: ReplayWeatherSnapshot,
  47. }
  48. impl ReplayHeader {
  49. /// Recovers a custom map blueprint by label/id when an older replay was recorded
  50. /// with a fallback `ClassicFoothills` header.
  51. pub fn resolve_map_source(
  52. &self,
  53. mods: &crate::modding::registry::ModRegistry,
  54. ) -> HandshakeMapSource {
  55. if matches!(self.map_source, HandshakeMapSource::ClassicFoothills) {
  56. let lbl = self.map_label.trim();
  57. if !lbl.is_empty()
  58. && !lbl.eq_ignore_ascii_case("Foothill Valley")
  59. && !lbl.eq_ignore_ascii_case("Classic: Foothill River Town")
  60. {
  61. if let Some(bp) = mods
  62. .maps
  63. .iter()
  64. .find(|m| m.id.eq_ignore_ascii_case(lbl) || m.name.eq_ignore_ascii_case(lbl))
  65. {
  66. return HandshakeMapSource::CustomMap(bp.clone());
  67. }
  68. }
  69. }
  70. self.map_source.clone()
  71. }
  72. }
  73. #[derive(Clone, Debug, Serialize, Deserialize)]
  74. pub enum ReplayEventKind {
  75. Kill {
  76. killer_name: String,
  77. victim_name: String,
  78. victim_soldier_id: usize,
  79. weapon: String,
  80. headshot: bool,
  81. distance_m: f32,
  82. },
  83. Explosion {
  84. radius: f32,
  85. },
  86. Destruction {
  87. radius: f32,
  88. seed: u64,
  89. },
  90. ObjectiveCapture {
  91. name: String,
  92. faction: Faction,
  93. },
  94. RadioLog {
  95. sender: String,
  96. freq_khz: Option<u32>,
  97. text: String,
  98. },
  99. AdminBookmark {
  100. label: String,
  101. note: String,
  102. },
  103. }
  104. impl ReplayEventKind {
  105. pub fn short_tag(&self) -> &'static str {
  106. match self {
  107. Self::Kill { .. } => "KILL",
  108. Self::Explosion { .. } => "BLAST",
  109. Self::Destruction { .. } => "DESTRUCT",
  110. Self::ObjectiveCapture { .. } => "CAP",
  111. Self::RadioLog { .. } => "RADIO",
  112. Self::AdminBookmark { .. } => "BOOKMARK",
  113. }
  114. }
  115. pub fn summary(&self) -> String {
  116. match self {
  117. Self::Kill {
  118. killer_name,
  119. victim_name,
  120. weapon,
  121. headshot,
  122. distance_m,
  123. ..
  124. } => {
  125. let hs = if *headshot { " [HS]" } else { "" };
  126. format!("{killer_name} -> {victim_name} ({weapon}{hs}, {distance_m:.0}m)")
  127. }
  128. Self::Explosion { radius } => format!("Explosion (r={radius:.1}m)"),
  129. Self::Destruction { radius, .. } => format!("CSG Breach (r={radius:.1}m)"),
  130. Self::ObjectiveCapture { name, faction } => format!("{name} captured by {faction:?}"),
  131. Self::RadioLog { sender, freq_khz, text } => {
  132. if let Some(f) = freq_khz {
  133. format!("[{:.3}] {sender}: {text}", *f as f32 / 1000.0)
  134. } else {
  135. format!("{sender}: {text}")
  136. }
  137. }
  138. Self::AdminBookmark { label, note } => {
  139. if note.is_empty() {
  140. format!("Bookmark: {label}")
  141. } else {
  142. format!("{label} — {note}")
  143. }
  144. }
  145. }
  146. }
  147. }
  148. #[derive(Clone, Debug, Serialize, Deserialize)]
  149. pub struct ReplayEvent {
  150. pub time_secs: f32,
  151. pub pos: [f32; 3],
  152. pub kind: ReplayEventKind,
  153. }
  154. #[derive(Clone, Debug, Default, Serialize, Deserialize)]
  155. pub struct ReplayFrame {
  156. pub time_secs: f32,
  157. pub soldiers: Vec<NetSoldierState>,
  158. pub vehicles: Vec<NetVehicleState>,
  159. pub tracers: Vec<NetTracer>,
  160. pub fx_events: Vec<NetCombatFx>,
  161. pub sounds: Vec<NetSoundFx>,
  162. pub roster: Vec<NetPlayerRoster>,
  163. pub player_soldier_map: Vec<(PlayerId, String, usize)>,
  164. }
  165. #[derive(Clone, Debug, Serialize, Deserialize)]
  166. pub struct ReplayVehicleDesc {
  167. pub id: usize,
  168. pub name: String,
  169. pub kind: VehicleKind,
  170. pub faction: Faction,
  171. #[serde(default)]
  172. pub custom_mod_id: Option<String>,
  173. }
  174. #[derive(Clone, Debug, Serialize, Deserialize)]
  175. pub struct ReplayFile {
  176. pub header: ReplayHeader,
  177. pub frames: Vec<ReplayFrame>,
  178. pub destruction_events: Vec<(f32, NetDestructionEvent)>,
  179. pub events: Vec<ReplayEvent>,
  180. pub cinematic: CinematicTimeline,
  181. #[serde(default)]
  182. pub vehicle_catalog: Vec<ReplayVehicleDesc>,
  183. }
  184. impl ReplayFile {
  185. pub fn save(&self, path: &Path) -> Result<(), String> {
  186. if let Some(parent) = path.parent() {
  187. if !parent.as_os_str().is_empty() {
  188. std::fs::create_dir_all(parent)
  189. .map_err(|e| format!("Failed to create dir {}: {e}", parent.display()))?;
  190. }
  191. }
  192. let json = serde_json::to_string(self)
  193. .map_err(|e| format!("Failed to serialize replay: {e}"))?;
  194. std::fs::write(path, json)
  195. .map_err(|e| format!("Failed to write {}: {e}", path.display()))
  196. }
  197. pub fn load(path: &Path) -> Result<Self, String> {
  198. let raw = std::fs::read_to_string(path)
  199. .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
  200. let mut replay: Self = serde_json::from_str(&raw)
  201. .map_err(|e| format!("Invalid replay {}: {e}", path.display()))?;
  202. if replay.header.schema_version > REPLAY_SCHEMA_VERSION {
  203. return Err(format!(
  204. "Unsupported replay schema v{} (engine supports <= v{})",
  205. replay.header.schema_version, REPLAY_SCHEMA_VERSION
  206. ));
  207. }
  208. replay.sanitize_and_deduplicate();
  209. Ok(replay)
  210. }
  211. /// Removes duplicate craters/events caused by repeated per-tick emission in older recordings.
  212. pub fn sanitize_and_deduplicate(&mut self) {
  213. let mut seen_destr: HashSet<(i32, i32, i32, u32, u64)> = HashSet::new();
  214. self.destruction_events.retain(|(_, ev)| {
  215. let key = (
  216. (ev.pos.x * 20.0).round() as i32,
  217. (ev.pos.y * 20.0).round() as i32,
  218. (ev.pos.z * 20.0).round() as i32,
  219. (ev.radius * 100.0).round() as u32,
  220. ev.seed,
  221. );
  222. seen_destr.insert(key)
  223. });
  224. let mut seen_ev_destr: HashSet<(i32, i32, i32, u32, u64)> = HashSet::new();
  225. let mut seen_ev_exp: HashSet<(i32, i32, i32, i32, u32)> = HashSet::new();
  226. self.events.retain(|ev| match ev.kind {
  227. ReplayEventKind::Destruction { radius, seed } => {
  228. let key = (
  229. (ev.pos[0] * 20.0).round() as i32,
  230. (ev.pos[1] * 20.0).round() as i32,
  231. (ev.pos[2] * 20.0).round() as i32,
  232. (radius * 100.0).round() as u32,
  233. seed,
  234. );
  235. seen_ev_destr.insert(key)
  236. }
  237. ReplayEventKind::Explosion { radius } => {
  238. let key = (
  239. (ev.time_secs * 10.0).round() as i32,
  240. (ev.pos[0] * 4.0).round() as i32,
  241. (ev.pos[1] * 4.0).round() as i32,
  242. (ev.pos[2] * 4.0).round() as i32,
  243. (radius * 10.0).round() as u32,
  244. );
  245. seen_ev_exp.insert(key)
  246. }
  247. _ => true,
  248. });
  249. }
  250. pub fn kill_count(&self) -> usize {
  251. self.events
  252. .iter()
  253. .filter(|e| matches!(e.kind, ReplayEventKind::Kill { .. }))
  254. .count()
  255. }
  256. pub fn bookmark_count(&self) -> usize {
  257. self.events
  258. .iter()
  259. .filter(|e| matches!(e.kind, ReplayEventKind::AdminBookmark { .. }))
  260. .count()
  261. }
  262. }
  263. #[derive(Clone, Debug)]
  264. pub struct ReplayCatalogEntry {
  265. pub path: PathBuf,
  266. pub file_name: String,
  267. pub title: String,
  268. pub map_label: String,
  269. pub duration_secs: f32,
  270. pub recorded_unix_secs: u64,
  271. pub kill_count: usize,
  272. pub bookmark_count: usize,
  273. pub file_bytes: u64,
  274. pub is_multiplayer: bool,
  275. }
  276. pub fn default_replay_filename(title: &str, unix_secs: u64) -> String {
  277. let clean: String = title
  278. .chars()
  279. .map(|c| {
  280. if c.is_ascii_alphanumeric() {
  281. c.to_ascii_lowercase()
  282. } else {
  283. '_'
  284. }
  285. })
  286. .collect();
  287. let trimmed = clean.trim_matches('_');
  288. let slug = if trimmed.is_empty() { "replay" } else { trimmed };
  289. format!("{slug}_{unix_secs}.cwrep.json")
  290. }
  291. pub fn list_replay_files(dir: &Path) -> Vec<ReplayCatalogEntry> {
  292. let Ok(rd) = std::fs::read_dir(dir) else {
  293. return Vec::new();
  294. };
  295. let mut entries = Vec::new();
  296. for item in rd.flatten() {
  297. let path = item.path();
  298. let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
  299. continue;
  300. };
  301. if !name.ends_with(".cwrep.json") {
  302. continue;
  303. }
  304. let file_bytes = std::fs::metadata(&path).map_or(0, |m| m.len());
  305. if let Ok(rep) = ReplayFile::load(&path) {
  306. entries.push(ReplayCatalogEntry {
  307. path: path.clone(),
  308. file_name: name.to_string(),
  309. title: rep.header.title.clone(),
  310. map_label: rep.header.map_label.clone(),
  311. duration_secs: rep.header.duration_secs,
  312. recorded_unix_secs: rep.header.recorded_unix_secs,
  313. kill_count: rep.kill_count(),
  314. bookmark_count: rep.bookmark_count(),
  315. file_bytes,
  316. is_multiplayer: rep.header.is_multiplayer,
  317. });
  318. }
  319. }
  320. entries.sort_by(|a, b| b.recorded_unix_secs.cmp(&a.recorded_unix_secs));
  321. entries
  322. }