Skip to main content

open_dis_rust/
live_entity_records.rs

1//     open-dis-rust - Rust implementation of the IEEE 1278.1-2012 Distributed Interactive
2//                     Simulation (DIS) application protocol
3//     Copyright (C) 2026 Cameron Howell
4//
5//     Licensed under the BSD 2-Clause License
6
7use crate::records::{EntityType, ExerciseIdentifier, Timestamp};
8use crate::siso::enums::{
9    DISLiveEntitySubprotocolNumber, DeadReckoningAlgorithm, MunitionDescriptorFuse,
10    MunitionDescriptorWarhead, PduType, ProtocolFamily, ProtocolVersion,
11};
12
13macro_rules! fixed_binary {
14    ($name:ident, $raw:ty, $bits:literal) => {
15            #[doc = concat!(
16                "A ", stringify!($bits), "-bit signed fixed binary number with `FRAC` fractional bits.\n\n",
17                "On the wire it's a two's complement `", stringify!($raw), "`; its value is that integer ",
18                "divided by 2^`FRAC`. Each Live Entity field defines its own `FRAC` and units, so use the ",
19                "type alias for the field rather than choosing `FRAC` yourself."
20            )]
21            #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
22            #[deku(
23                endian = "endian",
24                ctx = "endian: deku::ctx::Endian",
25                ctx_default = "deku::ctx::Endian::Big"
26            )]
27            pub struct $name<const FRAC: u32> {
28                raw: $raw,
29            }
30
31            impl<const FRAC: u32> $name<FRAC> {
32                /// Fails to compile when `FRAC` leaves no room for the sign bit.
33                const VALID: () = assert!(FRAC < $bits, "FRAC must be less than the number of bits");
34
35                #[allow(clippy::as_conversions, reason = "u32 to f64 is exact, and `From` isn't const")]
36                const SCALE: f64 = (1u32 << FRAC) as f64;
37
38                /// The difference between two adjacent values: 2^-`FRAC`.
39                pub const RESOLUTION: f64 = 1.0 / Self::SCALE;
40
41                /// The smallest value the type can hold.
42                #[allow(clippy::as_conversions, reason = "integer to f64 is exact, and `From` isn't const")]
43                pub const MIN: f64 = <$raw>::MIN as f64 / Self::SCALE;
44
45                /// The largest value the type can hold.
46                #[allow(clippy::as_conversions, reason = "integer to f64 is exact, and `From` isn't const")]
47                pub const MAX: f64 = <$raw>::MAX as f64 / Self::SCALE;
48
49                /// The value nearest to `value`, or `None` if `value` is out of range or isn't finite.
50                #[must_use]
51                pub fn new(value: f64) -> Option<Self> {
52                    let () = Self::VALID;
53                    let scaled = (value * Self::SCALE).round();
54                    (f64::from(<$raw>::MIN)..=f64::from(<$raw>::MAX))
55                        .contains(&scaled)
56                        .then(|| Self::from_scaled(scaled))
57                }
58
59                /// The value nearest to `value`, clamped to [`MIN`](Self::MIN) and
60                /// [`MAX`](Self::MAX). NaN becomes 0.
61                #[must_use]
62                pub fn saturating(value: f64) -> Self {
63                    let () = Self::VALID;
64                    Self::from_scaled((value * Self::SCALE).round())
65                }
66
67                /// The number's value.
68                #[must_use]
69                pub fn to_f64(self) -> f64 {
70                    f64::from(self.raw) / Self::SCALE
71                }
72
73                /// A number from its wire value.
74                #[must_use]
75                pub const fn from_raw(raw: $raw) -> Self {
76                    Self { raw }
77                }
78
79                /// The number's wire value.
80                #[must_use]
81                pub const fn to_raw(self) -> $raw {
82                    self.raw
83                }
84
85                #[allow(
86                    clippy::as_conversions,
87                    clippy::cast_possible_truncation,
88                    reason = "float-to-integer `as` saturates and maps NaN to 0, which is the behavior wanted"
89                )]
90                const fn from_scaled(scaled: f64) -> Self {
91                    Self { raw: scaled as $raw }
92                }
93            }
94        };
95}
96
97fixed_binary!(FixedBinary8, i8, 8);
98fixed_binary!(FixedBinary16, i16, 16);
99
100/// The 12-octet header of a Live Entity Information/Interaction PDU. It has a
101/// subprotocol number in octet 10, where other PDUs have their PDU status record.
102#[derive(Copy, Clone, Debug, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
103#[deku(
104    endian = "endian",
105    ctx = "endian: deku::ctx::Endian",
106    ctx_default = "deku::ctx::Endian::Big"
107)]
108pub struct LiveEntityPduHeader {
109    /// The version of the protocol
110    pub protocol_version: ProtocolVersion,
111    /// Exercise ID
112    pub exercise_id: ExerciseIdentifier,
113    /// Type of PDU set from the PDU when it is encoded. Read it with
114    /// [`pdu_type`](Self::pdu_type).
115    pub(crate) pdu_type: PduType,
116    /// Protocol family set from the PDU when it is encoded. Read it with
117    /// [`protocol_family`](Self::protocol_family).
118    pub(crate) protocol_family: ProtocolFamily,
119    /// When the data in the PDU was valid. New headers use [`Timestamp::now`].
120    pub timestamp: Timestamp,
121    /// Length of the PDU in octets, including the header. This value is set
122    /// upon encoding. Read it with [`length`](Self::length).
123    pub(crate) length: u16,
124    /// The subprotocol to be used to decode the PDU
125    pub subprotocol_number: DISLiveEntitySubprotocolNumber,
126    /// Padded so that this header maintains the same length as the PDU Header
127    padding: u8,
128}
129
130impl Default for LiveEntityPduHeader {
131    fn default() -> Self {
132        Self {
133            protocol_version: ProtocolVersion::IEEE1278_1_2012,
134            exercise_id: ExerciseIdentifier::new(1),
135            pdu_type: PduType::default(),
136            protocol_family: ProtocolFamily::default(),
137            timestamp: Timestamp::now(),
138            length: 0,
139            subprotocol_number: DISLiveEntitySubprotocolNumber::default(),
140            padding: 0,
141        }
142    }
143}
144
145impl LiveEntityPduHeader {
146    /// The PDU type, set from the PDU when it is encoded.
147    #[must_use]
148    pub const fn pdu_type(&self) -> PduType {
149        self.pdu_type
150    }
151
152    /// The protocol family, set from the PDU when it is encoded.
153    #[must_use]
154    pub const fn protocol_family(&self) -> ProtocolFamily {
155        self.protocol_family
156    }
157
158    /// The PDU's length in octets, header included, set when it is encoded.
159    #[must_use]
160    pub const fn length(&self) -> u16 {
161        self.length
162    }
163
164    /// Encodes the header alone and appends it to `buf`
165    pub fn serialize(&self, buf: &mut Vec<u8>) {
166        let _ = crate::wire::write(self, buf);
167    }
168
169    /// Decodes a header from the front of `buf`, advancing `buf` past it. Pass it to
170    /// [`Pdu::deserialize_without_header`](crate::Pdu::deserialize_without_header)
171    /// to decode the rest of the PDU.
172    ///
173    /// # Errors
174    ///
175    /// Will return a `DekuError` if `buf` does not start with a valid header.
176    pub fn deserialize(buf: &mut &[u8]) -> Result<Self, crate::DISError> {
177        crate::wire::read(buf).map_err(crate::DISError::from_wire)
178    }
179}
180
181impl crate::pdu::DerivedFields for LiveEntityPduHeader {
182    #[cfg(test)]
183    fn length(&self) -> u16 {
184        self.length
185    }
186
187    fn set_pdu_type(&mut self, value: PduType) {
188        self.pdu_type = value;
189    }
190
191    fn set_protocol_family(&mut self, value: ProtocolFamily) {
192        self.protocol_family = value;
193    }
194
195    fn set_length(&mut self, value: u16) {
196        self.length = value;
197    }
198}
199
200/// Dead reckoning parameters in the compact Live Entity form.
201#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
202#[deku(
203    endian = "endian",
204    ctx = "endian: deku::ctx::Endian",
205    ctx_default = "deku::ctx::Endian::Big"
206)]
207pub struct LEDeadReckoningParameters {
208    pub dead_reckoning_algorithm: DeadReckoningAlgorithm,
209    pub entity_linear_acceleration: LEEntityLinearAcceleration,
210    pub entity_angular_velocity: LEEntityAngularVelocity,
211}
212
213impl LEDeadReckoningParameters {
214    #[must_use]
215    pub const fn new(
216        dead_reckoning_algorithm: DeadReckoningAlgorithm,
217        entity_linear_acceleration: LEEntityLinearAcceleration,
218        entity_angular_velocity: LEEntityAngularVelocity,
219    ) -> Self {
220        Self {
221            dead_reckoning_algorithm,
222            entity_linear_acceleration,
223            entity_angular_velocity,
224        }
225    }
226}
227
228/// One component of [`LEEntityAngularVelocity`].
229pub type LEAngularVelocityComponent = FixedBinary8<0>;
230
231#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
232#[deku(
233    endian = "endian",
234    ctx = "endian: deku::ctx::Endian",
235    ctx_default = "deku::ctx::Endian::Big"
236)]
237/// Implemented according to IEEE 1278.1-2012 §6.2.7
238/// For all fields, assume right-hand rule for directionality
239pub struct LEEntityAngularVelocity {
240    /// The angular velocity in radians/second about the entity's X-axis
241    pub rate_about_x_axis: LEAngularVelocityComponent,
242    /// The angular velocity in radians/second about the entity's Y-axis
243    pub rate_about_y_axis: LEAngularVelocityComponent,
244    /// The angular velocity in radians/second about the entity's Z-axis
245    pub rate_about_z_axis: LEAngularVelocityComponent,
246}
247
248impl LEEntityAngularVelocity {
249    /// Create a new `AngularVelocity` struct with existing values
250    #[must_use]
251    pub fn new() -> Self {
252        Self::default()
253    }
254}
255
256#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
257#[deku(
258    endian = "endian",
259    ctx = "endian: deku::ctx::Endian",
260    ctx_default = "deku::ctx::Endian::Big"
261)]
262/// Implemented according to IEEE 1278.1-2012 §6.2.28
263pub struct LEEntityId {
264    /// The unique identification number of the site
265    pub site_number: u8,
266    /// The unique identification number of the application
267    pub application_number: u8,
268    /// The unique identification number of the entity
269    pub entity_number: u16,
270}
271
272impl LEEntityId {
273    #[must_use]
274    pub const fn new(site_number: u8, application_number: u8, entity_number: u16) -> Self {
275        Self {
276            site_number,
277            application_number,
278            entity_number,
279        }
280    }
281}
282
283/// One component of [`LEEntityLinearAcceleration`].
284pub type LELinearAccelerationComponent = FixedBinary8<0>;
285
286/// An entity's linear acceleration in the compact Live Entity form.
287#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
288#[deku(
289    endian = "endian",
290    ctx = "endian: deku::ctx::Endian",
291    ctx_default = "deku::ctx::Endian::Big"
292)]
293pub struct LEEntityLinearAcceleration {
294    pub first_vector_component: LELinearAccelerationComponent,
295    pub second_vector_component: LELinearAccelerationComponent,
296    pub third_vector_component: LELinearAccelerationComponent,
297}
298
299impl LEEntityLinearAcceleration {
300    #[must_use]
301    pub const fn new(
302        x: LELinearAccelerationComponent,
303        y: LELinearAccelerationComponent,
304        z: LELinearAccelerationComponent,
305    ) -> Self {
306        Self {
307            first_vector_component: x,
308            second_vector_component: y,
309            third_vector_component: z,
310        }
311    }
312}
313
314/// One angle of [`LEEulerAngles`].
315pub type LEEulerAnglesComponent = FixedBinary8<0>;
316
317/// Implemented according to IEEE 1278.1-2012 §6.2.32
318#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
319#[deku(
320    endian = "endian",
321    ctx = "endian: deku::ctx::Endian",
322    ctx_default = "deku::ctx::Endian::Big"
323)]
324pub struct LEEulerAngles {
325    /// Angle of rotation about the Z-axis
326    pub psi: LEEulerAnglesComponent,
327    /// Angle of rotation about the Y-axis
328    pub theta: LEEulerAnglesComponent,
329    /// Angle of rotation about the X-axis
330    pub phi: LEEulerAnglesComponent,
331}
332
333impl LEEulerAngles {
334    #[must_use]
335    #[allow(clippy::similar_names)]
336    pub const fn new(
337        psi: LEEulerAnglesComponent,
338        theta: LEEulerAnglesComponent,
339        phi: LEEulerAnglesComponent,
340    ) -> Self {
341        Self { psi, theta, phi }
342    }
343}
344
345/// An event identifier in the compact Live Entity form: 8-bit site and application
346/// numbers and a 16-bit event number.
347#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
348#[deku(
349    endian = "endian",
350    ctx = "endian: deku::ctx::Endian",
351    ctx_default = "deku::ctx::Endian::Big"
352)]
353pub struct LiveEventIdentifier {
354    pub site_number: u8,
355    pub application_number: u8,
356    pub event_number: u16,
357}
358
359impl LiveEventIdentifier {
360    #[must_use]
361    pub const fn new(site_number: u8, application_number: u8, event_number: u16) -> Self {
362        Self {
363            site_number,
364            application_number,
365            event_number,
366        }
367    }
368}
369
370/// One component of [`LELinearVelocity`].
371pub type LELinearVelocityComponent = FixedBinary16<0>;
372
373/// An entity's linear velocity in the compact Live Entity form.
374#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
375#[deku(
376    endian = "endian",
377    ctx = "endian: deku::ctx::Endian",
378    ctx_default = "deku::ctx::Endian::Big"
379)]
380pub struct LELinearVelocity {
381    pub x_component: LELinearVelocityComponent,
382    pub y_component: LELinearVelocityComponent,
383    pub z_component: LELinearVelocityComponent,
384}
385
386impl LELinearVelocity {
387    #[must_use]
388    pub const fn new(
389        x_component: LELinearVelocityComponent,
390        y_component: LELinearVelocityComponent,
391        z_component: LELinearVelocityComponent,
392    ) -> Self {
393        Self {
394            x_component,
395            y_component,
396            z_component,
397        }
398    }
399}
400
401/// An entity's orientation as three 16-bit angles in the compact Live Entity form.
402#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
403#[deku(
404    endian = "endian",
405    ctx = "endian: deku::ctx::Endian",
406    ctx_default = "deku::ctx::Endian::Big"
407)]
408pub struct LiveEntityOrientation16 {
409    pub psi: i16,
410    pub theta: i16,
411    pub phi: i16,
412}
413
414impl LiveEntityOrientation16 {
415    #[must_use]
416    pub const fn new(psi: i16, theta: i16, phi: i16) -> Self {
417        Self { psi, theta, phi }
418    }
419}
420
421/// One component of [`OrientationError`].
422pub type OrientationErrorComponent = FixedBinary16<8>;
423
424/// The estimated error in a live entity's orientation.
425#[derive(Debug, Clone, Copy, Default, deku::DekuRead, deku::DekuWrite)]
426#[deku(
427    endian = "endian",
428    ctx = "endian: deku::ctx::Endian",
429    ctx_default = "deku::ctx::Endian::Big"
430)]
431pub struct OrientationError {
432    pub azimuth_error: OrientationErrorComponent,
433    pub elevation_error: OrientationErrorComponent,
434    pub rotation_error: OrientationErrorComponent,
435}
436
437impl OrientationError {
438    #[must_use]
439    pub const fn new(
440        azimuth_error: OrientationErrorComponent,
441        elevation_error: OrientationErrorComponent,
442        rotation_error: OrientationErrorComponent,
443    ) -> Self {
444        Self {
445            azimuth_error,
446            elevation_error,
447            rotation_error,
448        }
449    }
450}
451
452/// One component of [`PositionError`].
453pub type PositionErrorComponent = FixedBinary16<3>;
454
455/// The estimated error in a live entity's position.
456#[derive(Debug, Clone, Copy, Default, deku::DekuRead, deku::DekuWrite)]
457#[deku(
458    endian = "endian",
459    ctx = "endian: deku::ctx::Endian",
460    ctx_default = "deku::ctx::Endian::Big"
461)]
462pub struct PositionError {
463    pub horizontal_error: PositionErrorComponent,
464    pub vertical_error: PositionErrorComponent,
465}
466
467impl PositionError {
468    #[must_use]
469    pub const fn new(
470        horizontal_error: PositionErrorComponent,
471        vertical_error: PositionErrorComponent,
472    ) -> Self {
473        Self {
474            horizontal_error,
475            vertical_error,
476        }
477    }
478}
479
480/// One component of [`RelativeWorldCoordinates`].
481pub type RelativeWorldCoordinatesComponent = FixedBinary16<3>;
482
483/// A live entity's location relative to a reference point.
484#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
485#[deku(
486    endian = "endian",
487    ctx = "endian: deku::ctx::Endian",
488    ctx_default = "deku::ctx::Endian::Big"
489)]
490pub struct RelativeWorldCoordinates {
491    pub reference_point: u16,
492    pub delta_x: RelativeWorldCoordinatesComponent,
493    pub delta_y: RelativeWorldCoordinatesComponent,
494    pub delta_z: RelativeWorldCoordinatesComponent,
495}
496
497impl RelativeWorldCoordinates {
498    #[must_use]
499    pub const fn new(
500        reference_point: u16,
501        delta_x: RelativeWorldCoordinatesComponent,
502        delta_y: RelativeWorldCoordinatesComponent,
503        delta_z: RelativeWorldCoordinatesComponent,
504    ) -> Self {
505        Self {
506            reference_point,
507            delta_x,
508            delta_y,
509            delta_z,
510        }
511    }
512}
513
514/// A location relative to a reference point in the compact Live Entity form.
515#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
516#[deku(
517    endian = "endian",
518    ctx = "endian: deku::ctx::Endian",
519    ctx_default = "deku::ctx::Endian::Big"
520)]
521pub struct LiveEntityRelativeLocation {
522    pub x: i16,
523    pub y: i16,
524    pub z: i16,
525}
526
527/// The Munition Descriptor record (§6.2.19.2) as the LE Fire and LE
528/// Detonation PDUs carry it: "the warhead, fuse, quantity, and rate fields of
529/// this record shall be optional" (§9.4.5.6 h, §9.4.6.8 j).
530///
531/// The PDU's flags say which optional parts are present, so this record is
532/// read and written with them as context. `serialize` sets the flags from
533/// the options.
534#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
535#[deku(
536    endian = "endian",
537    ctx = "endian: deku::ctx::Endian, warhead_and_fuse_included: bool, quantity_and_rate_included: bool"
538)]
539pub struct LiveMunitionDescriptor {
540    pub munition_type: EntityType,
541    /// `None` means the munition's default warhead and fuse.
542    #[deku(cond = "warhead_and_fuse_included")]
543    pub warhead_and_fuse: Option<WarheadAndFuse>,
544    /// `None` means a single round: a quantity of one and a rate of zero
545    /// (§9.4.5.4).
546    #[deku(cond = "quantity_and_rate_included")]
547    pub quantity_and_rate: Option<QuantityAndRate>,
548}
549
550/// The warhead and fuse of a [`LiveMunitionDescriptor`]
551#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
552#[deku(
553    endian = "endian",
554    ctx = "endian: deku::ctx::Endian",
555    ctx_default = "deku::ctx::Endian::Big"
556)]
557pub struct WarheadAndFuse {
558    pub warhead: MunitionDescriptorWarhead,
559    pub fuse: MunitionDescriptorFuse,
560}
561
562/// The quantity and rate of a [`LiveMunitionDescriptor`]
563#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
564#[deku(
565    endian = "endian",
566    ctx = "endian: deku::ctx::Endian",
567    ctx_default = "deku::ctx::Endian::Big"
568)]
569pub struct QuantityAndRate {
570    pub quantity: u16,
571    pub rate: u16,
572}
573
574#[cfg(test)]
575#[allow(
576    clippy::float_cmp,
577    reason = "every value compared here is exactly representable"
578)]
579mod tests {
580    use super::*;
581
582    type Meters = FixedBinary16<3>;
583    type Fine = FixedBinary8<5>;
584
585    #[test]
586    fn converts_with_the_binary_point_from_the_type() {
587        assert_eq!(Meters::new(1.25).unwrap().to_raw(), 10);
588        assert_eq!(Meters::from_raw(10).to_f64(), 1.25);
589        assert_eq!(Fine::new(1.25).unwrap().to_raw(), 40);
590        assert_eq!(Fine::RESOLUTION, 1.0 / 32.0);
591    }
592
593    #[test]
594    fn rounds_to_the_nearest_step() {
595        assert_eq!(Meters::new(1.3).unwrap().to_f64(), 1.25);
596        assert_eq!(Meters::new(1.32).unwrap().to_f64(), 1.375);
597        assert_eq!(Meters::new(-0.0625).unwrap().to_f64(), -0.125); // ties round away from zero
598    }
599
600    #[test]
601    fn range_matches_the_integer_range() {
602        assert_eq!(Meters::MAX, 4095.875);
603        assert_eq!(Meters::MIN, -4096.0);
604        assert_eq!(Fine::MAX, 127.0 / 32.0);
605        assert!(Meters::new(Meters::MAX).is_some());
606        assert!(Meters::new(4096.0).is_none());
607        assert!(Meters::new(f64::NAN).is_none());
608        assert!(Meters::new(f64::INFINITY).is_none());
609    }
610
611    #[test]
612    fn saturating_clamps_and_maps_nan_to_zero() {
613        assert_eq!(Meters::saturating(1e9).to_f64(), Meters::MAX);
614        assert_eq!(Meters::saturating(-1e9).to_f64(), Meters::MIN);
615        assert_eq!(Meters::saturating(f64::NAN).to_raw(), 0);
616    }
617
618    #[test]
619    fn encodes_as_the_big_endian_integer() {
620        let mut buf = Vec::new();
621        crate::wire::write(&Meters::from_raw(-2), &mut buf).unwrap();
622        assert_eq!(buf, [0xFF, 0xFE]);
623        let back: Meters = crate::wire::read(&mut buf.as_slice()).unwrap();
624        assert_eq!(back.to_f64(), -0.25);
625    }
626}