wows_replays 0.14.0

A parser for World of Warships replay 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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use kinded::Kinded;
use nom::{
    bytes::complete::take, number::complete::le_f32, number::complete::le_i32,
    number::complete::le_i64, number::complete::le_u8, number::complete::le_u16,
    number::complete::le_u32,
};

use serde::Serialize;
use std::collections::HashMap;
use std::convert::TryInto;

use crate::error::*;
use crate::types::{EntityId, GameClock, GameParamId};
use wowsunpack::rpc::entitydefs::*;
use wowsunpack::rpc::typedefs::ArgValue;

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

impl Vec3 {
    pub fn parse(i: &[u8]) -> IResult<&[u8], Self> {
        let (i, x) = le_f32(i)?;
        let (i, y) = le_f32(i)?;
        let (i, z) = le_f32(i)?;
        Ok((i, Vec3 { x, y, z }))
    }
}

#[derive(Debug, Serialize, Clone)]
pub struct Rot3 {
    pub roll: f32,
    pub pitch: f32,
    pub yaw: f32,
}

impl Rot3 {
    pub fn parse(i: &[u8]) -> IResult<&[u8], Self> {
        let (i, roll) = le_f32(i)?;
        let (i, pitch) = le_f32(i)?;
        let (i, yaw) = le_f32(i)?;
        Ok((i, Rot3 { roll, pitch, yaw }))
    }
}

#[derive(Debug, Serialize, Clone)]
pub struct PositionPacket {
    pub pid: EntityId,
    pub position: Vec3,
    pub position_error: Vec3,
    pub rotation: Rot3,
    pub is_error: bool,
}

#[derive(Debug, Serialize)]
pub struct EntityPacket<'replay> {
    pub supertype: u32,
    pub entity_id: EntityId,
    pub subtype: u32,
    pub payload: &'replay [u8],
}

#[derive(Debug, Serialize)]
pub struct EntityPropertyPacket<'argtype> {
    pub entity_id: EntityId,
    pub property: &'argtype str,
    pub value: ArgValue<'argtype>,
}

#[derive(Debug, Serialize)]
pub struct EntityMethodPacket<'argtype> {
    pub entity_id: EntityId,
    pub method: &'argtype str,
    pub args: Vec<ArgValue<'argtype>>,
}

#[derive(Debug, Serialize)]
pub struct EntityCreatePacket<'argtype> {
    pub entity_id: EntityId,
    pub spec_idx: usize,
    pub entity_type: &'argtype str,
    pub space_id: u32,
    pub vehicle_id: GameParamId,
    pub position: Vec3,
    pub rotation: Rot3,
    pub state_length: u32,
    pub props: HashMap<&'argtype str, ArgValue<'argtype>>,
}

/// Note that this packet frequently appears twice - it appears that it
/// describes both the player's boat location/orientation as well as the
/// camera orientation. When the camera is attached to an object, the ID of
/// that object will be given in the parent_id field.
#[derive(Debug, Serialize, Clone)]
pub struct PlayerOrientationPacket {
    pub pid: EntityId,
    pub parent_id: EntityId,
    pub position: Vec3,
    pub rotation: Rot3,
}

#[derive(Debug, Serialize)]
pub struct InvalidPacket<'a> {
    message: String,
    raw: &'a [u8],
}

#[derive(Debug, Serialize)]
pub struct BasePlayerCreatePacket<'argtype> {
    pub entity_id: EntityId,
    pub entity_type: &'argtype str,
    pub props: HashMap<&'argtype str, ArgValue<'argtype>>,
}

#[derive(Debug, Serialize)]
pub struct CellPlayerCreatePacket<'argtype> {
    pub entity_id: EntityId,
    pub entity_type: &'argtype str,
    pub space_id: u32,
    pub unknown: u16,
    pub vehicle_id: GameParamId,
    pub position: Vec3,
    pub rotation: Rot3,
    pub props: HashMap<&'argtype str, ArgValue<'argtype>>,
}

#[derive(Debug, Serialize)]
pub struct EntityLeavePacket {
    pub entity_id: EntityId,
}

#[derive(Debug, Serialize)]
pub struct EntityEnterPacket {
    pub entity_id: EntityId,
    pub space_id: u32,
    pub vehicle_id: GameParamId,
}

#[derive(Debug, Serialize)]
pub struct PropertyUpdatePacket<'argtype> {
    /// Indicates the entity to update the property on
    pub entity_id: EntityId,
    /// Indicates the property to update. Note that some properties have many
    /// sub-properties.
    pub property: &'argtype str,
    /// Indicates the update command to perform.
    pub update_cmd: crate::nested_property_path::PropertyNesting<'argtype>,
}

#[derive(Debug, Serialize)]
pub struct CameraPacket {
    pub unknown: Vec3,
    pub unknown2: u32,
    pub absolute_position: Vec3,
    pub fov: f32,
    pub position: Vec3,
    pub rotation: Rot3,
}

#[derive(Debug, Serialize)]
pub struct CruiseState {
    pub key: u32,
    pub value: i32,
}

// ============================================================================
// The following packet types were identified through AI-assisted analysis of
// raw replay data. Their structure and semantics are best-effort
// interpretations and may not be 100% accurate. Field names and purposes are
// inferred from observed patterns across replays.
// ============================================================================

/// Packet 0x02: Believed to be EntityControl — transfers entity ownership to
/// the client. Confirmed by the Python reference parser's PACKETS_MAPPING.
#[derive(Debug, Serialize)]
pub struct EntityControlPacket {
    pub entity_id: EntityId,
    pub is_controlled: bool,
}

/// Packet 0x2a: Believed to be a SmokeScreen position drift update (wind).
/// The entity IDs observed are exclusively SmokeScreen entities, and the two
/// non-zero floats closely track the EntityCreate position with gradual drift
/// over the entity's lifetime.
#[derive(Debug, Serialize)]
pub struct SmokeScreenDriftPacket {
    pub entity_id: EntityId,
    /// Believed to be the updated world-space X/Z position of the smoke cloud.
    pub position: Vec3,
    pub unknown: [f32; 4],
}

/// Packet 0x1d: Believed to be a packed player view direction. Fires at ~10Hz,
/// same count as Camera (0x25) packets. Two bytes: one appears to encode
/// heading, the other pitch.
#[derive(Debug, Serialize)]
pub struct ViewDirectionPacket {
    pub heading: u8,
    pub pitch: u8,
}

/// Packet 0x0f: Believed to be a server timestamp. Single f64 at clock=0.
#[derive(Debug, Serialize)]
pub struct ServerTimestampPacket {
    pub timestamp: f64,
}

/// Packet 0x20: Believed to link the Avatar to its owned ship entity. The
/// entity ID observed matches the Avatar's `ownShipId` property.
#[derive(Debug, Serialize)]
pub struct OwnShipPacket {
    pub entity_id: EntityId,
}

/// Packet 0x30: References a vehicle entity mid-game. Purpose not fully
/// understood — observed to reference vehicles that die later in the match.
#[derive(Debug, Serialize)]
pub struct VehicleRefPacket {
    pub unknown1: u32,
    pub entity_id: EntityId,
    pub unknown2: u32,
}

#[derive(Debug, Serialize)]
pub struct MapPacket<'replay> {
    pub space_id: u32,
    pub arena_id: i64,
    pub unknown1: u32,
    pub unknown2: u32,
    pub blob: &'replay [u8],
    pub map_name: &'replay str,
    /// Note: We suspect that this matrix is always the unit matrix, hence
    /// we don't spend the computation to parse it.
    pub matrix: &'replay [u8],
    pub unknown: u8, // bool?
}

#[derive(Debug, Serialize, Kinded)]
pub enum PacketType<'replay, 'argtype> {
    Position(PositionPacket),
    BasePlayerCreate(BasePlayerCreatePacket<'argtype>),
    CellPlayerCreate(CellPlayerCreatePacket<'argtype>),
    EntityEnter(EntityEnterPacket),
    EntityLeave(EntityLeavePacket),
    EntityCreate(EntityCreatePacket<'argtype>),
    EntityProperty(EntityPropertyPacket<'argtype>),
    EntityMethod(EntityMethodPacket<'argtype>),
    PropertyUpdate(PropertyUpdatePacket<'argtype>),
    PlayerOrientation(PlayerOrientationPacket),
    CruiseState(CruiseState),
    Version(String),
    Camera(CameraPacket),
    CameraMode(u32),
    CameraFreeLook(u8),
    Map(MapPacket<'replay>),
    BattleResults(&'replay str),
    // The following variants were identified through AI-assisted replay analysis.
    // Their semantics are best-effort interpretations.
    EntityControl(EntityControlPacket),
    SmokeScreenDrift(SmokeScreenDriftPacket),
    ViewDirection(ViewDirectionPacket),
    ServerTimestamp(ServerTimestampPacket),
    OwnShip(OwnShipPacket),
    VehicleRef(VehicleRefPacket),
    /// Packet 0x0e: Believed to be a server tick rate constant (always 1/7).
    ServerTick(f64),
    Unknown(&'replay [u8]),

    /// These are packets which we thought we understood, but couldn't parse
    Invalid(InvalidPacket<'replay>),
}

#[derive(Debug, Serialize)]
pub struct Packet<'replay, 'argtype> {
    pub packet_size: u32,
    pub packet_type: u32,
    pub clock: GameClock,
    pub payload: PacketType<'replay, 'argtype>,
    pub raw: &'replay [u8],
}

#[derive(Debug)]
pub struct Entity<'argtype> {
    entity_type: u16,
    properties: Vec<ArgValue<'argtype>>,
}

pub struct Parser<'argtype> {
    specs: &'argtype [EntitySpec],
    entities: HashMap<u32, Entity<'argtype>>,
}

impl<'argtype> Parser<'argtype> {
    pub fn new(entities: &'argtype [EntitySpec]) -> Parser<'argtype> {
        Parser {
            specs: entities,
            entities: HashMap::new(),
        }
    }

    fn parse_entity_property_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'argtype>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, prop_id) = le_u32(i)?;
        let (i, payload_length) = le_u32(i)?;
        let (i, payload) = take(payload_length)(i)?;

        let entity_type = self.entities.get(&entity_id).unwrap().entity_type;
        let spec = &self.specs[entity_type as usize - 1].properties[prop_id as usize];

        let (_, pval) = spec.prop_type.parse_value(payload).unwrap();

        Ok((
            i,
            PacketType::EntityProperty(EntityPropertyPacket {
                entity_id: entity_id.into(),
                property: &spec.name,
                value: pval,
            }),
        ))
    }

    fn parse_entity_method_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, method_id) = le_u32(i)?;
        let (i, payload_length) = le_u32(i)?;
        let (i, payload) = take(payload_length)(i)?;
        assert!(i.is_empty());

        let entity_type = self.entities.get(&entity_id).unwrap().entity_type;

        let methods = &self.specs[entity_type as usize - 1].client_methods;
        if method_id as usize >= methods.len() {
            return Ok((
                i,
                PacketType::Invalid(InvalidPacket {
                    message: format!(
                        "method_id {} out of bounds for entity type {} (has {} methods)",
                        method_id,
                        entity_type,
                        methods.len()
                    ),
                    raw: payload,
                }),
            ));
        }
        let spec = &methods[method_id as usize];

        let mut i = payload;
        let mut args = vec![];
        for (idx, arg) in spec.args.iter().enumerate() {
            let (new_i, pval) = match arg.parse_value(i) {
                Ok(x) => x,
                Err(e) => {
                    return Err(failure_from_kind(crate::ErrorKind::UnableToParseRpcValue {
                        method: spec.name.to_string(),
                        argnum: idx,
                        argtype: format!("{:?}", arg),
                        packet: i.to_vec(),
                        error: format!("{:?}", e),
                    }));
                }
            };
            args.push(pval);
            i = new_i;
        }

        Ok((
            i,
            PacketType::EntityMethod(EntityMethodPacket {
                entity_id: entity_id.into(),
                method: &spec.name,
                args,
            }),
        ))
    }

    fn parse_battle_results<'replay, 'b>(
        &'b mut self,
        i: &'replay [u8],
    ) -> IResult<&'replay [u8], PacketType<'replay, 'argtype>> {
        let (i, len) = le_u32(i)?;
        assert_eq!(len as usize, i.len());
        let (i, battle_results) = take(len)(i)?;

        let results = std::str::from_utf8(battle_results).map_err(|_| {
            failure_from_kind(crate::ErrorKind::ParsingFailure(
                "Invalid UTF-8 data in battle results".to_string(),
            ))
        })?;

        Ok((i, PacketType::BattleResults(results)))
    }

    fn parse_nested_property_update<'replay, 'b>(
        &'b mut self,
        i: &'replay [u8],
    ) -> IResult<&'replay [u8], PacketType<'replay, 'argtype>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, is_slice) = le_u8(i)?;
        let (i, payload_size) = le_u8(i)?;
        let (i, unknown) = take(3usize)(i)?;
        assert_eq!(unknown, [0, 0, 0]); // Note: This is almost certainly the upper 3 bytes of a u32
        let payload = i;
        assert_eq!(payload_size as usize, payload.len());

        let entity = self.entities.get_mut(&entity_id).unwrap();
        let entity_type = entity.entity_type;

        let spec = &self.specs[entity_type as usize - 1];

        assert!(is_slice & 0xFE == 0);

        let mut reader = bitreader::BitReader::new(payload);
        let cont = reader.read_u8(1).unwrap();
        assert!(cont == 1);
        let prop_idx = reader
            .read_u8(spec.properties.len().next_power_of_two().trailing_zeros() as u8)
            .unwrap();
        if prop_idx as usize >= entity.properties.len() {
            // This is almost certainly a nested property set on the player avatar.
            // Currently, we assume that all properties are created when the entity is
            // created. However, apparently the properties can go un-initialized at the
            // beginning, and then later get created by a nested property update.
            //
            // We should do two things:
            // - Store the entity's properties as a HashMap
            // - Separate finding the path from updating the property value, and then here
            //   we can create the entry if the property hasn't been created yet.
            return Err(failure_from_kind(
                crate::ErrorKind::UnsupportedInternalPropSet {
                    entity_id,
                    entity_type: spec.name.clone(),
                    payload: payload.to_vec(),
                },
            ));
        }

        let update_cmd = crate::nested_property_path::get_nested_prop_path_helper(
            is_slice & 0x1 == 1,
            &spec.properties[prop_idx as usize].prop_type,
            &mut entity.properties[prop_idx as usize],
            reader,
        );

        Ok((
            i,
            PacketType::PropertyUpdate(PropertyUpdatePacket {
                entity_id: entity_id.into(),
                update_cmd,
                property: &spec.properties[prop_idx as usize].name,
            }),
        ))
    }

    fn parse_version_packet<'replay, 'b>(
        &'b self,
        i: &'replay [u8],
    ) -> IResult<&'replay [u8], PacketType<'replay, 'argtype>> {
        let (i, len) = le_u32(i)?;
        let (i, data) = take(len)(i)?;
        Ok((
            i,
            PacketType::Version(std::str::from_utf8(data).unwrap().to_string()),
        ))
    }

    fn parse_camera_mode_packet<'replay, 'b>(
        &'b self,
        i: &'replay [u8],
    ) -> IResult<&'replay [u8], PacketType<'replay, 'argtype>> {
        let (i, mode) = le_u32(i)?;
        Ok((i, PacketType::CameraMode(mode)))
    }

    fn parse_camera_freelook_packet<'replay, 'b>(
        &'b self,
        i: &'replay [u8],
    ) -> IResult<&'replay [u8], PacketType<'replay, 'argtype>> {
        let (i, freelook) = le_u8(i)?;
        Ok((i, PacketType::CameraFreeLook(freelook)))
    }

    fn parse_position_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, pid) = le_u32(i)?;
        let (i, zero) = le_u32(i)?;
        if zero != 0 {
            panic!("What does this field mean?");
        }
        let (i, position) = Vec3::parse(i)?;
        let (i, position_error) = Vec3::parse(i)?;
        let (i, rotation) = Rot3::parse(i)?;
        let (i, is_error_byte) = le_u8(i)?;
        let is_error = is_error_byte != 0;
        Ok((
            i,
            PacketType::Position(PositionPacket {
                pid: pid.into(),
                position,
                position_error,
                rotation,
                is_error,
            }),
        ))
    }

    fn parse_player_orientation_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        assert!(i.len() == 0x20);
        let (i, pid) = le_u32(i)?;
        let (i, parent_id) = le_u32(i)?;
        let (i, position) = Vec3::parse(i)?;
        let (i, rotation) = Rot3::parse(i)?;
        Ok((
            i,
            PacketType::PlayerOrientation(PlayerOrientationPacket {
                pid: pid.into(),
                parent_id: parent_id.into(),
                position,
                rotation,
            }),
        ))
    }

    fn parse_camera_packet<'a, 'b>(&'b self, i: &'a [u8]) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, unknown) = Vec3::parse(i)?;
        let (i, unknown2) = le_u32(i)?;
        let (i, absolute_position) = Vec3::parse(i)?;
        let (i, fov) = le_f32(i)?;
        let (i, position) = Vec3::parse(i)?;
        let (i, rotation) = Rot3::parse(i)?;
        Ok((
            i,
            PacketType::Camera(CameraPacket {
                unknown,
                unknown2,
                absolute_position,
                fov,
                position,
                rotation,
            }),
        ))
    }

    fn parse_entity_control_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, is_controlled) = le_u8(i)?;
        Ok((
            i,
            PacketType::EntityControl(EntityControlPacket {
                entity_id: entity_id.into(),
                is_controlled: is_controlled != 0,
            }),
        ))
    }

    fn parse_smoke_screen_drift_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, f0) = le_f32(i)?;
        let (i, x) = le_f32(i)?;
        let (i, f2) = le_f32(i)?;
        let (i, z) = le_f32(i)?;
        let (i, f4) = le_f32(i)?;
        let (i, f5) = le_f32(i)?;
        let (i, _f6) = le_f32(i)?;
        Ok((
            i,
            PacketType::SmokeScreenDrift(SmokeScreenDriftPacket {
                entity_id: entity_id.into(),
                position: Vec3 { x, y: 0.0, z },
                unknown: [f0, f2, f4, f5],
            }),
        ))
    }

    fn parse_view_direction_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, heading) = le_u8(i)?;
        let (i, pitch) = le_u8(i)?;
        Ok((
            i,
            PacketType::ViewDirection(ViewDirectionPacket { heading, pitch }),
        ))
    }

    fn parse_server_timestamp_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        use nom::number::complete::le_f64;
        let (i, timestamp) = le_f64(i)?;
        Ok((
            i,
            PacketType::ServerTimestamp(ServerTimestampPacket { timestamp }),
        ))
    }

    fn parse_server_tick_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        use nom::number::complete::le_f64;
        let (i, tick_rate) = le_f64(i)?;
        Ok((i, PacketType::ServerTick(tick_rate)))
    }

    fn parse_own_ship_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        Ok((
            i,
            PacketType::OwnShip(OwnShipPacket {
                entity_id: entity_id.into(),
            }),
        ))
    }

    fn parse_vehicle_ref_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, unknown1) = le_u32(i)?;
        let (i, entity_id) = le_u32(i)?;
        let (i, unknown2) = le_u32(i)?;
        Ok((
            i,
            PacketType::VehicleRef(VehicleRefPacket {
                unknown1,
                entity_id: entity_id.into(),
                unknown2,
            }),
        ))
    }

    fn parse_unknown_packet<'a, 'b>(
        &'b self,
        i: &'a [u8],
        payload_size: u32,
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, contents) = take(payload_size)(i)?;
        Ok((i, PacketType::Unknown(contents)))
    }

    fn parse_base_player_create<'a, 'b>(
        &'b mut self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, entity_type) = le_u16(i)?;
        let spec = &self.specs[entity_type as usize - 1];

        let mut i = i;
        let mut props: HashMap<&str, _> = HashMap::new();
        let mut stored_props: Vec<_> = vec![];
        for prop_id in 0..spec.base_properties.len() {
            let spec = &spec.base_properties[prop_id];
            let (new_i, value) = match spec.prop_type.parse_value(i) {
                Ok(x) => x,
                Err(e) => {
                    return Err(failure_from_kind(crate::ErrorKind::UnableToParseRpcValue {
                        method: format!("BasePlayerCreate::{}", spec.name),
                        argnum: prop_id,
                        argtype: format!("{:?}", spec),
                        packet: i.to_vec(),
                        error: format!("{:?}", e),
                    }));
                }
            };
            i = new_i;
            stored_props.push(value.clone());
            props.insert(&spec.name, value);
        }

        //assert!(i.is_empty());

        self.entities.insert(
            entity_id,
            Entity {
                entity_type,
                // TODO: Parse the state
                properties: stored_props,
            },
        );
        Ok((
            i,
            PacketType::BasePlayerCreate(BasePlayerCreatePacket {
                entity_id: entity_id.into(),
                entity_type: &spec.name,
                props,
            }),
        ))
    }

    fn parse_entity_create<'a, 'b>(
        &'b mut self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, entity_type) = le_u16(i)?;
        let (i, vehicle_id) = le_u32(i)?;
        let (i, space_id) = le_u32(i)?;
        let (i, position) = Vec3::parse(i)?;
        let (i, rotation) = Rot3::parse(i)?;
        let (i, state_length) = le_u32(i)?;
        let (_, state) = take(i.len())(i)?;
        if self.entities.contains_key(&entity_id) {
            //println!("DBG: Entity {} got created twice!", entity_id);
        }

        let (i, num_props) = le_u8(state)?;
        let mut i = i;
        let mut props: HashMap<&str, _> = HashMap::new();
        let mut stored_props: Vec<_> = vec![];
        for _ in 0..num_props {
            let (new_i, prop_id) = le_u8(i)?;
            let spec = &self.specs[entity_type as usize - 1].properties[prop_id as usize];
            let (new_i, value) = match spec.prop_type.parse_value(new_i) {
                Ok(x) => x,
                Err(e) => {
                    return Err(failure_from_kind(crate::ErrorKind::UnableToParseRpcValue {
                        method: format!("EntityCreate::{}", spec.name),
                        argnum: prop_id as usize,
                        argtype: format!("{:?}", spec),
                        packet: i.to_vec(),
                        error: format!("{:?}", e),
                    }));
                }
            };
            i = new_i;
            stored_props.push(value.clone());
            props.insert(&spec.name, value);
        }

        self.entities.insert(
            entity_id,
            Entity {
                entity_type,
                properties: stored_props,
            },
        );

        Ok((
            i,
            PacketType::EntityCreate(EntityCreatePacket {
                entity_id: entity_id.into(),
                spec_idx: entity_type as usize,
                entity_type: &self.specs[entity_type as usize - 1].name,
                space_id,
                vehicle_id: vehicle_id.into(),
                position,
                rotation,
                state_length,
                props,
            }),
        ))
    }

    fn parse_cell_player_create<'a, 'b>(
        &'b mut self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, space_id) = le_u32(i)?;
        // let (i, _unknown) = le_u16(i)?;
        let (i, vehicle_id) = le_u32(i)?;
        let (i, position) = Vec3::parse(i)?;
        let (i, rotation) = Rot3::parse(i)?;
        let (i, props_len) = le_u32(i)?;
        let (_i, props_data) = take(props_len)(i)?;

        if !self.entities.contains_key(&entity_id) {
            panic!(
                "Cell player, entity id {}, was created before base player!",
                entity_id
            );
        }

        // The value can be parsed into all internal properties
        /*println!(
            "{} {} {} {} {},{},{} {},{},{} value.len()={}",
            entity_id,
            space_id,
            5, //unknown,
            vehicle_id,
            posx,
            posy,
            posz,
            dirx,
            diry,
            dirz,
            value.len()
        );*/
        let entity_type = self.entities.get(&entity_id).unwrap().entity_type;
        let spec = &self.specs[entity_type as usize - 1];

        let mut i = props_data;
        let mut props: HashMap<&str, _> = HashMap::new();
        let mut stored_props: Vec<_> = vec![];
        for prop_id in 0..spec.internal_properties.len() {
            let spec = &spec.internal_properties[prop_id];
            let (new_i, value) = match spec.prop_type.parse_value(i) {
                Ok(x) => x,
                Err(e) => {
                    return Err(failure_from_kind(crate::ErrorKind::UnableToParseRpcValue {
                        method: format!("CellPlayerCreate::{}", spec.name),
                        argnum: prop_id,
                        argtype: format!("{:?}", spec),
                        packet: i.to_vec(),
                        error: format!("{:?}", e),
                    }));
                }
            };
            i = new_i;
            stored_props.push(value.clone());
            props.insert(&spec.name, value);
        }

        Ok((
            i,
            PacketType::CellPlayerCreate(CellPlayerCreatePacket {
                entity_id: entity_id.into(),
                entity_type: &spec.name,
                vehicle_id: vehicle_id.into(),
                space_id,
                position,
                rotation,
                unknown: 5,
                props,
            }),
        ))
    }

    fn parse_entity_leave<'a, 'b>(&'b self, i: &'a [u8]) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        Ok((
            i,
            PacketType::EntityLeave(EntityLeavePacket {
                entity_id: entity_id.into(),
            }),
        ))
    }

    fn parse_entity_enter<'a, 'b>(
        &'b mut self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, entity_id) = le_u32(i)?;
        let (i, space_id) = le_u32(i)?;
        let (i, vehicle_id) = le_u32(i)?;
        Ok((
            i,
            PacketType::EntityEnter(EntityEnterPacket {
                entity_id: entity_id.into(),
                space_id,
                vehicle_id: vehicle_id.into(),
            }),
        ))
    }

    fn parse_cruise_state<'a, 'b>(
        &'b mut self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, key) = le_u32(i)?;
        let (i, value) = le_i32(i)?;
        Ok((i, PacketType::CruiseState(CruiseState { key, value })))
    }

    fn parse_map_packet<'a, 'b>(
        &'b mut self,
        i: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        let (i, space_id) = le_u32(i)?;
        let (i, arena_id) = le_i64(i)?;
        let (i, unknown1) = le_u32(i)?;
        let (i, unknown2) = le_u32(i)?;
        let (i, blob) = take(128usize)(i)?;
        let (i, string_size) = le_u32(i)?;
        let (i, map_name) = take(string_size)(i)?;
        let (i, matrix) = take(4usize * 4 * 4)(i)?;
        let (i, unknown) = le_u8(i)?;
        let packet = MapPacket {
            space_id,
            arena_id,
            unknown1,
            unknown2,
            blob,
            // TODO: Use a nom combinator for this (for error handling)
            map_name: std::str::from_utf8(map_name).unwrap(),
            matrix,
            unknown,
        };
        Ok((i, PacketType::Map(packet)))
    }

    fn parse_naked_packet<'a, 'b>(
        &'b mut self,
        packet_type: u32,
        packet: &'a [u8],
    ) -> IResult<&'a [u8], PacketType<'a, 'b>> {
        /*
        PACKETS_MAPPING = {
            0x0: BasePlayerCreate,
            0x1: CellPlayerCreate,
            0x2: EntityControl,
            0x3: EntityEnter,
            0x4: EntityLeave,
            0x5: EntityCreate,
            # 0x6
            0x7: EntityProperty,
            0x8: EntityMethod,
            0x27: Map,
            0x22: NestedProperty,
            0x0a: Position
        }
        */
        let (i, payload) = match packet_type {
            //0x7 | 0x8 => self.parse_entity_packet(version, packet_type, i)?,
            0x0 => self.parse_base_player_create(packet)?,
            0x1 => self.parse_cell_player_create(packet)?,
            0x2 => self.parse_entity_control_packet(packet)?,
            0x3 => self.parse_entity_enter(packet)?,
            0x4 => self.parse_entity_leave(packet)?,
            0x5 => self.parse_entity_create(packet)?,
            0x7 => self.parse_entity_property_packet(packet)?,
            0x8 => self.parse_entity_method_packet(packet)?,
            0xA => self.parse_position_packet(packet)?,
            0x0e => self.parse_server_tick_packet(packet)?,
            0x0f => self.parse_server_timestamp_packet(packet)?,
            0x16 => self.parse_version_packet(packet)?,
            0x1d => self.parse_view_direction_packet(packet)?,
            0x20 => self.parse_own_ship_packet(packet)?,
            0x22 => self.parse_battle_results(packet)?,
            0x23 => self.parse_nested_property_update(packet)?,
            0x25 => self.parse_camera_packet(packet)?,
            0x27 => self.parse_camera_mode_packet(packet)?,
            0x28 => self.parse_map_packet(packet)?,
            0x2a => self.parse_smoke_screen_drift_packet(packet)?,
            0x2c => self.parse_player_orientation_packet(packet)?,
            0x2f => self.parse_camera_freelook_packet(packet)?,
            0x30 => self.parse_vehicle_ref_packet(packet)?,
            0x32 => self.parse_cruise_state(packet)?,
            // 0x10: 1-byte init flag, 0x13: empty init marker, 0x18: secondary
            // camera (paired with 0x25), 0x26: avatar init — left as Unknown
            // since they carry no actionable data.
            _ => self.parse_unknown_packet(packet, packet.len().try_into().unwrap())?,
        };
        Ok((i, payload))
    }

    pub fn parse_packet<'a, 'b>(&'b mut self, i: &'a [u8]) -> IResult<&'a [u8], Packet<'a, 'b>> {
        let (i, packet_size) = le_u32(i)?;
        let (i, packet_type) = le_u32(i)?;
        let (i, raw_clock) = le_f32(i)?;
        let clock = GameClock(raw_clock);
        let (remaining, packet_data) = take(packet_size)(i)?;
        let raw = packet_data;
        let (_i, payload) = match self.parse_naked_packet(packet_type, packet_data) {
            Ok(x) => x,
            Err(nom::Err::Failure(Error {
                kind: ErrorKind::UnsupportedReplayVersion(n),
                ..
            })) => {
                return Err(failure_from_kind(ErrorKind::UnsupportedReplayVersion(n)));
            }
            Err(e) => {
                (
                    &packet_data[0..0], // Empty reference
                    PacketType::Invalid(InvalidPacket {
                        message: format!("{:?}", e),
                        raw: packet_data,
                    }),
                )
            }
        };
        // TODO: Add this back
        //assert!(i.len() == 0);
        Ok((
            remaining,
            Packet {
                packet_size,
                packet_type,
                clock,
                payload,
                raw,
            },
        ))
    }
}