boxcars 0.11.0

Rocket league replay parser
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
use crate::{bits::RlBits, network::attributes::Attribute};
use bitter::{BitReader, LittleEndianReader};
use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Vector3f {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl Vector3f {
    #[inline]
    pub fn decode(bits: &mut LittleEndianReader<'_>, net_version: i32) -> Option<Vector3f> {
        Vector3i::decode(bits, net_version).map(|vec| Vector3f {
            x: (vec.x as f32) / 100.0,
            y: (vec.y as f32) / 100.0,
            z: (vec.z as f32) / 100.0,
        })
    }
}

/// An object's current vector
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Vector3i {
    pub x: i32,
    pub y: i32,
    pub z: i32,
}

impl Vector3i {
    #[inline]
    pub fn decode(bits: &mut LittleEndianReader<'_>, net_version: i32) -> Option<Vector3i> {
        // Do we have enough data available to blindly refill the lookahead twice?
        // Note: this code doesn't actually use the unchecked bitter API as the
        // compiler was able to emit the same code with both as long as we
        // ensured there was 16 bytes left (even though a `Vector3i` will never
        // need that many bytes).
        if bits.unbuffered_bytes_remaining() >= 16 {
            bits.refill_lookahead();
            let size_bits = bits.peek_bits_max_computed(4, if net_version >= 7 { 22 } else { 20 });
            let bias = 1 << (size_bits + 1);
            let bit_limit = (size_bits + 2) as u32;
            let dx = bits.peek_and_consume(bit_limit) as u32;
            bits.refill_lookahead();
            let dy = bits.peek_and_consume(bit_limit) as u32;
            let dz = bits.peek_and_consume(bit_limit) as u32;
            Some(Vector3i {
                x: (dx as i32) - bias,
                y: (dy as i32) - bias,
                z: (dz as i32) - bias,
            })
        } else {
            Vector3i::eof_decode(bits, net_version)
        }
    }

    #[cold]
    pub fn eof_decode(bits: &mut LittleEndianReader<'_>, net_version: i32) -> Option<Vector3i> {
        bits.refill_lookahead();
        if bits.lookahead_bits() < 5 {
            return None;
        }

        let size_bits = bits.peek_bits_max_computed(4, if net_version >= 7 { 22 } else { 20 });
        let bias = 1 << (size_bits + 1);
        let bit_limit = (size_bits + 2) as u32;

        if !bits.has_bits_remaining(3 * bit_limit as usize) {
            return None;
        }

        let dx = bits.peek_and_consume(bit_limit) as u32;

        bits.refill_lookahead();
        debug_assert!(bits.lookahead_bits() >= bit_limit * 2);

        let dy = bits.peek_and_consume(bit_limit) as u32;
        let dz = bits.peek_and_consume(bit_limit) as u32;
        Some(Vector3i {
            x: (dx as i32) - bias,
            y: (dy as i32) - bias,
            z: (dz as i32) - bias,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Quaternion {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub w: f32,
}

impl Quaternion {
    #[inline]
    fn unpack(val: u32) -> f32 {
        let max_value = (1 << 18) - 1;
        let pos_range = (val as f32) / (max_value as f32);
        let range = (pos_range - 0.5) * 2.0;
        range * std::f32::consts::FRAC_1_SQRT_2
    }

    #[inline]
    fn compressed_f32(bits: &mut LittleEndianReader<'_>) -> f32 {
        // algorithm from jjbott/RocketLeagueReplayParser.
        // Note that this code is heavily adapted. I noticed that there were branches that should
        // never execute. Specifically in jjbott implementation:
        //
        // ```
        // br.ReadFixedCompressedFloat(1, 16);
        // ```
        //
        // These values are hardcoded and this function is only used in one place. There's a branch
        // that compares these two hard coded numbers. I've removed said branch from this
        // implementation.
        //
        // Bakkes copied jjbott. Rattletrap is more in line here
        let res = bits.peek_and_consume(16) as i32;
        ((res + i32::from(i16::MIN)) as f32) * (i16::MAX as f32).recip()
    }

    pub fn decode_compressed(bits: &mut LittleEndianReader<'_>) -> Option<Self> {
        bits.refill_lookahead();
        if bits.lookahead_bits() >= 3 * 16 {
            let x = Quaternion::compressed_f32(bits);
            let y = Quaternion::compressed_f32(bits);
            let z = Quaternion::compressed_f32(bits);
            Some(Quaternion { x, y, z, w: 0.0 })
        } else {
            None
        }
    }

    pub fn decode(bits: &mut LittleEndianReader<'_>) -> Option<Self> {
        bits.refill_lookahead();
        if bits.lookahead_bits() < 2 + 3 * 18 {
            return None;
        }

        let largest = bits.peek_and_consume(2) as u32;
        let a = Quaternion::unpack(bits.peek_and_consume(18) as u32);
        let b = Quaternion::unpack(bits.peek_and_consume(18) as u32);
        let c = Quaternion::unpack(bits.peek_and_consume(18) as u32);
        let extra = (c.mul_add(-c, b.mul_add(-b, a.mul_add(-a, 1.0)))).sqrt();
        match largest {
            0 => Some(Quaternion {
                x: extra,
                y: a,
                z: b,
                w: c,
            }),
            1 => Some(Quaternion {
                x: a,
                y: extra,
                z: b,
                w: c,
            }),
            2 => Some(Quaternion {
                x: a,
                y: b,
                z: extra,
                w: c,
            }),
            3 => Some(Quaternion {
                x: a,
                y: b,
                z: c,
                w: extra,
            }),
            _ => unreachable!(),
        }
    }
}

/// An object's current rotation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Rotation {
    pub yaw: Option<i8>,
    pub pitch: Option<i8>,
    pub roll: Option<i8>,
}

impl Rotation {
    pub fn decode(bits: &mut LittleEndianReader<'_>) -> Option<Rotation> {
        bits.refill_lookahead();
        if bits.lookahead_bits() >= 3 * 9 {
            let has_yaw = bits.peek_and_consume(1);
            let yaw = bits.peek_and_consume((has_yaw << 3) as u32) as i8;
            let has_pitch = bits.peek_and_consume(1);
            let pitch = bits.peek_and_consume((has_pitch << 3) as u32) as i8;
            let has_roll = bits.peek_and_consume(1);
            let roll = bits.peek_and_consume((has_roll << 3) as u32) as i8;
            Some(Rotation {
                yaw: if has_yaw != 0 { Some(yaw) } else { None },
                pitch: if has_pitch != 0 { Some(pitch) } else { None },
                roll: if has_roll != 0 { Some(roll) } else { None },
            })
        } else {
            let yaw = bits.if_get(LittleEndianReader::read_i8)?;
            let pitch = bits.if_get(LittleEndianReader::read_i8)?;
            let roll = bits.if_get(LittleEndianReader::read_i8)?;
            Some(Rotation { yaw, pitch, roll })
        }
    }
}

/// When a new actor spawns in rocket league it will either have a location, location and rotation,
/// or none of the above
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpawnTrajectory {
    None,
    Location,
    LocationAndRotation,
}

/// Notifies that an actor has had one of their properties updated (most likely their rigid body
/// state (location / rotation) has changed)
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct UpdatedAttribute {
    /// The actor that had an attribute updated
    pub actor_id: ActorId,

    /// The attribute stream id that was decoded
    pub stream_id: StreamId,

    /// The attribute's object id
    pub object_id: ObjectId,

    /// The actual data from the decoded attribute
    pub attribute: Attribute,
}

/// Contains the time and any new information that occurred during a frame
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Frame {
    /// The time in seconds that the frame is recorded at
    pub time: f32,

    /// Time difference between previous frame
    pub delta: f32,

    /// List of new actors seen during the frame
    pub new_actors: Vec<NewActor>,

    /// List of actor id's that are deleted / destroyed
    pub deleted_actors: Vec<ActorId>,

    /// List of properties updated on the actors
    pub updated_actors: Vec<UpdatedAttribute>,
}

/// A replay encodes a list of objects that appear in the network data. The index of an object in
/// this list is used as a key in many places: reconstructing the attribute hierarchy and new
/// actors in the network data.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Serialize, Default)]
pub struct ObjectId(pub i32);

impl From<ObjectId> for i32 {
    fn from(x: ObjectId) -> i32 {
        x.0
    }
}

impl From<ObjectId> for usize {
    fn from(x: ObjectId) -> usize {
        x.0 as usize
    }
}

impl fmt::Display for ObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A `StreamId` is an attribute's object id in the network data. It is a more compressed form of
/// the object id. Whereas the an object id might need to take up 9 bits, a stream id may only take
/// up 6 bits.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Serialize)]
pub struct StreamId(pub i32);

impl From<StreamId> for i32 {
    fn from(x: StreamId) -> i32 {
        x.0
    }
}

impl From<StreamId> for usize {
    fn from(val: StreamId) -> Self {
        val.0 as usize
    }
}

impl fmt::Display for StreamId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// An actor in the network data stream. Could identify a ball, car, etc. Ids are not unique
/// across a replay (eg. an actor that is destroyed may have its id repurposed).
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash, Serialize)]
pub struct ActorId(pub i32);

impl From<ActorId> for i32 {
    fn from(x: ActorId) -> i32 {
        x.0
    }
}

impl From<ActorId> for usize {
    fn from(val: ActorId) -> Self {
        val.0 as usize
    }
}

impl fmt::Display for ActorId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Information for a new actor that appears in the game
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct NewActor {
    /// The id given to the new actor
    pub actor_id: ActorId,

    /// An name id
    pub name_id: Option<i32>,

    /// The actor's object id.
    pub object_id: ObjectId,

    /// The initial trajectory of the new actor
    pub initial_trajectory: Trajectory,
}

/// Contains the optional location and rotation of an object when it spawns
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Trajectory {
    pub location: Option<Vector3i>,
    pub rotation: Option<Rotation>,
}

impl Trajectory {
    pub fn from_spawn(
        bits: &mut LittleEndianReader<'_>,
        sp: SpawnTrajectory,
        net_version: i32,
    ) -> Option<Trajectory> {
        match sp {
            SpawnTrajectory::None => Some(Trajectory {
                location: None,
                rotation: None,
            }),

            SpawnTrajectory::Location => Vector3i::decode(bits, net_version).map(|v| Trajectory {
                location: Some(v),
                rotation: None,
            }),

            SpawnTrajectory::LocationAndRotation => {
                let v = Vector3i::decode(bits, net_version)?;
                let r = Rotation::decode(bits)?;
                Some(Trajectory {
                    location: Some(v),
                    rotation: Some(r),
                })
            }
        }
    }
}

/// Oftentimes a replay contains many different objects of the same type. For instance, each rumble
/// pickup item is of the same type but has a different name. The name of:
/// `stadium_foggy_p.TheWorld:PersistentLevel.VehiclePickup_Boost_TA_30` should be normalized to
/// `TheWorld:PersistentLevel.VehiclePickup_Boost_TA` so that we don't have to work around each
/// stadium and pickup that is released.
pub(crate) fn normalize_object(name: &str) -> &str {
    const PREFIX: &str = "TheWorld:PersistentLevel.";
    if name.len() <= "TheWorld:PersistentLevel.CrowdActor_TA".len() {
        return name;
    }

    // Fast path: name starts directly with the prefix (no stadium prefix).
    // Slow path: name has a stadium prefix ending with '.', e.g. "stadium_p.TheWorld:..."
    let Some(rest) = name.strip_prefix(PREFIX).or_else(|| {
        name.split_once('.')
            .and_then(|(_, suffix)| suffix.strip_prefix(PREFIX))
    }) else {
        return name;
    };

    if rest.starts_with("CrowdActor_TA") {
        "TheWorld:PersistentLevel.CrowdActor_TA"
    } else if rest.starts_with("CrowdManager_TA") {
        "TheWorld:PersistentLevel.CrowdManager_TA"
    } else if rest.starts_with("VehiclePickup_Boost_TA") {
        "TheWorld:PersistentLevel.VehiclePickup_Boost_TA"
    } else if rest.starts_with("InMapScoreboard_TA") {
        "TheWorld:PersistentLevel.InMapScoreboard_TA"
    } else if rest.starts_with("BreakOutActor_Platform_TA") {
        "TheWorld:PersistentLevel.BreakOutActor_Platform_TA"
    } else if rest.starts_with("PlayerStart_Platform_TA") {
        "TheWorld:PersistentLevel.PlayerStart_Platform_TA"
    } else {
        name
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_decode_vector() {
        let mut bitter =
            LittleEndianReader::new(&[0b0000_0110, 0b0000_1000, 0b1101_1000, 0b0000_1101]);
        let v = Vector3i::decode(&mut bitter, 5).unwrap();
        assert_eq!(v, Vector3i { x: 0, y: 0, z: 93 });
    }

    #[test]
    fn test_decode_rotation() {
        let mut bitter = LittleEndianReader::new(&[0b0000_0101, 0b0000_0000]);
        let v = Rotation::decode(&mut bitter).unwrap();
        assert_eq!(
            v,
            Rotation {
                yaw: Some(2),
                pitch: None,
                roll: None,
            }
        );
    }
}