Skip to main content

openstranded_common_items/
item_def.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5/// Category of an item.
6///
7/// Mapped from the `group=` field in `.inf` files.
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10pub enum ItemGroup {
11    /// Raw materials (wood, stone, ore, …).
12    Material,
13    /// Edible items (meat, fruit, herbs, …).
14    Food,
15    /// Miscellaneous items (bags, quest items, decorations, …).
16    Stuff,
17    /// Tools (hammer, fishing rod, axe, …).
18    Tool,
19    /// Weapons (swords, bows, spears, …).
20    Weapon,
21    /// Ammunition (arrows, bullets, …).
22    Ammo,
23    /// Potions and drinkable liquids.
24    Potion,
25    /// Any other group not covered by the standard categories.
26    #[serde(untagged)]
27    Custom(String),
28}
29
30impl ItemGroup {
31    /// Parse a group string from `.inf` files.
32    #[must_use]
33    pub fn from_inf(s: &str) -> Self {
34        match s.trim() {
35            "material" => Self::Material,
36            "food" => Self::Food,
37            "stuff" => Self::Stuff,
38            "tool" => Self::Tool,
39            "weapon" => Self::Weapon,
40            "ammo" => Self::Ammo,
41            "potion" => Self::Potion,
42            other => Self::Custom(other.to_owned()),
43        }
44    }
45
46    /// Return the canonical string representation.
47    #[must_use]
48    pub fn as_str(&self) -> &str {
49        match self {
50            Self::Material => "material",
51            Self::Food => "food",
52            Self::Stuff => "stuff",
53            Self::Tool => "tool",
54            Self::Weapon => "weapon",
55            Self::Ammo => "ammo",
56            Self::Potion => "potion",
57            Self::Custom(s) => s.as_str(),
58        }
59    }
60}
61
62/// Material type of an item.
63///
64/// Used for interactions (cutting wood, mining stone),
65/// damage types, and crafting filters.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum Material {
69    /// Wood / plant fibre.
70    Wood,
71    /// Stone / rock.
72    Stone,
73    /// Metal / ore.
74    Metal,
75    /// Flesh / meat / organic animal tissue.
76    Flesh,
77    /// Fruit / plant produce.
78    Fruit,
79    /// Leaf / foliage.
80    Leaf,
81    /// Glass / brittle.
82    Glass,
83    /// Dust / powder / grain.
84    Dust,
85    /// Water / liquid.
86    Water,
87    /// Dirt / soil / mud.
88    Dirt,
89    /// Cloth / fabric / wool.
90    Cloth,
91    /// No particular material / unknown.
92    #[serde(rename = "none")]
93    None,
94    /// Any other material not covered by the standard set.
95    #[serde(untagged)]
96    Custom(String),
97}
98
99impl Material {
100    /// Parse a material string from `.inf` files.
101    #[must_use]
102    pub fn from_inf(s: &str) -> Self {
103        match s.trim() {
104            "wood" => Self::Wood,
105            "stone" => Self::Stone,
106            "metal" => Self::Metal,
107            "flesh" => Self::Flesh,
108            "fruit" => Self::Fruit,
109            "leaf" => Self::Leaf,
110            "glass" => Self::Glass,
111            "dust" => Self::Dust,
112            "water" => Self::Water,
113            "dirt" => Self::Dirt,
114            "cloth" | "wool" => Self::Cloth,
115            "none" => Self::None,
116            other => Self::Custom(other.to_owned()),
117        }
118    }
119
120    /// Return the canonical string representation.
121    #[must_use]
122    pub fn as_str(&self) -> &str {
123        match self {
124            Self::Wood => "wood",
125            Self::Stone => "stone",
126            Self::Metal => "metal",
127            Self::Flesh => "flesh",
128            Self::Fruit => "fruit",
129            Self::Leaf => "leaf",
130            Self::Glass => "glass",
131            Self::Dust => "dust",
132            Self::Water => "water",
133            Self::Dirt => "dirt",
134            Self::Cloth => "cloth",
135            Self::None => "none",
136            Self::Custom(s) => s.as_str(),
137        }
138    }
139}
140
141// ── Defaults ───────────────────────────────────────────────────────
142
143impl Default for ItemGroup {
144    fn default() -> Self {
145        Self::Material
146    }
147}
148
149impl Default for Material {
150    fn default() -> Self {
151        Self::None
152    }
153}
154
155impl std::fmt::Display for ItemGroup {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.write_str(self.as_str())
158    }
159}
160
161impl std::fmt::Display for Material {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        f.write_str(self.as_str())
164    }
165}
166
167/// Full definition of a single item type.
168///
169/// Represents one entry from an item `.inf` file, serialisable to/from
170/// RON, JSON, or any serde-compatible format.
171///
172/// Most fields are optional and default to `None` — only the identity
173/// fields (`id`, `name`, `icon`) are required for construction via
174/// [`from_inf_fields`](ItemDef::from_inf_fields).
175///
176/// # Construction from `.inf` fields
177///
178/// ```rust
179/// use std::collections::HashMap;
180/// use openstranded_common_items::ItemDef;
181///
182/// let mut fields = HashMap::new();
183/// fields.insert("id".into(), vec!["2".into()]);
184/// fields.insert("name".into(), vec!["small Crystal".into()]);
185/// fields.insert("icon".into(), vec!["gfx\\crystal01.bmp".into()]);
186/// fields.insert("group".into(), vec!["material".into()]);
187/// fields.insert("mat".into(), vec!["stone".into()]);
188/// fields.insert("weight".into(), vec!["200".into()]);
189///
190/// let item = ItemDef::from_inf_fields(&fields).unwrap();
191/// assert_eq!(item.id, 2);
192/// ```
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
194pub struct ItemDef {
195    // ── Identity ────────────────────────────────────────────────────
196    /// Unique numeric identifier.
197    pub id: u32,
198
199    /// Display name.
200    pub name: String,
201
202    /// Category group.
203    #[serde(default)]
204    pub group: ItemGroup,
205
206    /// Path to the icon texture (`.png` after conversion).
207    pub icon: String,
208
209    /// Path to the 3D model (`.glb` after conversion).
210    #[serde(default)]
211    pub model: Option<String>,
212
213    /// Base material type.
214    #[serde(default)]
215    pub material: Material,
216
217    /// Weight in grams.
218    #[serde(default)]
219    pub weight: u32,
220
221    /// Short description / info text.
222    #[serde(default)]
223    pub description: Option<String>,
224
225    // ── Visual properties ──────────────────────────────────────────
226    /// RGB colour tint.
227    #[serde(default)]
228    pub color: Option<[u8; 3]>,
229
230    /// Uniform scale factor.
231    #[serde(default)]
232    pub scale: Option<f32>,
233
234    /// Blitz3D FX flags.
235    #[serde(default)]
236    pub fx: Option<u32>,
237
238    /// Alpha transparency.
239    #[serde(default)]
240    pub alpha: Option<f32>,
241
242    /// Shininess / specular intensity.
243    #[serde(default)]
244    pub shininess: Option<f32>,
245
246    /// Blend mode.
247    #[serde(default)]
248    pub blend: Option<u32>,
249
250    // ── Gameplay properties ─────────────────────────────────────────
251    /// Item durability / hit points.
252    #[serde(default)]
253    pub durability: Option<f32>,
254
255    /// Health change when consumed.
256    #[serde(default)]
257    pub health_change: Option<f32>,
258
259    /// Behaviour type string (e.g. `"throw"`, `"blade"`, `"ammo:51"`).
260    #[serde(default)]
261    pub behaviour: Option<String>,
262
263    /// Damage value (number or formula string).
264    #[serde(default)]
265    pub damage: Option<String>,
266
267    /// Projectile speed or weapon range.
268    #[serde(default)]
269    pub speed: Option<f32>,
270
271    /// Air drag for projectiles.
272    #[serde(default)]
273    pub drag: Option<f32>,
274
275    /// Fire rate / use cooldown in milliseconds.
276    #[serde(default)]
277    pub rate: Option<u32>,
278
279    /// Weapon state effect (e.g. `"intoxication"`).
280    #[serde(default)]
281    pub weapon_state: Option<String>,
282
283    // ── Physics / collision ─────────────────────────────────────────
284    /// Pick radius for collision.
285    #[serde(default)]
286    pub radius: Option<f32>,
287
288    /// Collision type index.
289    #[serde(default)]
290    pub collision: Option<u32>,
291}
292
293// ── .inf field parsing helpers ─────────────────────────────────────
294
295/// Parse a colour string `"R,G,B"` into `[R, G, B]`.
296fn parse_color(s: &str) -> Option<[u8; 3]> {
297    let parts: Vec<&str> = s.split(',').collect();
298    if parts.len() != 3 {
299        return None;
300    }
301    Some([
302        parts[0].trim().parse().ok()?,
303        parts[1].trim().parse().ok()?,
304        parts[2].trim().parse().ok()?,
305    ])
306}
307
308/// Get the first value of a field as `&str`, if present.
309fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
310    fields.get(key)?.first().map(String::as_str)
311}
312
313/// Get the first value of a field parsed as `u32`.
314fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
315    first_str(fields, key)?.parse().ok()
316}
317
318/// Get the first value of a field parsed as `f32`.
319fn first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
320    first_str(fields, key)?.parse().ok()
321}
322
323/// Get the first value of a field as an owned `String`.
324fn first_string(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
325    first_str(fields, key).map(ToOwned::to_owned)
326}
327
328impl ItemDef {
329    /// Construct an `ItemDef` from the raw fields of a parsed `.inf` entry.
330    ///
331    /// This is the main entry point for WASM plugins that receive
332    /// registry data in the `InfEntry` format and want to convert it
333    /// to a strongly-typed `ItemDef`.
334    ///
335    /// Unknown or unparseable fields are silently ignored; missing
336    /// required fields (`id`, `name`, `icon`) return `None`.
337    #[must_use]
338    pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
339        let id = first_u32(fields, "id")?;
340        let name = first_string(fields, "name")?;
341        let icon = first_string(fields, "icon")?;
342
343        let group = first_str(fields, "group")
344            .map(ItemGroup::from_inf)
345            .unwrap_or_default();
346
347        let model = first_string(fields, "model");
348
349        let material = first_str(fields, "mat")
350            .map(Material::from_inf)
351            .unwrap_or_default();
352
353        let weight = first_u32(fields, "weight")
354            .or_else(|| first_u32(fields, "w"))
355            .unwrap_or(0);
356
357        let description = first_string(fields, "info");
358
359        // Visuals
360        let color = first_str(fields, "color").and_then(parse_color);
361        let scale = first_f32(fields, "scale");
362        let fx = first_u32(fields, "fx");
363        let alpha = first_f32(fields, "alpha");
364        let shininess = first_f32(fields, "shine");
365        let blend = first_u32(fields, "blend");
366
367        // Gameplay
368        let durability = first_f32(fields, "health");
369        let health_change = first_f32(fields, "healthchange");
370        let behaviour = first_string(fields, "behaviour");
371        let damage = first_string(fields, "damage");
372        let speed = first_f32(fields, "speed").or_else(|| first_f32(fields, "range"));
373        let drag = first_f32(fields, "drag");
374        let rate = first_u32(fields, "rate");
375        let weapon_state = first_string(fields, "weaponstate");
376
377        // Physics
378        let radius = first_f32(fields, "radius");
379        let collision = first_u32(fields, "col");
380
381        Some(Self {
382            id,
383            name,
384            group,
385            icon,
386            model,
387            material,
388            weight,
389            description,
390            color,
391            scale,
392            fx,
393            alpha,
394            shininess,
395            blend,
396            durability,
397            health_change,
398            behaviour,
399            damage,
400            speed,
401            drag,
402            rate,
403            weapon_state,
404            radius,
405            collision,
406        })
407    }
408}
409
410// ── Tests ──────────────────────────────────────────────────────────
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn test_item_group_from_inf() {
418        assert_eq!(ItemGroup::from_inf("material"), ItemGroup::Material);
419        assert_eq!(ItemGroup::from_inf("food"), ItemGroup::Food);
420        assert_eq!(ItemGroup::from_inf("custom"), ItemGroup::Custom("custom".into()));
421    }
422
423    #[test]
424    fn test_item_group_as_str() {
425        assert_eq!(ItemGroup::Material.as_str(), "material");
426        assert_eq!(ItemGroup::Custom("quest".into()).as_str(), "quest");
427    }
428
429    #[test]
430    fn test_material_from_inf() {
431        assert_eq!(Material::from_inf("wood"), Material::Wood);
432        assert_eq!(Material::from_inf("stone"), Material::Stone);
433        assert_eq!(Material::from_inf("wool"), Material::Cloth);
434        assert_eq!(Material::from_inf("none"), Material::None);
435        assert_eq!(Material::from_inf("plastic"), Material::Custom("plastic".into()));
436    }
437
438    #[test]
439    fn test_material_as_str() {
440        assert_eq!(Material::Wood.as_str(), "wood");
441        assert_eq!(Material::Custom("rubber".into()).as_str(), "rubber");
442    }
443
444    #[test]
445    fn test_from_inf_fields_minimal() {
446        let mut fields = HashMap::new();
447        fields.insert("id".into(), vec!["1".into()]);
448        fields.insert("name".into(), vec!["Bag".into()]);
449        fields.insert("icon".into(), vec!["gfx\\bag.bmp".into()]);
450
451        let item = ItemDef::from_inf_fields(&fields).unwrap();
452        assert_eq!(item.id, 1);
453        assert_eq!(item.name, "Bag");
454        assert_eq!(item.group, ItemGroup::Material);
455        assert_eq!(item.material, Material::None);
456        assert_eq!(item.weight, 0);
457        assert!(item.model.is_none());
458    }
459
460    #[test]
461    fn test_from_inf_fields_full() {
462        let mut fields = HashMap::new();
463        fields.insert("id".into(), vec!["2".into()]);
464        fields.insert("name".into(), vec!["small Crystal".into()]);
465        fields.insert("group".into(), vec!["material".into()]);
466        fields.insert("icon".into(), vec!["gfx\\crystal01.bmp".into()]);
467        fields.insert("model".into(), vec!["gfx\\crystal01.b3d".into()]);
468        fields.insert("color".into(), vec!["0,255,0".into()]);
469        fields.insert("shine".into(), vec!["1".into()]);
470        fields.insert("blend".into(), vec!["3".into()]);
471        fields.insert("scale".into(), vec!["2".into()]);
472        fields.insert("mat".into(), vec!["stone".into()]);
473        fields.insert("weight".into(), vec!["200".into()]);
474        fields.insert("info".into(), vec!["a small crystal".into()]);
475        fields.insert("healthchange".into(), vec!["0".into()]);
476
477        let item = ItemDef::from_inf_fields(&fields).unwrap();
478        assert_eq!(item.id, 2);
479        assert_eq!(item.name, "small Crystal");
480        assert_eq!(item.group, ItemGroup::Material);
481        assert_eq!(item.icon, "gfx\\crystal01.bmp");
482        assert_eq!(item.model.as_deref(), Some("gfx\\crystal01.b3d"));
483        assert_eq!(item.color, Some([0, 255, 0]));
484        assert_eq!(item.shininess, Some(1.0));
485        assert_eq!(item.blend, Some(3));
486        assert_eq!(item.scale, Some(2.0));
487        assert_eq!(item.material, Material::Stone);
488        assert_eq!(item.weight, 200);
489        assert_eq!(item.description.as_deref(), Some("a small crystal"));
490        assert_eq!(item.health_change, Some(0.0));
491    }
492
493    #[test]
494    fn test_from_inf_fields_missing_id() {
495        let mut fields = HashMap::new();
496        fields.insert("name".into(), vec!["No ID".into()]);
497        fields.insert("icon".into(), vec!["icon.bmp".into()]);
498        assert!(ItemDef::from_inf_fields(&fields).is_none());
499    }
500
501    #[test]
502    fn test_parse_color() {
503        assert_eq!(parse_color("255,0,128"), Some([255, 0, 128]));
504        assert_eq!(parse_color("0,0,0"), Some([0, 0, 0]));
505        assert_eq!(parse_color("invalid"), None);
506        assert_eq!(parse_color("1,2"), None);
507    }
508
509    #[test]
510    fn test_from_inf_weapon_fields() {
511        let mut fields = HashMap::new();
512        fields.insert("id".into(), vec!["28".into()]);
513        fields.insert("name".into(), vec!["Machete".into()]);
514        fields.insert("group".into(), vec!["weapon".into()]);
515        fields.insert("icon".into(), vec!["gfx\\matchet.bmp".into()]);
516        fields.insert("model".into(), vec!["gfx\\matchet.b3d".into()]);
517        fields.insert("scale".into(), vec!["0.2".into()]);
518        fields.insert("behaviour".into(), vec!["blade".into()]);
519        fields.insert("mat".into(), vec!["metal".into()]);
520        fields.insert("weight".into(), vec!["1000".into()]);
521        fields.insert("damage".into(), vec!["9".into()]);
522
523        let item = ItemDef::from_inf_fields(&fields).unwrap();
524        assert_eq!(item.id, 28);
525        assert_eq!(item.group, ItemGroup::Weapon);
526        assert_eq!(item.behaviour.as_deref(), Some("blade"));
527        assert_eq!(item.damage.as_deref(), Some("9"));
528        assert_eq!(item.material, Material::Metal);
529    }
530
531    #[test]
532    fn test_display() {
533        assert_eq!(ItemGroup::Tool.to_string(), "tool");
534        assert_eq!(Material::Flesh.to_string(), "flesh");
535    }
536
537    /// Verify that ItemDef derives Serialize + Deserialize by running
538    /// them through a serde_json-simulated buffer.
539    /// This only compiles if both derives are well-formed.
540    #[test]
541    fn test_serde_derives_compile() {
542        // The derives themselves are checked at compile time.
543        // This test ensures the struct is constructible and the
544        // serde impls don't panic on the default values.
545        let _ = ItemDef {
546            id: 1,
547            name: "test".into(),
548            group: ItemGroup::Material,
549            icon: "test.png".into(),
550            model: None,
551            material: Material::None,
552            weight: 0,
553            description: None,
554            color: None,
555            scale: None,
556            fx: None,
557            alpha: None,
558            shininess: None,
559            blend: None,
560            durability: None,
561            health_change: None,
562            behaviour: None,
563            damage: None,
564            speed: None,
565            drag: None,
566            rate: None,
567            weapon_state: None,
568            radius: None,
569            collision: None,
570        };
571    }
572}