rust-samp-sdk 3.5.0

Low-level FFI bindings for the SA-MP AMX virtual machine and open.mp native component ABI. Used internally by `rust-samp`; depend on it directly only if you need raw access without the higher-level macros and lifecycle.
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
//! Player events straight from the Open Multiplayer server.
//!
//! A plugin that wants `OnPlayerConnect` today goes through Pawn: the SDK
//! detours `amx_Exec` and watches the gamemode's callbacks (see
//! [`crate::omp::events`]). That works on both servers, but it only sees what
//! the script is told, and it costs a detour.
//!
//! Open Multiplayer offers the same events natively: `ICore` hands out an
//! `IPlayerPool`, the pool hands out an `IEventDispatcher<PlayerConnectEventHandler>`,
//! and a component registers a handler on it. No Pawn, no detour — the server
//! calls the plugin directly.
//!
//! ## Slots, per ABI
//!
//! | Method | Itanium | MSVC |
//! | ------ | :-----: | :--: |
//! | `ICore::getPlayers` | 8 | 7 |
//! | `IPlayerPool::getPlayerConnectDispatcher` | 10 | 9 |
//!
//! Itanium values come from the vtable dumps of the official `omp-server`
//! (`PlayerPool` and `Core` keep their symbols). MSVC shifts by one because it
//! emits a single destructor slot where Itanium emits two — the same rule as
//! everywhere else in this module, and `scripts/check-abi-slots.py` re-derives
//! it from the binaries.
//!
//! ## `PlayerConnectEventHandler`
//!
//! Declared in `player.hpp` with no virtual destructor, so four slots on both
//! ABIs:
//!
//! ```text
//! [0] onIncomingConnection(IPlayer&, StringView ip, u16 port)
//! [1] onPlayerConnect(IPlayer&)
//! [2] onPlayerDisconnect(IPlayer&, PeerDisconnectReason)
//! [3] onPlayerClientInit(IPlayer&)
//! ```

use super::component::ICore;
use super::types::{Colour, StringView, UID, Vector3};
use super::vehicles::IVehicle;
use super::vtable::call_vtable;

/// Slot of `ICore::getPlayers()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_GET_PLAYERS: usize = 8;
#[cfg(target_env = "msvc")]
const SLOT_GET_PLAYERS: usize = 7;

/// Slot of `IPlayerPool::getPlayerConnectDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_CONNECT_DISPATCHER: usize = 10;
#[cfg(target_env = "msvc")]
const SLOT_CONNECT_DISPATCHER: usize = 9;

/// Opaque handle for the server's `IPlayerPool*`.
#[repr(C)]
pub struct IPlayerPool {
    _opaque: [u8; 0],
}

/// Slot of `IPlayer::kick()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_KICK: usize = 6;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_KICK: usize = 5;

/// Slot of `IPlayer::isBot()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_IS_BOT: usize = 8;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_IS_BOT: usize = 7;

/// Slot of `IPlayer::getName()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_NAME: usize = 27;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_NAME: usize = 26;

/// Slot of `IPlayer::setHealth(float)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_HEALTH: usize = 77;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_HEALTH: usize = 76;

/// Slot of `IPlayer::getHealth()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_HEALTH: usize = 78;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_HEALTH: usize = 77;

/// Offset of the `IEntity` subobject inside an `IPlayer`.
///
/// `IPlayer : public IExtensible, public IEntity`, so position, rotation and
/// virtual world live in a **secondary** vtable rather than the primary one:
/// the `this` pointer has to be adjusted before indexing. The offset is the
/// size of `IExtensible`, which is why it matches the one `OmpComponent` uses
/// for `IUIDProvider`. Derived from clang's record layout for both ABIs.
#[cfg(not(target_env = "msvc"))]
pub(crate) const ENTITY_OFFSET: isize = 40;
#[cfg(target_env = "msvc")]
pub(crate) const ENTITY_OFFSET: isize = 56;

/// Offset of the `IReadOnlyPool<IPlayer>` subobject inside an `IPlayerPool`.
///
/// Same reasoning as [`ENTITY_OFFSET`]: the pool interface is a secondary base,
/// so looking a player up by id means adjusting `this` first. From clang's
/// record layout of `IPlayerPool`.
#[cfg(not(target_env = "msvc"))]
const PLAYER_POOL_OFFSET: isize = 40;
#[cfg(target_env = "msvc")]
const PLAYER_POOL_OFFSET: isize = 56;

/// `IReadOnlyPool<T>::get(int)` is its first method, and `bounds()` the second.
/// Neither interface declares a destructor, so both ABIs agree.
pub(crate) const SLOT_POOL_GET_PUB: usize = 0;
const SLOT_POOL_GET: usize = SLOT_POOL_GET_PUB;
pub(crate) const SLOT_POOL_BOUNDS: usize = 1;

/// `IExtensible::getExtension(UID)` — slot [0] of every entity's primary
/// vtable, since `IExtensible` is the first base and declares it first.
const SLOT_GET_EXTENSION: usize = 0;

/// Slots inside the `IEntity` vtable. It declares no destructor, so the
/// numbering is identical on both ABIs.
pub(crate) const SLOT_ENTITY_GET_ID: usize = 0;
pub(crate) const SLOT_ENTITY_GET_POSITION: usize = 1;
const SLOT_ENTITY_SET_POSITION: usize = 2;
const SLOT_ENTITY_GET_VIRTUAL_WORLD: usize = 5;
const SLOT_ENTITY_SET_VIRTUAL_WORLD: usize = 6;

/// Slot of `IPlayer::setMoney(int)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_MONEY: usize = 62;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_MONEY: usize = 61;

/// Slot of `IPlayer::giveMoney(int)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GIVE_MONEY: usize = 63;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GIVE_MONEY: usize = 62;

/// Slot of `IPlayer::setArmour(float)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_ARMOUR: usize = 81;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_ARMOUR: usize = 80;

/// Slot of `IPlayer::getArmour()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_ARMOUR: usize = 82;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_ARMOUR: usize = 81;

/// Slot of `IPlayer::setTeam(int)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_TEAM: usize = 95;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_TEAM: usize = 94;

/// Slot of `IPlayer::getTeam()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_TEAM: usize = 96;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_TEAM: usize = 95;

/// Slot of `IPlayer::setSkin(int, bool)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_SKIN: usize = 97;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_SKIN: usize = 96;

/// Slots of the plain `int` accessors, all reached through
/// [`player_set_i32`] / [`player_get_i32`]. Every pair is one apart between
/// ABIs, the usual destructor shift, and comes from `scripts/omp-vtable.py`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_DRUNK: usize = 40;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_DRUNK: usize = 39;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_WANTED: usize = 49;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_WANTED: usize = 48;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_WANTED: usize = 50;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_WANTED: usize = 49;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_MONEY: usize = 65;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_MONEY: usize = 64;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_SKIN: usize = 98;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_SKIN: usize = 97;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_WEATHER: usize = 107;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_WEATHER: usize = 106;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_INTERIOR: usize = 118;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_INTERIOR: usize = 117;

#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_INTERIOR: usize = 119;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_INTERIOR: usize = 118;

/// Slot of `IPlayer::setControllable(bool)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_CONTROLLABLE: usize = 46;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_CONTROLLABLE: usize = 45;

/// Slot of `IPlayer::setScore(int)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SET_SCORE: usize = 79;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SET_SCORE: usize = 78;

/// Slot of `IPlayer::getScore()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_GET_SCORE: usize = 80;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_GET_SCORE: usize = 79;

/// Slot of `IPlayer::sendClientMessage(const Colour&, StringView)`.
#[cfg(not(target_env = "msvc"))]
const SLOT_PLAYER_SEND_MESSAGE: usize = 100;
#[cfg(target_env = "msvc")]
const SLOT_PLAYER_SEND_MESSAGE: usize = 99;

/// Opaque handle for the server's `IPlayer*`, as received by a handler.
#[repr(C)]
pub struct IPlayer {
    _opaque: [u8; 0],
}

/// Slot of `IPlayerPool::getPlayerSpawnDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_SPAWN_DISPATCHER: usize = 9;
#[cfg(target_env = "msvc")]
const SLOT_SPAWN_DISPATCHER: usize = 8;

/// Slot of `IPlayerPool::getPlayerTextDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_TEXT_DISPATCHER: usize = 12;
#[cfg(target_env = "msvc")]
const SLOT_TEXT_DISPATCHER: usize = 11;

/// Slot of `IPlayerPool::getPlayerDamageDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_DAMAGE_DISPATCHER: usize = 15;
#[cfg(target_env = "msvc")]
const SLOT_DAMAGE_DISPATCHER: usize = 14;

/// Slot of `IPlayerPool::getPlayerStreamDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_STREAM_DISPATCHER: usize = 11;
#[cfg(target_env = "msvc")]
const SLOT_STREAM_DISPATCHER: usize = 10;

/// Slot of `IPlayerPool::getPlayerShotDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_SHOT_DISPATCHER: usize = 13;
#[cfg(target_env = "msvc")]
const SLOT_SHOT_DISPATCHER: usize = 12;

/// Slot of `IPlayerPool::getPlayerChangeDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_CHANGE_DISPATCHER: usize = 14;
#[cfg(target_env = "msvc")]
const SLOT_CHANGE_DISPATCHER: usize = 13;

/// Slot of `IPlayerPool::getPlayerClickDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_CLICK_DISPATCHER: usize = 16;
#[cfg(target_env = "msvc")]
const SLOT_CLICK_DISPATCHER: usize = 15;

/// Slot of `IPlayerPool::getPlayerCheckDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_CHECK_DISPATCHER: usize = 17;
#[cfg(target_env = "msvc")]
const SLOT_CHECK_DISPATCHER: usize = 16;

/// Slot of `IPlayerPool::getPlayerUpdateDispatcher()`.
#[cfg(not(target_env = "msvc"))]
const SLOT_UPDATE_DISPATCHER: usize = 18;
#[cfg(target_env = "msvc")]
const SLOT_UPDATE_DISPATCHER: usize = 17;

/// Opaque handle for `IEventDispatcher<PlayerConnectEventHandler>*`.
#[repr(C)]
pub struct IPlayerConnectDispatcher {
    _opaque: [u8; 0],
}

/// Why the server dropped a player (`PeerDisconnectReason` in `network.hpp`).
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisconnectReason {
    Timeout = 0,
    Quit = 1,
    Kicked = 2,
    Custom = 3,
    ModeEnd = 4,
}

impl DisconnectReason {
    /// Maps the raw value the server passes, treating an unknown one as
    /// [`DisconnectReason::Custom`] rather than transmuting it into a variant
    /// that does not exist.
    #[must_use]
    pub fn from_raw(value: i32) -> Self {
        match value {
            0 => Self::Timeout,
            1 => Self::Quit,
            2 => Self::Kicked,
            4 => Self::ModeEnd,
            _ => Self::Custom,
        }
    }
}

/// `PlayerConnectEventHandler` vtable — Itanium ABI.
#[cfg(not(target_env = "msvc"))]
#[repr(C)]
pub struct PlayerConnectHandlerVTable {
    pub on_incoming_connection:
        unsafe extern "C" fn(*mut PlayerConnectHandler, *mut IPlayer, StringView, u16),
    pub on_player_connect: unsafe extern "C" fn(*mut PlayerConnectHandler, *mut IPlayer),
    pub on_player_disconnect: unsafe extern "C" fn(*mut PlayerConnectHandler, *mut IPlayer, i32),
    pub on_player_client_init: unsafe extern "C" fn(*mut PlayerConnectHandler, *mut IPlayer),
}

/// `PlayerConnectEventHandler` vtable — MSVC ABI (`this` in ECX).
#[cfg(target_env = "msvc")]
#[repr(C)]
pub struct PlayerConnectHandlerVTable {
    pub on_incoming_connection:
        unsafe extern "thiscall" fn(*mut PlayerConnectHandler, *mut IPlayer, StringView, u16),
    pub on_player_connect: unsafe extern "thiscall" fn(*mut PlayerConnectHandler, *mut IPlayer),
    pub on_player_disconnect:
        unsafe extern "thiscall" fn(*mut PlayerConnectHandler, *mut IPlayer, i32),
    pub on_player_client_init: unsafe extern "thiscall" fn(*mut PlayerConnectHandler, *mut IPlayer),
}

/// Object the server calls on player connection events.
///
/// Layout: vtable pointer at offset 0, like every C++ object with virtuals. The
/// server keeps the pointer, so it must outlive the registration — leak it, or
/// keep it alive for the plugin's lifetime and remove it before dropping.
#[repr(C)]
pub struct PlayerConnectHandler {
    vtable: *const PlayerConnectHandlerVTable,
}

// SAFETY: the handler is only ever touched on the server's main thread.
unsafe impl Send for PlayerConnectHandler {}
unsafe impl Sync for PlayerConnectHandler {}

impl PlayerConnectHandler {
    /// Builds a handler backed by `vtable`.
    #[must_use]
    pub fn new(vtable: *const PlayerConnectHandlerVTable) -> Self {
        Self { vtable }
    }
}

/// Opaque handles for the objects a shot can hit, beyond the vehicle the
/// [`vehicles`](super::vehicles) module already defines.
#[repr(C)]
pub struct IObject {
    _opaque: [u8; 0],
}

/// See [`IObject`].
#[repr(C)]
pub struct IPlayerObject {
    _opaque: [u8; 0],
}

/// `PlayerBulletData`, passed by const reference — opaque here, since reading
/// it means pinning another layout.
#[repr(C)]
pub struct PlayerBulletData {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerSpawnEventHandler>*`.
#[repr(C)]
pub struct IPlayerSpawnDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerTextEventHandler>*`.
#[repr(C)]
pub struct IPlayerTextDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerDamageEventHandler>*`.
#[repr(C)]
pub struct IPlayerDamageDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerStreamEventHandler>*`.
#[repr(C)]
pub struct IPlayerStreamDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerShotEventHandler>*`.
#[repr(C)]
pub struct IPlayerShotDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerChangeEventHandler>*`.
#[repr(C)]
pub struct IPlayerChangeDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerClickEventHandler>*`.
#[repr(C)]
pub struct IPlayerClickDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerCheckEventHandler>*`.
#[repr(C)]
pub struct IPlayerCheckDispatcher {
    _opaque: [u8; 0],
}

/// Opaque handle for `IEventDispatcher<PlayerUpdateEventHandler>*`.
#[repr(C)]
pub struct IPlayerUpdateDispatcher {
    _opaque: [u8; 0],
}

/// Writes a handler vtable struct for both ABIs — the server calls through it,
/// so the convention is the platform's: `extern "C"` on Itanium, `thiscall`
/// on MSVC. None of these handlers declares a virtual destructor, so the slot
/// numbering is the declaration order on both.
macro_rules! handler_vtable {
    (
        $(#[$meta:meta])*
        $name:ident for $handler:ident {
            $($field:ident: fn($($arg:ty),* $(,)?) $(-> $ret:ty)?),* $(,)?
        }
    ) => {
        $(#[$meta])*
        #[cfg(not(target_env = "msvc"))]
        #[repr(C)]
        pub struct $name {
            $(pub $field: unsafe extern "C" fn(*mut $handler, $($arg),*) $(-> $ret)?),*
        }

        $(#[$meta])*
        #[cfg(target_env = "msvc")]
        #[repr(C)]
        pub struct $name {
            $(pub $field: unsafe extern "thiscall" fn(*mut $handler, $($arg),*) $(-> $ret)?),*
        }

        /// Object the server calls through [`
        #[doc = stringify!($name)]
        /// `]. Layout: vtable pointer at offset 0, like any C++ object with
        /// virtuals. The server keeps the pointer, so it must outlive the
        /// registration.
        #[repr(C)]
        pub struct $handler {
            vtable: *const $name,
        }

        // SAFETY: handlers are only ever touched on the server's main thread.
        unsafe impl Send for $handler {}
        unsafe impl Sync for $handler {}

        impl $handler {
            /// Builds a handler backed by `vtable`.
            #[must_use]
            pub fn new(vtable: *const $name) -> Self {
                Self { vtable }
            }
        }
    };
}

handler_vtable! {
    /// `PlayerSpawnEventHandler` — `onPlayerRequestSpawn` returning `false`
    /// denies the spawn.
    PlayerSpawnHandlerVTable for PlayerSpawnHandler {
        on_player_request_spawn: fn(*mut IPlayer) -> bool,
        on_player_spawn: fn(*mut IPlayer),
    }
}

handler_vtable! {
    /// `PlayerTextEventHandler` — `onPlayerText` returning `false` blocks the
    /// message; `onPlayerCommandText` returning `true` marks the command as
    /// handled.
    PlayerTextHandlerVTable for PlayerTextHandler {
        on_player_text: fn(*mut IPlayer, StringView) -> bool,
        on_player_command_text: fn(*mut IPlayer, StringView) -> bool,
    }
}

handler_vtable! {
    /// `PlayerDamageEventHandler`. `killer` is null when nobody killed the
    /// player, and `part` is a `BodyPart` value.
    PlayerDamageHandlerVTable for PlayerDamageHandler {
        on_player_death: fn(*mut IPlayer, *mut IPlayer, i32),
        on_player_take_damage: fn(*mut IPlayer, *mut IPlayer, f32, u32, i32),
        on_player_give_damage: fn(*mut IPlayer, *mut IPlayer, f32, u32, i32),
    }
}

/// `ICore::getPlayers()` — the server's player pool.
///
/// # Safety
/// `core` must be the `ICore*` the server passed to `on_load`.
#[must_use]
pub unsafe fn player_pool(core: *mut ICore) -> *mut IPlayerPool {
    call_vtable!(
        core.cast::<u8>(),
        0,
        SLOT_GET_PLAYERS,
        () -> *mut IPlayerPool,
        (),
        std::ptr::null_mut()
    )
}

/// `IPlayerPool::getPlayerConnectDispatcher()`.
///
/// # Safety
/// `pool` must come from [`player_pool`].
#[must_use]
pub unsafe fn player_connect_dispatcher(pool: *mut IPlayerPool) -> *mut IPlayerConnectDispatcher {
    #[cfg(not(target_env = "msvc"))]
    type GetDispatcherFn = unsafe extern "C" fn(*mut u8) -> *mut IPlayerConnectDispatcher;
    #[cfg(target_env = "msvc")]
    type GetDispatcherFn = unsafe extern "thiscall" fn(*mut u8) -> *mut IPlayerConnectDispatcher;

    let Some((this, f_ptr)) = (unsafe {
        super::vtable::secondary_call_target_ptr(pool.cast::<u8>(), 0, SLOT_CONNECT_DISPATCHER)
    }) else {
        return std::ptr::null_mut();
    };
    let get_dispatcher: GetDispatcherFn = unsafe { std::mem::transmute(f_ptr) };
    unsafe { get_dispatcher(this) }
}

/// Registers `handler` on the dispatcher (`addEventHandler`, slot [0]).
///
/// Returns what the server returned: `false` means the handler was already
/// registered.
///
/// # Safety
/// Both pointers must be valid, and `handler` must outlive the registration.
pub unsafe fn add_player_connect_handler(
    dispatcher: *mut IPlayerConnectDispatcher,
    handler: *mut PlayerConnectHandler,
) -> bool {
    #[cfg(not(target_env = "msvc"))]
    type AddFn = unsafe extern "C" fn(*mut u8, *mut PlayerConnectHandler, i8) -> bool;
    #[cfg(target_env = "msvc")]
    type AddFn = unsafe extern "thiscall" fn(*mut u8, *mut PlayerConnectHandler, i8) -> bool;

    // `IEventDispatcher<T>` declares no destructor, so `addEventHandler` is
    // slot [0] on both ABIs — same layout the Pawn dispatcher uses.
    let Some((this, f_ptr)) =
        (unsafe { super::vtable::secondary_call_target_ptr(dispatcher.cast::<u8>(), 0, 0) })
    else {
        return false;
    };
    let add: AddFn = unsafe { std::mem::transmute(f_ptr) };
    unsafe { add(this, handler, 0) }
}

handler_vtable! {
    /// `PlayerStreamEventHandler` — a player entering or leaving another's
    /// stream radius.
    PlayerStreamHandlerVTable for PlayerStreamHandler {
        on_player_stream_in: fn(*mut IPlayer, *mut IPlayer),
        on_player_stream_out: fn(*mut IPlayer, *mut IPlayer),
    }
}

handler_vtable! {
    /// `PlayerShotEventHandler` — returning `false` rejects the shot.
    /// `bullet_data` points at a `PlayerBulletData` the server owns.
    PlayerShotHandlerVTable for PlayerShotHandler {
        on_player_shot_missed: fn(*mut IPlayer, *const PlayerBulletData) -> bool,
        on_player_shot_player: fn(*mut IPlayer, *mut IPlayer, *const PlayerBulletData) -> bool,
        on_player_shot_vehicle: fn(*mut IPlayer, *mut IVehicle, *const PlayerBulletData) -> bool,
        on_player_shot_object: fn(*mut IPlayer, *mut IObject, *const PlayerBulletData) -> bool,
        on_player_shot_player_object:
            fn(*mut IPlayer, *mut IPlayerObject, *const PlayerBulletData) -> bool,
    }
}

handler_vtable! {
    /// `PlayerChangeEventHandler`. `PlayerState` and the key masks arrive as
    /// plain integers.
    PlayerChangeHandlerVTable for PlayerChangeHandler {
        on_player_score_change: fn(*mut IPlayer, i32),
        on_player_name_change: fn(*mut IPlayer, StringView),
        on_player_interior_change: fn(*mut IPlayer, u32, u32),
        on_player_state_change: fn(*mut IPlayer, i32, i32),
        on_player_key_state_change: fn(*mut IPlayer, u32, u32),
    }
}

handler_vtable! {
    /// `PlayerClickEventHandler`. `Vector3` is passed by value, as the header
    /// declares it.
    PlayerClickHandlerVTable for PlayerClickHandler {
        on_player_click_map: fn(*mut IPlayer, Vector3),
        on_player_click_player: fn(*mut IPlayer, *mut IPlayer, i32),
    }
}

handler_vtable! {
    /// `PlayerCheckEventHandler` — the reply to a client check request.
    PlayerCheckHandlerVTable for PlayerCheckHandler {
        on_client_check_response: fn(*mut IPlayer, i32, i32, i32),
    }
}

handler_vtable! {
    /// `PlayerUpdateEventHandler` — fires for every player on every server
    /// tick, so keep the body short. Returning `false` drops the update.
    ///
    /// `now` is a `TimePoint` (`steady_clock`, nanoseconds): one 64-bit value
    /// passed by value, which on i686 lands on the stack either way.
    PlayerUpdateHandlerVTable for PlayerUpdateHandler {
        on_player_update: fn(*mut IPlayer, i64) -> bool,
    }
}

/// Calls `IPlayer::kick()` — drops the player from the server.
///
/// # Safety
/// `player` must be an `IPlayer*` the server handed to a handler, and still
/// connected.
pub unsafe fn player_kick(player: *mut IPlayer) {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_KICK, () -> (), (), ())
}

/// `IPlayer::isBot()` — whether this "player" is an NPC.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_is_bot(player: *mut IPlayer) -> bool {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_IS_BOT, () -> bool, (), false)
}

/// `IPlayer::getName()` — the player's name, copied into a `String`.
///
/// The server returns a `StringView` into memory it owns, so the bytes are
/// copied out rather than borrowed. `None` when the view is empty or not valid
/// UTF-8.
///
/// Both ABIs return the 8-byte `StringView` through a hidden pointer, the same
/// shape `component_name` uses.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_name(player: *mut IPlayer) -> Option<String> {
    // Return convention differs: the Itanium ABI hands back this 8-byte,
    // trivially copyable struct in EAX:EDX, while MSVC writes it through a
    // hidden pointer the caller supplies.
    #[cfg(not(target_env = "msvc"))]
    type GetNameFn = unsafe extern "C" fn(*mut u8) -> StringView;
    #[cfg(target_env = "msvc")]
    type GetNameFn = unsafe extern "thiscall" fn(*mut u8, *mut StringView) -> *mut StringView;

    let (this, f_ptr) = unsafe {
        super::vtable::secondary_call_target_ptr(player.cast::<u8>(), 0, SLOT_PLAYER_GET_NAME)
    }?;
    let get_name: GetNameFn = unsafe { std::mem::transmute(f_ptr) };

    #[cfg(not(target_env = "msvc"))]
    let view = unsafe { get_name(this) };

    #[cfg(target_env = "msvc")]
    let view = {
        let mut view = StringView {
            data: std::ptr::null(),
            len: 0,
        };
        unsafe { get_name(this, &raw mut view) };
        view
    };
    if view.data.is_null() || view.len == 0 {
        return None;
    }
    let bytes = unsafe { std::slice::from_raw_parts(view.data, view.len) };
    std::str::from_utf8(bytes).ok().map(String::from)
}

/// `IPlayer::getHealth()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_health(player: *mut IPlayer) -> f32 {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_GET_HEALTH, () -> f32, (), 0.0)
}

/// `IPlayer::setHealth(float)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_health(player: *mut IPlayer, health: f32) {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_SET_HEALTH, (f32) -> (), (health), ())
}

/// `IPlayer::getScore()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_score(player: *mut IPlayer) -> i32 {
    #[cfg(not(target_env = "msvc"))]
    type GetScoreFn = unsafe extern "C" fn(*mut u8) -> i32;
    #[cfg(target_env = "msvc")]
    type GetScoreFn = unsafe extern "thiscall" fn(*mut u8) -> i32;

    let Some((this, f_ptr)) = (unsafe {
        super::vtable::secondary_call_target_ptr(player.cast::<u8>(), 0, SLOT_PLAYER_GET_SCORE)
    }) else {
        return 0;
    };
    let get_score: GetScoreFn = unsafe { std::mem::transmute(f_ptr) };
    unsafe { get_score(this) }
}

/// `IPlayer::setScore(int)`.
///
/// Unlike health, the score is the server's own value — a client cannot
/// overwrite it on the next sync packet.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_score(player: *mut IPlayer, score: i32) {
    #[cfg(not(target_env = "msvc"))]
    type SetScoreFn = unsafe extern "C" fn(*mut u8, i32);
    #[cfg(target_env = "msvc")]
    type SetScoreFn = unsafe extern "thiscall" fn(*mut u8, i32);

    let Some((this, f_ptr)) = (unsafe {
        super::vtable::secondary_call_target_ptr(player.cast::<u8>(), 0, SLOT_PLAYER_SET_SCORE)
    }) else {
        return;
    };
    let set_score: SetScoreFn = unsafe { std::mem::transmute(f_ptr) };
    unsafe { set_score(this, score) };
}

/// `IEntity::getPosition()` — where the player is.
///
/// A `Vector3` is twelve bytes, too large to come back in registers, so the
/// caller supplies a hidden pointer. The details differ per ABI and are easy to
/// get wrong by hand — on i386 System V the pointer goes **before** `this` and
/// the callee pops it (`ret $0x4` in the server's own `Player::getPosition`),
/// so writing the pointer as an ordinary argument unbalances the stack.
///
/// Declaring the return type and letting the compiler apply the rule avoids all
/// of that.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_position(player: *mut IPlayer) -> Vector3 {
    let zero = Vector3 {
        x: 0.0,
        y: 0.0,
        z: 0.0,
    };
    call_vtable!(
        player.cast::<u8>(),
        ENTITY_OFFSET,
        SLOT_ENTITY_GET_POSITION,
        () -> Vector3,
        (),
        zero
    )
}

/// `IEntity::setPosition(Vector3)` — teleports the player.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_position(player: *mut IPlayer, position: Vector3) {
    call_vtable!(
        player.cast::<u8>(),
        ENTITY_OFFSET,
        SLOT_ENTITY_SET_POSITION,
        (Vector3) -> (),
        (position),
        ()
    )
}

/// `IEntity::getVirtualWorld()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_virtual_world(player: *mut IPlayer) -> i32 {
    call_vtable!(
        player.cast::<u8>(),
        ENTITY_OFFSET,
        SLOT_ENTITY_GET_VIRTUAL_WORLD,
        () -> i32,
        (),
        0
    )
}

/// `IEntity::setVirtualWorld(int)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_virtual_world(player: *mut IPlayer, world: i32) {
    call_vtable!(
        player.cast::<u8>(),
        ENTITY_OFFSET,
        SLOT_ENTITY_SET_VIRTUAL_WORLD,
        (i32) -> (),
        (world),
        ()
    )
}

/// Calls a `void(int)` setter on the player's primary vtable.
unsafe fn player_set_i32(player: *mut IPlayer, slot: usize, value: i32) {
    call_vtable!(player.cast::<u8>(), 0, slot, (i32) -> (), (value), ())
}

/// Calls an `int()` getter on the player's primary vtable.
unsafe fn player_get_i32(player: *mut IPlayer, slot: usize) -> i32 {
    call_vtable!(player.cast::<u8>(), 0, slot, () -> i32, (), 0)
}

/// `IPlayer::setMoney(int)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_money(player: *mut IPlayer, amount: i32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_SET_MONEY, amount) };
}

/// `IPlayer::giveMoney(int)` — adds to what the player already has.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_give_money(player: *mut IPlayer, amount: i32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_GIVE_MONEY, amount) };
}

/// `IPlayer::setTeam(int)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_team(player: *mut IPlayer, team: i32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_SET_TEAM, team) };
}

/// `IPlayer::getTeam()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_team(player: *mut IPlayer) -> i32 {
    unsafe { player_get_i32(player, SLOT_PLAYER_GET_TEAM) }
}

/// `IPlayer::setArmour(float)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_armour(player: *mut IPlayer, armour: f32) {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_SET_ARMOUR, (f32) -> (), (armour), ())
}

/// `IPlayer::getArmour()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_armour(player: *mut IPlayer) -> f32 {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_GET_ARMOUR, () -> f32, (), 0.0)
}

/// `IPlayer::setSkin(int, bool)` — `send` asks the server to tell the other
/// players about the change, which is what a script normally wants.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_skin(player: *mut IPlayer, skin: i32, send: bool) {
    call_vtable!(player.cast::<u8>(), 0, SLOT_PLAYER_SET_SKIN, (i32, bool) -> (), (skin, send), ())
}

/// `IEntity::getID()` — the id Pawn scripts know this player by.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_id(player: *mut IPlayer) -> i32 {
    call_vtable!(player.cast::<u8>(), ENTITY_OFFSET, SLOT_ENTITY_GET_ID, () -> i32, (), -1)
}

/// `IReadOnlyPool<IPlayer>::get(int)` — the player with that id, or null.
///
/// Answers "who is player 7?" without touching the pool's hash set, whose
/// layout belongs to `robin_hood` and would have to be mirrored to iterate.
///
/// # Safety
/// `pool` must come from [`player_pool`].
#[must_use]
pub unsafe fn player_by_id(pool: *mut IPlayerPool, id: i32) -> *mut IPlayer {
    call_vtable!(
        pool.cast::<u8>(),
        PLAYER_POOL_OFFSET,
        SLOT_POOL_GET,
        (i32) -> *mut IPlayer,
        (id),
        std::ptr::null_mut()
    )
}

/// `IPlayer::getMoney()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_money(player: *mut IPlayer) -> i32 {
    unsafe { player_get_i32(player, SLOT_PLAYER_GET_MONEY) }
}

/// `IPlayer::getSkin()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_skin(player: *mut IPlayer) -> i32 {
    unsafe { player_get_i32(player, SLOT_PLAYER_GET_SKIN) }
}

/// `IPlayer::setWantedLevel(unsigned)` — zero to six, as the game shows.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_wanted_level(player: *mut IPlayer, level: u32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_SET_WANTED, level as i32) };
}

/// `IPlayer::getWantedLevel()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_wanted_level(player: *mut IPlayer) -> u32 {
    unsafe { player_get_i32(player, SLOT_PLAYER_GET_WANTED) as u32 }
}

/// `IPlayer::setInterior(unsigned)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_interior(player: *mut IPlayer, interior: u32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_SET_INTERIOR, interior as i32) };
}

/// `IPlayer::getInterior()`.
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_interior(player: *mut IPlayer) -> u32 {
    unsafe { player_get_i32(player, SLOT_PLAYER_GET_INTERIOR) as u32 }
}

/// `IPlayer::setWeather(int)` — for this player alone.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_weather(player: *mut IPlayer, weather: i32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_SET_WEATHER, weather) };
}

/// `IPlayer::setDrunkLevel(int)`.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_drunk_level(player: *mut IPlayer, level: i32) {
    unsafe { player_set_i32(player, SLOT_PLAYER_SET_DRUNK, level) };
}

/// `IPlayer::setControllable(bool)` — `false` freezes the player.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_set_controllable(player: *mut IPlayer, controllable: bool) {
    call_vtable!(
        player.cast::<u8>(),
        0,
        SLOT_PLAYER_SET_CONTROLLABLE,
        (bool) -> (),
        (controllable),
        ()
    )
}

/// The range of ids a pool can hand out, as `IReadOnlyPool<T>::bounds()`
/// reports it: inclusive on both ends.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PoolBounds {
    pub first: usize,
    pub last: usize,
}

/// `IReadOnlyPool<T>::bounds()` for any pool, given the offset of its
/// subobject.
///
/// Walking these ids and asking for each one is how this SDK iterates a pool.
/// The alternative, `entries()`, returns a `robin_hood` hash set whose layout
/// would have to be mirrored, and mirroring it wrong reads the server's memory
/// at random.
///
/// # Safety
/// `pool` must point at an object carrying `IReadOnlyPool<T>` at `offset`.
#[must_use]
pub unsafe fn pool_bounds(pool: *mut u8, offset: isize) -> PoolBounds {
    // `bounds()` returns a `Pair<size_t, size_t>`. Eight bytes, but the two
    // ABIs disagree on how: GCC hands it back in registers, while MSVC sees a
    // type with a constructor and returns it through a hidden pointer. Rust
    // cannot infer that difference from a `#[repr(C)]` struct — it applies the
    // C rule, registers on both — so the MSVC side is spelled out.
    #[cfg(not(target_env = "msvc"))]
    type BoundsFn = unsafe extern "C" fn(*mut u8) -> PoolBounds;
    #[cfg(target_env = "msvc")]
    type BoundsFn = unsafe extern "thiscall" fn(*mut u8, *mut PoolBounds) -> *mut PoolBounds;

    // An empty range: `first > last`, so a loop over it runs zero times.
    let empty = PoolBounds { first: 1, last: 0 };
    let Some((this, f_ptr)) =
        (unsafe { super::vtable::secondary_call_target_ptr(pool, offset, SLOT_POOL_BOUNDS) })
    else {
        return empty;
    };
    let bounds: BoundsFn = unsafe { std::mem::transmute(f_ptr) };

    #[cfg(not(target_env = "msvc"))]
    let result = unsafe { bounds(this) };

    #[cfg(target_env = "msvc")]
    let result = {
        let mut out = empty;
        unsafe { bounds(this, &raw mut out) };
        out
    };

    result
}

/// Every player currently in the pool.
///
/// Named `all_players` rather than `players`, which at a call site would read
/// as the module of that name.
///
/// Named  rather than  so it does not read as the module
/// of the same name at a call site.
///
/// Walks the ids `bounds()` reports and keeps the ones the pool answers for, so
/// a gap in the middle costs one call and nothing else.
///
/// # Safety
/// `pool` must come from [`player_pool`].
#[must_use]
pub unsafe fn all_players(pool: *mut IPlayerPool) -> Vec<*mut IPlayer> {
    let bounds = unsafe { pool_bounds(pool.cast::<u8>(), PLAYER_POOL_OFFSET) };
    let mut found = Vec::new();
    for id in bounds.first..=bounds.last {
        let Ok(id) = i32::try_from(id) else { break };
        let player = unsafe { player_by_id(pool, id) };
        if !player.is_null() {
            found.push(player);
        }
    }
    found
}

/// `IExtensible::getExtension(UID)` on a player.
///
/// **This reaches less than it looks like it should.** Components attach their
/// per-player data with `addExtension`, which files it in a `robin_hood` map
/// that the virtual `getExtension` does not consult — the C++ side finds it
/// through `queryExtension<T>()`, a template that checks the map first and only
/// then calls the virtual. So the stock components' data (dialogs, checkpoints,
/// a player's menu) comes back null here.
///
/// What this does reach is an extension a component exposes by overriding
/// `getExtension` itself. For the rest, the Pawn natives are the working route:
/// `Amx::call_native("ShowPlayerDialog", ...)`. Reading the map would mean
/// mirroring `robin_hood`'s layout, which this SDK does not do — see the note
/// on `entries()` in [`pool_bounds`].
///
/// # Safety
/// See [`player_kick`].
#[must_use]
pub unsafe fn player_extension(player: *mut IPlayer, uid: UID) -> *mut u8 {
    call_vtable!(
        player.cast::<u8>(),
        0,
        SLOT_GET_EXTENSION,
        (UID) -> *mut u8,
        (uid),
        std::ptr::null_mut()
    )
}

/// `IPlayer::sendClientMessage(const Colour&, StringView)` — a chat line for
/// this player only.
///
/// `colour` is RGBA, the order [`Colour`] stores. The text is borrowed for the
/// duration of the call: the server copies what it needs, and a `StringView`
/// carries a length, so no NUL terminator is required.
///
/// # Safety
/// See [`player_kick`].
pub unsafe fn player_send_message(player: *mut IPlayer, colour: Colour, text: &str) {
    let text = StringView {
        data: text.as_ptr(),
        len: text.len(),
    };
    call_vtable!(
        player.cast::<u8>(),
        0,
        SLOT_PLAYER_SEND_MESSAGE,
        (*const Colour, StringView) -> (),
        (&raw const colour, text),
        ()
    )
}

/// Writes the `get<X>Dispatcher` + `add_<x>_handler` pair for one event group.
macro_rules! dispatcher_pair {
    ($getter:ident -> $dispatcher:ident @ $slot:ident, $adder:ident($handler:ident)) => {
        /// The pool's dispatcher for this event group.
        ///
        /// # Safety
        /// `pool` must come from [`player_pool`].
        #[must_use]
        pub unsafe fn $getter(pool: *mut IPlayerPool) -> *mut $dispatcher {
            #[cfg(not(target_env = "msvc"))]
            type GetFn = unsafe extern "C" fn(*mut u8) -> *mut $dispatcher;
            #[cfg(target_env = "msvc")]
            type GetFn = unsafe extern "thiscall" fn(*mut u8) -> *mut $dispatcher;

            let Some((this, f_ptr)) =
                (unsafe { super::vtable::secondary_call_target_ptr(pool.cast::<u8>(), 0, $slot) })
            else {
                return std::ptr::null_mut();
            };
            let get: GetFn = unsafe { std::mem::transmute(f_ptr) };
            unsafe { get(this) }
        }

        /// Registers `handler` on the dispatcher (`addEventHandler`, slot [0]).
        ///
        /// Returns what the server returned: `false` means it was already
        /// registered.
        ///
        /// # Safety
        /// Both pointers must be valid, and `handler` must outlive the
        /// registration.
        pub unsafe fn $adder(dispatcher: *mut $dispatcher, handler: *mut $handler) -> bool {
            #[cfg(not(target_env = "msvc"))]
            type AddFn = unsafe extern "C" fn(*mut u8, *mut $handler, i8) -> bool;
            #[cfg(target_env = "msvc")]
            type AddFn = unsafe extern "thiscall" fn(*mut u8, *mut $handler, i8) -> bool;

            let Some((this, f_ptr)) = (unsafe {
                super::vtable::secondary_call_target_ptr(dispatcher.cast::<u8>(), 0, 0)
            }) else {
                return false;
            };
            let add: AddFn = unsafe { std::mem::transmute(f_ptr) };
            unsafe { add(this, handler, 0) }
        }
    };
}

dispatcher_pair!(player_spawn_dispatcher -> IPlayerSpawnDispatcher @ SLOT_SPAWN_DISPATCHER,
                 add_player_spawn_handler(PlayerSpawnHandler));
dispatcher_pair!(player_text_dispatcher -> IPlayerTextDispatcher @ SLOT_TEXT_DISPATCHER,
                 add_player_text_handler(PlayerTextHandler));
dispatcher_pair!(player_damage_dispatcher -> IPlayerDamageDispatcher @ SLOT_DAMAGE_DISPATCHER,
                 add_player_damage_handler(PlayerDamageHandler));

dispatcher_pair!(player_stream_dispatcher -> IPlayerStreamDispatcher @ SLOT_STREAM_DISPATCHER,
                 add_player_stream_handler(PlayerStreamHandler));
dispatcher_pair!(player_shot_dispatcher -> IPlayerShotDispatcher @ SLOT_SHOT_DISPATCHER,
                 add_player_shot_handler(PlayerShotHandler));
dispatcher_pair!(player_change_dispatcher -> IPlayerChangeDispatcher @ SLOT_CHANGE_DISPATCHER,
                 add_player_change_handler(PlayerChangeHandler));
dispatcher_pair!(player_click_dispatcher -> IPlayerClickDispatcher @ SLOT_CLICK_DISPATCHER,
                 add_player_click_handler(PlayerClickHandler));
dispatcher_pair!(player_check_dispatcher -> IPlayerCheckDispatcher @ SLOT_CHECK_DISPATCHER,
                 add_player_check_handler(PlayerCheckHandler));
dispatcher_pair!(player_update_dispatcher -> IPlayerUpdateDispatcher @ SLOT_UPDATE_DISPATCHER,
                 add_player_update_handler(PlayerUpdateHandler));

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

    #[test]
    fn slots_match_the_official_binaries() {
        // Dumped from `omp-server`: Core [8] getPlayers, PlayerPool [10]
        // getPlayerConnectDispatcher. MSVC drops one destructor slot.
        #[cfg(not(target_env = "msvc"))]
        {
            assert_eq!(SLOT_GET_PLAYERS, 8);
            assert_eq!(SLOT_CONNECT_DISPATCHER, 10);
        }
        #[cfg(target_env = "msvc")]
        {
            assert_eq!(SLOT_GET_PLAYERS, 7);
            assert_eq!(SLOT_CONNECT_DISPATCHER, 9);
        }
    }

    #[test]
    fn the_other_dispatcher_slots_match_the_dump() {
        // From the `PlayerPool` vtable of the official `omp-server`:
        // [9] spawn, [10] connect, [12] text, [15] damage.
        #[cfg(not(target_env = "msvc"))]
        {
            assert_eq!(SLOT_SPAWN_DISPATCHER, 9);
            assert_eq!(SLOT_TEXT_DISPATCHER, 12);
            assert_eq!(SLOT_DAMAGE_DISPATCHER, 15);
        }
        #[cfg(target_env = "msvc")]
        {
            assert_eq!(SLOT_SPAWN_DISPATCHER, 8);
            assert_eq!(SLOT_TEXT_DISPATCHER, 11);
            assert_eq!(SLOT_DAMAGE_DISPATCHER, 14);
        }
    }

    #[test]
    fn every_handler_vtable_has_the_slots_its_header_declares() {
        let pointer = std::mem::size_of::<*const ()>();
        assert_eq!(std::mem::size_of::<PlayerSpawnHandlerVTable>(), 2 * pointer);
        assert_eq!(std::mem::size_of::<PlayerTextHandlerVTable>(), 2 * pointer);
        assert_eq!(
            std::mem::size_of::<PlayerDamageHandlerVTable>(),
            3 * pointer
        );
        assert_eq!(std::mem::offset_of!(PlayerSpawnHandler, vtable), 0);
        assert_eq!(std::mem::offset_of!(PlayerTextHandler, vtable), 0);
        assert_eq!(std::mem::offset_of!(PlayerDamageHandler, vtable), 0);
    }

    #[test]
    fn the_remaining_dispatcher_slots_match_the_dump() {
        // PlayerPool vtable of the official `omp-server`: [11] stream,
        // [13] shot, [14] change, [16] click, [17] check, [18] update.
        #[cfg(not(target_env = "msvc"))]
        let expected = [11, 13, 14, 16, 17, 18];
        #[cfg(target_env = "msvc")]
        let expected = [10, 12, 13, 15, 16, 17];
        assert_eq!(
            [
                SLOT_STREAM_DISPATCHER,
                SLOT_SHOT_DISPATCHER,
                SLOT_CHANGE_DISPATCHER,
                SLOT_CLICK_DISPATCHER,
                SLOT_CHECK_DISPATCHER,
                SLOT_UPDATE_DISPATCHER,
            ],
            expected
        );
    }

    #[test]
    fn the_remaining_vtables_have_the_slots_their_headers_declare() {
        let p = std::mem::size_of::<*const ()>();
        assert_eq!(std::mem::size_of::<PlayerStreamHandlerVTable>(), 2 * p);
        assert_eq!(std::mem::size_of::<PlayerShotHandlerVTable>(), 5 * p);
        assert_eq!(std::mem::size_of::<PlayerChangeHandlerVTable>(), 5 * p);
        assert_eq!(std::mem::size_of::<PlayerClickHandlerVTable>(), 2 * p);
        assert_eq!(std::mem::size_of::<PlayerCheckHandlerVTable>(), p);
        assert_eq!(std::mem::size_of::<PlayerUpdateHandlerVTable>(), p);
    }

    #[test]
    fn player_method_slots_match_the_dump() {
        // `Player` vtable of the official `omp-server`: [6] kick, [8] isBot,
        // [27] getName. MSVC drops the second destructor slot, and no
        // `IEntity` override (secondary base) sits before any of these, so the
        // shift is exactly one. Unlike the component classes, the Windows
        // server carries no RTTI for `Player`, so these cannot be re-derived
        // from the binary — `scripts/omp-vtable.py` derives them from the
        // headers with clang, and a running server proves them.
        #[cfg(not(target_env = "msvc"))]
        let expected = [6, 8, 27, 77, 78, 79, 80, 100];
        #[cfg(target_env = "msvc")]
        let expected = [5, 7, 26, 76, 77, 78, 79, 99];

        // The plain accessors added later, same source, same shift.
        #[cfg(not(target_env = "msvc"))]
        assert_eq!(
            [
                SLOT_PLAYER_SET_DRUNK,
                SLOT_PLAYER_SET_CONTROLLABLE,
                SLOT_PLAYER_SET_WANTED,
                SLOT_PLAYER_GET_WANTED,
                SLOT_PLAYER_GET_MONEY,
                SLOT_PLAYER_GET_SKIN,
                SLOT_PLAYER_SET_WEATHER,
                SLOT_PLAYER_SET_INTERIOR,
                SLOT_PLAYER_GET_INTERIOR,
            ],
            [40, 46, 49, 50, 65, 98, 107, 118, 119]
        );
        #[cfg(target_env = "msvc")]
        assert_eq!(
            [
                SLOT_PLAYER_SET_DRUNK,
                SLOT_PLAYER_SET_CONTROLLABLE,
                SLOT_PLAYER_SET_WANTED,
                SLOT_PLAYER_GET_WANTED,
                SLOT_PLAYER_GET_MONEY,
                SLOT_PLAYER_GET_SKIN,
                SLOT_PLAYER_SET_WEATHER,
                SLOT_PLAYER_SET_INTERIOR,
                SLOT_PLAYER_GET_INTERIOR,
            ],
            [39, 45, 48, 49, 64, 97, 106, 117, 118]
        );
        assert_eq!(
            [
                SLOT_PLAYER_KICK,
                SLOT_PLAYER_IS_BOT,
                SLOT_PLAYER_GET_NAME,
                SLOT_PLAYER_SET_HEALTH,
                SLOT_PLAYER_GET_HEALTH,
                SLOT_PLAYER_SET_SCORE,
                SLOT_PLAYER_GET_SCORE,
                SLOT_PLAYER_SEND_MESSAGE,
            ],
            expected
        );
    }

    #[test]
    fn the_entity_subobject_sits_where_iextensible_ends() {
        // clang's record layout for `IPlayer`: the `IEntity` base starts at 40
        // under Itanium and 56 under MSVC — the size of `IExtensible` on each,
        // the same number `OmpComponent` uses for its `IUIDProvider`.
        #[cfg(not(target_env = "msvc"))]
        assert_eq!(ENTITY_OFFSET, 40);
        #[cfg(target_env = "msvc")]
        assert_eq!(ENTITY_OFFSET, 56);

        // `IEntity` declares no destructor, so both ABIs number it the same.
        assert_eq!(
            [
                SLOT_ENTITY_GET_POSITION,
                SLOT_ENTITY_SET_POSITION,
                SLOT_ENTITY_GET_VIRTUAL_WORLD,
                SLOT_ENTITY_SET_VIRTUAL_WORLD,
            ],
            [1, 2, 5, 6]
        );
    }

    #[test]
    fn handler_layout_is_a_bare_vtable_pointer() {
        assert_eq!(std::mem::offset_of!(PlayerConnectHandler, vtable), 0);
        assert_eq!(
            std::mem::size_of::<PlayerConnectHandler>(),
            std::mem::size_of::<*const ()>()
        );
        assert_eq!(
            std::mem::size_of::<PlayerConnectHandlerVTable>(),
            4 * std::mem::size_of::<*const ()>(),
            "four slots: no virtual destructor in the header"
        );
    }

    #[test]
    fn unknown_disconnect_reason_does_not_invent_a_variant() {
        assert_eq!(DisconnectReason::from_raw(1), DisconnectReason::Quit);
        assert_eq!(DisconnectReason::from_raw(99), DisconnectReason::Custom);
    }
}