Skip to main content

openstranded_common_survival/
survival_params.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5/// Complexity level of the health/survival system.
6///
7/// Mapped from the `healthsystem=` field in `game.inf`.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9pub enum HealthSystem {
10    /// No health system — player cannot die.
11    None = 0,
12    /// Simple health only.
13    Simple = 1,
14    /// Health + hunger.
15    Basic = 2,
16    /// Health + hunger + thirst.
17    Advanced = 3,
18    /// Health + hunger + thirst + exhaustion.
19    Full = 4,
20}
21
22impl HealthSystem {
23    /// Parse a health system value from `.inf` files.
24    #[must_use]
25    pub fn from_inf(n: u32) -> Self {
26        match n {
27            0 => Self::None,
28            1 => Self::Simple,
29            2 => Self::Basic,
30            3 => Self::Advanced,
31            _ => Self::Full,
32        }
33    }
34}
35
36impl Default for HealthSystem {
37    fn default() -> Self {
38        Self::Full
39    }
40}
41
42/// A triple rate affecting health, hunger, and thirst respectively.
43///
44/// Each activity (moving, swimming, jumping, attacking) consumes
45/// health, hunger, and thirst at different rates. This struct holds
46/// one set of rates for a single activity.
47#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
48pub struct ExhaustRate {
49    /// Rate of health consumption.
50    pub health: f32,
51    /// Rate of hunger consumption.
52    pub hunger: f32,
53    /// Rate of thirst consumption.
54    pub thirst: f32,
55}
56
57impl ExhaustRate {
58    /// Parse from a comma-separated triple string e.g. `"0.02,0.02,0.016"`.
59    #[must_use]
60    pub fn from_inf(s: &str) -> Option<Self> {
61        let parts: Vec<&str> = s.split(',').collect();
62        if parts.len() != 3 {
63            return None;
64        }
65        Some(Self {
66            health: parts[0].trim().parse().ok()?,
67            hunger: parts[1].trim().parse().ok()?,
68            thirst: parts[2].trim().parse().ok()?,
69        })
70    }
71}
72
73impl Default for ExhaustRate {
74    fn default() -> Self {
75        Self {
76            health: 0.0,
77            hunger: 0.0,
78            thirst: 0.0,
79        }
80    }
81}
82
83/// Exhaustion rates for all player actions.
84#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
85pub struct ExhaustParams {
86    /// Rate while walking / running.
87    pub move_rate: ExhaustRate,
88    /// Rate while swimming.
89    pub swim_rate: ExhaustRate,
90    /// Rate per jump.
91    pub jump_rate: ExhaustRate,
92    /// Rate per attack.
93    pub attack_rate: ExhaustRate,
94}
95
96impl Default for ExhaustParams {
97    fn default() -> Self {
98        Self {
99            move_rate: ExhaustRate::default(),
100            swim_rate: ExhaustRate::default(),
101            jump_rate: ExhaustRate::default(),
102            attack_rate: ExhaustRate::default(),
103        }
104    }
105}
106
107/// Underwater / diving parameters.
108#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
109pub struct DiveParams {
110    /// Maximum dive time in milliseconds.
111    pub time: u32,
112    /// Damage per tick while underwater beyond max time.
113    pub damage: u32,
114}
115
116impl Default for DiveParams {
117    fn default() -> Self {
118        Self {
119            time: 20000,
120            damage: 10,
121        }
122    }
123}
124
125/// Jump parameters.
126#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
127pub struct JumpParams {
128    /// Jump cooldown in milliseconds.
129    pub time: u32,
130    /// Jump height multiplier.
131    pub factor: f32,
132}
133
134impl Default for JumpParams {
135    fn default() -> Self {
136        Self {
137            time: 450,
138            factor: 1.1,
139        }
140    }
141}
142
143/// All survival-related parameters extracted from `game.inf`.
144///
145/// # `.inf` fields consumed
146///
147/// | Field | Maps to |
148/// |-------|---------|
149/// | `healthsystem` | [`HealthSystem`] |
150/// | `exhaust_move` | [`ExhaustParams::move_rate`] |
151/// | `exhaust_swim` | [`ExhaustParams::swim_rate`] |
152/// | `exhaust_jump` | [`ExhaustParams::jump_rate`] |
153/// | `exhaust_attack` | [`ExhaustParams::attack_rate`] |
154/// | `exhausted_damage` | damage when exhausted (health, hunger, thirst) |
155/// | `dive_time` | [`DiveParams::time`] |
156/// | `dive_damage` | [`DiveParams::damage`] |
157/// | `jumptime` | [`JumpParams::time`] |
158/// | `jumpfactor` | [`JumpParams::factor`] |
159#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
160pub struct SurvivalParams {
161    /// Health system complexity level.
162    #[serde(default)]
163    pub health_system: HealthSystem,
164
165    /// Exhaustion rates for various actions.
166    #[serde(default)]
167    pub exhaust: ExhaustParams,
168
169    /// Damage applied when exhausted — `[health, hunger, thirst]`.
170    #[serde(default)]
171    pub exhausted_damage: [f32; 3],
172
173    /// Diving parameters.
174    #[serde(default)]
175    pub dive: DiveParams,
176
177    /// Jump parameters.
178    #[serde(default)]
179    pub jump: JumpParams,
180}
181
182impl Default for SurvivalParams {
183    fn default() -> Self {
184        Self {
185            health_system: HealthSystem::Full,
186            exhaust: ExhaustParams::default(),
187            exhausted_damage: [5.0, 5.0, 5.0],
188            dive: DiveParams::default(),
189            jump: JumpParams::default(),
190        }
191    }
192}
193
194// ── Parsing helpers ────────────────────────────────────────────────
195
196fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
197    fields.get(key)?.first().map(String::as_str)
198}
199
200fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
201    first_str(fields, key)?.parse().ok()
202}
203
204fn first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
205    first_str(fields, key)?.parse().ok()
206}
207
208/// Parse a triple like `"5,5,5"` into `[5.0, 5.0, 5.0]`.
209fn parse_f32_triple(s: &str) -> Option<[f32; 3]> {
210    let parts: Vec<&str> = s.split(',').collect();
211    if parts.len() != 3 {
212        return None;
213    }
214    Some([
215        parts[0].trim().parse().ok()?,
216        parts[1].trim().parse().ok()?,
217        parts[2].trim().parse().ok()?,
218    ])
219}
220
221impl SurvivalParams {
222    /// Construct `SurvivalParams` from the raw fields of a parsed
223    /// `game.inf` entry.
224    ///
225    /// Only survival-related fields are extracted; other game
226    /// configuration fields are silently ignored.
227    #[must_use]
228    pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
229        let health_system = first_u32(fields, "healthsystem")
230            .map(HealthSystem::from_inf)
231            .unwrap_or_default();
232
233        let exhaust = ExhaustParams {
234            move_rate: first_str(fields, "exhaust_move")
235                .and_then(ExhaustRate::from_inf)
236                .unwrap_or_default(),
237            swim_rate: first_str(fields, "exhaust_swim")
238                .and_then(ExhaustRate::from_inf)
239                .unwrap_or_default(),
240            jump_rate: first_str(fields, "exhaust_jump")
241                .and_then(ExhaustRate::from_inf)
242                .unwrap_or_default(),
243            attack_rate: first_str(fields, "exhaust_attack")
244                .and_then(ExhaustRate::from_inf)
245                .unwrap_or_default(),
246        };
247
248        let exhausted_damage = first_str(fields, "exhausted_damage")
249            .and_then(parse_f32_triple)
250            .unwrap_or([5.0, 5.0, 5.0]);
251
252        let dive = DiveParams {
253            time: first_u32(fields, "dive_time").unwrap_or(20000),
254            damage: first_u32(fields, "dive_damage").unwrap_or(10),
255        };
256
257        let jump = JumpParams {
258            time: first_u32(fields, "jumptime").unwrap_or(450),
259            factor: first_f32(fields, "jumpfactor").unwrap_or(1.1),
260        };
261
262        Some(Self {
263            health_system,
264            exhaust,
265            exhausted_damage,
266            dive,
267            jump,
268        })
269    }
270}
271
272// ── Tests ──────────────────────────────────────────────────────────
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    #[test]
279    fn test_health_system_from_inf() {
280        assert_eq!(HealthSystem::from_inf(0), HealthSystem::None);
281        assert_eq!(HealthSystem::from_inf(1), HealthSystem::Simple);
282        assert_eq!(HealthSystem::from_inf(2), HealthSystem::Basic);
283        assert_eq!(HealthSystem::from_inf(3), HealthSystem::Advanced);
284        assert_eq!(HealthSystem::from_inf(4), HealthSystem::Full);
285        assert_eq!(HealthSystem::from_inf(99), HealthSystem::Full);
286    }
287
288    #[test]
289    fn test_exhaust_rate_from_inf() {
290        let rate = ExhaustRate::from_inf("0.02,0.02,0.016").unwrap();
291        assert!((rate.health - 0.02).abs() < 1e-6);
292        assert!((rate.hunger - 0.02).abs() < 1e-6);
293        assert!((rate.thirst - 0.016).abs() < 1e-6);
294    }
295
296    #[test]
297    fn test_exhaust_rate_invalid() {
298        assert!(ExhaustRate::from_inf("0.02").is_none());
299        assert!(ExhaustRate::from_inf("").is_none());
300    }
301
302    #[test]
303    fn test_exhaust_rate_default() {
304        let rate = ExhaustRate::default();
305        assert!((rate.health - 0.0).abs() < 1e-6);
306        assert!((rate.hunger - 0.0).abs() < 1e-6);
307        assert!((rate.thirst - 0.0).abs() < 1e-6);
308    }
309
310    #[test]
311    fn test_survival_params_from_game_inf() {
312        let mut fields = HashMap::new();
313        fields.insert("healthsystem".into(), vec!["4".into()]);
314        fields.insert("exhaust_move".into(), vec!["0.02,0.02,0.016".into()]);
315        fields.insert("exhaust_swim".into(), vec!["0.06,0.05,0.06".into()]);
316        fields.insert("exhaust_jump".into(), vec!["0.8,0.8,0.8".into()]);
317        fields.insert("exhaust_attack".into(), vec!["0.15,0.15,0.15".into()]);
318        fields.insert("exhausted_damage".into(), vec!["5,5,5".into()]);
319        fields.insert("dive_time".into(), vec!["20000".into()]);
320        fields.insert("dive_damage".into(), vec!["10".into()]);
321        fields.insert("jumptime".into(), vec!["450".into()]);
322        fields.insert("jumpfactor".into(), vec!["1.1".into()]);
323
324        let params = SurvivalParams::from_inf_fields(&fields).unwrap();
325        assert_eq!(params.health_system, HealthSystem::Full);
326        assert!((params.exhaust.move_rate.health - 0.02).abs() < 1e-6);
327        assert!((params.exhaust.swim_rate.thirst - 0.06).abs() < 1e-6);
328        assert!((params.exhaust.jump_rate.hunger - 0.8).abs() < 1e-6);
329        assert!((params.exhaust.attack_rate.health - 0.15).abs() < 1e-6);
330        assert_eq!(params.exhausted_damage, [5.0, 5.0, 5.0]);
331        assert_eq!(params.dive.time, 20000);
332        assert_eq!(params.dive.damage, 10);
333        assert_eq!(params.jump.time, 450);
334        assert!((params.jump.factor - 1.1).abs() < 1e-6);
335    }
336
337    #[test]
338    fn test_survival_params_default() {
339        let params = SurvivalParams::default();
340        assert_eq!(params.health_system, HealthSystem::Full);
341    }
342
343    #[test]
344    fn test_survival_params_empty_fields() {
345        let fields = HashMap::new();
346        let params = SurvivalParams::from_inf_fields(&fields).unwrap();
347        // Should return defaults for everything
348        assert_eq!(params.health_system, HealthSystem::Full);
349    }
350
351    #[test]
352    fn test_parse_f32_triple() {
353        assert_eq!(parse_f32_triple("1,2,3"), Some([1.0, 2.0, 3.0]));
354        assert_eq!(parse_f32_triple(" 1 , 2 , 3 "), Some([1.0, 2.0, 3.0]));
355        assert!(parse_f32_triple("1,2").is_none());
356        assert!(parse_f32_triple("").is_none());
357    }
358
359    #[test]
360    fn test_serde_derives_compile() {
361        let params = SurvivalParams::default();
362        assert_eq!(params.health_system, HealthSystem::Full);
363    }
364}