1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
16pub struct AnimFrame {
17 pub start: u32,
19 pub end: u32,
21 pub speed: f32,
23}
24
25impl AnimFrame {
26 #[must_use]
28 pub fn from_inf(s: &str) -> Option<Self> {
29 let parts: Vec<&str> = s.split(',').collect();
30 if parts.len() != 3 {
31 return None;
32 }
33 Some(Self {
34 start: parts[0].trim().parse().ok()?,
35 end: parts[1].trim().parse().ok()?,
36 speed: parts[2].trim().parse().ok()?,
37 })
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct UnitAnimations {
44 pub idle1: Option<AnimFrame>,
46 pub idle2: Option<AnimFrame>,
48 pub idle3: Option<AnimFrame>,
50 pub move_: Option<AnimFrame>,
52 pub attack: Option<AnimFrame>,
54 pub use_: Option<AnimFrame>,
56 pub die: Option<AnimFrame>,
58 pub special: Option<AnimFrame>,
60}
61
62impl Default for UnitAnimations {
63 fn default() -> Self {
64 Self {
65 idle1: None,
66 idle2: None,
67 idle3: None,
68 move_: None,
69 attack: None,
70 use_: None,
71 die: None,
72 special: None,
73 }
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
88pub struct LootEntry {
89 pub item_id: u32,
91 pub max_count: u32,
93}
94
95impl LootEntry {
96 #[must_use]
98 pub fn from_inf(s: &str) -> Self {
99 let parts: Vec<&str> = s.split(',').collect();
100 let item_id = parts.first().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
101 let max_count = parts
102 .get(1)
103 .and_then(|p| p.trim().parse().ok())
104 .unwrap_or(1);
105 let max_count = if max_count <= 1 { 1 } else { max_count };
106 Self { item_id, max_count }
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
114pub struct VehicleParams {
115 pub acceleration: f32,
117 pub friction: f32,
119 pub steering: u32,
121 pub max_depth: u32,
123 pub fly_speed: f32,
125}
126
127impl Default for VehicleParams {
128 fn default() -> Self {
129 Self {
130 acceleration: 0.03,
131 friction: 0.04,
132 steering: 2,
133 max_depth: 3,
134 fly_speed: 3.0,
135 }
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub struct UnitDef {
192 pub id: u32,
195
196 pub name: String,
198
199 #[serde(default)]
201 pub group: String,
202
203 #[serde(default)]
206 pub icon: Option<String>,
207
208 #[serde(default)]
210 pub model: Option<String>,
211
212 #[serde(default = "default_scale")]
214 pub scale: f32,
215
216 #[serde(default)]
218 pub fx: Option<u32>,
219
220 #[serde(default)]
222 pub color: Option<[u8; 3]>,
223
224 #[serde(default = "default_alpha")]
226 pub alpha: f32,
227
228 #[serde(default)]
230 pub shininess: Option<f32>,
231
232 #[serde(default = "default_autofade")]
234 pub auto_fade: u32,
235
236 #[serde(default = "default_col")]
239 pub collision_mode: u32,
240
241 #[serde(default = "default_col_radius")]
243 pub collision_x_radius: f32,
244
245 #[serde(default = "default_col_radius")]
247 pub collision_y_radius: f32,
248
249 #[serde(default = "default_mat")]
252 pub material: String,
253
254 #[serde(default = "default_unit_health")]
256 pub health: f32,
257
258 #[serde(default)]
260 pub health_change: Option<f32>,
261
262 #[serde(default = "default_damage")]
264 pub damage: f32,
265
266 #[serde(default = "default_speed")]
268 pub speed: f32,
269
270 #[serde(default = "default_turn_speed")]
272 pub turn_speed: f32,
273
274 #[serde(default)]
276 pub eye_height: f32,
277
278 #[serde(default = "default_store")]
280 pub store: f32,
281
282 #[serde(default = "default_max_weight")]
284 pub max_weight: u32,
285
286 #[serde(default)]
289 pub behaviour: Option<String>,
290
291 #[serde(default = "default_range")]
293 pub perception_range: u32,
294
295 #[serde(default = "default_attack_range")]
297 pub attack_range: u32,
298
299 #[serde(default)]
301 pub territory: u32,
302
303 #[serde(default)]
305 pub search_ratio: f32,
306
307 #[serde(default)]
310 pub loot: Vec<LootEntry>,
311
312 #[serde(default)]
315 pub sfx: Option<String>,
316
317 #[serde(default)]
320 pub state: UnitState,
321
322 #[serde(default)]
324 pub align: u32,
325
326 #[serde(default = "default_ride_offset")]
329 pub ride_offset: f32,
330
331 #[serde(default)]
333 pub vehicle: Option<VehicleParams>,
334
335 #[serde(default)]
338 pub animations: UnitAnimations,
339
340 #[serde(default)]
342 pub loop_move_anim: bool,
343
344 #[serde(default)]
347 pub script: Option<String>,
348
349 #[serde(default)]
351 pub description: Option<String>,
352
353 #[serde(default = "default_true")]
355 pub in_editor: bool,
356}
357
358#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
362#[serde(rename_all = "snake_case")]
363pub enum UnitState {
364 Random,
366 Fixed(f32, f32, f32),
368}
369
370impl Default for UnitState {
371 fn default() -> Self {
372 Self::Random
373 }
374}
375
376const fn default_scale() -> f32 {
379 1.0
380}
381
382const fn default_alpha() -> f32 {
383 1.0
384}
385
386const fn default_autofade() -> u32 {
387 500
388}
389
390const fn default_col() -> u32 {
391 1
392}
393
394const fn default_col_radius() -> f32 {
395 1.0
396}
397
398fn default_mat() -> String {
399 "flesh".to_owned()
400}
401
402const fn default_unit_health() -> f32 {
403 5.0
404}
405
406const fn default_damage() -> f32 {
407 1.0
408}
409
410const fn default_speed() -> f32 {
411 2.0
412}
413
414const fn default_turn_speed() -> f32 {
415 2.0
416}
417
418const fn default_store() -> f32 {
419 100.0
420}
421
422const fn default_max_weight() -> u32 {
423 100000
424}
425
426const fn default_range() -> u32 {
427 300
428}
429
430const fn default_attack_range() -> u32 {
431 50
432}
433
434const fn default_ride_offset() -> f32 {
435 30.0
436}
437
438const fn default_true() -> bool {
439 true
440}
441
442fn first_str<'a>(fields: &'a HashMap<String, Vec<String>>, key: &str) -> Option<&'a str> {
445 fields.get(key)?.first().map(String::as_str)
446}
447
448fn first_string(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<String> {
449 first_str(fields, key).map(ToOwned::to_owned)
450}
451
452fn first_u32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<u32> {
453 first_str(fields, key)?.parse().ok()
454}
455
456fn first_f32(fields: &HashMap<String, Vec<String>>, key: &str) -> Option<f32> {
457 first_str(fields, key)?.parse().ok()
458}
459
460fn parse_color(s: &str) -> Option<[u8; 3]> {
461 let parts: Vec<&str> = s.split(',').collect();
462 if parts.len() != 3 {
463 return None;
464 }
465 Some([
466 parts[0].trim().parse().ok()?,
467 parts[1].trim().parse().ok()?,
468 parts[2].trim().parse().ok()?,
469 ])
470}
471
472fn parse_loot(fields: &HashMap<String, Vec<String>>) -> Vec<LootEntry> {
473 fields
474 .get("loot")
475 .map(|vals| vals.iter().map(|v| LootEntry::from_inf(v)).collect())
476 .unwrap_or_default()
477}
478
479impl UnitDef {
480 #[must_use]
484 pub fn from_inf_fields(fields: &HashMap<String, Vec<String>>) -> Option<Self> {
485 let id = first_u32(fields, "id")?;
486 let name = first_string(fields, "name")?;
487
488 let group = first_string(fields, "group").unwrap_or_default();
489 let icon = first_string(fields, "icon");
490 let model = first_string(fields, "model");
491 let behaviour = first_string(fields, "behaviour");
492
493 let scale = first_f32(fields, "scale").unwrap_or(1.0);
495 let fx = first_u32(fields, "fx");
496 let color = first_str(fields, "color").and_then(parse_color).or_else(|| {
497 let r = first_u32(fields, "r")? as u8;
498 let g = first_u32(fields, "g")? as u8;
499 let b = first_u32(fields, "b")? as u8;
500 Some([r, g, b])
501 });
502 let alpha = first_f32(fields, "alpha").unwrap_or(1.0);
503 let shininess = first_f32(fields, "shine");
504 let auto_fade = first_u32(fields, "autofade").unwrap_or(500);
505
506 let collision_mode = first_u32(fields, "col").unwrap_or(1);
508 let collision_x_radius = first_f32(fields, "colxr").unwrap_or(1.0);
509 let collision_y_radius = first_f32(fields, "colyr").unwrap_or(1.0);
510
511 let material = first_string(fields, "mat").unwrap_or_else(|| "flesh".to_owned());
513 let health = first_f32(fields, "health").unwrap_or(5.0);
514 let health_change = first_f32(fields, "healthchange");
515 let damage = first_f32(fields, "damage").unwrap_or(1.0);
516 let speed = first_f32(fields, "speed").unwrap_or(2.0);
517 let turn_speed = first_f32(fields, "turnspeed").unwrap_or(2.0);
518 let eye_height = first_f32(fields, "eyes").unwrap_or(0.0);
519 let store = first_f32(fields, "store").unwrap_or(100.0);
520 let max_weight = first_u32(fields, "maxweight").unwrap_or(100000);
521
522 let perception_range = first_u32(fields, "range").unwrap_or(300);
524 let attack_range = first_u32(fields, "attackrange").unwrap_or(50);
525 let territory = first_u32(fields, "territory").unwrap_or(0);
526 let search_ratio = first_f32(fields, "searchratio").unwrap_or(0.0);
527
528 let loot = parse_loot(fields);
530
531 let sfx = first_string(fields, "sfx");
533
534 let state = match first_str(fields, "state") {
536 Some("random") | None => UnitState::Random,
537 Some(s) => {
538 let parts: Vec<&str> = s.split(',').collect();
539 if parts.len() == 3 {
540 if let (Ok(a), Ok(b), Ok(c)) = (
541 parts[0].trim().parse(),
542 parts[1].trim().parse(),
543 parts[2].trim().parse(),
544 ) {
545 UnitState::Fixed(a, b, c)
546 } else {
547 UnitState::Random
548 }
549 } else {
550 UnitState::Random
551 }
552 }
553 };
554 let align = first_u32(fields, "align").unwrap_or(0);
555
556 let ride_offset = first_f32(fields, "rideoffset").unwrap_or(30.0);
558
559 let has_any_vehicle_field = first_f32(fields, "acceleration").is_some()
560 || first_f32(fields, "friction").is_some()
561 || first_u32(fields, "steering").is_some()
562 || first_u32(fields, "maxdepth").is_some()
563 || first_f32(fields, "flyspeed").is_some();
564
565 let vehicle = if has_any_vehicle_field {
566 Some(VehicleParams {
567 acceleration: first_f32(fields, "acceleration").unwrap_or(0.03),
568 friction: first_f32(fields, "friction").unwrap_or(0.04),
569 steering: first_u32(fields, "steering").unwrap_or(2),
570 max_depth: first_u32(fields, "maxdepth").unwrap_or(3),
571 fly_speed: first_f32(fields, "flyspeed").unwrap_or(3.0),
572 })
573 } else {
574 None
575 };
576
577 let animations = UnitAnimations {
579 idle1: first_str(fields, "ani_idle1").and_then(AnimFrame::from_inf),
580 idle2: first_str(fields, "ani_idle2").and_then(AnimFrame::from_inf),
581 idle3: first_str(fields, "ani_idle3").and_then(AnimFrame::from_inf),
582 move_: first_str(fields, "ani_move").and_then(AnimFrame::from_inf),
583 attack: first_str(fields, "ani_attack").and_then(AnimFrame::from_inf),
584 use_: first_str(fields, "ani_use").and_then(AnimFrame::from_inf),
585 die: first_str(fields, "ani_die").and_then(AnimFrame::from_inf),
586 special: first_str(fields, "ani_special").and_then(AnimFrame::from_inf),
587 };
588
589 let loop_move_anim = first_u32(fields, "loopmoveani").unwrap_or(0) != 0;
590
591 let in_editor = first_u32(fields, "editor").map_or(true, |v| v != 0);
593
594 let script = None;
596 let description = None;
597
598 Some(Self {
599 id,
600 name,
601 group,
602 icon,
603 model,
604 scale,
605 fx,
606 color,
607 alpha,
608 shininess,
609 auto_fade,
610 collision_mode,
611 collision_x_radius,
612 collision_y_radius,
613 material,
614 health,
615 health_change,
616 damage,
617 speed,
618 turn_speed,
619 eye_height,
620 store,
621 max_weight,
622 behaviour,
623 perception_range,
624 attack_range,
625 territory,
626 search_ratio,
627 loot,
628 sfx,
629 state,
630 align,
631 ride_offset,
632 vehicle,
633 animations,
634 loop_move_anim,
635 script,
636 description,
637 in_editor,
638 })
639 }
640
641 #[must_use]
643 pub fn with_script(mut self, script: Option<String>) -> Self {
644 self.script = script;
645 self
646 }
647
648 #[must_use]
650 pub fn with_description(mut self, description: Option<String>) -> Self {
651 self.description = description;
652 self
653 }
654}
655
656#[cfg(test)]
659mod tests {
660 use super::*;
661
662 #[test]
665 fn test_anim_frame_from_inf() {
666 let frame = AnimFrame::from_inf("2,3,0.06").unwrap();
667 assert_eq!(frame.start, 2);
668 assert_eq!(frame.end, 3);
669 assert!((frame.speed - 0.06).abs() < 1e-6);
670 }
671
672 #[test]
673 fn test_anim_frame_invalid() {
674 assert!(AnimFrame::from_inf("2,3").is_none());
675 assert!(AnimFrame::from_inf("").is_none());
676 }
677
678 #[test]
681 fn test_loot_entry_from_inf() {
682 let loot = LootEntry::from_inf("9,3");
683 assert_eq!(loot.item_id, 9);
684 assert_eq!(loot.max_count, 3);
685 }
686
687 #[test]
688 fn test_loot_entry_minimal() {
689 let loot = LootEntry::from_inf("11");
690 assert_eq!(loot.item_id, 11);
691 assert_eq!(loot.max_count, 1);
692 }
693
694 #[test]
695 fn test_loot_entry_clamp() {
696 let loot = LootEntry::from_inf("5,0");
697 assert_eq!(loot.item_id, 5);
698 assert_eq!(loot.max_count, 1);
699 }
700
701 #[test]
704 fn test_unit_from_inf_minimal() {
705 let mut fields = HashMap::new();
706 fields.insert("id".into(), vec!["1".into()]);
707 fields.insert("name".into(), vec!["Player".into()]);
708
709 let unit = UnitDef::from_inf_fields(&fields).unwrap();
710 assert_eq!(unit.id, 1);
711 assert_eq!(unit.name, "Player");
712 assert_eq!(unit.group, "");
713 assert!((unit.health - 5.0).abs() < 1e-6);
714 assert_eq!(unit.material, "flesh");
715 assert!(unit.in_editor);
716 }
717
718 #[test]
719 fn test_unit_from_inf_full() {
720 let mut fields = HashMap::new();
721 fields.insert("id".into(), vec!["2".into()]);
722 fields.insert("name".into(), vec!["Raptor".into()]);
723 fields.insert("group".into(), vec!["animal".into()]);
724 fields.insert("icon".into(), vec!["gfx/raptor.png".into()]);
725 fields.insert("model".into(), vec!["gfx/raptor.glb".into()]);
726 fields.insert("behaviour".into(), vec!["raptor".into()]);
727 fields.insert("col".into(), vec!["1".into()]);
728 fields.insert("colxr".into(), vec!["15".into()]);
729 fields.insert("colyr".into(), vec!["30".into()]);
730 fields.insert("health".into(), vec!["110".into()]);
731 fields.insert("mat".into(), vec!["flesh".into()]);
732 fields.insert("damage".into(), vec!["24".into()]);
733 fields.insert("speed".into(), vec!["2.5".into()]);
734 fields.insert("turnspeed".into(), vec!["3.0".into()]);
735 fields.insert("eyes".into(), vec!["10".into()]);
736 fields.insert("store".into(), vec!["100".into()]);
737 fields.insert("maxweight".into(), vec!["25000".into()]);
738 fields.insert("range".into(), vec!["300".into()]);
739 fields.insert("attackrange".into(), vec!["65".into()]);
740 fields.insert("loot".into(), vec!["9,3".into(), "94,8".into()]);
741 fields.insert("sfx".into(), vec!["raptor".into()]);
742 fields.insert("scale".into(), vec!["0.5".into()]);
743 fields.insert("fx".into(), vec!["16".into()]);
744 fields.insert("ani_move".into(), vec!["2,3,0.06".into()]);
745 fields.insert("ani_attack".into(), vec!["12,16,0.07".into()]);
746 fields.insert("ani_idle1".into(), vec!["4,8,0.02".into()]);
747 fields.insert("ani_die".into(), vec!["8,11,0.05".into()]);
748
749 let unit = UnitDef::from_inf_fields(&fields).unwrap();
750 assert_eq!(unit.id, 2);
751 assert_eq!(unit.name, "Raptor");
752 assert_eq!(unit.group, "animal");
753 assert_eq!(unit.behaviour.as_deref(), Some("raptor"));
754 assert!((unit.health - 110.0).abs() < 1e-6);
755 assert!((unit.damage - 24.0).abs() < 1e-6);
756 assert!((unit.speed - 2.5).abs() < 1e-6);
757 assert!((unit.turn_speed - 3.0).abs() < 1e-6);
758 assert!((unit.eye_height - 10.0).abs() < 1e-6);
759 assert!((unit.scale - 0.5).abs() < 1e-6);
760 assert_eq!(unit.loot.len(), 2);
761 assert_eq!(unit.loot[0].item_id, 9);
762 assert_eq!(unit.loot[0].max_count, 3);
763 assert_eq!(unit.sfx.as_deref(), Some("raptor"));
764
765 let anim = unit.animations.move_.unwrap();
767 assert_eq!(anim.start, 2);
768 assert_eq!(anim.end, 3);
769 }
770
771 #[test]
772 fn test_unit_missing_id() {
773 let fields = HashMap::new();
774 assert!(UnitDef::from_inf_fields(&fields).is_none());
775 }
776
777 #[test]
778 fn test_unit_with_vehicle_params() {
779 let mut fields = HashMap::new();
780 fields.insert("id".into(), vec!["10".into()]);
781 fields.insert("name".into(), vec!["Boat".into()]);
782 fields.insert("acceleration".into(), vec!["0.05".into()]);
783 fields.insert("friction".into(), vec!["0.02".into()]);
784 fields.insert("steering".into(), vec!["3".into()]);
785 fields.insert("maxdepth".into(), vec!["10".into()]);
786 fields.insert("flyspeed".into(), vec!["0".into()]);
787 fields.insert("rideoffset".into(), vec!["5".into()]);
788
789 let unit = UnitDef::from_inf_fields(&fields).unwrap();
790 let v = unit.vehicle.unwrap();
791 assert!((v.acceleration - 0.05).abs() < 1e-6);
792 assert!((v.friction - 0.02).abs() < 1e-6);
793 assert_eq!(v.steering, 3);
794 assert_eq!(v.max_depth, 10);
795 assert!((unit.ride_offset - 5.0).abs() < 1e-6);
796 }
797
798 #[test]
799 fn test_unit_with_regular_fields_no_vehicle() {
800 let mut fields = HashMap::new();
801 fields.insert("id".into(), vec!["3".into()]);
802 fields.insert("name".into(), vec!["Crab".into()]);
803 fields.insert("health".into(), vec!["40".into()]);
804
805 let unit = UnitDef::from_inf_fields(&fields).unwrap();
806 assert!(unit.vehicle.is_none());
807 }
808
809 #[test]
810 fn test_unit_with_script_and_description() {
811 let mut fields = HashMap::new();
812 fields.insert("id".into(), vec!["1".into()]);
813 fields.insert("name".into(), vec!["Player".into()]);
814
815 let unit = UnitDef::from_inf_fields(&fields)
816 .unwrap()
817 .with_script(Some("on:start { msg \"Hello\"; }".into()))
818 .with_description(Some("The player character".into()));
819
820 assert_eq!(
821 unit.script.as_deref(),
822 Some("on:start { msg \"Hello\"; }")
823 );
824 assert_eq!(unit.description.as_deref(), Some("The player character"));
825 }
826
827 #[test]
828 fn test_state_serde_derives_compile() {
829 let unit = UnitDef {
830 id: 1,
831 name: "test".into(),
832 group: String::new(),
833 icon: None,
834 model: None,
835 scale: 1.0,
836 fx: None,
837 color: None,
838 alpha: 1.0,
839 shininess: None,
840 auto_fade: 500,
841 collision_mode: 1,
842 collision_x_radius: 1.0,
843 collision_y_radius: 1.0,
844 material: "flesh".into(),
845 health: 5.0,
846 health_change: None,
847 damage: 1.0,
848 speed: 2.0,
849 turn_speed: 2.0,
850 eye_height: 0.0,
851 store: 100.0,
852 max_weight: 100000,
853 behaviour: None,
854 perception_range: 300,
855 attack_range: 50,
856 territory: 0,
857 search_ratio: 0.0,
858 loot: vec![],
859 sfx: None,
860 state: UnitState::Random,
861 align: 0,
862 ride_offset: 30.0,
863 vehicle: None,
864 animations: UnitAnimations::default(),
865 loop_move_anim: false,
866 script: None,
867 description: None,
868 in_editor: true,
869 };
870 assert_eq!(unit.id, 1);
871 }
872}