openscenario-rs 0.3.1

Rust library for parsing and manipulating OpenSCENARIO files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Controller system types for OpenSCENARIO.
//!
//! This module provides comprehensive controller functionality for entity behavior management,
//! including controller definitions, activation actions, and parameter management.

use crate::types::basic::{Boolean, OSString, ParameterDeclarations, Value};
use crate::types::catalogs::references::ControllerCatalogReference;
use crate::types::distributions::ParameterValueDistribution;
use crate::types::entities::vehicle::{File, Properties, Property};
use crate::types::enums::ControllerType;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[derive(Default)]
pub struct ParameterAssignments {
    pub assignments: Vec<ParameterAssignment>,
}


#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ParameterAssignment {
    pub parameter_ref: OSString,
    pub value: OSString,
}

impl Default for ParameterAssignment {
    fn default() -> Self {
        Self {
            parameter_ref: Value::Literal("defaultParam".to_string()),
            value: Value::Literal("defaultValue".to_string()),
        }
    }
}

// CatalogReference is now imported from crate::types::catalogs::references

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Directory {
    pub path: OSString,
}

impl Default for Directory {
    fn default() -> Self {
        Self {
            path: Value::Literal("./".to_string()),
        }
    }
}

/// Main controller definition with type information and properties.
///
/// Represents a controller that can be assigned to entities to manage their behavior.
/// Controllers can have parameters, properties, and specific controller types.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Controller {
    /// Name of the controller
    #[serde(rename = "@name")]
    pub name: OSString,

    /// Type of controller (interactive, external, etc.)
    #[serde(rename = "@controllerType", skip_serializing_if = "Option::is_none")]
    pub controller_type: Option<ControllerType>,

    /// Parameter declarations for the controller
    #[serde(
        rename = "ParameterDeclarations",
        skip_serializing_if = "Option::is_none"
    )]
    pub parameter_declarations: Option<ParameterDeclarations>,

    /// Additional properties for the controller
    #[serde(rename = "Properties", skip_serializing_if = "Option::is_none")]
    pub properties: Option<Properties>,
}

impl Default for Controller {
    fn default() -> Self {
        Self {
            name: Value::Literal("DefaultController".to_string()),
            controller_type: Some(ControllerType::Movement),
            parameter_declarations: None,
            properties: None,
        }
    }
}

/// Object controller wrapper that can reference a controller definition or catalog.
///
/// This is the controller structure used in ScenarioObject entities.
/// It can either contain a direct controller definition or reference a controller catalog.
/// According to XSD schema, exactly one of Controller or CatalogReference must be present.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ObjectController {
    /// Optional name attribute for the controller
    #[serde(rename = "@name", skip_serializing_if = "Option::is_none")]
    pub name: Option<OSString>,

    /// Direct controller definition
    #[serde(rename = "Controller", skip_serializing_if = "Option::is_none")]
    pub controller: Option<Controller>,

    /// Reference to a controller in a catalog
    #[serde(rename = "CatalogReference", skip_serializing_if = "Option::is_none")]
    pub catalog_reference: Option<ControllerCatalogReference>,
}

// Custom deserializer to handle XSD choice group validation
impl<'de> Deserialize<'de> for ObjectController {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        #[derive(Deserialize)]
        #[serde(field_identifier)]
        enum Field {
            #[serde(rename = "@name")]
            Name,
            #[serde(rename = "Controller")]
            Controller,
            #[serde(rename = "CatalogReference")]
            CatalogReference,
        }

        struct ObjectControllerVisitor;

        impl<'de> Visitor<'de> for ObjectControllerVisitor {
            type Value = ObjectController;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct ObjectController")
            }

            fn visit_map<V>(self, mut map: V) -> std::result::Result<ObjectController, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut name = None;
                let mut controller = None;
                let mut catalog_reference = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Name => {
                            if name.is_some() {
                                return Err(de::Error::duplicate_field("name"));
                            }
                            name = Some(map.next_value()?);
                        }
                        Field::Controller => {
                            if controller.is_some() {
                                return Err(de::Error::duplicate_field("Controller"));
                            }
                            controller = Some(map.next_value()?);
                        }
                        Field::CatalogReference => {
                            if catalog_reference.is_some() {
                                return Err(de::Error::duplicate_field("CatalogReference"));
                            }
                            catalog_reference = Some(map.next_value()?);
                        }
                    }
                }

                // XSD choice group validation: exactly one of Controller or CatalogReference must be present
                // However, we allow empty ObjectController elements for backward compatibility
                match (controller.is_some(), catalog_reference.is_some()) {
                    (true, false) | (false, true) | (false, false) => {
                        Ok(ObjectController {
                            name,
                            controller,
                            catalog_reference,
                        })
                    }
                    (true, true) => Err(de::Error::custom(
                        "ObjectController must contain exactly one of Controller or CatalogReference, found both"
                    )),
                }
            }
        }

        const FIELDS: &[&str] = &["@name", "Controller", "CatalogReference"];
        deserializer.deserialize_struct("ObjectController", FIELDS, ObjectControllerVisitor)
    }
}

impl Default for ObjectController {
    fn default() -> Self {
        Self {
            name: None,
            controller: Some(Controller::default()),
            catalog_reference: None,
        }
    }
}

/// Collection of controller-specific properties.
///
/// Provides a container for controller parameters and configuration options.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[derive(Default)]
pub struct ControllerProperties {
    /// List of controller properties
    #[serde(rename = "Property")]
    pub properties: Vec<Property>,
}


/// Action to activate a controller for an entity.
///
/// This action enables a controller and optionally sets parameter values.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ActivateControllerAction {
    /// Reference to the controller to activate
    #[serde(rename = "@controllerRef")]
    pub controller_ref: OSString,

    /// Parameter assignments for controller activation
    #[serde(
        rename = "ParameterAssignments",
        skip_serializing_if = "Option::is_none"
    )]
    pub parameter_assignments: Option<ParameterAssignments>,
}

impl Default for ActivateControllerAction {
    fn default() -> Self {
        Self {
            controller_ref: Value::Literal("DefaultController".to_string()),
            parameter_assignments: None,
        }
    }
}

/// Action to override controller parameter values.
///
/// This action modifies controller behavior by overriding specific parameter values
/// and can activate or deactivate the override.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OverrideControllerValueAction {
    /// Reference to the controller to override
    #[serde(rename = "@controllerRef")]
    pub controller_ref: OSString,

    /// Parameter assignments for the override
    #[serde(rename = "ParameterAssignments")]
    pub parameter_assignments: ParameterAssignments,

    /// Whether the override is active
    #[serde(rename = "@active")]
    pub active: Boolean,
}

impl Default for OverrideControllerValueAction {
    fn default() -> Self {
        Self {
            controller_ref: Value::Literal("DefaultController".to_string()),
            parameter_assignments: ParameterAssignments::default(),
            active: Value::Literal(true),
        }
    }
}

/// Assignment of a controller to a specific entity.
///
/// Defines the relationship between a controller and the entity it manages.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ControllerAssignment {
    /// Reference to the controller
    #[serde(rename = "@controllerRef")]
    pub controller_ref: OSString,

    /// Target entity for the controller
    #[serde(rename = "@targetEntity")]
    pub target_entity: OSString,
}

impl Default for ControllerAssignment {
    fn default() -> Self {
        Self {
            controller_ref: Value::Literal("DefaultController".to_string()),
            target_entity: Value::Literal("Ego".to_string()),
        }
    }
}

/// Catalog location for controller definitions.
///
/// Specifies where controller catalog files can be found.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
#[derive(Default)]
pub struct ControllerCatalogLocation {
    /// Directory containing controller catalog files
    #[serde(rename = "Directory")]
    pub directory: Directory,
}


/// Distribution configuration for controller parameters.
///
/// Allows for statistical or deterministic variation of controller parameters
/// across multiple scenario runs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ControllerDistribution {
    /// Type of controller this distribution applies to
    #[serde(rename = "@controllerType")]
    pub controller_type: ControllerType,

    /// Parameter distribution specification
    #[serde(rename = "ParameterValueDistribution")]
    pub distribution: ParameterValueDistribution,
}

impl Default for ControllerDistribution {
    fn default() -> Self {
        use crate::types::distributions::deterministic::*;

        // Create a simple deterministic distribution
        let single_param_dist = DeterministicSingleParameterDistribution {
            parameter_name: Value::Literal("controllerParam".to_string()),
            distribution_set: Some(DistributionSet {
                elements: vec![DistributionSetElement {
                    value: Value::Literal("default".to_string()),
                }],
            }),
            distribution_range: None,
            user_defined_distribution: None,
        };

        let deterministic = crate::types::distributions::Deterministic {
            single_distributions: vec![single_param_dist],
            multi_distributions: vec![],
        };

        Self {
            controller_type: ControllerType::Movement,
            distribution: ParameterValueDistribution::new_deterministic(
                File {
                    filepath: "default.xosc".to_string(),
                },
                deterministic,
            ),
        }
    }
}

// Helper implementations for common controller operations

impl Controller {
    /// Creates a new controller with the specified name and type.
    pub fn new(name: String, controller_type: ControllerType) -> Self {
        Self {
            name: Value::Literal(name),
            controller_type: Some(controller_type),
            parameter_declarations: None,
            properties: None,
        }
    }

    /// Creates a controller with parameters.
    pub fn with_parameters(
        name: String,
        controller_type: ControllerType,
        parameters: ParameterDeclarations,
    ) -> Self {
        Self {
            name: Value::Literal(name),
            controller_type: Some(controller_type),
            parameter_declarations: Some(parameters),
            properties: None,
        }
    }

    /// Creates a controller with properties.
    pub fn with_properties(
        name: String,
        controller_type: ControllerType,
        properties: Properties,
    ) -> Self {
        Self {
            name: Value::Literal(name),
            controller_type: Some(controller_type),
            parameter_declarations: None,
            properties: Some(properties),
        }
    }
}

impl ObjectController {
    /// Creates an ObjectController with a direct controller definition.
    pub fn with_controller(controller: Controller) -> Self {
        Self {
            name: None,
            controller: Some(controller),
            catalog_reference: None,
        }
    }

    /// Creates an ObjectController with a catalog reference.
    pub fn with_catalog_reference(catalog_reference: ControllerCatalogReference) -> Self {
        Self {
            name: None,
            controller: None,
            catalog_reference: Some(catalog_reference),
        }
    }

    /// Creates an ObjectController with a name and direct controller definition.
    pub fn with_named_controller(name: String, controller: Controller) -> Self {
        Self {
            name: Some(Value::Literal(name)),
            controller: Some(controller),
            catalog_reference: None,
        }
    }

    /// Creates an ObjectController with a name and catalog reference.
    pub fn with_named_catalog_reference(
        name: String,
        catalog_reference: ControllerCatalogReference,
    ) -> Self {
        Self {
            name: Some(Value::Literal(name)),
            controller: None,
            catalog_reference: Some(catalog_reference),
        }
    }

    /// Validates that at most one of Controller or CatalogReference is present
    /// Empty ObjectController elements are allowed for backward compatibility
    pub fn validate(&self) -> Result<(), String> {
        match (self.controller.is_some(), self.catalog_reference.is_some()) {
            (true, false) | (false, true) | (false, false) => Ok(()),
            (true, true) => Err("ObjectController must contain at most one of Controller or CatalogReference, found both".to_string()),
        }
    }

    /// Validates strict XSD compliance (exactly one of Controller or CatalogReference must be present)
    pub fn validate_strict(&self) -> Result<(), String> {
        match (self.controller.is_some(), self.catalog_reference.is_some()) {
            (true, false) | (false, true) => Ok(()),
            (true, true) => Err("ObjectController must contain exactly one of Controller or CatalogReference, found both".to_string()),
            (false, false) => Err("ObjectController must contain exactly one of Controller or CatalogReference, found neither".to_string()),
        }
    }
}

impl ActivateControllerAction {
    /// Creates an action to activate a controller by name.
    pub fn new(controller_ref: String) -> Self {
        Self {
            controller_ref: Value::Literal(controller_ref),
            parameter_assignments: None,
        }
    }

    /// Creates an action to activate a controller with parameter assignments.
    pub fn with_parameters(
        controller_ref: String,
        parameter_assignments: ParameterAssignments,
    ) -> Self {
        Self {
            controller_ref: Value::Literal(controller_ref),
            parameter_assignments: Some(parameter_assignments),
        }
    }
}

impl OverrideControllerValueAction {
    /// Creates an action to override controller values.
    pub fn new(
        controller_ref: String,
        parameter_assignments: ParameterAssignments,
        active: bool,
    ) -> Self {
        Self {
            controller_ref: Value::Literal(controller_ref),
            parameter_assignments,
            active: Value::Literal(active),
        }
    }
}

impl ControllerAssignment {
    /// Creates a controller assignment.
    pub fn new(controller_ref: String, target_entity: String) -> Self {
        Self {
            controller_ref: Value::Literal(controller_ref),
            target_entity: Value::Literal(target_entity),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::enums::ControllerType;

    #[test]
    fn test_controller_creation() {
        let controller = Controller::new("TestController".to_string(), ControllerType::Movement);

        assert_eq!(controller.name.as_literal().unwrap(), "TestController");
        assert_eq!(controller.controller_type, Some(ControllerType::Movement));
    }

    #[test]
    fn test_object_controller_with_direct_controller() {
        let controller = Controller::new("DirectController".to_string(), ControllerType::Lateral);
        let object_controller = ObjectController::with_controller(controller);

        assert!(object_controller.controller.is_some());
        assert!(object_controller.catalog_reference.is_none());
    }

    #[test]
    fn test_activate_controller_action() {
        let action = ActivateControllerAction::new("MainController".to_string());

        assert_eq!(
            action.controller_ref.as_literal().unwrap(),
            "MainController"
        );
        assert!(action.parameter_assignments.is_none());
    }

    #[test]
    fn test_override_controller_action() {
        let assignments = ParameterAssignments::default();
        let action =
            OverrideControllerValueAction::new("TestController".to_string(), assignments, true);

        assert_eq!(
            action.controller_ref.as_literal().unwrap(),
            "TestController"
        );
        assert_eq!(action.active.as_literal().unwrap(), &true);
    }

    #[test]
    fn test_controller_assignment() {
        let assignment =
            ControllerAssignment::new("AIController".to_string(), "Vehicle1".to_string());

        assert_eq!(
            assignment.controller_ref.as_literal().unwrap(),
            "AIController"
        );
        assert_eq!(assignment.target_entity.as_literal().unwrap(), "Vehicle1");
    }

    #[test]
    fn test_controller_serialization() {
        let controller = Controller::new("SerializationTest".to_string(), ControllerType::Movement);

        // Test XML serialization
        let xml = quick_xml::se::to_string(&controller).unwrap();
        assert!(xml.contains("SerializationTest"));
        assert!(xml.contains("movement"));

        // Test deserialization
        let deserialized: Controller = quick_xml::de::from_str(&xml).unwrap();
        assert_eq!(controller, deserialized);
    }

    #[test]
    fn test_controller_distribution() {
        let distribution = ControllerDistribution::default();

        assert_eq!(distribution.controller_type, ControllerType::Movement);
        assert!(matches!(
            distribution.distribution,
            ParameterValueDistribution { .. }
        ));
    }

    #[test]
    fn test_controller_properties() {
        let mut properties = ControllerProperties::default();
        // Create a simple property with correct String types
        let property = Property {
            name: "testProp".to_string(),
            value: "testValue".to_string(),
        };
        properties.properties.push(property);

        assert_eq!(properties.properties.len(), 1);
    }

    #[test]
    fn test_controller_defaults() {
        let controller = Controller::default();
        let object_controller = ObjectController::default();
        let properties = ControllerProperties::default();
        let activate_action = ActivateControllerAction::default();
        let override_action = OverrideControllerValueAction::default();
        let assignment = ControllerAssignment::default();

        // All defaults should be valid
        assert!(controller.name.as_literal().is_some());
        assert!(object_controller.controller.is_some());
        assert!(properties.properties.is_empty());
        assert!(activate_action.controller_ref.as_literal().is_some());
        assert!(override_action.active.as_literal().is_some());
        assert!(assignment.target_entity.as_literal().is_some());
    }

    #[test]
    fn test_object_controller_validation() {
        // Test valid controller with direct controller
        let valid_direct = ObjectController {
            name: None,
            controller: Some(Controller::default()),
            catalog_reference: None,
        };
        assert!(valid_direct.validate().is_ok());

        // Test valid controller with catalog reference
        let valid_catalog = ObjectController {
            name: None,
            controller: None,
            catalog_reference: Some(ControllerCatalogReference::new(
                "catalog".to_string(),
                "entry".to_string(),
            )),
        };
        assert!(valid_catalog.validate().is_ok());

        // Test empty controller (allowed for backward compatibility)
        let empty_controller = ObjectController {
            name: None,
            controller: None,
            catalog_reference: None,
        };
        assert!(empty_controller.validate().is_ok());
        // But strict validation should fail
        assert!(empty_controller.validate_strict().is_err());

        // Test invalid controller with both controller and reference
        let invalid_both = ObjectController {
            name: None,
            controller: Some(Controller::default()),
            catalog_reference: Some(ControllerCatalogReference::new(
                "catalog".to_string(),
                "entry".to_string(),
            )),
        };
        assert!(invalid_both.validate().is_err());

        // Test named controller
        let named_controller = ObjectController::with_named_controller(
            "TestController".to_string(),
            Controller::default(),
        );
        assert!(named_controller.validate().is_ok());
        assert_eq!(
            named_controller
                .name
                .as_ref()
                .unwrap()
                .as_literal()
                .unwrap(),
            "TestController"
        );
    }
}