nimble_protocol/
serialize.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/nimble-rust/nimble
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5
6use crate::host_to_client::TickIdUtil;
7use flood_rs::{Deserialize, ReadOctetStream, Serialize, WriteOctetStream};
8use nimble_participant::ParticipantId;
9use nimble_step_map::StepMap;
10use seq_map::SeqMap;
11use std::collections::HashSet;
12use std::fmt::{Debug, Display, Formatter};
13use std::io;
14use tick_id::TickId;
15
16#[derive(Debug, Clone, Eq, PartialEq)]
17pub struct CombinedSteps<StepT: Deserialize + Serialize + Debug + Clone + Display> {
18    pub tick_id: TickId,
19    pub steps: Vec<StepMap<StepT>>,
20}
21
22impl<StepT: Deserialize + Serialize + Debug + Clone + Display> Display for CombinedSteps<StepT> {
23    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
24        write!(f, "[{} step_count:{}]", self.tick_id, self.steps.len())
25    }
26}
27
28impl<StepT: Deserialize + Serialize + Debug + Clone + Display> Serialize for CombinedSteps<StepT> {
29    fn serialize(&self, stream: &mut impl WriteOctetStream) -> io::Result<()> {
30        TickIdUtil::to_stream(self.tick_id, stream)?;
31        self.to_internal().serialize(stream)
32    }
33}
34
35impl<StepT: Deserialize + Serialize + Debug + Clone + Display> Deserialize
36    for CombinedSteps<StepT>
37{
38    fn deserialize(stream: &mut impl ReadOctetStream) -> io::Result<Self> {
39        let start_tick_id = TickIdUtil::from_stream(stream)?;
40        let internal = InternalAllParticipantVectors::deserialize(stream)?;
41        Ok(Self::from_internal(&internal, start_tick_id))
42    }
43}
44
45impl<StepT: Deserialize + Serialize + Debug + Clone + Display> CombinedSteps<StepT> {
46    #[must_use]
47    pub fn to_internal(&self) -> InternalAllParticipantVectors<StepT> {
48        let mut hash_map = StepMap::<InternalStepVectorForOneParticipant<StepT>>::new();
49
50        let mut unique_participant_ids: HashSet<ParticipantId> = HashSet::new();
51
52        for auth_step in &self.steps {
53            for key in auth_step.keys() {
54                unique_participant_ids.insert(*key);
55            }
56        }
57
58        let mut sorted_unique_ids: Vec<ParticipantId> =
59            unique_participant_ids.into_iter().collect();
60        sorted_unique_ids.sort();
61
62        for participant_id in sorted_unique_ids {
63            hash_map
64                .insert(
65                    participant_id,
66                    InternalStepVectorForOneParticipant::<StepT> {
67                        delta_tick_id: 0,
68                        steps: vec![],
69                    },
70                )
71                .expect("participant ids to be unique");
72        }
73
74        for (index_in_range, combined_auth_step) in self.steps.iter().enumerate() {
75            for (participant_id, auth_step_for_one_player) in combined_auth_step {
76                let vector_for_one_person = hash_map.get_mut(participant_id).unwrap();
77                if vector_for_one_person.steps.is_empty() {
78                    vector_for_one_person.delta_tick_id = index_in_range as u8;
79                }
80                vector_for_one_person
81                    .steps
82                    .push(auth_step_for_one_player.clone());
83            }
84        }
85
86        InternalAllParticipantVectors::<StepT> {
87            participant_step_vectors: hash_map,
88        }
89    }
90
91    #[must_use]
92    pub fn from_internal(
93        separate_vectors: &InternalAllParticipantVectors<StepT>,
94        start_tick_id: TickId,
95    ) -> Self {
96        let mut max_vector_length = 0;
97
98        for serialized_step_vector in separate_vectors.participant_step_vectors.values() {
99            if serialized_step_vector.steps.len() > max_vector_length {
100                max_vector_length = serialized_step_vector.steps.len();
101            }
102        }
103
104        let mut auth_step_range_vec = Vec::<StepMap<StepT>>::new();
105        for _ in 0..max_vector_length {
106            auth_step_range_vec.push(SeqMap::new());
107        }
108
109        for (participant_id, serialized_step_vector) in &separate_vectors.participant_step_vectors {
110            for (index, serialized_step) in serialized_step_vector.steps.iter().enumerate() {
111                let hash_map_for_auth_step = auth_step_range_vec.get_mut(index).unwrap();
112                hash_map_for_auth_step
113                    .insert(*participant_id, serialized_step.clone())
114                    .expect("expect unique participant_id");
115            }
116        }
117
118        Self {
119            tick_id: start_tick_id,
120            steps: auth_step_range_vec,
121        }
122    }
123}
124
125#[derive(Debug, PartialEq, Eq, Clone)]
126pub struct InternalStepVectorForOneParticipant<StepT: Serialize + Deserialize> {
127    pub delta_tick_id: u8, // enables one vector to start at a later tick_id than the others
128    pub steps: Vec<StepT>,
129}
130
131impl<StepT: Serialize + Deserialize + Display> Display
132    for InternalStepVectorForOneParticipant<StepT>
133{
134    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
135        write!(
136            f,
137            "delta_tick {} step_count:{}",
138            self.delta_tick_id,
139            self.steps.len()
140        )
141    }
142}
143
144#[derive(Debug, PartialEq, Eq, Clone)]
145pub struct InternalAllParticipantVectors<StepT: Serialize + Deserialize + Display> {
146    pub participant_step_vectors: SeqMap<ParticipantId, InternalStepVectorForOneParticipant<StepT>>,
147}
148
149impl<StepT: Serialize + Deserialize + Debug + Display> InternalAllParticipantVectors<StepT> {
150    pub fn serialize(&self, stream: &mut impl WriteOctetStream) -> io::Result<()>
151    where
152        Self: Sized,
153    {
154        // How many participants streams follows
155        stream.write_u8(self.participant_step_vectors.len() as u8)?;
156
157        for (participant_id, authoritative_steps_for_one_player_vector) in
158            &self.participant_step_vectors
159        {
160            participant_id.serialize(stream)?;
161            stream.write_u8(authoritative_steps_for_one_player_vector.delta_tick_id)?;
162            stream.write_u8(authoritative_steps_for_one_player_vector.steps.len() as u8)?;
163
164            for authoritative_step_for_one_player in
165                &authoritative_steps_for_one_player_vector.steps
166            {
167                authoritative_step_for_one_player.serialize(stream)?;
168            }
169        }
170        Ok(())
171    }
172
173    pub fn deserialize(stream: &mut impl ReadOctetStream) -> io::Result<Self> {
174        let required_participant_count_in_range = stream.read_u8()?;
175        let mut authoritative_participants = SeqMap::new();
176        for _ in 0..required_participant_count_in_range {
177            let participant_id = ParticipantId::deserialize(stream)?;
178            let delta_tick_id_from_range = stream.read_u8()?;
179            let number_of_steps_that_follows = stream.read_u8()? as usize;
180
181            let mut authoritative_steps_for_one_participant =
182                Vec::with_capacity(number_of_steps_that_follows);
183
184            for _ in 0..number_of_steps_that_follows {
185                let authoritative_step = StepT::deserialize(stream)?;
186                authoritative_steps_for_one_participant.push(authoritative_step);
187            }
188
189            authoritative_participants
190                .insert(
191                    participant_id,
192                    InternalStepVectorForOneParticipant {
193                        delta_tick_id: delta_tick_id_from_range,
194                        steps: authoritative_steps_for_one_participant,
195                    },
196                )
197                .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
198        }
199
200        Ok(Self {
201            participant_step_vectors: authoritative_participants,
202        })
203    }
204}
205
206// ----
207
208#[derive(Debug)]
209pub struct InternalAuthoritativeStepRange<StepT: Deserialize + Serialize + Debug + Clone + Display>
210{
211    pub delta_tick_id_from_previous: u8,
212    pub authoritative_steps: InternalAllParticipantVectors<StepT>,
213}