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
//! # GGRS
//!
//! GGRS (good game rollback system) is a reimagination of the GGPO network SDK written in Rust.
//! Instead of the callback-style API from the original library, GGRS returns a list of [`GgrsRequest`]s
//! for you to fulfill each frame.
//!
//! ## How It Works
//!
//! Rollback networking lets your game run at full speed using only local input, predicting what
//! remote players are doing. When real remote inputs arrive, GGRS detects any misprediction,
//! rolls the game back to the last correct state, and re-simulates forward. To support this, your
//! game needs to be able to:
//!
//! 1. **Save** its state to a [`GameStateCell`] on request.
//! 2. **Load** a previously saved state from a [`GameStateCell`] on request.
//! 3. **Advance** by one frame given a set of player inputs.
//!
//! GGRS handles everything else: input exchange, prediction, rollback scheduling, time
//! synchronization, and desync detection.
//!
//! ## Quick Start
//!
//! ### 1. Implement `Config`
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Copy, Clone, PartialEq, Default, Serialize, Deserialize)]
//! pub struct Input { pub left: bool, pub right: bool, pub jump: bool }
//!
//! pub struct GameState { /* ... */ }
//!
//! pub struct GgrsConfig;
//! impl ggrs::Config for GgrsConfig {
//! type Input = Input;
//! type InputPredictor = ggrs::PredictRepeatLast;
//! type State = GameState;
//! type Address = std::net::SocketAddr;
//! }
//! ```
//!
//! ### 2. Build a Session
//!
//! ```rust,no_run
//! # use ggrs::{SessionBuilder, PlayerType, UdpNonBlockingSocket};
//! # struct GgrsConfig; impl ggrs::Config for GgrsConfig { type Input = u8; type InputPredictor = ggrs::PredictRepeatLast; type State = u8; type Address = std::net::SocketAddr; }
//! let socket = UdpNonBlockingSocket::bind_to_port(7000).unwrap();
//! let mut session = SessionBuilder::<GgrsConfig>::new()
//! .with_num_players(2).unwrap()
//! .with_input_delay(2)
//! .add_player(PlayerType::Local, 0).unwrap()
//! .add_player(PlayerType::Remote("127.0.0.1:7001".parse().unwrap()), 1).unwrap()
//! .start_p2p_session(socket).unwrap();
//! ```
//!
//! ### 3. Drive the Game Loop
//!
//! Each tick, poll the network, drain events, then advance the frame:
//!
//! ```rust,no_run
//! # use ggrs::*;
//! # struct GgrsConfig;
//! # impl Config for GgrsConfig { type Input = u8; type InputPredictor = PredictRepeatLast; type State = u8; type Address = std::net::SocketAddr; }
//! # let socket = UdpNonBlockingSocket::bind_to_port(7000).unwrap();
//! # let mut session: P2PSession<GgrsConfig> = SessionBuilder::new()
//! # .add_player(PlayerType::Local, 0).unwrap()
//! # .add_player(PlayerType::Remote("127.0.0.1:7001".parse().unwrap()), 1).unwrap()
//! # .start_p2p_session(socket).unwrap();
//! # let local_handle = 0usize; let my_input: u8 = 0;
//! session.poll_remote_clients();
//! for event in session.events() { /* handle GgrsEvents */ }
//! session.add_local_input(local_handle, my_input).unwrap();
//! match session.advance_frame() {
//! Ok(requests) => {
//! for request in requests {
//! // handle SaveGameState, LoadGameState, AdvanceFrame — in order
//! }
//! }
//! Err(GgrsError::PredictionThreshold) => { /* skip frame */ }
//! Err(e) => panic!("{e}"),
//! }
//! ```
//!
//! ## Session Types
//!
//! | Type | Use case |
//! |---|---|
//! | [`P2PSession`] | Main multiplayer session; connects peers directly. |
//! | [`SpectatorSession`] | Watch a game without contributing input. |
//! | [`SyncTestSession`] | Local determinism testing; no network required. |
//!
//! All session types are constructed with [`SessionBuilder`].
//!
//! ## Feature Flags
//!
//! - **`sync-send`**: Adds `Send + Sync` bounds to [`Config`], [`NonBlockingSocket`], and session
//! types. Enable this if you need to share sessions across threads.
//! - **`wasm-bindgen`**: Enables WASM support. Required when targeting `wasm32` with browser APIs.
//!
//! ## Further Reading
//!
//! See the [`docs/`](https://github.com/gschup/ggrs/tree/main/docs) folder for guides on sessions,
//! the main loop, requests and events, time synchronization, and more.
// let us try
use ;
pub use GgrsError;
pub use Message;
pub use NetworkStats;
pub use UdpNonBlockingSocket;
use ;
pub use SessionBuilder;
pub use P2PSession;
pub use SpectatorSession;
pub use SyncTestSession;
pub use ;
pub
pub
pub
pub
pub
pub
pub
// #############
// # CONSTANTS #
// #############
/// Internally, -1 represents no frame / invalid frame.
pub const NULL_FRAME: i32 = -1;
/// A frame is a single step of execution.
pub type Frame = i32;
/// Each player is identified by a player handle.
pub type PlayerHandle = usize;
// #############
// # ENUMS #
// #############
/// Desync detection by comparing checksums between peers.
/// Defines the three types of players that GGRS considers:
/// - local players, who play on the local device,
/// - remote players, who play on other devices and
/// - spectators, who are remote players that do not contribute to the game input.
/// Both [`PlayerType::Remote`] and [`PlayerType::Spectator`] have a socket address associated with them.
/// A session is always in one of these states. You can query the current state of a session via [`current_state`].
///
/// [`current_state`]: P2PSession#method.current_state
/// [`InputStatus`] will always be given together with player inputs when requested to advance the frame.
/// Notifications that you can receive from the session. Handling them is up to the user.
/// Requests that you can receive from the session. Handling them is mandatory.
// #############
// # TRAITS #
// #############
// special thanks to james7132 for the idea of a config trait that bundles all generics
/// Compile time parameterization for sessions.
/// Custom transport layer for GGRS sessions.
///
/// Implement this trait to use GGRS with any transport that can send and receive discrete,
/// unordered, unreliable packets — WebRTC data channels, Steam networking, shared-memory
/// queues for testing, etc. GGRS provides its own reliability and ordering on top.
///
/// The built-in [`UdpNonBlockingSocket`] implements this trait for standard UDP.
///
/// # WASM / WebRTC example
///
/// On WASM, UDP sockets are unavailable. A common approach is to use
/// [matchbox_socket](https://github.com/johanhelsing/matchbox) which wraps WebRTC data
/// channels with a UDP-like interface. The implementation pattern looks like this:
///
/// ```ignore
/// use ggrs::{Message, NonBlockingSocket};
/// use matchbox_socket::{PeerId, WebRtcSocket};
///
/// pub struct MatchboxSocket(WebRtcSocket);
///
/// impl NonBlockingSocket<PeerId> for MatchboxSocket {
/// fn send_to(&mut self, msg: &Message, addr: &PeerId) {
/// let encoded = bincode::serialize(msg).expect("serialization failed");
/// self.0.send(encoded.into(), *addr);
/// }
///
/// fn receive_all_messages(&mut self) -> Vec<(PeerId, Message)> {
/// self.0.receive()
/// .filter_map(|(peer, packet)| {
/// let msg = bincode::deserialize(&packet).ok()?;
/// Some((peer, msg))
/// })
/// .collect()
/// }
/// }
/// ```
///
/// Then use `PeerId` as `Config::Address` and pass your `MatchboxSocket` to
/// [`SessionBuilder::start_p2p_session()`].
///
/// [`SessionBuilder::start_p2p_session()`]: crate::SessionBuilder::start_p2p_session
/// Compile time parameterization for sessions.
/// Custom transport layer for GGRS sessions.
///
/// Implement this trait to use GGRS with any transport that can send and receive discrete,
/// unordered, unreliable packets — WebRTC data channels, Steam networking, shared-memory
/// queues for testing, etc. GGRS provides its own reliability and ordering on top.
///
/// The built-in [`UdpNonBlockingSocket`] implements this trait for standard UDP.
///
/// # WASM / WebRTC example
///
/// On WASM, UDP sockets are unavailable. A common approach is to use
/// [matchbox_socket](https://github.com/johanhelsing/matchbox) which wraps WebRTC data
/// channels with a UDP-like interface. The implementation pattern looks like this:
///
/// ```ignore
/// use ggrs::{Message, NonBlockingSocket};
/// use matchbox_socket::{PeerId, WebRtcSocket};
///
/// pub struct MatchboxSocket(WebRtcSocket);
///
/// impl NonBlockingSocket<PeerId> for MatchboxSocket {
/// fn send_to(&mut self, msg: &Message, addr: &PeerId) {
/// let encoded = bincode::serialize(msg).expect("serialization failed");
/// self.0.send(encoded.into(), *addr);
/// }
///
/// fn receive_all_messages(&mut self) -> Vec<(PeerId, Message)> {
/// self.0.receive()
/// .filter_map(|(peer, packet)| {
/// let msg = bincode::deserialize(&packet).ok()?;
/// Some((peer, msg))
/// })
/// .collect()
/// }
/// }
/// ```
///
/// Then use `PeerId` as `Config::Address` and pass your `MatchboxSocket` to
/// [`SessionBuilder::start_p2p_session()`].
///
/// [`SessionBuilder::start_p2p_session()`]: crate::SessionBuilder::start_p2p_session
/// An [InputPredictor] allows GGRS to predict the next input for a player based on previous input
/// received.
///
/// # Bundled Predictors
///
/// [PredictRepeatLast] is a good default choice for most action games where inputs consist of the
/// buttons player are holding down; if your game input instead consists of sporadic one-off events
/// which are almost never repeated, then [PredictDefault] may better suit.
///
/// You are welcome to implement your own predictor to exploit known properties of your input.
///
/// # Understanding Predictions
///
/// A correct prediction means a rollback will not happen when input is received late from a remote
/// player. An incorrect prediction will later cause GGRS to request your game to rollback. It is
/// normal and expected that some predictions will be incorrect, but the more incorrect predictions
/// are given to GGRS, the more work your game will have to do to resimulate past game states (and
/// the more rollbacks may be noticeable to your human players).
///
/// For example, if your chosen input predictor says a player's input always makes them crouch, but
/// in your game players only crouch in 1% of frames, then:
///
/// * GGRS will make it seem to your game as if all remote players crouch on every frame.
/// * When GGRS receives input from a remote player and finds out they are not crouching, it will
/// ask your game to roll back to the frame that input was from and resimulate it plus all
/// subsequent frames up to and including the present frame.
/// * Therefore 99% of frames will be resimulated.
///
/// # Improving Prediction Accuracy
///
/// ## Quantize Inputs
///
/// Input prediction based on repeating past inputs works best if your inputs are discrete (or
/// quantized), as this increases the chances of them being the same from frame to frame.
///
/// For example, say your game allows players to move forward or stand still using an analog
/// joystick; here are two ways you could represent player input:
///
/// * `moving_forward: bool` set to `true` when the joystick is pressed forward and `false`
/// otherwise.
/// * `forward_speed: f32` with a range from `0.0` to `1.0` depending on how far the joystick is
/// pressed forward.
///
/// The former works well with [PredictRepeatLast], but the (fairly) continuous nature of a 32-bit
/// floating point number plus the precision of an analog joystick plus the inability of most humans
/// to hold a joystick perfectly still means that the value of `forward_speed` from one frame to the
/// next will almost always differ; this in turn will cause many mispredictions when used with
/// [PredictRepeatLast].
///
/// Quantization generally incurs a tradeoff between input precision and prediction accuracy, with
/// the right choice depending on the game's design:
///
/// * in a keyboard-only game, move-forward input is likely a binary "move or not" anyway, so
/// quantizing is unnecessary.
/// * in a 2D fighting game played with analog joysticks, it might be fine for movement to be
/// represented as "stand still", "walk forward", and "run forward" based on how far the joystick
/// is pressed forward.
/// * in a platformer played with analog joysticks, 5 to 10 discrete moving forward speeds may be
/// required in order for the game to feel precise enough.
///
/// ## State-based vs Transition-based Input
///
/// The bundled predictors works best if your input either captures the current state of player
/// input ([PredictRepeatLast]) OR captures transitions between states ([PredictDefault]).
///
/// For example, say your game allows players to hold a button to crouch; here are two ways you
/// could represent player input:
///
/// * state-based: `crouching_button_held`, set to `true` as long as the player is crouching
/// * transition-based: `crouching_button_pressed` and `crouching_button_released`, which are set to
/// true on the frames where the player first presses and and releases the crouch button
/// (respectively)
///
/// Given a sequence of these inputs over time, these two representations capture the same
/// information (with some bookkeeping, your game can trivially convert between the two). But,
/// consider a single instance of a player crouching for several frames in a row:
///
/// In the first case (state-based), [PredictRepeatLast] will make two mispredictions: once on the
/// first frame when crouching begins, and once on the last frame when the player releases the
/// crouch button.
///
/// But in the second case (transition-based), [PredictRepeatLast] will make four mispredictions:
///
/// * When the player first presses the crouch button
/// * The frame immediately after the crouch button was pressed
/// * When the player releases the crouch button
/// * The frame immediately after the crouch button was released
///
/// Therefore, [PredictRepeatLast] is better suited to a state-based representation of input, and
/// [PredictDefault] is better suited to a transition-based representation of input.
///
/// If your input is a mix of both states and transitions, then consider implementing your own
/// prediction strategy that exploits that.
/// An [InputPredictor] that predicts that the next input for any player will be identical to the
/// last received input for that player.
///
/// This is a good default choice, and a sane starting point for any custom input prediction logic.
;
/// An input predictor that always predicts that the next input for any given player will be the
/// [Default](Default::default()) input, regardless of what the previous input was.
///
/// This is appropriate if your inputs capture transitions between rather than states themselves;
/// see the discussion at [PredictRepeatLast] (which is better suited for inputs that capture
/// state) for a concrete example.
;