Skip to content

Commit

Permalink
nes: Move the protocol name. Change to using a pre-formatted vec for …
Browse files Browse the repository at this point in the history
…button combos.
  • Loading branch information
tepperson2 committed Feb 2, 2024
1 parent 285bc28 commit 9f321d3
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 27 deletions.
26 changes: 17 additions & 9 deletions nes/rust/src/network/emulator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use common_emulator::streaming::{StreamingIn, StreamingOut};
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum MessageToFromNetwork {
/// Controller data for a specific controller.
ControllerData(u8, Box<crate::controller::ButtonCombination>),
ControllerData(u8, Vec<u8>),
/// Part of the emulator audio video stream.
EmulatorVideoStream(Vec<u8>),
/// A request for a specific role in the network.
Expand Down Expand Up @@ -61,11 +61,11 @@ pub struct Protocol {
protocols: Vec<ProtocolId>,
}

impl Default for Protocol {
fn default() -> Self {
impl Protocol {
fn new(s: &'static str) -> Self {
Self {
protocols: vec![ProtocolId {
protocol: StreamProtocol::new("/nes/0.0.1"),
protocol: StreamProtocol::new(s),
}],
}
}
Expand Down Expand Up @@ -226,7 +226,7 @@ impl Handler {
/// Represents messages that can be send between the networkbehaviour and the connectionhandler.
pub enum MessageToFromBehavior {
/// Controller data for a specific controller.
ControllerData(u8, Box<ButtonCombination>),
ControllerData(u8, Vec<u8>),
/// A request for a specific role on the network.
RequestRole(PeerId, NodeRole),
/// A request for a specific controller on the emulator.
Expand Down Expand Up @@ -527,12 +527,20 @@ impl std::fmt::Debug for Message {
}

/// Represents a protocol configuration for the behavior.
#[derive(Clone, Default)]
#[derive(Clone)]
pub struct Config {
/// The supported protocol
protocol: Protocol,
}

impl Config {
fn new(s: &'static str) -> Self {
Self {
protocol: Protocol::new(s),
}
}
}

#[derive(Copy, Clone)]
/// The details necessary to run an emulator host.
struct ServerDetails {
Expand Down Expand Up @@ -572,7 +580,7 @@ impl Behavior {
/// Construct a new Self
pub fn new() -> Self {
Self {
config: Config::default(),
config: Config::new("/nes/0.0.1"),
messages: VecDeque::new(),
waker: Arc::new(Mutex::new(None)),
clients: HashSet::new(),
Expand Down Expand Up @@ -641,7 +649,7 @@ impl Behavior {
}

/// Send the given controller data to the host.
pub fn send_controller_data(&mut self, index: u8, data: Box<ButtonCombination>) {
pub fn send_controller_data(&mut self, index: u8, data: Vec<u8>) {
if let Some(pid) = &self.server {
self.messages.push_back(ToSwarm::NotifyHandler {
peer_id: *pid,
Expand Down Expand Up @@ -741,7 +749,7 @@ impl Behavior {
/// Represents the types of messages that can be sent to the swarm from the network behaviour.
pub enum MessageToSwarm {
/// Controller data from a user
ControllerData(u8, Box<ButtonCombination>),
ControllerData(u8, Vec<u8>),
/// A role request from a user.
RequestRole(PeerId, NodeRole),
/// A command from a host to set the role of a user.
Expand Down
30 changes: 17 additions & 13 deletions nes/rust/src/network/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub enum NodeRole {
#[derive(Debug)]
pub enum MessageToNetworkThread {
/// Controller data from the player, with which controller index and the button data.
ControllerData(u8, Box<ButtonCombination>),
ControllerData(u8, Vec<u8>),
/// Signal to start PlayerHost mode
StartServer {
/// The width of the image
Expand Down Expand Up @@ -69,7 +69,7 @@ pub enum MessageFromNetworkThread {
/// Emulator video and audio data.
AvStream(Vec<u8>),
/// Controller data from one of the players.
ControllerData(u8, Box<ButtonCombination>),
ControllerData(u8, Vec<u8>),
/// Indicates that the host has a new address
NewAddress(Multiaddr),
/// Indicates that the host no longer has the specified address
Expand Down Expand Up @@ -395,7 +395,9 @@ pub struct Network {
/// The role for this node in the network.
role: NodeRole,
/// The cached button inputs for all possible players in the game.
buttons: [Option<ButtonCombination>; 4],
buttons: [Option<Vec<u8>>; 4],
/// Holds data for a disconnected player
buttons_disconnect: Vec<u8>,
/// The controller that this node is holding. None indicates that no controller is held.
my_controller: Option<u8>,
/// Indicates who is holding each controller, if there is somebody holding that controller.
Expand All @@ -417,6 +419,7 @@ impl Network {
pub fn new(
proxy: egui_multiwin::winit::event_loop::EventLoopProxy<common_emulator::event::Event>,
audio_rate: u32,
blank_controller: Vec<u8>,
) -> Self {
let (s1, r1) = async_channel::bounded(1000);
let (s2, r2) = async_channel::bounded(1000);
Expand All @@ -433,7 +436,8 @@ impl Network {
addresses: HashSet::new(),
server_running: false,
role: NodeRole::Unknown,
buttons: [None; 4],
buttons: [None, None, None, None],
buttons_disconnect: blank_controller,
my_controller: None,
controller_holder: [None; 4],
connected: false,
Expand All @@ -449,9 +453,9 @@ impl Network {
&self.addresses
}

/// Retrieve the specified index of button data, cloned.
pub fn get_button_data(&mut self, i: u8) -> Option<ButtonCombination> {
self.buttons[i as usize]
/// Retrieve the specified index of button data.
pub fn get_button_data(&mut self, i: u8) -> &Option<Vec<u8>> {
&self.buttons[i as usize]
}

/// Process all messages received from the network thread.
Expand All @@ -464,7 +468,7 @@ impl Network {
if let Some(p) = self.controller_holder[i] {
if peer == p {
if let Some(b) = &mut self.buttons[i] {
b.clear_buttons();
*b = self.buttons_disconnect.clone();
}
self.controller_holder[i] = None;
break;
Expand Down Expand Up @@ -493,7 +497,7 @@ impl Network {
if peer == p {
println!("Clear controller {}", i);
if let Some(b) = &mut self.buttons[i] {
b.clear_buttons();
*b = self.buttons_disconnect.clone();
}
self.controller_holder[i] = None;
break;
Expand All @@ -511,7 +515,7 @@ impl Network {
if let Some(peer) = self.controller_holder[i] {
if peer == p {
if let Some(b) = &mut self.buttons[i] {
b.clear_buttons();
*b = self.buttons_disconnect.clone();
}
self.controller_holder[i] = None;
let _ = self.sender.send_blocking(
Expand Down Expand Up @@ -549,7 +553,7 @@ impl Network {
}
MessageFromNetworkThread::ControllerData(i, d) => {
if self.controller_holder[i as usize].is_some() {
self.buttons[i as usize] = Some(*d);
self.buttons[i as usize] = Some(d);
}
}
MessageFromNetworkThread::NewAddress(a) => {
Expand Down Expand Up @@ -716,12 +720,12 @@ impl Network {
pub fn send_controller_data(
&mut self,
i: u8,
data: crate::controller::ButtonCombination,
data: Vec<u8>,
) -> Result<(), async_channel::SendError<MessageToNetworkThread>> {
if let Some(id) = &self.my_controller {
if *id == i {
self.sender
.send_blocking(MessageToNetworkThread::ControllerData(i, Box::new(data)))?;
.send_blocking(MessageToNetworkThread::ControllerData(i, data))?;
}
}
Ok(())
Expand Down
20 changes: 15 additions & 5 deletions nes/rust/src/windows/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
//!
use std::io::Write;

use crate::{controller::NesControllerTrait, network::NodeRole, NesEmulatorData};
use crate::{
controller::{ButtonCombination, NesControllerTrait},
network::NodeRole,
NesEmulatorData,
};

use common_emulator::audio::AudioProducerWithRate;
use common_emulator::recording::Recording;
Expand Down Expand Up @@ -464,15 +468,21 @@ impl TrackedWindow for MainNesWindow {
NodeRole::Player => {
let controller = c.mb.get_controller_ref(0);
for i in 0..4 {
let _e = network.send_controller_data(i, controller.button_data());
let _e = network.send_controller_data(
i,
bincode::serialize(&controller.button_data()).unwrap(),
);
}
}
NodeRole::PlayerHost => {
for i in 0..4 {
if let Some(bc) = network.get_button_data(i) {
let controller = c.mb.get_controller_mut(i);
if let Some(con) = controller.get_buttons_iter_mut().next() {
*con = bc;
if let Ok(bc) = bincode::deserialize::<ButtonCombination>(bc) {
let controller = c.mb.get_controller_mut(i);
if let Some(con) = controller.get_buttons_iter_mut().next()
{
*con = bc;
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions nes/rust/src/windows/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,13 @@ impl TrackedWindow for Window {
ui.label("Network is not active");
if ui.button("Enable networking").clicked() {
if let Some(proxy) = c.local.get_proxy() {
let mut button = crate::controller::ButtonCombination::new();
button.clear_buttons();
let button = bincode::serialize(&button).unwrap();
olocal.network = Some(crate::network::Network::new(
proxy,
c.local.get_sound_rate(),
button,
));
}
}
Expand Down

0 comments on commit 9f321d3

Please sign in to comment.