refactor the rest of the fucking code

This commit is contained in:
jake 2022-10-18 04:46:21 -06:00
parent 27931adb5a
commit fdce44cdd8
52 changed files with 3757 additions and 2218 deletions

10
Cargo.lock generated
View File

@ -1061,7 +1061,6 @@ checksum = "739e9d7726dc32173fed2d69d17eef3c54682169e4e20ff1d0a45dcd37063cef"
[[package]] [[package]]
name = "libpso" name = "libpso"
version = "0.1.0" version = "0.1.0"
source = "git+http://git.sharnoth.com/jake/libpso#4fba0529aef169c67a99709582109ca5c68f15de"
dependencies = [ dependencies = [
"chrono", "chrono",
"psopacket", "psopacket",
@ -1420,7 +1419,6 @@ dependencies = [
[[package]] [[package]]
name = "psopacket" name = "psopacket"
version = "1.0.0" version = "1.0.0"
source = "git+http://git.sharnoth.com/jake/libpso#4fba0529aef169c67a99709582109ca5c68f15de"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -2071,18 +2069,18 @@ dependencies = [
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.30" version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
dependencies = [ dependencies = [
"thiserror-impl", "thiserror-impl",
] ]
[[package]] [[package]]
name = "thiserror-impl" name = "thiserror-impl"
version = "1.0.30" version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",

View File

@ -2,7 +2,7 @@
name = "elseware" name = "elseware"
version = "0.1.0" version = "0.1.0"
authors = ["Jake Probst <jake.probst@gmail.com>"] authors = ["Jake Probst <jake.probst@gmail.com>"]
edition = "2018" edition = "2021"
[dependencies] [dependencies]
libpso = { git = "http://git.sharnoth.com/jake/libpso" } libpso = { git = "http://git.sharnoth.com/jake/libpso" }
@ -22,7 +22,7 @@ fern = { version = "0.5", features = ["colored"] }
byteorder = "1" byteorder = "1"
enum-utils = "0.1.2" enum-utils = "0.1.2"
derive_more = { version = "0.99.3", features = ["display"]} derive_more = { version = "0.99.3", features = ["display"]}
thiserror = "1.0.15" thiserror = "1.0.37"
ages-prs = "0.1" ages-prs = "0.1"
async-trait = "0.1.51" async-trait = "0.1.51"
async-recursion= "1.0.0" async-recursion= "1.0.0"

View File

@ -1,11 +1,12 @@
use log::{info}; use log::{info};
use elseware::entity::gateway::postgres::PostgresGateway; //use elseware::entity::gateway::postgres::PostgresGateway;
use elseware::login::login::LoginServerState; use elseware::login::login::LoginServerState;
use elseware::login::character::CharacterServerState; use elseware::login::character::CharacterServerState;
use elseware::common::mainloop::{login_mainloop, character_mainloop}; //use elseware::common::mainloop::{login_mainloop, character_mainloop};
use elseware::common::interserver::AuthToken; //use elseware::common::interserver::AuthToken;
fn main() { fn main() {
/*
let colors = fern::colors::ColoredLevelConfig::new() let colors = fern::colors::ColoredLevelConfig::new()
.error(fern::colors::Color::Red) .error(fern::colors::Color::Red)
.warn(fern::colors::Color::Yellow) .warn(fern::colors::Color::Yellow)
@ -48,4 +49,5 @@ fn main() {
async_std::task::block_on(async move { async_std::task::block_on(async move {
futures::future::join_all(vec![login_loop, character_loop]).await futures::future::join_all(vec![login_loop, character_loop]).await
}); });
*/
} }

View File

@ -1,13 +1,15 @@
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use log::{info}; use log::{info};
use async_std::channel;
use elseware::patch::patch::{PatchServerState, generate_patch_tree, load_config, load_motd}; use elseware::patch::patch::{PatchServerState, generate_patch_tree, load_config, load_motd};
use elseware::login::login::LoginServerState; use elseware::login::login::LoginServerState;
use elseware::login::character::CharacterServerState; use elseware::login::character::CharacterServerState;
use elseware::ship::ship::ShipServerStateBuilder; //use elseware::ship::ship::ShipServerStateBuilder;
use elseware::entity::account::{NewUserAccountEntity, NewUserSettingsEntity}; use elseware::entity::account::{NewUserAccountEntity, NewUserSettingsEntity};
#[allow(unused_imports)] #[allow(unused_imports)]
use elseware::entity::gateway::{EntityGateway, InMemoryGateway, PostgresGateway}; //use elseware::entity::gateway::{EntityGateway, InMemoryGateway, PostgresGateway};
use elseware::entity::gateway::{EntityGateway, InMemoryGateway};
use elseware::entity::character::NewCharacterEntity; use elseware::entity::character::NewCharacterEntity;
use elseware::entity::item::{NewItemEntity, ItemDetail, InventoryItemEntity}; use elseware::entity::item::{NewItemEntity, ItemDetail, InventoryItemEntity};
use elseware::common::interserver::AuthToken; use elseware::common::interserver::AuthToken;
@ -330,6 +332,7 @@ fn main() {
entity_gateway.set_character_bank(&character.id, &item::BankEntity::default(), &item::BankName("".into())).await.unwrap(); entity_gateway.set_character_bank(&character.id, &item::BankEntity::default(), &item::BankName("".into())).await.unwrap();
} }
/*
info!("[patch] starting server"); info!("[patch] starting server");
let patch_config = load_config(); let patch_config = load_config();
let patch_motd = load_motd(); let patch_motd = load_motd();
@ -376,5 +379,96 @@ fn main() {
let ship_loop3 = ship_mainloop(*ship_state, elseware::ship::ship::SHIP_PORT+3000, std::net::Ipv4Addr::new(127, 0, 0, 1), elseware::login::login::COMMUNICATION_PORT); let ship_loop3 = ship_mainloop(*ship_state, elseware::ship::ship::SHIP_PORT+3000, std::net::Ipv4Addr::new(127, 0, 0, 1), elseware::login::login::COMMUNICATION_PORT);
futures::future::join_all(vec![patch_loop, login_loop, character_loop, ship_loop, ship_loop2, ship_loop3]).await; futures::future::join_all(vec![patch_loop, login_loop, character_loop, ship_loop, ship_loop2, ship_loop3]).await;
*/
info!("[patch] starting server");
let patch_config = load_config();
let patch_motd = load_motd();
let (patch_file_tree, patch_file_lookup) = generate_patch_tree(patch_config.path.as_str());
let patch_state = PatchServerState::new(patch_file_tree, patch_file_lookup, patch_motd);
let patch_loop = async_std::task::spawn(async move {
elseware::common::mainloop::run_server(patch_state, patch_config.port).await;
});
info!("[auth] starting server");
let auth_entity_gateway = entity_gateway.clone();
let login_state = LoginServerState::new(auth_entity_gateway, "127.0.0.1".parse().unwrap());
let login_loop = async_std::task::spawn(async move {
elseware::common::mainloop::run_server(login_state, elseware::login::login::LOGIN_PORT).await;
});
info!("[character] starting server");
let character_entity_gateway = entity_gateway.clone();
let char_state = CharacterServerState::new(character_entity_gateway, AuthToken("".into()));
let sub_char_state = char_state.clone();
let character_loop = async_std::task::spawn(async move {
elseware::common::mainloop::run_server(sub_char_state, elseware::login::character::CHARACTER_PORT).await;
});
let sub_char_state = char_state.clone();
let inter_character_loop = async_std::task::spawn(async move {
elseware::common::mainloop::run_interserver_listen(sub_char_state, elseware::login::login::COMMUNICATION_PORT).await;
});
/*
let inter_character_loop_recv = async_std::task::spawn(|| async {
crate::common::mainloop::run_interserver_receiver(char_state, elseware::login::character::COMMUNICATION_PORT).await
});
let inter_character_loop_send = async_std::task::spawn(|| async {
crate::common::mainloop::run_interserver_sender(char_state, interserver_rx).await
*/
let ship_entity_gateway = entity_gateway.clone();
info!("[ship] starting server");
//let (interserver_tx, interserver_rx) = async_std::channel::unbounded();
/*
let ship_state = ShipServerStateBuilder::default()
.name("US/Sona-Nyl".into())
.ip(Ipv4Addr::new(127,0,0,1))
.port(elseware::ship::ship::SHIP_PORT)
.gateway(thread_entity_gateway)
.interserver_sender(|msg| async move {
interserver_tx.send(msg).await
})
.build();
let sub_ship_state = ship_state.clone();
let ship_loop = async_std::task::spawn(|| async {
crate::common::mainloop::run_server(sub_ship_state, elseware::ship::ship::SHIP_PORT);
});
/*
/*, std::net::Ipv4Addr::new(127, 0, 0, 1), elseware::login::login::COMMUNICATION_PORT*/
let inter_ship_loop = async_std::task::spawn(|| async {
crate::common::mainloop::run_interserver_receiver(ship_state, elseware::login::login::COMMUNICATION_PORT);
});
*/
let ship_entity_gateway = entity_gateway.clone();
let ship_state = Box::new(ShipServerStateBuilder::default()
.name("EU/Dylath-Leen".into())
.ip(Ipv4Addr::new(127,0,0,1))
.port(elseware::ship::ship::SHIP_PORT+2000)
.gateway(thread_entity_gateway)
.build());
let sub_ship_state = ship_state.clone();
let ship_loop2 = async_std::task::spawn(|| async {
crate::common::mainloop::run_server(sub_ship_state, elseware::ship::ship::SHIP_PORT);
});
let thread_entity_gateway = entity_gateway.clone();
let ship_state = Box::new(ShipServerStateBuilder::default()
.name("JP/Thalarion".into())
.ip(Ipv4Addr::new(127,0,0,1))
.port(elseware::ship::ship::SHIP_PORT+3000)
.gateway(thread_entity_gateway)
.build());
let sub_ship_state = ship_state.clone();
let ship_loop3 = async_std::task::spawn(|| async {
crate::common::mainloop::run_server(sub_ship_state, elseware::ship::ship::SHIP_PORT);
});
futures::future::join_all(vec![patch_loop, login_loop, character_loop, ship_loop, ship_loop2, ship_loop3]).await;
*/
futures::future::join_all(vec![patch_loop, login_loop, character_loop, inter_character_loop]).await;
}); });
} }

View File

@ -1,8 +1,9 @@
use elseware::patch::patch::{PatchServerState, generate_patch_tree, load_config_env, load_motd}; use elseware::patch::patch::{PatchServerState, generate_patch_tree, load_config_env, load_motd};
use log::{info}; use log::{info};
use elseware::common::mainloop::patch_mainloop; //use elseware::common::mainloop::patch_mainloop;
fn main() { fn main() {
/*
info!("[patch] starting server"); info!("[patch] starting server");
let patch_config = load_config_env(); let patch_config = load_config_env();
let patch_motd = load_motd(); let patch_motd = load_motd();
@ -13,4 +14,5 @@ fn main() {
async_std::task::block_on(async move { async_std::task::block_on(async move {
patch_loop.await patch_loop.await
}); });
*/
} }

View File

@ -1,10 +1,11 @@
use log::{info}; use log::{info};
use elseware::entity::gateway::postgres::PostgresGateway; //use elseware::entity::gateway::postgres::PostgresGateway;
use elseware::ship::ship::ShipServerStateBuilder; //use elseware::ship::ship::ShipServerStateBuilder;
use elseware::common::mainloop::ship_mainloop; //use elseware::common::mainloop::ship_mainloop;
use elseware::common::interserver::AuthToken; //use elseware::common::interserver::AuthToken;
fn main() { fn main() {
/*
let colors = fern::colors::ColoredLevelConfig::new() let colors = fern::colors::ColoredLevelConfig::new()
.error(fern::colors::Color::Red) .error(fern::colors::Color::Red)
.warn(fern::colors::Color::Yellow) .warn(fern::colors::Color::Yellow)
@ -52,4 +53,5 @@ fn main() {
async_std::task::block_on(async move { async_std::task::block_on(async move {
ship_loop.await ship_loop.await
}); });
*/
} }

View File

@ -1,4 +1,6 @@
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use async_std::sync::Arc;
use async_std::channel;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use crate::entity::account::UserAccountId; use crate::entity::account::UserAccountId;
@ -46,12 +48,14 @@ pub enum ShipMessage {
#[async_trait::async_trait] #[async_trait::async_trait]
pub trait InterserverActor { pub trait InterserverActor: Clone {
type SendMessage: Serialize; type SendMessage: Serialize;
type RecvMessage: DeserializeOwned; type RecvMessage: DeserializeOwned;
type Error; type Error;
async fn on_connect(&mut self, id: ServerId) -> Vec<(ServerId, Self::SendMessage)>; async fn on_connect(&mut self, id: ServerId) -> Vec<(ServerId, Self::SendMessage)>;
async fn action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error>; async fn on_action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error>;
async fn on_disconnect(&mut self, id: ServerId) -> Vec<(ServerId, Self::SendMessage)>; async fn on_disconnect(&mut self, id: ServerId) -> Vec<(ServerId, Self::SendMessage)>;
//fn set_sender(&mut self, server_id: ServerId, func: Arc<Box<dyn Fn(Self::SendMessage) -> Box<dyn futures::future::Future<Output = ()>>>>);
fn set_sender(&mut self, server_id: ServerId, tx: channel::Sender<Self::SendMessage>);
} }

View File

@ -1,9 +1,10 @@
use std::pin::Pin; use std::pin::pin;
use futures::future::Future; use futures::future::Future;
use log::{trace, info, warn}; use log::{trace, info, warn};
use async_std::sync::{Arc, Mutex}; use async_std::sync::{Arc, Mutex};
use async_std::io::prelude::{ReadExt, WriteExt}; use async_std::io::prelude::{ReadExt, WriteExt};
use std::collections::HashMap; use std::collections::HashMap;
use std::pin::Pin;
use libpso::crypto::{PSOCipher, NullCipher, CipherError}; use libpso::crypto::{PSOCipher, NullCipher, CipherError};
use libpso::PacketParseError; use libpso::PacketParseError;
@ -39,15 +40,16 @@ impl From<PacketParseError> for NetworkError {
} }
} }
struct PacketReceiver { pub struct PacketReceiver<C: PSOCipher> {
socket: Arc<async_std::net::TcpStream>, socket: async_std::net::TcpStream,
cipher: Arc<Mutex<Box<dyn PSOCipher + Send>>>, //cipher: Arc<Mutex<Box<dyn PSOCipher + Send>>>,
cipher: C,
recv_buffer: Vec<u8>, recv_buffer: Vec<u8>,
incoming_data: Vec<u8>, incoming_data: Vec<u8>,
} }
impl PacketReceiver { impl<C: PSOCipher> PacketReceiver<C> {
fn new(socket: Arc<async_std::net::TcpStream>, cipher: Arc<Mutex<Box<dyn PSOCipher + Send>>>) -> PacketReceiver { pub fn new(socket: async_std::net::TcpStream, cipher: C) -> PacketReceiver<C> {
PacketReceiver { PacketReceiver {
socket, socket,
cipher, cipher,
@ -59,7 +61,7 @@ impl PacketReceiver {
async fn fill_recv_buffer(&mut self) -> Result<(), NetworkError> { async fn fill_recv_buffer(&mut self) -> Result<(), NetworkError> {
let mut data = [0u8; 0x8000]; let mut data = [0u8; 0x8000];
let mut socket = &*self.socket; let mut socket = self.socket.clone();
let len = socket.read(&mut data).await?; let len = socket.read(&mut data).await?;
if len == 0 { if len == 0 {
return Err(NetworkError::ClientDisconnected); return Err(NetworkError::ClientDisconnected);
@ -68,17 +70,17 @@ impl PacketReceiver {
self.recv_buffer.extend_from_slice(&data[..len]); self.recv_buffer.extend_from_slice(&data[..len]);
let mut dec_buf = { let mut dec_buf = {
let mut cipher = self.cipher.lock().await; //let mut cipher = self.cipher.lock().await;
let block_chunk_len = self.recv_buffer.len() / cipher.block_size() * cipher.block_size(); let block_chunk_len = self.recv_buffer.len() / self.cipher.block_size() * self.cipher.block_size();
let buf = self.recv_buffer.drain(..block_chunk_len).collect(); let buf = self.recv_buffer.drain(..block_chunk_len).collect();
cipher.decrypt(&buf)? self.cipher.decrypt(&buf)?
}; };
self.incoming_data.append(&mut dec_buf); self.incoming_data.append(&mut dec_buf);
Ok(()) Ok(())
} }
async fn recv_pkts<R: RecvServerPacket + Send + std::fmt::Debug>(&mut self) -> Result<Vec<R>, NetworkError> { pub async fn recv_pkts<R: RecvServerPacket + std::fmt::Debug>(&mut self) -> Result<Vec<R>, NetworkError> {
self.fill_recv_buffer().await?; self.fill_recv_buffer().await?;
let mut result = Vec::new(); let mut result = Vec::new();
@ -88,7 +90,7 @@ impl PacketReceiver {
} }
let pkt_size = u16::from_le_bytes([self.incoming_data[0], self.incoming_data[1]]) as usize; let pkt_size = u16::from_le_bytes([self.incoming_data[0], self.incoming_data[1]]) as usize;
let mut pkt_len = pkt_size; let mut pkt_len = pkt_size;
while pkt_len % self.cipher.lock().await.block_size() != 0 { while pkt_len % self.cipher.block_size() != 0 {
pkt_len += 1; pkt_len += 1;
} }
@ -113,6 +115,7 @@ impl PacketReceiver {
Ok(result) Ok(result)
} }
} }
/*
async fn send_pkt<S: SendServerPacket + Send + std::fmt::Debug>(socket: Arc<async_std::net::TcpStream>, async fn send_pkt<S: SendServerPacket + Send + std::fmt::Debug>(socket: Arc<async_std::net::TcpStream>,
cipher: Arc<Mutex<Box<dyn PSOCipher + Send>>>, pkt: S) cipher: Arc<Mutex<Box<dyn PSOCipher + Send>>>, pkt: S)
@ -150,13 +153,14 @@ where
{ {
async_std::task::spawn(async move { async_std::task::spawn(async move {
server_sender.send(ClientAction::NewClient(client_id, client_sender)).await.unwrap(); server_sender.send(ClientAction::NewClient(client_id, client_sender)).await.unwrap();
let mut pkt_receiver = PacketReceiver::new(socket, cipher); /*
let mut pkt_receiver = PacketReceiver::new(*socket, cipher);
loop { loop {
match pkt_receiver.recv_pkts().await { match pkt_receiver.recv_pkts().await {
Ok(pkts) => { Ok(pkts) => {
for pkt in pkts { for pkt in pkts {
info!("[recv from {:?}] {:?}", client_id, pkt); info!("[recv from {:?}] {:#?}", client_id, pkt);
server_sender.send(ClientAction::Packet(client_id, pkt)).await.unwrap(); server_sender.send(ClientAction::Packet(client_id, pkt)).await.unwrap();
} }
}, },
@ -174,6 +178,7 @@ where
} }
} }
} }
*/
}); });
} }
@ -194,7 +199,7 @@ where
*cipher_out.lock().await = outc; *cipher_out.lock().await = outc;
} }
ServerStateAction::Packet(pkt) => { ServerStateAction::Packet(pkt) => {
info!("[send to {:?}] {:?}", client_id, pkt); info!("[send to {:?}] {:#?}", client_id, pkt);
if let Err(err) = send_pkt(socket.clone(), cipher_out.clone(), pkt).await { if let Err(err) = send_pkt(socket.clone(), cipher_out.clone(), pkt).await {
warn!("[client {:?} send error ] {:?}", client_id, err); warn!("[client {:?} send error ] {:?}", client_id, err);
} }
@ -315,3 +320,4 @@ where
})) }))
} }
*/

View File

@ -10,10 +10,14 @@ use serde::de::DeserializeOwned;
use crate::common::interserver::{ServerId, InterserverActor}; use crate::common::interserver::{ServerId, InterserverActor};
use libpso::crypto::{PSOCipher, NullCipher, CipherError};
use crate::common::serverstate::{ServerState, SendServerPacket, RecvServerPacket};
use crate::login::character::CharacterServerState; use crate::login::character::CharacterServerState;
use crate::ship::ship::ShipServerState; //use crate::ship::ship::ShipServerState;
use crate::entity::gateway::entitygateway::EntityGateway; use crate::entity::gateway::entitygateway::EntityGateway;
use async_std::channel;
#[derive(Debug)] #[derive(Debug)]
enum MessageReceiverError { enum MessageReceiverError {
//InvalidSize, //InvalidSize,
@ -46,6 +50,7 @@ impl MessageReceiver {
Ok(msg) Ok(msg)
} }
} }
/*
#[derive(Debug)] #[derive(Debug)]
enum InterserverInputAction<S, R> { enum InterserverInputAction<S, R> {
@ -209,7 +214,9 @@ pub fn login_listen_mainloop<EG: EntityGateway + Clone + 'static>(state: Arc<Mut
} }
})) }))
} }
*/
/*
pub fn ship_connect_mainloop<EG: EntityGateway + Clone + 'static>(state: Arc<Mutex<ShipServerState<EG>>>, ip: std::net::Ipv4Addr, port: u16) -> Pin<Box<dyn Future<Output = ()>>> { pub fn ship_connect_mainloop<EG: EntityGateway + Clone + 'static>(state: Arc<Mutex<ShipServerState<EG>>>, ip: std::net::Ipv4Addr, port: u16) -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async_std::task::spawn(async move { Box::pin(async_std::task::spawn(async move {
let mut id = 0; let mut id = 0;
@ -258,3 +265,4 @@ pub fn ship_connect_mainloop<EG: EntityGateway + Clone + 'static>(state: Arc<Mut
})) }))
} }
*/

View File

@ -1,22 +1,40 @@
#![allow(unused_imports)]
mod client; mod client;
mod interserver; mod interserver;
use std::collections::HashMap;
use log::{trace, info, warn};
use std::pin::Pin; use std::pin::Pin;
use futures::future::{Future, join_all, FutureExt}; use futures::future::{Future, join_all, FutureExt};
use async_std::sync::{Arc, Mutex}; use async_std::sync::{Arc, Mutex, RwLock};
use crate::common::mainloop::client::client_accept_mainloop; use std::fmt::Debug;
use crate::common::mainloop::interserver::{ship_connect_mainloop, login_listen_mainloop};
use async_std::io::prelude::{ReadExt, WriteExt};
//use crate::common::mainloop::client::client_accept_mainloop;
//use crate::common::mainloop::interserver::{ship_connect_mainloop, login_listen_mainloop};
pub use crate::common::mainloop::client::NetworkError; pub use crate::common::mainloop::client::NetworkError;
use crate::common::mainloop::client::PacketReceiver;
use crate::common::serverstate::ClientId;
use crate::common::serverstate::{RecvServerPacket, SendServerPacket, ServerState, OnConnect};
use crate::common::interserver::{ServerId, InterserverActor};
use crate::patch::patch::PatchServerState; use crate::patch::patch::PatchServerState;
use crate::login::login::LoginServerState; use crate::login::login::LoginServerState;
use crate::login::character::CharacterServerState; use crate::login::character::CharacterServerState;
use crate::ship::ship::ShipServerState; //use crate::ship::ship::ShipServerState;
use crate::entity::gateway::entitygateway::EntityGateway; use crate::entity::gateway::entitygateway::EntityGateway;
use libpso::crypto::{PSOCipher, NullCipher, CipherError};
use async_std::channel;
/*
pub fn patch_mainloop(patch_state: PatchServerState, patch_port: u16) -> Pin<Box<dyn Future<Output = ()>>> { pub fn patch_mainloop(patch_state: PatchServerState, patch_port: u16) -> Pin<Box<dyn Future<Output = ()>>> {
let patch_state = Arc::new(Mutex::new(patch_state)); let patch_state = Arc::new(Mutex::new(patch_state));
let client_mainloop = client_accept_mainloop(patch_state, patch_port); let client_mainloop = client_accept_mainloop(patch_state, patch_port);
@ -43,3 +61,488 @@ pub fn ship_mainloop<EG: EntityGateway + Clone + 'static>(ship_state: ShipServer
let login_communication_mainloop = ship_connect_mainloop(ship_state, comm_ip, comm_port); let login_communication_mainloop = ship_connect_mainloop(ship_state, comm_ip, comm_port);
Box::pin(join_all(vec![client_mainloop, login_communication_mainloop]).map(|_| ())) Box::pin(join_all(vec![client_mainloop, login_communication_mainloop]).map(|_| ()))
} }
*/
#[derive(Debug)]
enum MessageReceiverError {
//InvalidSize,
InvalidPayload,
//NetworkError(std::io::Error),
Disconnected,
}
struct MessageReceiver {
socket: async_std::net::TcpStream,
}
impl MessageReceiver {
fn new(socket: async_std::net::TcpStream) -> MessageReceiver {
MessageReceiver {
socket,
}
}
async fn recv<R: serde::de::DeserializeOwned + std::fmt::Debug>(&mut self) -> Result<R, MessageReceiverError> {
let mut size_buf = [0u8; 4];
self.socket.read_exact(&mut size_buf).await.map_err(|_| MessageReceiverError::Disconnected)?;
let size = u32::from_le_bytes(size_buf) as usize;
let mut payload = vec![0u8; size];
self.socket.read_exact(&mut payload).await.map_err(|_| MessageReceiverError::Disconnected)?;
let payload = String::from_utf8(payload).map_err(|_| MessageReceiverError::InvalidPayload)?;
let msg = serde_json::from_str(&payload).map_err(|_| MessageReceiverError::InvalidPayload)?;
Ok(msg)
}
}
/*
enum ServerAction<S> {
NewClient(ClientId, channel::Sender<S>),
Packet(ClientId, S),
Disconnect(ClientId),
}
*/
async fn recv_loop<STATE, S, R, C, E>(mut state: STATE,
socket: async_std::net::TcpStream,
client_id: ClientId,
cipher: C,
clients: Arc<RwLock<HashMap<ClientId, channel::Sender<S>>>>)
where
STATE: ServerState<SendPacket=S, RecvPacket=R, Cipher=C, PacketError=E> + Send,
S: SendServerPacket + Debug + Send,
R: RecvServerPacket + Debug + Send,
C: PSOCipher + Send,
E: std::fmt::Debug + Send,
{
let mut pkt_receiver = PacketReceiver::new(socket, cipher);
loop {
match pkt_receiver.recv_pkts::<R>().await {
Ok(pkts) => {
for pkt in pkts {
info!("[recv from {:?}] {:#?}", client_id, pkt);
match state.handle(client_id, pkt).await {
Ok(response) => {
for resp in response {
clients
.read()
.await
.get(&resp.0)
.unwrap()
.send(resp.1)
.await;
}
},
Err(err) => {
warn!("[client recv {:?}] error {:?} ", client_id, err);
}
}
}
},
Err(err) => {
match err {
NetworkError::ClientDisconnected => {
info!("[client recv {:?}] disconnected", client_id);
for pkt in state.on_disconnect(client_id).await.unwrap() {
clients
.read()
.await
.get(&pkt.0)
.unwrap()
.send(pkt.1)
.await;
}
clients
.write()
.await
.remove(&client_id);
break;
}
_ => {
warn!("[client {:?} recv error] {:?}", client_id, err);
}
}
}
}
}
}
async fn send_pkt<S, C>(socket: &mut async_std::net::TcpStream,
cipher: &mut C,
pkt: &S)
-> Result<(), NetworkError>
where
S: SendServerPacket + std::fmt::Debug,
C: PSOCipher,
{
let buf = pkt.as_bytes();
trace!("[send buf] {:?}", buf);
let cbuf = cipher.encrypt(&buf)?;
socket.write_all(&cbuf).await?;
Ok(())
}
async fn send_loop<S, C>(mut socket: async_std::net::TcpStream, client_id: ClientId, mut cipher: C, packet_queue: channel::Receiver<S>)
where
S: SendServerPacket + std::fmt::Debug,
C: PSOCipher,
{
loop {
let pkt = packet_queue.recv().await.unwrap();
if let Err(err) = send_pkt(&mut socket, &mut cipher, &pkt).await {
warn!("error sending pkt {:#?} to {:?} {:?}", pkt, client_id, err);
}
}
}
/*
pub async fn server_multiplex<STATE, S, R, E>(state: STATE, packet_queue: channel::Receiver<ServerAction<S>>)
where
STATE: ServerState<SendPacket=S, RecvPacket=R, PacketError=E>,
S: SendServerPacket + std::fmt::Debug,
R: RecvServerPacket + std::fmt::Debug,
E: std::fmt::Debug,
{
let mut clients = HashMap::new();
loop {
let action = packet_queue.recv().await.unwrap();
match action {
ServerAction::NewClient(client_id, sender) => {
clients.insert(client_id, sender);
},
ServerAction::Packet(client_id, pkt) => {
if let Some(sender) = clients.get(&client_id) {
sender.send(pkt).await;
}
},
ServerAction::Disconnect(client_id) => {
clients.remove(&client_id);
}
}
}
}
*/
pub async fn run_server<STATE, S, R, C, E>(mut state: STATE, port: u16)
where
STATE: ServerState<SendPacket=S, RecvPacket=R, Cipher=C, PacketError=E> + Send + 'static,
S: SendServerPacket + std::fmt::Debug + Send + 'static,
R: RecvServerPacket + std::fmt::Debug + Send,
C: PSOCipher + Send + 'static,
E: std::fmt::Debug + Send,
{
let listener = async_std::net::TcpListener::bind(&std::net::SocketAddr::from((std::net::Ipv4Addr::new(0,0,0,0), port))).await.unwrap();
let mut id = 0;
//let (packet_sender, packet_receiver) = async_std::channel::unbounded();
let clients = Arc::new(RwLock::new(HashMap::new()));
//let cstate = state.clone();
/*
async_std::task::spawn(async move {
server_multiplex(cstate, packet_receiver).await
});
*/
loop {
let (mut socket, addr) = listener.accept().await.unwrap();
id += 1;
let client_id = crate::common::serverstate::ClientId(id);
info!("new client {:?} {:?} {:?}", client_id, socket, addr);
let (client_tx, client_rx) = async_std::channel::unbounded();
//packet_sender.send(ServerAction::NewClient()).await;
clients
.write()
.await
.insert(client_id, client_tx.clone());
let mut cipher_in: Option<C> = None;
let mut cipher_out: Option<C> = None;
for action in state.on_connect(client_id).await.unwrap() {
match action {
OnConnect::Cipher(cin, cout) => {
cipher_in = Some(cin);
cipher_out = Some(cout);
},
OnConnect::Packet(pkt) => {
send_pkt(&mut socket, &mut NullCipher {}, &pkt).await;
}
}
}
let rstate = state.clone();
let rsocket = socket.clone();
let rclients = clients.clone();
async_std::task::spawn(async move {
/*
rstate;
rsocket;
client_id;
cipher_in.unwrap();
rclients;
*/
//client_tx.send(12).await
recv_loop(rstate, rsocket, client_id, cipher_in.unwrap(), rclients).await
//recv_loop2(rstate, rsocket, client_id, cipher_in.unwrap()).await
});
//let sstate = state.clone();
async_std::task::spawn(async move {
send_loop(socket, client_id, cipher_out.unwrap(), client_rx).await
});
}
}
/*
pub async fn listen_interserver<STATE, S, R, C, E>(state: STATE, port: u16)
where
STATE: InterserverActor<SendMessage=S, RecvMessage=R, Error=E>,
S: serde::Serialize,
R: serde::de::DeserializeOwned,
{
let listener = async_std::net::TcpListener::bind(&std::net::SocketAddr::from((std::net::Ipv4Addr::new(0,0,0,0), port))).await.unwrap();
let mut id = 0;
loop {
let (socket, addr) = listener.accept().await.unwrap();
info!("new interserver connection: {:?} {:?}", socket, addr);
id += 1;
let server_id = crate::common::interserver::ServerId(id);
}
}
pub async fn run_interserver_receiver<STATE, S, R, E>(state: STATE, ip: std::net::Ipv4Addr, port: u16)
where
STATE: InterserverActor<SendMessage=S, RecvMessage=R, Error=E>,
S: serde::Serialize,
R: serde::de::DeserializeOwned,
{
loop {
}
}
pub async fn run_interserver_sender<STATE, S, R, E>(state: STATE, to_send: channel::Receiver<S>)
where
STATE: InterserverActor<SendMessage=S, RecvMessage=R, Error=E>,
S: serde::Serialize,
R: serde::de::DeserializeOwned,
{
loop {
let msg = to_send.recv().await.unwrap();
let response = state.on_action(msg);
}
}
*/
async fn interserver_recv_loop<STATE, S, R, E>(mut state: STATE, server_id: ServerId, socket: async_std::net::TcpStream, ships: Arc<RwLock<HashMap<ServerId, channel::Sender<S>>>>)
where
STATE: InterserverActor<SendMessage=S, RecvMessage=R, Error=E> + Send,
S: serde::Serialize + Debug + Send,
R: serde::de::DeserializeOwned + Debug + Send,
E: Debug + Send,
{
let mut msg_receiver = MessageReceiver::new(socket);
loop {
match msg_receiver.recv::<R>().await {
Ok(msg) => {
info!("[interserver recv {:?}] {:?}", server_id, msg);
match state.on_action(server_id, msg).await {
Ok(response) => {
for resp in response {
ships
.read()
.await
.get(&resp.0)
.unwrap()
.send(resp.1)
.await;
}
},
Err(err) => {
warn!("[interserver recv {:?}] error {:?}", server_id, err);
}
}
},
Err(err) => {
if let MessageReceiverError::Disconnected = err {
info!("[interserver recv {:?}] disconnected", server_id);
for (_, sender) in ships.read().await.iter() {
for pkt in state.on_disconnect(server_id).await {
ships
.read()
.await
.get(&pkt.0)
.unwrap()
.send(pkt.1)
.await;
}
}
ships
.write()
.await
.remove(&server_id);
break;
}
info!("[interserver recv {:?}] error {:?}", server_id, err);
}
}
}
}
async fn interserver_send_loop<S>(server_id: ServerId, mut socket: async_std::net::TcpStream, to_send: channel::Receiver<S>)
where
S: serde::Serialize + std::fmt::Debug,
{
loop {
let msg = to_send.recv().await.unwrap();
let payload = serde_json::to_string(&msg);
if let Ok(payload) = payload {
let len_bytes = u32::to_le_bytes(payload.len() as u32);
if let Err(err) = socket.write_all(&len_bytes).await {
warn!("[interserver send {:?}] failed: {:?}", server_id, err);
break;
}
if let Err(err) = socket.write_all(payload.as_bytes()).await {
warn!("[interserver send {:?}] failed: {:?}", server_id, err);
break;
}
}
}
}
pub async fn run_interserver_listen<STATE, S, R, E>(mut state: STATE, port: u16)
where
STATE: InterserverActor<SendMessage=S, RecvMessage=R, Error=E> + Send + 'static,
S: serde::Serialize + Debug + Send + 'static,
R: serde::de::DeserializeOwned + Debug + Send,
E: Debug + Send,
{
let listener = async_std::net::TcpListener::bind(&std::net::SocketAddr::from((std::net::Ipv4Addr::new(0,0,0,0), port))).await.unwrap();
let mut id = 0;
let ships = Arc::new(RwLock::new(HashMap::new()));
loop {
let (socket, addr) = listener.accept().await.unwrap();
info!("[interserver listen] new server: {:?} {:?}", socket, addr);
id += 1;
let server_id = crate::common::interserver::ServerId(id);
let (client_tx, client_rx) = async_std::channel::unbounded();
//let sclient_tx = client_tx.clone();
/*
state.set_sender(server_id, Arc::new(Box::new(move |msg| {
let sclient_tx = sclient_tx.clone();
Box::new(async move {
sclient_tx.send(msg).await;
})})));
*/
state.set_sender(server_id, client_tx.clone());
ships
.write()
.await
.insert(server_id, client_tx.clone());
for msg in state.on_connect(server_id).await {
if let Some(ship_sender) = ships.read().await.get(&msg.0) {
ship_sender.send(msg.1).await;
}
}
let rstate = state.clone();
let rsocket = socket.clone();
let rships = ships.clone();
async_std::task::spawn(async move {
interserver_recv_loop(rstate, server_id, rsocket, rships).await;
});
async_std::task::spawn(async move {
interserver_send_loop(server_id, socket, client_rx).await;
});
}
}
pub async fn run_interserver_connect<STATE, S, R, E>(mut state: STATE, ip: std::net::Ipv4Addr, port: u16)
where
STATE: InterserverActor<SendMessage=S, RecvMessage=R, Error=E> + Send + 'static,
S: serde::Serialize + Debug + Send + 'static,
R: serde::de::DeserializeOwned + Debug + Send,
E: Debug + Send,
{
let mut id = 0;
loop {
info!("[interserver connect] trying to connect to server");
let socket = match async_std::net::TcpStream::connect((ip, port)).await {
Ok(socket) => socket,
Err(err) => {
info!("err trying to connect to loginserv {:?}", err);
async_std::task::sleep(std::time::Duration::from_secs(10)).await;
continue;
}
};
id += 1;
let server_id = crate::common::interserver::ServerId(id);
info!("[interserver connect] found loginserv: {:?} {:?}", server_id, socket);
let (client_tx, client_rx) = async_std::channel::unbounded();
state.set_sender(server_id, client_tx.clone());
/*
let sclient_tx = client_tx.clone();
state.set_sender(server_id, Arc::new(Box::new(move |msg| {
let sclient_tx = sclient_tx.clone();
Box::new(async move {
sclient_tx.send(msg).await;
})})));
*/
let other_server = vec![(server_id, client_tx.clone())].into_iter().collect();
let rstate = state.clone();
let rsocket = socket.clone();
async_std::task::spawn(async move {
interserver_recv_loop(rstate, server_id, rsocket, Arc::new(RwLock::new(other_server))).await;
});
let ssocket = socket.clone();
async_std::task::spawn(async move {
interserver_send_loop(server_id, ssocket, client_rx).await;
});
let mut buf = [0u8; 1];
loop {
let peek = socket.peek(&mut buf).await;
match peek {
Ok(len) if len == 0 => {
break
},
_ => {
}
}
}
}
}

View File

@ -4,9 +4,10 @@ use libpso::crypto::PSOCipher;
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, derive_more::Display)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, derive_more::Display)]
pub struct ClientId(pub usize); pub struct ClientId(pub usize);
pub enum OnConnect<S: SendServerPacket> { pub enum OnConnect<S: SendServerPacket, C: PSOCipher> {
Packet(S), Packet(S),
Cipher((Box<dyn PSOCipher + Send + Sync>, Box<dyn PSOCipher + Send + Sync>)), Cipher(C, C),
//Cipher((Box<dyn PSOCipher + Send + Sync>, Box<dyn PSOCipher + Send + Sync>)),
} }
pub trait RecvServerPacket: Sized + Sync { pub trait RecvServerPacket: Sized + Sync {
@ -19,14 +20,14 @@ pub trait SendServerPacket: Sized + Sync {
// TODO: rename this trait, this isn't the state but the actionability of the state re: the client // TODO: rename this trait, this isn't the state but the actionability of the state re: the client
#[async_trait::async_trait] #[async_trait::async_trait]
pub trait ServerState { pub trait ServerState: Clone {
type SendPacket: SendServerPacket; type SendPacket: SendServerPacket;
type RecvPacket: RecvServerPacket; type RecvPacket: RecvServerPacket;
type Cipher: PSOCipher;
type PacketError; type PacketError;
async fn on_connect(&mut self, id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket>>, Self::PacketError>; async fn on_connect(&mut self, id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket, Self::Cipher>>, Self::PacketError>;
async fn handle(&mut self, id: ClientId, pkt: &Self::RecvPacket) async fn handle(&mut self, id: ClientId, pkt: Self::RecvPacket) -> Result<Vec<(ClientId, Self::SendPacket)>, Self::PacketError>;
-> Result<Box<dyn Iterator<Item = (ClientId, Self::SendPacket)> + Send>, Self::PacketError>; //-> Result<Box<dyn Iterator<Item = (ClientId, Self::SendPacket)>>, Self::PacketError>;
async fn on_disconnect(&mut self, id: ClientId) -> Result<Vec<(ClientId, Self::SendPacket)>, Self::PacketError>; async fn on_disconnect(&mut self, id: ClientId) -> Result<Vec<(ClientId, Self::SendPacket)>, Self::PacketError>;
} }

View File

@ -4,8 +4,9 @@
#![feature(try_blocks)] #![feature(try_blocks)]
#![feature(once_cell)] #![feature(once_cell)]
#![feature(pin_macro)] #![feature(pin_macro)]
#![feature(test)]
extern crate test;
extern crate fix_hidden_lifetime_bug; extern crate fix_hidden_lifetime_bug;

View File

@ -2,6 +2,9 @@
use std::io::Read; use std::io::Read;
use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::collections::{BTreeMap, BTreeSet, HashMap};
use async_std::sync::Arc;
use async_std::channel;
use rand::Rng; use rand::Rng;
use crc::{crc32, Hasher32}; use crc::{crc32, Hasher32};
@ -15,7 +18,7 @@ use libpso::character::character;
use crate::common::cipherkeys::{ELSEWHERE_PRIVATE_KEY, ELSEWHERE_PARRAY}; use crate::common::cipherkeys::{ELSEWHERE_PRIVATE_KEY, ELSEWHERE_PARRAY};
use crate::common::serverstate::{SendServerPacket, RecvServerPacket, ServerState, OnConnect, ClientId}; use crate::common::serverstate::{SendServerPacket, RecvServerPacket, ServerState, OnConnect, ClientId};
use crate::common::interserver::{ServerId, InterserverActor, LoginMessage, ShipMessage, Ship}; use crate::common::interserver::{ServerId, InterserverActor, LoginMessage, ShipMessage, Ship};
use crate::common::leveltable::CharacterLevelTable; use crate::common::leveltable::LEVEL_TABLE;
use libpso::{utf8_to_array, utf8_to_utf16_array}; use libpso::{utf8_to_array, utf8_to_utf16_array};
use crate::entity::gateway::{EntityGateway, GatewayError}; use crate::entity::gateway::{EntityGateway, GatewayError};
@ -179,22 +182,24 @@ struct ConnectedClient {
expires: Option<chrono::DateTime<chrono::Utc>>, expires: Option<chrono::DateTime<chrono::Utc>>,
} }
pub struct CharacterServerState<EG: EntityGateway> { #[derive(Clone)]
pub struct CharacterServerState<EG: EntityGateway + Clone> {
entity_gateway: EG, entity_gateway: EG,
param_header: ParamDataHeader, param_header: ParamDataHeader,
param_data: Vec<u8>, param_data: Vec<u8>,
clients: HashMap<ClientId, ClientState>, clients: HashMap<ClientId, ClientState>,
ships: BTreeMap<ServerId, Ship>, ships: BTreeMap<ServerId, Ship>,
level_table: CharacterLevelTable, //level_table: CharacterLevelTable,
auth_token: AuthToken, auth_token: AuthToken,
connected_clients: BTreeMap<UserAccountId, ConnectedClient>, connected_clients: BTreeMap<UserAccountId, ConnectedClient>,
authenticated_ships: BTreeSet<ServerId>, authenticated_ships: BTreeSet<ServerId>,
ship_sender: BTreeMap<ServerId, Box<dyn Fn(LoginMessage) + Send>>, //ship_sender: BTreeMap<ServerId, Arc<Box<dyn Fn(LoginMessage) -> Box<dyn futures::future::Future<Output = ()>> + Send>>>,
ship_sender: BTreeMap<ServerId, channel::Sender<LoginMessage>>,
} }
async fn new_character<EG: EntityGateway>(entity_gateway: &mut EG, user: &UserAccountEntity, preview: &CharacterPreview) -> Result<(), anyhow::Error> { async fn new_character<EG: EntityGateway + Clone>(entity_gateway: &mut EG, user: &UserAccountEntity, preview: &CharacterPreview) -> Result<(), anyhow::Error> {
let mut character = new_character_from_preview(user, preview); let mut character = new_character_from_preview(user, preview);
match character.char_class { match character.char_class {
CharacterClass::FOmar | CharacterClass::FOmarl| CharacterClass::FOnewm | CharacterClass::FOnewearl => character.techs.set_tech(Technique::Foie, TechLevel(1)), CharacterClass::FOmar | CharacterClass::FOmarl| CharacterClass::FOnewm | CharacterClass::FOnewearl => character.techs.set_tech(Technique::Foie, TechLevel(1)),
@ -306,7 +311,7 @@ async fn new_character<EG: EntityGateway>(entity_gateway: &mut EG, user: &UserAc
} }
impl<EG: EntityGateway> CharacterServerState<EG> { impl<EG: EntityGateway + Clone> CharacterServerState<EG> {
pub fn new(entity_gateway: EG, auth_token: AuthToken) -> CharacterServerState<EG> { pub fn new(entity_gateway: EG, auth_token: AuthToken) -> CharacterServerState<EG> {
let (param_header, param_data) = generate_param_data("data/param/"); let (param_header, param_data) = generate_param_data("data/param/");
@ -316,7 +321,7 @@ impl<EG: EntityGateway> CharacterServerState<EG> {
param_data, param_data,
clients: HashMap::new(), clients: HashMap::new(),
ships: BTreeMap::new(), ships: BTreeMap::new(),
level_table: CharacterLevelTable::default(), //level_table: CharacterLevelTable::default(),
auth_token, auth_token,
authenticated_ships: BTreeSet::new(), authenticated_ships: BTreeSet::new(),
ship_sender: BTreeMap::new(), ship_sender: BTreeMap::new(),
@ -324,10 +329,6 @@ impl<EG: EntityGateway> CharacterServerState<EG> {
} }
} }
pub fn set_sender(&mut self, server_id: ServerId, sender: Box<dyn Fn(LoginMessage) + Send>) {
self.ship_sender.insert(server_id, sender);
}
async fn validate_login(&mut self, id: ClientId, pkt: &Login) -> Result<Vec<SendCharacterPacket>, anyhow::Error> { async fn validate_login(&mut self, id: ClientId, pkt: &Login) -> Result<Vec<SendCharacterPacket>, anyhow::Error> {
match get_login_status(&mut self.entity_gateway, pkt).await { match get_login_status(&mut self.entity_gateway, pkt).await {
Ok(user) => { Ok(user) => {
@ -404,7 +405,7 @@ impl<EG: EntityGateway> CharacterServerState<EG> {
if select.reason == 0 { if select.reason == 0 {
let chars = client.characters.as_ref().unwrap(); let chars = client.characters.as_ref().unwrap();
Ok(if let Some(char) = &chars[select.slot as usize] { Ok(if let Some(char) = &chars[select.slot as usize] {
let (level, _stats) = self.level_table.get_stats_from_exp(char.char_class, char.exp); let (level, _stats) = LEVEL_TABLE.get_stats_from_exp(char.char_class, char.exp);
vec![SendCharacterPacket::CharacterPreview(CharacterPreview { vec![SendCharacterPacket::CharacterPreview(CharacterPreview {
slot: select.slot, slot: select.slot,
character: SelectScreenCharacterBuilder::new() character: SelectScreenCharacterBuilder::new()
@ -552,12 +553,13 @@ impl<EG: EntityGateway> CharacterServerState<EG> {
} }
#[async_trait::async_trait] #[async_trait::async_trait]
impl<EG: EntityGateway> ServerState for CharacterServerState<EG> { impl<EG: EntityGateway + Clone> ServerState for CharacterServerState<EG> {
type SendPacket = SendCharacterPacket; type SendPacket = SendCharacterPacket;
type RecvPacket = RecvCharacterPacket; type RecvPacket = RecvCharacterPacket;
type Cipher = PSOBBCipher;
type PacketError = anyhow::Error; type PacketError = anyhow::Error;
async fn on_connect(&mut self, id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket>>, anyhow::Error> { async fn on_connect(&mut self, id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket, Self::Cipher>>, anyhow::Error> {
self.clients.insert(id, ClientState::new()); self.clients.insert(id, ClientState::new());
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
@ -568,56 +570,57 @@ impl<EG: EntityGateway> ServerState for CharacterServerState<EG> {
rng.fill(&mut client_key[..]); rng.fill(&mut client_key[..]);
Ok(vec![OnConnect::Packet(SendCharacterPacket::LoginWelcome(LoginWelcome::new(server_key, client_key))), Ok(vec![OnConnect::Packet(SendCharacterPacket::LoginWelcome(LoginWelcome::new(server_key, client_key))),
OnConnect::Cipher((Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key)), OnConnect::Cipher(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key),
Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key)))) PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key))
//OnConnect::Cipher((Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key)),
// Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key))))
]) ])
} }
async fn handle(&mut self, id: ClientId, pkt: &RecvCharacterPacket) async fn handle(&mut self, id: ClientId, pkt: RecvCharacterPacket) -> Result<Vec<(ClientId, SendCharacterPacket)>, anyhow::Error> {
-> Result<Box<dyn Iterator<Item = (ClientId, SendCharacterPacket)> + Send>, anyhow::Error> {
Ok(match pkt { Ok(match pkt {
RecvCharacterPacket::Login(login) => { RecvCharacterPacket::Login(login) => {
if login.session.action == SessionAction::SelectCharacter { if login.session.action == SessionAction::SelectCharacter {
Box::new(self.send_ship_list(id, login)?.into_iter().map(move |pkt| (id, pkt))) self.send_ship_list(id, &login)?.into_iter().map(move |pkt| (id, pkt)).collect()
} }
else { else {
Box::new(self.validate_login(id, login).await?.into_iter().map(move |pkt| (id, pkt))) self.validate_login(id, &login).await?.into_iter().map(move |pkt| (id, pkt)).collect()
} }
}, },
RecvCharacterPacket::RequestSettings(_req) => { RecvCharacterPacket::RequestSettings(_req) => {
Box::new(self.get_settings(id).await?.into_iter().map(move |pkt| (id, pkt))) self.get_settings(id).await?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::CharSelect(sel) => { RecvCharacterPacket::CharSelect(sel) => {
Box::new(self.char_select(id, sel).await?.into_iter().map(move |pkt| (id, pkt))) self.char_select(id, &sel).await?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::Checksum(_checksum) => { RecvCharacterPacket::Checksum(_checksum) => {
Box::new(self.validate_checksum().into_iter().map(move |pkt| (id, pkt))) self.validate_checksum().into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::GuildcardDataRequest(_request) => { RecvCharacterPacket::GuildcardDataRequest(_request) => {
Box::new(self.guildcard_data_header(id).await?.into_iter().map(move |pkt| (id, pkt))) self.guildcard_data_header(id).await?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::GuildcardDataChunkRequest(request) => { RecvCharacterPacket::GuildcardDataChunkRequest(request) => {
Box::new(self.guildcard_data_chunk(id, request.chunk, request.again)?.into_iter().map(move |pkt| (id, pkt))) self.guildcard_data_chunk(id, request.chunk, request.again)?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::ParamDataRequest(_request) => { RecvCharacterPacket::ParamDataRequest(_request) => {
Box::new(vec![SendCharacterPacket::ParamDataHeader(self.param_header.clone())].into_iter().map(move |pkt| (id, pkt))) vec![SendCharacterPacket::ParamDataHeader(self.param_header.clone())].into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::SetFlag(flag) => { RecvCharacterPacket::SetFlag(flag) => {
Box::new(self.set_flag(id, flag).await?.map(move |pkt| (id, pkt))) self.set_flag(id, &flag).await?.map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::ParamDataChunkRequest(request) => { RecvCharacterPacket::ParamDataChunkRequest(request) => {
Box::new(self.param_data_chunk_request(id, request)?.into_iter().map(move |pkt| (id, pkt))) self.param_data_chunk_request(id, &request)?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::CharacterPreview(preview) => { RecvCharacterPacket::CharacterPreview(preview) => {
Box::new(self.character_preview(id, preview).await?.into_iter().map(move |pkt| (id, pkt))) self.character_preview(id, &preview).await?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::MenuSelect(menuselect) => { RecvCharacterPacket::MenuSelect(menuselect) => {
Box::new(self.select_ship(id, menuselect)?.into_iter().map(move |pkt| (id, pkt))) self.select_ship(id, &menuselect)?.into_iter().map(move |pkt| (id, pkt)).collect()
}, },
RecvCharacterPacket::MenuDetail(menudetail) => { RecvCharacterPacket::MenuDetail(menudetail) => {
match menudetail.menu { match menudetail.menu {
SHIP_MENU_ID => Box::new(self.ship_detail(menudetail)?.into_iter().map(move |pkt| (id, pkt))), SHIP_MENU_ID => self.ship_detail(&menudetail)?.into_iter().map(move |pkt| (id, pkt)).collect(),
_ => Box::new(Vec::new().into_iter()) _ => Vec::new()
} }
} }
}) })
@ -634,7 +637,7 @@ impl<EG: EntityGateway> ServerState for CharacterServerState<EG> {
} }
#[async_trait::async_trait] #[async_trait::async_trait]
impl<EG: EntityGateway> InterserverActor for CharacterServerState<EG> { impl<EG: EntityGateway + Clone> InterserverActor for CharacterServerState<EG> {
type SendMessage = LoginMessage; type SendMessage = LoginMessage;
type RecvMessage = ShipMessage; type RecvMessage = ShipMessage;
type Error = (); type Error = ();
@ -643,7 +646,7 @@ impl<EG: EntityGateway> InterserverActor for CharacterServerState<EG> {
Vec::new() Vec::new()
} }
async fn action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error> { async fn on_action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error> {
match msg { match msg {
ShipMessage::Authenticate(auth_token) => { ShipMessage::Authenticate(auth_token) => {
if self.auth_token == auth_token { if self.auth_token == auth_token {
@ -711,6 +714,10 @@ impl<EG: EntityGateway> InterserverActor for CharacterServerState<EG> {
.collect(); .collect();
Vec::new() Vec::new()
} }
fn set_sender(&mut self, server_id: ServerId, sender: channel::Sender<LoginMessage>) {
self.ship_sender.insert(server_id, sender);
}
} }
@ -840,9 +847,7 @@ mod test {
}); });
server.clients.insert(ClientId(5), clientstate); server.clients.insert(ClientId(5), clientstate);
let send = server.handle(ClientId(5), &RecvCharacterPacket::RequestSettings(RequestSettings{})).await let send = server.handle(ClientId(5), RecvCharacterPacket::RequestSettings(RequestSettings{})).await.unwrap();
.unwrap()
.collect::<Vec<_>>();
assert!(send.len() == 1); assert!(send.len() == 1);
assert!(send[0].0 == ClientId(5)); assert!(send[0].0 == ClientId(5));
@ -857,9 +862,9 @@ mod test {
struct TestData; struct TestData;
impl EntityGateway for TestData {} impl EntityGateway for TestData {}
let mut server = CharacterServerState::new(TestData {}, AuthToken("".into())); let mut server = CharacterServerState::new(TestData {}, AuthToken("".into()));
let send = server.handle(ClientId(1), &RecvCharacterPacket::Checksum(Checksum {checksum: 1234, let send = server.handle(ClientId(1), RecvCharacterPacket::Checksum(Checksum {checksum: 1234,
padding: 0, padding: 0,
})).await.unwrap().collect::<Vec<_>>(); })).await.unwrap();
assert!(send.len() == 1); assert!(send.len() == 1);
let bytes = send[0].1.as_bytes(); let bytes = send[0].1.as_bytes();
@ -888,9 +893,9 @@ mod test {
let mut server = CharacterServerState::new(test_data.clone(), AuthToken("".into())); let mut server = CharacterServerState::new(test_data.clone(), AuthToken("".into()));
server.clients.insert(ClientId(1), fake_user.clone()); server.clients.insert(ClientId(1), fake_user.clone());
let mut send = server.handle(ClientId(1), &RecvCharacterPacket::SetFlag(SetFlag {flags: 1})).await.unwrap().collect::<Vec<_>>(); let mut send = server.handle(ClientId(1), RecvCharacterPacket::SetFlag(SetFlag {flags: 1})).await.unwrap();
assert!(test_data.get_user_by_id(UserAccountId(3)).await.unwrap().flags == 1); assert!(test_data.get_user_by_id(UserAccountId(3)).await.unwrap().flags == 1);
send = server.handle(ClientId(1), &RecvCharacterPacket::CharacterPreview(CharacterPreview {slot: 1, character: character::SelectScreenCharacter { send = server.handle(ClientId(1), RecvCharacterPacket::CharacterPreview(CharacterPreview {slot: 1, character: character::SelectScreenCharacter {
exp: 0, exp: 0,
level: 0, level: 0,
guildcard: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], guildcard: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
@ -916,7 +921,7 @@ mod test {
prop_y: 0.0, prop_y: 0.0,
name: [9, 69, 116, 101, 115, 116, 32, 110, 97, 109, 101, 0, 0, 0, 0, 0], // "\tEtest name" name: [9, 69, 116, 101, 115, 116, 32, 110, 97, 109, 101, 0, 0, 0, 0, 0], // "\tEtest name"
play_time: 0, play_time: 0,
} })).await.unwrap().collect::<Vec<_>>(); } })).await.unwrap();
assert!(send.len() == 2); assert!(send.len() == 2);
let chars = test_data.get_characters_by_user(&fake_user.user.unwrap()).await.unwrap(); let chars = test_data.get_characters_by_user(&fake_user.user.unwrap()).await.unwrap();

View File

@ -93,13 +93,14 @@ pub fn check_if_already_online(user: UserAccountEntity) -> Result<UserAccountEnt
*/ */
} }
pub struct LoginServerState<EG: EntityGateway> { #[derive(Clone)]
pub struct LoginServerState<EG: EntityGateway + Clone> {
character_server_ip: net::Ipv4Addr, character_server_ip: net::Ipv4Addr,
entity_gateway: EG, entity_gateway: EG,
clients: HashMap<ClientId, String>, clients: HashMap<ClientId, String>,
} }
impl<EG: EntityGateway> LoginServerState<EG> { impl<EG: EntityGateway + Clone> LoginServerState<EG> {
pub fn new(entity_gateway: EG, character_server_ip: net::Ipv4Addr) -> LoginServerState<EG> { pub fn new(entity_gateway: EG, character_server_ip: net::Ipv4Addr) -> LoginServerState<EG> {
LoginServerState { LoginServerState {
entity_gateway, entity_gateway,
@ -128,13 +129,14 @@ impl<EG: EntityGateway> LoginServerState<EG> {
} }
#[async_trait::async_trait] #[async_trait::async_trait]
impl<EG: EntityGateway> ServerState for LoginServerState<EG> { impl<EG: EntityGateway + Clone> ServerState for LoginServerState<EG> {
type SendPacket = SendLoginPacket; type SendPacket = SendLoginPacket;
type RecvPacket = RecvLoginPacket; type RecvPacket = RecvLoginPacket;
type Cipher = PSOBBCipher;
//type PacketError = LoginError; //type PacketError = LoginError;
type PacketError = anyhow::Error; type PacketError = anyhow::Error;
async fn on_connect(&mut self, _id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket>>, anyhow::Error> { async fn on_connect(&mut self, _id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket, Self::Cipher>>, anyhow::Error> {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let mut server_key = [0u8; 48]; let mut server_key = [0u8; 48];
@ -143,20 +145,20 @@ impl<EG: EntityGateway> ServerState for LoginServerState<EG> {
rng.fill(&mut client_key[..]); rng.fill(&mut client_key[..]);
Ok(vec![OnConnect::Packet(SendLoginPacket::LoginWelcome(LoginWelcome::new(server_key, client_key))), Ok(vec![OnConnect::Packet(SendLoginPacket::LoginWelcome(LoginWelcome::new(server_key, client_key))),
OnConnect::Cipher((Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key)), OnConnect::Cipher(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key),
Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key)))) PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key))
]) ])
} }
async fn handle(&mut self, id: ClientId, pkt: &Self::RecvPacket) async fn handle(&mut self, id: ClientId, pkt: Self::RecvPacket) -> Result<Vec<(ClientId, Self::SendPacket)>, anyhow::Error> {
-> Result<Box<dyn Iterator<Item = (ClientId, Self::SendPacket)> + Send>, anyhow::Error> {
Ok(match pkt { Ok(match pkt {
RecvLoginPacket::Login(login) => { RecvLoginPacket::Login(login) => {
Box::new(self.validate_login(id, login).await? self.validate_login(id, &login).await?
.into_iter() .into_iter()
.map(move |pkt| { .map(move |pkt| {
(id, pkt) (id, pkt)
})) })
.collect()
} }
}) })
} }
@ -237,7 +239,7 @@ mod test {
let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap());
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>(); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap();
assert!(send == vec![ assert!(send == vec![
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {
status: AccountStatus::Ok, status: AccountStatus::Ok,
@ -275,7 +277,7 @@ mod test {
} }
let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap());
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>(); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap();
assert!(send == vec![ assert!(send == vec![
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {
@ -324,7 +326,7 @@ mod test {
} }
let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap());
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>(); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap();
assert!(send == vec![ assert!(send == vec![
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {
@ -373,7 +375,7 @@ mod test {
} }
let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap()); let mut server = LoginServerState::new(TestData {}, "127.0.0.1".parse().unwrap());
let send = server.handle(ClientId(1), &LOGIN_PACKET).await.unwrap().collect::<Vec<_>>(); let send = server.handle(ClientId(1), LOGIN_PACKET).await.unwrap();
assert!(send == vec![ assert!(send == vec![
(ClientId(1), SendLoginPacket::LoginResponse(LoginResponse { (ClientId(1), SendLoginPacket::LoginResponse(LoginResponse {

View File

@ -136,6 +136,7 @@ impl SendServerPacket for SendPatchPacket {
} }
#[derive(Clone)]
pub struct PatchServerState { pub struct PatchServerState {
patch_file_tree: PatchFileTree, patch_file_tree: PatchFileTree,
patch_file_lookup: HashMap<u32, PatchFile>, patch_file_lookup: HashMap<u32, PatchFile>,
@ -158,33 +159,40 @@ impl PatchServerState {
impl ServerState for PatchServerState { impl ServerState for PatchServerState {
type SendPacket = SendPatchPacket; type SendPacket = SendPatchPacket;
type RecvPacket = RecvPatchPacket; type RecvPacket = RecvPatchPacket;
type Cipher = PSOPCCipher;
type PacketError = PatchError; type PacketError = PatchError;
async fn on_connect(&mut self, _id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket>>, PatchError> { async fn on_connect(&mut self, _id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket, Self::Cipher>>, PatchError> {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let key_in: u32 = rng.gen(); let key_in: u32 = rng.gen();
let key_out: u32 = rng.gen(); let key_out: u32 = rng.gen();
Ok(vec![OnConnect::Packet(SendPatchPacket::PatchWelcome(PatchWelcome::new(key_out, key_in))), Ok(vec![OnConnect::Packet(SendPatchPacket::PatchWelcome(PatchWelcome::new(key_out, key_in))),
OnConnect::Cipher((Box::new(PSOPCCipher::new(key_in)), Box::new(PSOPCCipher::new(key_out)))) OnConnect::Cipher(PSOPCCipher::new(key_in), PSOPCCipher::new(key_out))
]) ])
} }
async fn handle(&mut self, id: ClientId, pkt: &RecvPatchPacket) async fn handle(&mut self, id: ClientId, pkt: RecvPatchPacket) -> Result<Vec<(ClientId, SendPatchPacket)>, PatchError> {
-> Result<Box<dyn Iterator<Item = (ClientId, SendPatchPacket)> + Send>, PatchError> {
Ok(match pkt { Ok(match pkt {
RecvPatchPacket::PatchWelcomeReply(_pkt) => { RecvPatchPacket::PatchWelcomeReply(_pkt) => {
Box::new(vec![SendPatchPacket::RequestLogin(RequestLogin {})].into_iter().map(move |pkt| (id, pkt))) vec![SendPatchPacket::RequestLogin(RequestLogin {})]
.into_iter()
.map(move |pkt| (id, pkt))
.collect()
}, },
RecvPatchPacket::LoginReply(_pkt) => { RecvPatchPacket::LoginReply(_pkt) => {
let mut p = vec![SendPatchPacket::Message(Message::new(self.patch_motd.clone()))]; let mut pkts = vec![SendPatchPacket::Message(Message::new(self.patch_motd.clone()))];
p.append(&mut get_file_list_packets(&self.patch_file_tree)); pkts.append(&mut get_file_list_packets(&self.patch_file_tree));
p.push(SendPatchPacket::PatchEndList(PatchEndList {})); pkts.push(SendPatchPacket::PatchEndList(PatchEndList {}));
Box::new(p.into_iter().map(move |pkt| (id, pkt))) pkts
.into_iter()
.map(move |pkt| (id, pkt))
.collect()
}, },
RecvPatchPacket::FileInfoReply(pkt) => { RecvPatchPacket::FileInfoReply(pkt) => {
self.patch_file_info.push(pkt.clone()); self.patch_file_info.push(pkt.clone());
Box::new(None.into_iter().map(move |pkt| (id, pkt))) Vec::new()
//None.into_iter().map(move |pkt| (id, pkt))
}, },
RecvPatchPacket::FileInfoListEnd(_pkt) => { RecvPatchPacket::FileInfoListEnd(_pkt) => {
let need_update = self.patch_file_info.iter() let need_update = self.patch_file_info.iter()
@ -194,10 +202,12 @@ impl ServerState for PatchServerState {
let total_size = need_update.iter().fold(0, |a, file_info| a + file_info.size); let total_size = need_update.iter().fold(0, |a, file_info| a + file_info.size);
let total_files = need_update.len() as u32; let total_files = need_update.len() as u32;
let p = vec![SendPatchPacket::FilesToPatchMetadata(FilesToPatchMetadata::new(total_size, total_files)), vec![SendPatchPacket::FilesToPatchMetadata(FilesToPatchMetadata::new(total_size, total_files)),
SendPatchPacket::PatchStartList(PatchStartList {}) SendPatchPacket::PatchStartList(PatchStartList {})]
]; .into_iter()
Box::new(p.into_iter().chain(SendFileIterator::new(self)).map(move |pkt| (id, pkt))) .chain(SendFileIterator::new(self))
.map(move |pkt| (id, pkt))
.collect()
} }
}) })
} }

View File

@ -29,9 +29,9 @@ pub(super) fn take_item_from_floor(character_id: CharacterEntityId, item_id: Cli
{ {
move |(mut item_state, transaction): (ItemStateProxy<'_>, Box<dyn EntityGatewayTransaction + '_>) , _| { move |(mut item_state, transaction): (ItemStateProxy<'_>, Box<dyn EntityGatewayTransaction + '_>) , _| {
Box::pin(async move { Box::pin(async move {
let mut floor = item_state.floor(&character_id)?; let mut floor = item_state.floor(&character_id).await?;
let item = floor.take_item(&item_id).ok_or(ItemStateError::NoFloorItem(item_id))?; let item = floor.take_item(&item_id).ok_or(ItemStateError::NoFloorItem(item_id))?;
item_state.set_floor(floor); item_state.set_floor(floor).await;
Ok(((item_state, transaction), item)) Ok(((item_state, transaction), item))
}) })
@ -46,7 +46,7 @@ pub(super) fn add_floor_item_to_inventory(character: &CharacterEntity)
move |(mut item_state, transaction), floor_item| { move |(mut item_state, transaction), floor_item| {
let character = character.clone(); let character = character.clone();
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character.id)?; let mut inventory = item_state.inventory(&character.id).await?;
let character_id = character.id; let character_id = character.id;
let transaction = floor_item.with_entity_id(transaction, |mut transaction, entity_id| { let transaction = floor_item.with_entity_id(transaction, |mut transaction, entity_id| {
@ -87,7 +87,7 @@ pub(super) fn take_item_from_inventory(character_id: CharacterEntityId, item_id:
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
let item = inventory.take_item(&item_id, amount).ok_or (ItemStateError::NoFloorItem(item_id))?; let item = inventory.take_item(&item_id, amount).ok_or (ItemStateError::NoFloorItem(item_id))?;
transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?; transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?;
@ -117,9 +117,9 @@ pub(super) fn add_inventory_item_to_shared_floor(character_id: CharacterEntityId
Ok(transaction) Ok(transaction)
}}).await?; }}).await?;
let mut floor = item_state.floor(&character_id)?; let mut floor = item_state.floor(&character_id).await?;
let floor_item = floor.add_inventory_item(inventory_item, map_area, drop_position).clone(); let floor_item = floor.add_inventory_item(inventory_item, map_area, drop_position).clone();
item_state.set_floor(floor); item_state.set_floor(floor).await;
Ok(((item_state, transaction), floor_item)) Ok(((item_state, transaction), floor_item))
}) })
@ -133,7 +133,7 @@ pub(super) fn take_meseta_from_inventory(character_id: CharacterEntityId, amount
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
inventory.remove_meseta(amount)?; inventory.remove_meseta(amount)?;
transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?; transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?;
item_state.set_inventory(inventory); item_state.set_inventory(inventory);
@ -149,7 +149,7 @@ pub(super) fn add_meseta_to_inventory(character_id: CharacterEntityId, amount: u
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
inventory.add_meseta(amount)?; inventory.add_meseta(amount)?;
transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?; transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?;
item_state.set_inventory(inventory); item_state.set_inventory(inventory);
@ -167,7 +167,7 @@ pub(super) fn add_meseta_to_shared_floor(character_id: CharacterEntityId, amount
move |(mut item_state, transaction), _| { move |(mut item_state, transaction), _| {
Box::pin(async move { Box::pin(async move {
let floor_item = FloorItem { let floor_item = FloorItem {
item_id: item_state.new_item_id()?, item_id: item_state.new_item_id().await?,
item: FloorItemDetail::Meseta(Meseta(amount)), item: FloorItemDetail::Meseta(Meseta(amount)),
map_area, map_area,
x: drop_position.0, x: drop_position.0,
@ -175,9 +175,9 @@ pub(super) fn add_meseta_to_shared_floor(character_id: CharacterEntityId, amount
z: drop_position.1, z: drop_position.1,
}; };
let mut floor = item_state.floor(&character_id)?; let mut floor = item_state.floor(&character_id).await?;
let floor_item = floor.add_shared_item(floor_item).clone(); let floor_item = floor.add_shared_item(floor_item).clone();
item_state.set_floor(floor); item_state.set_floor(floor).await;
Ok(((item_state, transaction), floor_item)) Ok(((item_state, transaction), floor_item))
}) })
@ -190,7 +190,7 @@ pub(super) fn take_meseta_from_bank(character_id: CharacterEntityId, amount: u32
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut bank = item_state.bank(&character_id)?; let mut bank = item_state.bank(&character_id).await?;
bank.remove_meseta(amount)?; bank.remove_meseta(amount)?;
transaction.gateway().set_bank_meseta(&character_id, &bank.name, bank.meseta).await?; transaction.gateway().set_bank_meseta(&character_id, &bank.name, bank.meseta).await?;
@ -205,7 +205,7 @@ pub(super) fn add_meseta_from_bank_to_inventory(character_id: CharacterEntityId,
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
inventory.add_meseta_no_overflow(amount)?; inventory.add_meseta_no_overflow(amount)?;
transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?; transaction.gateway().set_character_meseta(&character_id, inventory.meseta).await?;
@ -221,7 +221,7 @@ pub(super) fn add_meseta_to_bank(character_id: CharacterEntityId, amount: u32)
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut bank = item_state.bank(&character_id)?; let mut bank = item_state.bank(&character_id).await?;
bank.add_meseta(amount)?; bank.add_meseta(amount)?;
transaction.gateway().set_bank_meseta(&character_id, &bank.name, bank.meseta).await?; transaction.gateway().set_bank_meseta(&character_id, &bank.name, bank.meseta).await?;
@ -237,7 +237,7 @@ pub(super) fn take_item_from_bank(character_id: CharacterEntityId, item_id: Clie
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut bank = item_state.bank(&character_id)?; let mut bank = item_state.bank(&character_id).await?;
let item = bank.take_item(&item_id, amount).ok_or(ItemStateError::NoBankItem(item_id))?; let item = bank.take_item(&item_id, amount).ok_or(ItemStateError::NoBankItem(item_id))?;
transaction.gateway().set_character_bank(&character_id, &bank.as_bank_entity(), &bank.name).await?; transaction.gateway().set_character_bank(&character_id, &bank.as_bank_entity(), &bank.name).await?;
item_state.set_bank(bank); item_state.set_bank(bank);
@ -255,8 +255,8 @@ pub(super) fn add_bank_item_to_inventory(character: &CharacterEntity)
move |(mut item_state, transaction), bank_item| { move |(mut item_state, transaction), bank_item| {
let character = character.clone(); let character = character.clone();
Box::pin(async move { Box::pin(async move {
let bank_name = item_state.bank(&character.id)?.name; let bank_name = item_state.bank(&character.id).await?.name;
let mut inventory = item_state.inventory(&character.id)?; let mut inventory = item_state.inventory(&character.id).await?;
let character_id = character.id; let character_id = character.id;
let transaction = bank_item.with_entity_id(transaction, |mut transaction, entity_id| { let transaction = bank_item.with_entity_id(transaction, |mut transaction, entity_id| {
@ -300,7 +300,7 @@ pub(super) fn add_inventory_item_to_bank(character_id: CharacterEntityId)
{ {
move |(mut item_state, transaction), inventory_item| { move |(mut item_state, transaction), inventory_item| {
Box::pin(async move { Box::pin(async move {
let mut bank = item_state.bank(&character_id)?; let mut bank = item_state.bank(&character_id).await?;
let bank_name = bank.name.clone(); let bank_name = bank.name.clone();
let mut transaction = inventory_item.with_entity_id(transaction, move |mut transaction, entity_id| { let mut transaction = inventory_item.with_entity_id(transaction, move |mut transaction, entity_id| {
let bank_name = bank_name.clone(); let bank_name = bank_name.clone();
@ -330,7 +330,7 @@ pub(super) fn equip_inventory_item(character_id: CharacterEntityId, item_id: Cli
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
inventory.equip(&item_id, equip_slot); inventory.equip(&item_id, equip_slot);
transaction.gateway().set_character_equips(&character_id, &inventory.as_equipped_entity()).await?; transaction.gateway().set_character_equips(&character_id, &inventory.as_equipped_entity()).await?;
item_state.set_inventory(inventory); item_state.set_inventory(inventory);
@ -347,7 +347,7 @@ pub(super) fn unequip_inventory_item(character_id: CharacterEntityId, item_id: C
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
inventory.unequip(&item_id); inventory.unequip(&item_id);
transaction.gateway().set_character_equips(&character_id, &inventory.as_equipped_entity()).await?; transaction.gateway().set_character_equips(&character_id, &inventory.as_equipped_entity()).await?;
item_state.set_inventory(inventory); item_state.set_inventory(inventory);
@ -366,7 +366,7 @@ pub(super) fn sort_inventory_items(character_id: CharacterEntityId, item_ids: Ve
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
let item_ids = item_ids.clone(); let item_ids = item_ids.clone();
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
inventory.sort(&item_ids); inventory.sort(&item_ids);
transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?; transaction.gateway().set_character_inventory(&character_id, &inventory.as_inventory_entity(&character_id)).await?;
item_state.set_inventory(inventory); item_state.set_inventory(inventory);
@ -405,7 +405,7 @@ pub(super) fn feed_mag_item(character: CharacterEntity, mag_item_id: ClientItemI
move |(mut item_state, transaction), tool| { move |(mut item_state, transaction), tool| {
let character = character.clone(); let character = character.clone();
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character.id)?; let mut inventory = item_state.inventory(&character.id).await?;
let mag_entity = inventory.get_by_client_id_mut(&mag_item_id) let mag_entity = inventory.get_by_client_id_mut(&mag_item_id)
.ok_or(ItemStateError::InvalidItemId(mag_item_id))? .ok_or(ItemStateError::InvalidItemId(mag_item_id))?
.item .item
@ -454,7 +454,7 @@ pub(super) fn add_bought_item_to_inventory<'a>(character_id: CharacterEntityId,
{ {
move |(mut item_state, mut transaction), _| { move |(mut item_state, mut transaction), _| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
let bought_item = shop_item.as_item(); let bought_item = shop_item.as_item();
let inventory_item = match bought_item { let inventory_item = match bought_item {
@ -512,7 +512,7 @@ pub(super) fn sell_inventory_item<'a>(character_id: CharacterEntityId)
{ {
move |(mut item_state, transaction), inventory_item| { move |(mut item_state, transaction), inventory_item| {
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character_id)?; let mut inventory = item_state.inventory(&character_id).await?;
let price = inventory_item.item.sell_price()?; let price = inventory_item.item.sell_price()?;
inventory.add_meseta_no_overflow(price)?; inventory.add_meseta_no_overflow(price)?;
@ -648,7 +648,7 @@ pub(super) fn add_item_to_inventory(character: CharacterEntity)
move |(mut item_state, transaction), inventory_item| { move |(mut item_state, transaction), inventory_item| {
let character = character.clone(); let character = character.clone();
Box::pin(async move { Box::pin(async move {
let mut inventory = item_state.inventory(&character.id)?; let mut inventory = item_state.inventory(&character.id).await?;
let mut transaction = inventory_item.with_mag(transaction, |mut transaction, entity_id, _mag| { let mut transaction = inventory_item.with_mag(transaction, |mut transaction, entity_id, _mag| {
let character = character.clone(); let character = character.clone();
async move { async move {
@ -694,7 +694,7 @@ pub(super) fn assign_new_item_id()
{ {
move |(mut item_state, transaction), mut inventory_item| { move |(mut item_state, transaction), mut inventory_item| {
Box::pin(async move { Box::pin(async move {
inventory_item.item_id = item_state.new_item_id()?; inventory_item.item_id = item_state.new_item_id().await?;
Ok(((item_state, transaction), inventory_item)) Ok(((item_state, transaction), inventory_item))
}) })
} }
@ -732,7 +732,7 @@ pub(super) fn convert_item_drop_to_floor_item(character_id: CharacterEntityId, i
ItemDropType::Meseta(m) => ItemOrMeseta::Meseta(Meseta(m)), ItemDropType::Meseta(m) => ItemOrMeseta::Meseta(Meseta(m)),
}; };
let item_id = item_state.new_item_id()?; let item_id = item_state.new_item_id().await?;
let floor_item = match item { let floor_item = match item {
ItemOrMeseta::Individual(item_detail) => { ItemOrMeseta::Individual(item_detail) => {
@ -804,9 +804,9 @@ pub(super) fn add_item_to_local_floor(character_id: CharacterEntityId)
{ {
move |(mut item_state, transaction) , floor_item| { move |(mut item_state, transaction) , floor_item| {
Box::pin(async move { Box::pin(async move {
let mut floor = item_state.floor(&character_id)?; let mut floor = item_state.floor(&character_id).await?;
let item = floor.add_local_item(floor_item).clone(); let item = floor.add_local_item(floor_item).clone();
item_state.set_floor(floor); item_state.set_floor(floor).await;
Ok(((item_state, transaction), item)) Ok(((item_state, transaction), item))
}) })

View File

@ -107,7 +107,7 @@ async fn mag_cell<'a, EG>(item_state: &mut ItemStateProxy<'a>,
where where
EG: EntityGateway + ?Sized, EG: EntityGateway + ?Sized,
{ {
let mut inventory = item_state.inventory(&character.id)?; let mut inventory = item_state.inventory(&character.id).await?;
let (mag_entity_id, mag) = inventory.equipped_mag_mut() let (mag_entity_id, mag) = inventory.equipped_mag_mut()
.ok_or(ApplyItemError::ItemNotEquipped)?; .ok_or(ApplyItemError::ItemNotEquipped)?;

View File

@ -1,7 +1,12 @@
use std::collections::HashMap; use std::collections::HashMap;
use async_std::sync::{Arc, RwLock};
use crate::ship::items::ClientItemId; use crate::ship::items::ClientItemId;
use crate::entity::item::{ItemEntityId, ItemDetail, ItemEntity, InventoryItemEntity, BankItemEntity, BankName}; use crate::entity::item::{ItemEntityId, ItemDetail, ItemEntity, InventoryItemEntity, BankItemEntity, BankName};
use futures::future::join_all;
use crate::ship::location::{AreaClient, RoomId}; use crate::ship::location::{AreaClient, RoomId};
use crate::entity::character::{CharacterEntity, CharacterEntityId}; use crate::entity::character::{CharacterEntity, CharacterEntityId};
use crate::entity::gateway::{EntityGateway, GatewayError}; use crate::entity::gateway::{EntityGateway, GatewayError};
@ -141,46 +146,62 @@ pub enum AddItemResult {
} }
#[derive(Clone)]
pub struct ItemState { pub struct ItemState {
character_inventory: HashMap<CharacterEntityId, InventoryState>, character_inventory: Arc<RwLock<HashMap<CharacterEntityId, RwLock<InventoryState>>>>,
character_bank: HashMap<CharacterEntityId, BankState>, character_bank: Arc<RwLock<HashMap<CharacterEntityId, RwLock<BankState>>>>,
character_room: HashMap<CharacterEntityId, RoomId>, character_room: Arc<RwLock<HashMap<CharacterEntityId, RoomId>>>,
character_floor: HashMap<CharacterEntityId, LocalFloor>, character_floor: Arc<RwLock<HashMap<CharacterEntityId, RwLock<LocalFloor>>>>,
room_floor: HashMap<RoomId, SharedFloor>, room_floor: Arc<RwLock<HashMap<RoomId, RwLock<SharedFloor>>>>,
room_item_id_counter: u32, room_item_id_counter: Arc<RwLock<u32>>,
} }
impl Default for ItemState { impl Default for ItemState {
fn default() -> ItemState { fn default() -> ItemState {
ItemState { ItemState {
character_inventory: HashMap::new(), character_inventory: Arc::new(RwLock::new(HashMap::new())),
character_bank: HashMap::new(), character_bank: Arc::new(RwLock::new(HashMap::new())),
character_room: HashMap::new(), character_room: Arc::new(RwLock::new(HashMap::new())),
character_floor: HashMap::new(), character_floor: Arc::new(RwLock::new(HashMap::new())),
room_floor: HashMap::new(), room_floor: Arc::new(RwLock::new(HashMap::new())),
room_item_id_counter: 0x00810000, room_item_id_counter: Arc::new(RwLock::new(0x00810000)),
} }
} }
} }
impl ItemState { impl ItemState {
pub fn get_character_inventory(&self, character: &CharacterEntity) -> Result<&InventoryState, ItemStateError> { pub async fn get_character_inventory(&self, character: &CharacterEntity) -> Result<InventoryState, ItemStateError> {
self.character_inventory.get(&character.id) Ok(self.character_inventory
.ok_or(ItemStateError::NoCharacter(character.id)) .read()
.await
.get(&character.id)
.ok_or(ItemStateError::NoCharacter(character.id))?
.read()
.await
.clone())
} }
pub fn get_character_bank(&self, character: &CharacterEntity) -> Result<&BankState, ItemStateError> { pub async fn get_character_bank(&self, character: &CharacterEntity) -> Result<BankState, ItemStateError> {
self.character_bank.get(&character.id) Ok(self.character_bank
.ok_or(ItemStateError::NoCharacter(character.id)) .read()
.await
.get(&character.id)
.ok_or(ItemStateError::NoCharacter(character.id))?
.read()
.await
.clone())
} }
} }
impl ItemState { impl ItemState {
fn new_item_id(&mut self) -> Result<ClientItemId, ItemStateError> { async fn new_item_id(&mut self) -> Result<ClientItemId, ItemStateError> {
self.room_item_id_counter += 1; //self.room_item_id_counter += 1;
Ok(ClientItemId(self.room_item_id_counter)) *self.room_item_id_counter
.write()
.await += 1;
Ok(ClientItemId(*self.room_item_id_counter.read().await))
} }
pub async fn load_character<EG: EntityGateway>(&mut self, entity_gateway: &mut EG, character: &CharacterEntity) -> Result<(), ItemStateError> { pub async fn load_character<EG: EntityGateway>(&mut self, entity_gateway: &mut EG, character: &CharacterEntity) -> Result<(), ItemStateError> {
@ -216,7 +237,7 @@ impl ItemState {
}, },
}) })
}) })
.collect::<Result<Vec<_>, _>>()?; .collect::<Result<Vec<_>, ItemStateError>>()?;
let character_meseta = entity_gateway.get_character_meseta(&character.id).await?; let character_meseta = entity_gateway.get_character_meseta(&character.id).await?;
let inventory_state = InventoryState { let inventory_state = InventoryState {
@ -226,83 +247,155 @@ impl ItemState {
equipped, equipped,
meseta: character_meseta, meseta: character_meseta,
}; };
let bank_items = bank.items.into_iter() let bank_items = join_all(
.map(|item| -> Result<BankItem, ItemStateError> { bank.items.into_iter()
Ok(match item { .map(|item| {
BankItemEntity::Individual(item) => { let mut citem_state = self.clone();
BankItem { async move {
item_id: self.new_item_id()?, Ok(match item {
item: BankItemDetail::Individual(IndividualItemDetail { BankItemEntity::Individual(item) => {
entity_id: item.id, BankItem {
item: item.item, item_id: citem_state.new_item_id().await?,
}) item: BankItemDetail::Individual(IndividualItemDetail {
} entity_id: item.id,
}, item: item.item,
BankItemEntity::Stacked(items) => { })
BankItem { }
item_id: self.new_item_id()?, },
item: BankItemDetail::Stacked(StackedItemDetail { BankItemEntity::Stacked(items) => {
entity_ids: items.iter().map(|i| i.id).collect(), BankItem {
tool: items.get(0) item_id: citem_state.new_item_id().await?,
.ok_or_else(|| ItemStateError::StackedItemError(items.clone()))? item: BankItemDetail::Stacked(StackedItemDetail {
.item entity_ids: items.iter().map(|i| i.id).collect(),
.clone() tool: items.get(0)
.as_tool() .ok_or_else(|| ItemStateError::StackedItemError(items.clone()))?
.ok_or_else(|| ItemStateError::StackedItemError(items.clone()))? .item
}) .clone()
} .as_tool()
}, .ok_or_else(|| ItemStateError::StackedItemError(items.clone()))?
}) })
}) }
.collect::<Result<Vec<_>, _>>()?; },
})
}})
.collect::<Vec<_>>())
.await
.into_iter()
.collect::<Result<Vec<_>, ItemStateError>>()?;
let bank_meseta = entity_gateway.get_bank_meseta(&character.id, &BankName("".into())).await?; let bank_meseta = entity_gateway.get_bank_meseta(&character.id, &BankName("".into())).await?;
let bank_state = BankState::new(character.id, BankName("".into()), Bank::new(bank_items), bank_meseta); let bank_state = BankState::new(character.id, BankName("".into()), Bank::new(bank_items), bank_meseta);
self.character_inventory.insert(character.id, inventory_state); self.character_inventory
self.character_bank.insert(character.id, bank_state); .write()
.await
.insert(character.id, RwLock::new(inventory_state));
self.character_bank
.write()
.await
.insert(character.id, RwLock::new(bank_state));
Ok(()) Ok(())
} }
pub fn add_character_to_room(&mut self, room_id: RoomId, character: &CharacterEntity, area_client: AreaClient) { pub async fn add_character_to_room(&mut self, room_id: RoomId, character: &CharacterEntity, area_client: AreaClient) {
let base_inventory_id = ((area_client.local_client.id() as u32) << 21) | 0x10000; let base_inventory_id = ((area_client.local_client.id() as u32) << 21) | 0x10000;
let inventory = self.character_inventory.get_mut(&character.id).unwrap(); //let inventory = self.character_inventory.get_mut(&character.id).unwrap();
inventory.initialize_item_ids(base_inventory_id); self.character_inventory
.read()
.await
.get(&character.id)
.unwrap()
.write()
.await
.initialize_item_ids(base_inventory_id);
//inventory.initialize_item_ids(base_inventory_id);
let base_bank_id = ((area_client.local_client.id() as u32) << 21) | 0x20000; let base_bank_id = ((area_client.local_client.id() as u32) << 21) | 0x20000;
let default_bank = self.character_bank.get_mut(&character.id); //let default_bank = self.character_bank.get_mut(&character.id);
if let Some(default_bank ) = default_bank { self.character_bank
default_bank.initialize_item_ids(base_bank_id); .read()
} .await
self.character_room.insert(character.id, room_id); .get(&character.id)
self.character_floor.insert(character.id, LocalFloor::default()); .unwrap()
self.room_floor.entry(room_id).or_insert_with(SharedFloor::default); .write()
.await
.initialize_item_ids(base_bank_id);
//if let Some(default_bank) = default_bank {
//default_bank.initialize_item_ids(base_bank_id);
//}
self.character_room
.write()
.await
.insert(character.id, room_id);
self.character_floor
.write()
.await
.insert(character.id, RwLock::new(LocalFloor::default()));
self.room_floor
.write()
.await
.entry(room_id)
.or_insert_with(Default::default);
} }
pub fn remove_character_from_room(&mut self, character: &CharacterEntity) { pub async fn remove_character_from_room(&mut self, character: &CharacterEntity) {
self.character_inventory.remove(&character.id); self.character_inventory
self.character_floor.remove(&character.id); .write()
if let Some(room) = self.character_room.remove(&character.id).as_ref() { .await
if self.character_room.iter().any(|(_, r)| r == room) { .remove(&character.id);
self.room_floor.remove(room); self.character_floor
.write()
.await
.remove(&character.id);
let removed = {
self.character_room.write().await.remove(&character.id)
};
if let Some(room) = removed.as_ref() {
// TODO: this looks wrong, .all(r != room) maybe?
if self.character_room.read().await.iter().any(|(_, r)| r == room) {
self.room_floor
.write()
.await
.remove(room);
} }
} }
} }
pub fn get_floor_item(&self, character_id: &CharacterEntityId, item_id: &ClientItemId) -> Result<(&FloorItem, FloorType), ItemStateError> { pub async fn get_floor_item(&self, character_id: &CharacterEntityId, item_id: &ClientItemId) -> Result<(FloorItem, FloorType), ItemStateError> {
let local_floor = self.character_floor.get(character_id).ok_or(ItemStateError::NoCharacter(*character_id))?; let local_floors = self.character_floor
let room = self.character_room.get(character_id).ok_or(ItemStateError::NoCharacter(*character_id))?; .read()
let shared_floor = self.room_floor.get(room).ok_or(ItemStateError::NoCharacter(*character_id))?; .await;
let local_floor = local_floors
.get(character_id)
.ok_or(ItemStateError::NoCharacter(*character_id))?
.read()
.await;
let rooms = self.character_room
.read()
.await;
let room = rooms
.get(character_id)
.ok_or(ItemStateError::NoCharacter(*character_id))?;
let shared_floors = self.room_floor
.read()
.await;
let shared_floor = shared_floors
.get(room)
.ok_or(ItemStateError::NoCharacter(*character_id))?
.read()
.await;
local_floor.0 local_floor.0
.iter() .iter()
.find(|item| item.item_id == *item_id) .find(|item| item.item_id == *item_id)
.map(|item| (item, FloorType::Local)) .map(|item| (item.clone(), FloorType::Local))
.or_else(|| { .or_else(|| {
shared_floor.0 shared_floor.0
.iter() .iter()
.find(|item| item.item_id == *item_id) .find(|item| item.item_id == *item_id)
.map(|item| (item, FloorType::Shared)) .map(|item| (item.clone(), FloorType::Shared))
}) })
.ok_or(ItemStateError::NoFloorItem(*item_id)) .ok_or(ItemStateError::NoFloorItem(*item_id))
} }
@ -314,7 +407,7 @@ struct ProxiedItemState {
character_inventory: HashMap<CharacterEntityId, InventoryState>, character_inventory: HashMap<CharacterEntityId, InventoryState>,
character_bank: HashMap<CharacterEntityId, BankState>, character_bank: HashMap<CharacterEntityId, BankState>,
character_room: HashMap<CharacterEntityId, RoomId>, //character_room: HashMap<CharacterEntityId, RoomId>,
character_floor: HashMap<CharacterEntityId, LocalFloor>, character_floor: HashMap<CharacterEntityId, LocalFloor>,
room_floor: HashMap<RoomId, SharedFloor>, room_floor: HashMap<RoomId, SharedFloor>,
} }
@ -322,27 +415,99 @@ struct ProxiedItemState {
pub struct ItemStateProxy<'a> { pub struct ItemStateProxy<'a> {
item_state: &'a mut ItemState, item_state: &'a mut ItemState,
proxied_state: ProxiedItemState, proxied_state: ProxiedItemState,
//_a: std::marker::PhantomData<&'a ()>, // TODO: remove
} }
impl<'a> ItemStateProxy<'a> { impl<'a> ItemStateProxy<'a> {
pub fn commit(self) { pub async fn commit(self) {
self.item_state.character_inventory.extend(self.proxied_state.character_inventory.clone());
self.item_state.character_bank.extend(self.proxied_state.character_bank.clone()); async fn copy_back<K, V>(master: &Arc<RwLock<HashMap<K, RwLock<V>>>>,
self.item_state.character_room.extend(self.proxied_state.character_room.clone()); proxy: HashMap<K, V>)
self.item_state.character_floor.extend(self.proxied_state.character_floor.clone()); where
self.item_state.room_floor.extend(self.proxied_state.room_floor); K: Eq + std::hash::Hash,
{
for (key, value) in proxy {
if let Some(element) = master
.read()
.await
.get(&key) {
*element
.write()
.await = value;
}
}
}
copy_back(&self.item_state.character_inventory, self.proxied_state.character_inventory).await;
copy_back(&self.item_state.character_bank, self.proxied_state.character_bank).await;
//copy_back(self.item_state.character_room, self.proxied_state.character_room).await;
copy_back(&self.item_state.character_floor, self.proxied_state.character_floor).await;
copy_back(&self.item_state.room_floor, self.proxied_state.room_floor).await;
/*
self.item_state.character_inventory
.write()
.await
.extend(self.proxied_state.character_inventory.clone());
self.item_state.character_bank
.write()
.await
.extend(self.proxied_state.character_bank.clone());
self.item_state.character_room
.write()
.await
.extend(self.proxied_state.character_room.clone());
self.item_state.character_floor
.write()
.await
.extend(self.proxied_state.character_floor.clone());
self.item_state.room_floor
.write()
.await
.extend(self.proxied_state.room_floor);
*/
/*
for (character_id, character_inventory) in self.proxied_state.character_inventory {
if let Some(inventory) = self.item_state.character_inventory
.read()
.await
.get(&character_id) {
*inventory
.write()
.await = character_inventory;
}
}
*/
} }
} }
fn get_or_clone<K, V>(master: &HashMap<K, V>, proxy: &mut HashMap<K, V>, key: K, err: fn(K) -> ItemStateError) -> Result<V, ItemStateError> async fn get_or_clone<K, V>(master: &Arc<RwLock<HashMap<K, RwLock<V>>>>,
proxy: &mut HashMap<K, V>,
key: K,
err: fn(K) -> ItemStateError) -> Result<V, ItemStateError>
where where
K: Eq + std::hash::Hash + Copy, K: Eq + std::hash::Hash + Copy,
V: Clone V: Clone
{ {
/*
let existing_element = master.get(&key).ok_or_else(|| err(key))?; let existing_element = master.get(&key).ok_or_else(|| err(key))?;
Ok(proxy.entry(key) Ok(proxy.entry(key)
.or_insert_with(|| existing_element.clone()).clone()) .or_insert_with(|| existing_element.clone()).clone())
*/
let existing_element = master
.read()
.await
.get(&key)
.ok_or_else(|| err(key))?
.read()
.await
.clone();
Ok(proxy.entry(key)
.or_insert_with(|| existing_element)
.clone())
} }
@ -351,41 +516,50 @@ impl<'a> ItemStateProxy<'a> {
ItemStateProxy { ItemStateProxy {
item_state, item_state,
proxied_state: Default::default(), proxied_state: Default::default(),
//_a: Default::default(),
} }
} }
pub fn inventory(&mut self, character_id: &CharacterEntityId) -> Result<InventoryState, ItemStateError> { pub async fn inventory(&mut self, character_id: &CharacterEntityId) -> Result<InventoryState, ItemStateError> {
get_or_clone(&self.item_state.character_inventory, &mut self.proxied_state.character_inventory, *character_id, ItemStateError::NoCharacter) get_or_clone(&self.item_state.character_inventory,
&mut self.proxied_state.character_inventory,
*character_id,
ItemStateError::NoCharacter).await
} }
pub fn set_inventory(&mut self, inventory: InventoryState) { pub fn set_inventory(&mut self, inventory: InventoryState) {
self.proxied_state.character_inventory.insert(inventory.character_id, inventory); self.proxied_state.character_inventory.insert(inventory.character_id, inventory);
} }
pub fn bank(&mut self, character_id: &CharacterEntityId) -> Result<BankState, ItemStateError> { pub async fn bank(&mut self, character_id: &CharacterEntityId) -> Result<BankState, ItemStateError> {
get_or_clone(&self.item_state.character_bank, &mut self.proxied_state.character_bank, *character_id, ItemStateError::NoCharacter) get_or_clone(&self.item_state.character_bank,
&mut self.proxied_state.character_bank,
*character_id,
ItemStateError::NoCharacter).await
} }
pub fn set_bank(&mut self, bank: BankState) { pub fn set_bank(&mut self, bank: BankState) {
self.proxied_state.character_bank.insert(bank.character_id, bank); self.proxied_state.character_bank.insert(bank.character_id, bank);
} }
pub fn floor(&mut self, character_id: &CharacterEntityId) -> Result<FloorState, ItemStateError> { pub async fn floor(&mut self, character_id: &CharacterEntityId) -> Result<FloorState, ItemStateError> {
let room_id = get_or_clone(&self.item_state.character_room, &mut self.proxied_state.character_room, *character_id, ItemStateError::NoCharacter)?; //let room_id = get_or_clone(&self.item_state.character_room, &mut self.proxied_state.character_room, *character_id, ItemStateError::NoCharacter)?;
let room_id = *self.item_state.character_room.read().await.get(character_id).unwrap();
Ok(FloorState { Ok(FloorState {
character_id: *character_id, character_id: *character_id,
local: get_or_clone(&self.item_state.character_floor, &mut self.proxied_state.character_floor, *character_id, ItemStateError::NoCharacter)?, local: get_or_clone(&self.item_state.character_floor, &mut self.proxied_state.character_floor, *character_id, ItemStateError::NoCharacter).await?,
shared: get_or_clone(&self.item_state.room_floor, &mut self.proxied_state.room_floor, room_id, ItemStateError::NoRoom)?, shared: get_or_clone(&self.item_state.room_floor, &mut self.proxied_state.room_floor, room_id, ItemStateError::NoRoom).await?,
}) })
} }
pub fn set_floor(&mut self, floor: FloorState) { pub async fn set_floor(&mut self, floor: FloorState) {
let room_id = get_or_clone(&self.item_state.character_room, &mut self.proxied_state.character_room, floor.character_id, ItemStateError::NoCharacter).unwrap(); //let room_id = get_or_clone(&self.item_state.character_room, &mut self.proxied_state.character_room, floor.character_id, ItemStateError::NoCharacter).unwrap();
let room_id = *self.item_state.character_room.read().await.get(&floor.character_id).unwrap();
self.proxied_state.character_floor.insert(floor.character_id, floor.local); self.proxied_state.character_floor.insert(floor.character_id, floor.local);
self.proxied_state.room_floor.insert(room_id, floor.shared); self.proxied_state.room_floor.insert(room_id, floor.shared);
} }
pub fn new_item_id(&mut self) -> Result<ClientItemId, ItemStateError> { pub async fn new_item_id(&mut self) -> Result<ClientItemId, ItemStateError> {
self.item_state.new_item_id() self.item_state.new_item_id().await
} }
} }

View File

@ -32,7 +32,7 @@ where
.act(actions::add_floor_item_to_inventory(character)) .act(actions::add_floor_item_to_inventory(character))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -55,7 +55,7 @@ where
.act(actions::add_inventory_item_to_shared_floor(character.id, map_area, drop_position)) .act(actions::add_inventory_item_to_shared_floor(character.id, map_area, drop_position))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -79,7 +79,7 @@ where
.act(actions::add_inventory_item_to_shared_floor(character.id, map_area, (drop_position.0, 0.0, drop_position.1))) .act(actions::add_inventory_item_to_shared_floor(character.id, map_area, (drop_position.0, 0.0, drop_position.1)))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -104,7 +104,7 @@ where
.act(actions::add_meseta_to_shared_floor(character.id, amount, map_area, drop_position)) .act(actions::add_meseta_to_shared_floor(character.id, amount, map_area, drop_position))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -126,7 +126,7 @@ where
.act(actions::add_meseta_from_bank_to_inventory(character.id, amount)) .act(actions::add_meseta_from_bank_to_inventory(character.id, amount))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -148,7 +148,7 @@ where
.act(actions::add_meseta_to_bank(character.id, amount)) .act(actions::add_meseta_to_bank(character.id, amount))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, ())) Ok((transaction, ()))
}).await }).await
} }
@ -173,7 +173,7 @@ where
.act(actions::add_bank_item_to_inventory(character)) .act(actions::add_bank_item_to_inventory(character))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -196,7 +196,7 @@ where
.act(actions::add_inventory_item_to_bank(character.id)) .act(actions::add_inventory_item_to_bank(character.id))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -217,7 +217,7 @@ where
.act(actions::equip_inventory_item(character.id, *item_id, equip_slot)) .act(actions::equip_inventory_item(character.id, *item_id, equip_slot))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -238,7 +238,7 @@ where
.act(actions::unequip_inventory_item(character.id, *item_id)) .act(actions::unequip_inventory_item(character.id, *item_id))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -259,7 +259,7 @@ where
.act(actions::sort_inventory_items(character.id, item_ids)) .act(actions::sort_inventory_items(character.id, item_ids))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -282,7 +282,7 @@ where
.act(actions::use_consumed_item(character.clone())) .act(actions::use_consumed_item(character.clone()))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
*character = new_character; *character = new_character;
Ok((transaction, ())) Ok((transaction, ()))
}).await }).await
@ -306,7 +306,7 @@ where
.act(actions::feed_mag_item(character.clone(), *mag_item_id)) .act(actions::feed_mag_item(character.clone(), *mag_item_id))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, ())) Ok((transaction, ()))
}).await }).await
} }
@ -333,7 +333,7 @@ where
.act(actions::add_bought_item_to_inventory(character.id, shop_item, item_id, amount)) .act(actions::add_bought_item_to_inventory(character.id, shop_item, item_id, amount))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -356,7 +356,7 @@ where
.act(actions::sell_inventory_item(character.id)) .act(actions::sell_inventory_item(character.id))
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, result)) Ok((transaction, result))
}).await }).await
} }
@ -424,7 +424,7 @@ where
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, (p1_new_items, p2_new_items))) Ok((transaction, (p1_new_items, p2_new_items)))
}).await }).await
} }
@ -446,7 +446,7 @@ where
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, ())) Ok((transaction, ()))
}).await }).await
} }
@ -468,7 +468,7 @@ where
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, floor_item)) Ok((transaction, floor_item))
}).await }).await
} }
@ -494,7 +494,7 @@ where
.commit((item_state_proxy, transaction)) .commit((item_state_proxy, transaction))
.await?; .await?;
item_state_proxy.commit(); item_state_proxy.commit().await;
Ok((transaction, item)) Ok((transaction, item))
}).await }).await
} }

View File

@ -91,15 +91,22 @@ pub enum GetLeaderError {
} }
#[derive(Error, Debug, PartialEq, Eq)] #[derive(Error, Debug, PartialEq, Eq)]
#[error("clientlocation")]
pub enum ClientLocationError { pub enum ClientLocationError {
#[error("create room error {0}")]
CreateRoomError(#[from] CreateRoomError), CreateRoomError(#[from] CreateRoomError),
#[error("join room error {0}")]
JoinRoomError(#[from] JoinRoomError), JoinRoomError(#[from] JoinRoomError),
#[error("join lobby error {0}")]
JoinLobbyError(#[from] JoinLobbyError), JoinLobbyError(#[from] JoinLobbyError),
#[error("get area error {0}")]
GetAreaError(#[from] GetAreaError), GetAreaError(#[from] GetAreaError),
#[error("client removal error {0}")]
ClientRemovalError(#[from] ClientRemovalError), ClientRemovalError(#[from] ClientRemovalError),
#[error("get clients error {0}")]
GetClientsError(#[from] GetClientsError), GetClientsError(#[from] GetClientsError),
#[error("get neighbor error {0}")]
GetNeighborError(#[from] GetNeighborError), GetNeighborError(#[from] GetNeighborError),
#[error("get leader error {0}")]
GetLeaderError(#[from] GetLeaderError) GetLeaderError(#[from] GetLeaderError)
} }

View File

@ -318,8 +318,10 @@ impl fmt::Display for MapArea {
pub struct MapAreaLookup(HashMap<u16, MapArea>); pub struct MapAreaLookup(HashMap<u16, MapArea>);
impl MapAreaLookup { impl MapAreaLookup {
pub fn get_area_map(&self, map_area: u16) -> Result<&MapArea, MapAreaError> { pub fn get_area_map(&self, map_area: u16) -> Result<MapArea, MapAreaError> {
self.0.get(&map_area).ok_or(MapAreaError::UnknownMapArea(map_area)) self.0.get(&map_area)
.map(|a| *a)
.ok_or(MapAreaError::UnknownMapArea(map_area))
} }
fn default_ep1_maps() -> MapAreaLookup { fn default_ep1_maps() -> MapAreaLookup {

View File

@ -345,7 +345,6 @@ impl Maps {
pub fn roll_monster_appearance(&mut self, rare_monster_table: &RareMonsterAppearTable) { pub fn roll_monster_appearance(&mut self, rare_monster_table: &RareMonsterAppearTable) {
self.enemy_data = self.enemy_data self.enemy_data = self.enemy_data
.iter() .iter()
// .map(|&x| if x.is_some() && x.unwrap().has_rare_appearance() {
.map(|&x| .map(|&x|
if let Some(monster) = x { if let Some(monster) = x {
if monster.has_rare_appearance() { if monster.has_rare_appearance() {

View File

@ -2,6 +2,7 @@
pub mod ship; pub mod ship;
pub mod location; pub mod location;
pub mod character; pub mod character;
pub mod client;
pub mod room; pub mod room;
pub mod items; pub mod items;
pub mod item_stats; pub mod item_stats;

View File

@ -5,21 +5,34 @@ use crate::ship::location::{ClientLocation, LobbyId, ClientLocationError};
use crate::ship::packet::builder::{player_info}; use crate::ship::packet::builder::{player_info};
use crate::ship::items::state::ItemState; use crate::ship::items::state::ItemState;
use futures::future::join_all;
pub async fn join_lobby(id: ClientId, pub async fn join_lobby(id: ClientId,
lobby: LobbyId, lobby: LobbyId,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &Clients, clients: &Clients,
item_state: &ItemState) item_state: &ItemState)
-> Result<JoinLobby, anyhow::Error> { -> Result<JoinLobby, ShipError> {
let lobby_clients = client_location.get_clients_in_lobby(lobby).await.map_err(|err| -> ClientLocationError { err.into() })?; let lobby_clients = client_location.get_clients_in_lobby(lobby).await.map_err(|err| -> ClientLocationError { err.into() })?;
let playerinfo = lobby_clients.iter()
.map(|area_client| {
let client = clients.get(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client)).unwrap();
player_info(0x100, client, area_client, item_state)
});
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); let playerinfo = join_all(
lobby_clients.into_iter()
.map(|area_client| {
let item_state = item_state.clone();
async move {
clients.with(area_client.client, |client| Box::pin(async move {
let inventory = item_state.get_character_inventory(&client.character).await?;
Ok(player_info(0x100, client, &area_client, &inventory).await)
})).await?
}}))
.await
.into_iter()
.collect::<Result<Vec<_>, ShipError>>()?;
//let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id)).unwrap();
let client_block = clients.with(id, |client| Box::pin(async move {
client.block as u16
})).await?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let leader = client_location.get_lobby_leader(lobby).await.map_err(|err| -> ClientLocationError { err.into() })?; let leader = client_location.get_lobby_leader(lobby).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(JoinLobby { Ok(JoinLobby {
@ -27,10 +40,10 @@ pub async fn join_lobby(id: ClientId,
leader: leader.local_client.id(), leader: leader.local_client.id(),
one: 1, one: 1,
lobby: lobby.id(), lobby: lobby.id(),
block: client.block as u16, block: client_block,
event: 0, event: 0,
padding: 0, padding: 0,
playerinfo: playerinfo.collect(), playerinfo: playerinfo,
}) })
} }
@ -40,20 +53,24 @@ pub async fn add_to_lobby(id: ClientId,
clients: &Clients, clients: &Clients,
item_state: &ItemState) item_state: &ItemState)
-> Result<AddToLobby, ShipError> { -> Result<AddToLobby, ShipError> {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id)).unwrap();
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let leader = client_location.get_lobby_leader(lobby).await.map_err(|err| -> ClientLocationError { err.into() })?; let leader = client_location.get_lobby_leader(lobby).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(AddToLobby { clients.with(id, |client| {
flag: 1, let item_state = item_state.clone();
client: area_client.local_client.id(), Box::pin(async move {
leader: leader.local_client.id(), let inventory = item_state.get_character_inventory(&client.character).await?;
one: 1, Ok(AddToLobby {
lobby: lobby.id(), flag: 1,
block: client.block as u16, client: area_client.local_client.id(),
event: 0, leader: leader.local_client.id(),
padding: 0, one: 1,
playerinfo: player_info(0x100, client, &area_client, item_state), lobby: lobby.id(),
}) block: client.block as u16,
event: 0,
padding: 0,
playerinfo: player_info(0x100, client, &area_client, &inventory).await,
})
})}).await?
} }
pub async fn remove_from_lobby(id: ClientId, pub async fn remove_from_lobby(id: ClientId,

View File

@ -10,7 +10,7 @@ use crate::common::leveltable::LEVEL_TABLE;
use crate::ship::character::CharacterBytesBuilder; use crate::ship::character::CharacterBytesBuilder;
use crate::ship::ship::ClientState; use crate::ship::ship::ClientState;
use crate::ship::location::AreaClient; use crate::ship::location::AreaClient;
use crate::ship::items::state::ItemState; use crate::ship::items::inventory::InventoryState;
pub fn player_header(tag: u32, client: &ClientState, area_client: &AreaClient) -> PlayerHeader { pub fn player_header(tag: u32, client: &ClientState, area_client: &AreaClient) -> PlayerHeader {
PlayerHeader { PlayerHeader {
@ -23,9 +23,8 @@ pub fn player_header(tag: u32, client: &ClientState, area_client: &AreaClient) -
} }
} }
pub fn player_info(tag: u32, client: &ClientState, area_client: &AreaClient, item_state: &ItemState) -> PlayerInfo { pub async fn player_info(tag: u32, client: &ClientState, area_client: &AreaClient, inventory: &InventoryState) -> PlayerInfo {
let (level, stats) = LEVEL_TABLE.get_stats_from_exp(client.character.char_class, client.character.exp); let (level, stats) = LEVEL_TABLE.get_stats_from_exp(client.character.char_class, client.character.exp);
let inventory = item_state.get_character_inventory(&client.character).unwrap();
let character = CharacterBytesBuilder::default() let character = CharacterBytesBuilder::default()
.character(&client.character) .character(&client.character)
.stats(&stats) .stats(&stats)

View File

@ -19,12 +19,14 @@ pub async fn join_room(id: ClientId,
let players = futures::stream::iter(all_clients.iter()) let players = futures::stream::iter(all_clients.iter())
.enumerate() .enumerate()
.fold::<Result<_, ShipError>, _, _>(Ok([PlayerHeader::default(); 4]), |acc, (i, c)| async move { .fold::<Result<_, ShipError>, _, _>(Ok([PlayerHeader::default(); 4]), |acc, (i, c)| async move {
let header_client = clients.get(&c.client).ok_or(ShipError::ClientNotFound(id))?; //let header_client = clients.get(&c.client).ok_or(ShipError::ClientNotFound(id))?;
let header_area_client = client_location.get_local_client(id).await.map_err(|err| ShipError::ClientLocationError(err.into()))?; let header_area_client = client_location.get_local_client(id).await.map_err(|err| ShipError::ClientLocationError(err.into()))?;
acc.map(|mut a| { clients.with(c.client, |client| Box::pin(async move {
a[i] = player_header(0x10000, header_client, &header_area_client); acc.map(|mut a| {
a a[i] = player_header(0x10000, client, &header_area_client);
}) a
})
})).await?
}).await?; }).await?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
@ -50,7 +52,7 @@ pub async fn join_room(id: ClientId,
} }
pub fn add_to_room(_id: ClientId, pub async fn add_to_room(_id: ClientId,
client: &ClientState, client: &ClientState,
area_client: &AreaClient, area_client: &AreaClient,
leader: &AreaClient, leader: &AreaClient,
@ -58,7 +60,7 @@ pub fn add_to_room(_id: ClientId,
_room_id: RoomId, _room_id: RoomId,
) )
-> Result<AddToRoom, ShipError> { -> Result<AddToRoom, ShipError> {
let inventory = item_state.get_character_inventory(&client.character).await?;
Ok(AddToRoom { Ok(AddToRoom {
flag: 1, flag: 1,
client: area_client.local_client.id(), client: area_client.local_client.id(),
@ -68,7 +70,7 @@ pub fn add_to_room(_id: ClientId,
block: 0, block: 0,
event: 0, event: 0,
padding: 0, padding: 0,
playerinfo: player_info(0x10000, client, area_client, item_state), playerinfo: player_info(0x10000, client, area_client, &inventory).await,
}) })
} }

View File

@ -8,16 +8,19 @@ use crate::ship::items::state::ItemState;
use crate::common::interserver::ShipMessage; use crate::common::interserver::ShipMessage;
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub async fn validate_login<EG: EntityGateway>(id: ClientId, pub async fn validate_login<EG>(id: ClientId,
pkt: &Login, pkt: Login,
mut entity_gateway: EG, entity_gateway: &mut EG,
clients: &mut Clients, clients: &mut Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
shipgate_sender: &Option<Box<dyn Fn(ShipMessage) + Send + Sync>>, shipgate_sender: &Option<async_std::channel::Sender<ShipMessage>>,
ship_name: &str, ship_name: &str,
num_blocks: usize) num_blocks: usize)
-> Result<Vec<SendShipPacket>, anyhow::Error> { -> Result<Vec<SendShipPacket>, ShipError>
Ok(match get_login_status(&mut entity_gateway, pkt).await { where
EG: EntityGateway,
{
Ok(match get_login_status(entity_gateway, &pkt).await {
Ok(user) => { Ok(user) => {
let mut response = LoginResponse::by_status(AccountStatus::Ok, Session::new()); let mut response = LoginResponse::by_status(AccountStatus::Ok, Session::new());
response.guildcard = user.id.0 as u32; response.guildcard = user.id.0 as u32;
@ -30,12 +33,12 @@ pub async fn validate_login<EG: EntityGateway>(id: ClientId,
.clone(); .clone();
let settings = entity_gateway.get_user_settings_by_user(&user).await?; let settings = entity_gateway.get_user_settings_by_user(&user).await?;
item_state.load_character(&mut entity_gateway, &character).await?; item_state.load_character(entity_gateway, &character).await?;
if let Some(shipgate_sender) = shipgate_sender.as_ref() { if let Some(shipgate_sender) = shipgate_sender.as_ref() {
shipgate_sender(ShipMessage::AddUser(user.id)); shipgate_sender.send(ShipMessage::AddUser(user.id)).await;
} }
clients.insert(id, ClientState::new(user, settings, character, pkt.session)); clients.add(id, ClientState::new(user, settings, character, pkt.session)).await;
vec![SendShipPacket::LoginResponse(response), SendShipPacket::ShipBlockList(ShipBlockList::new(ship_name, num_blocks))] vec![SendShipPacket::LoginResponse(response), SendShipPacket::ShipBlockList(ShipBlockList::new(ship_name, num_blocks))]
}, },
Err(err) => { Err(err) => {

View File

@ -4,44 +4,58 @@ use crate::ship::ship::{SendShipPacket, ShipError, Clients};
use crate::ship::location::{ClientLocation}; use crate::ship::location::{ClientLocation};
use crate::entity::gateway::EntityGateway; use crate::entity::gateway::EntityGateway;
pub async fn player_chat(id: ClientId, use futures::future::join_all;
msg: &PlayerChat,
client_location: &ClientLocation,
clients: &Clients) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?;
let cmsg = PlayerChat::new(client.user.id.0, msg.message.clone());
Ok(Box::new(client_location.get_all_clients_by_client(id).await.unwrap().into_iter() pub async fn player_chat(id: ClientId,
.map(move |client| { msg: PlayerChat,
(client.client, SendShipPacket::PlayerChat(cmsg.clone())) client_location: &ClientLocation,
}))) clients: &Clients)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let cmsg = clients.with(id, |client| Box::pin(async move {
PlayerChat::new(client.user.id.0, msg.message)
})).await?;
Ok(client_location.get_all_clients_by_client(id).await.unwrap().into_iter()
.map(move |client| {
(client.client, SendShipPacket::PlayerChat(cmsg.clone()).clone())
})
.collect())
} }
pub async fn request_infoboard(id: ClientId, pub async fn request_infoboard(id: ClientId,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &Clients) clients: &Clients)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let area_clients = client_location.get_client_neighbors(id).await.unwrap(); let area_clients = client_location.get_client_neighbors(id).await.unwrap();
let r = area_clients.iter() let infoboards = join_all(
.filter_map(|c| { area_clients.iter()
clients.get(&c.client) .map(|client| async {
}) clients.with(client.client, |client| Box::pin(async move {
.map(|client| { InfoboardResponse {
InfoboardResponse { name: libpso::utf8_to_utf16_array!(client.character.name, 16),
name: libpso::utf8_to_utf16_array!(client.character.name, 16), message: client.character.info_board.as_bytes(),
message: client.character.info_board.as_bytes(), }
} })).await
}).collect(); }))
Box::new(vec![(id, SendShipPacket::ViewInfoboardResponse(ViewInfoboardResponse {response: r}))].into_iter()) .await
.into_iter()
.collect::<Result<Vec<_>, ShipError>>()?;
Ok(vec![(id, SendShipPacket::ViewInfoboardResponse(ViewInfoboardResponse {response: infoboards}))])
} }
pub async fn write_infoboard<EG: EntityGateway>(id: ClientId, pub async fn write_infoboard<EG>(id: ClientId,
new_infoboard: &WriteInfoboard, new_infoboard: WriteInfoboard,
clients: &mut Clients, clients: &Clients,
mut entity_gateway: EG) entity_gateway: &mut EG)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); where
client.character.info_board.update_infoboard(new_infoboard); EG: EntityGateway + Clone + 'static,
entity_gateway.save_character(&client.character).await.unwrap(); {
Box::new(None.into_iter()) clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
Box::pin(async move {
client.character.info_board.update_infoboard(&new_infoboard);
entity_gateway.save_character(&client.character).await
})}).await??;
Ok(Vec::new())
} }

View File

@ -5,9 +5,10 @@ use libpso::packet::ship::*;
use libpso::packet::messages::*; use libpso::packet::messages::*;
use crate::common::leveltable::LEVEL_TABLE; use crate::common::leveltable::LEVEL_TABLE;
use crate::common::serverstate::ClientId; use crate::common::serverstate::ClientId;
use crate::ship::ship::{SendShipPacket, ShipError, Clients, Rooms, ItemShops}; use crate::ship::ship::{SendShipPacket, ShipError, Clients, ItemShops};
use crate::ship::location::{ClientLocation, ClientLocationError}; use crate::ship::location::{ClientLocation, ClientLocationError};
use crate::ship::drops::ItemDrop; use crate::ship::drops::ItemDrop;
use crate::ship::room::Rooms;
use crate::ship::items::ClientItemId; use crate::ship::items::ClientItemId;
use crate::entity::gateway::EntityGateway; use crate::entity::gateway::EntityGateway;
use crate::entity::item; use crate::entity::item;
@ -38,70 +39,73 @@ async fn send_to_client(id: ClientId,
target: u8, target: u8,
msg: DirectMessage, msg: DirectMessage,
client_location: &ClientLocation) client_location: &ClientLocation)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Vec<(ClientId, SendShipPacket)> {
Box::new(client_location.get_all_clients_by_client(id).await.unwrap().into_iter() client_location.get_all_clients_by_client(id).await.unwrap().into_iter()
.filter(move |client| client.local_client.id() == target) .filter(move |client| client.local_client.id() == target)
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::DirectMessage(msg.clone())) (client.client, SendShipPacket::DirectMessage(msg.clone()))
})) })
.collect()
} }
pub async fn guildcard_send(id: ClientId, pub async fn guildcard_send(id: ClientId,
guildcard_send: &GuildcardSend, guildcard_send: GuildcardSend,
target: u32, target: u32,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &Clients) clients: &Clients)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let client = clients.get(&id).unwrap(); let msg = clients.with(id, |client| Box::pin(async move {
let msg = DirectMessage{ DirectMessage{
flag: target, flag: target,
msg: GameMessage::GuildcardRecv(GuildcardRecv { msg: GameMessage::GuildcardRecv(GuildcardRecv {
client: guildcard_send.client, client: guildcard_send.client,
target: guildcard_send.target, target: guildcard_send.target,
guildcard: client.user.id.0, guildcard: client.user.id.0,
name: utf8_to_utf16_array!(client.character.name, 0x18), name: utf8_to_utf16_array!(client.character.name, 0x18),
team: [0; 0x10], // TODO: teams not yet implemented team: [0; 0x10], // TODO: teams not yet implemented
desc: utf8_to_utf16_array!(client.character.guildcard.description, 0x58), desc: utf8_to_utf16_array!(client.character.guildcard.description, 0x58),
one: 1, one: 1,
language: 0, // TODO: add language flag to character language: 0, // TODO: add language flag to character
section_id: client.character.section_id.into(), section_id: client.character.section_id.into(),
class: client.character.char_class.into(), class: client.character.char_class.into(),
}), }),
}; }
send_to_client(id, target as u8, msg, client_location).await })).await?;
Ok(send_to_client(id, target as u8, msg, client_location).await)
} }
pub async fn request_item<EG>(id: ClientId, pub async fn request_item<EG>(id: ClientId,
request_item: &RequestItem, request_item: RequestItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
rooms: &mut Rooms, rooms: &Rooms,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway
{ {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0) let monster = rooms.with(room_id, |room| Box::pin(async move {
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))? room.maps.enemy_by_id(request_item.enemy_id as usize)
.as_mut() })).await??;
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let monster = room.maps.enemy_by_id(request_item.enemy_id as usize)?;
if monster.dropped_item { if monster.dropped_item {
return Err(ShipError::MonsterAlreadyDroppedItem(id, request_item.enemy_id).into()) return Err(ShipError::MonsterAlreadyDroppedItem(id, request_item.enemy_id).into())
} }
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let client_and_drop = rooms.with_mut(room_id, |room| Box::pin(async move {
let client_and_drop = clients_in_area.into_iter() clients_in_area.into_iter()
.filter_map(|area_client| { .filter_map(move |area_client| {
room.drop_table.get_drop(&monster.map_area, &monster.monster).map(|item_drop_type| { room.drop_table.get_drop(&monster.map_area, &monster.monster).map(|item_drop_type| {
(area_client, item_drop_type) (area_client, item_drop_type)
})
}) })
}); .collect::<Vec<_>>()
})).await?;
let mut item_drop_packets = Vec::new(); let mut item_drop_packets = Vec::new();
for (area_client, item_drop) in client_and_drop { for (area_client, item_drop) in client_and_drop {
let item_drop = ItemDrop { let item_drop = ItemDrop {
@ -111,100 +115,108 @@ where
z: request_item.z, z: request_item.z,
item: item_drop, item: item_drop,
}; };
let client = clients.get_mut(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client))?; let character_id = clients.with(id, |client| Box::pin(async move {
let floor_item = enemy_drops_item(item_state, &mut entity_gateway, client.character.id, item_drop).await?; client.character.id
})).await?;
let floor_item = enemy_drops_item(item_state, entity_gateway, character_id, item_drop).await?;
let item_drop_msg = builder::message::item_drop(request_item.client, request_item.target, &floor_item)?; let item_drop_msg = builder::message::item_drop(request_item.client, request_item.target, &floor_item)?;
item_drop_packets.push((area_client.client, SendShipPacket::Message(Message::new(GameMessage::ItemDrop(item_drop_msg))))); item_drop_packets.push((area_client.client, SendShipPacket::Message(Message::new(GameMessage::ItemDrop(item_drop_msg)))));
} }
Ok(Box::new(item_drop_packets.into_iter())) Ok(item_drop_packets)
} }
pub async fn pickup_item<EG>(id: ClientId, pub async fn pickup_item<EG>(id: ClientId,
pickup_item: &PickupItem, pickup_item: PickupItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let (item, floor_type) = item_state.get_floor_item(&client.character.id, &ClientItemId(pickup_item.item_id))?; clients.with(id, |client| {
let remove_item = builder::message::remove_item_from_floor(area_client, item)?; let mut entity_gateway = entity_gateway.clone();
let create_item = match &item.item { let mut item_state = item_state.clone();
FloorItemDetail::Individual(individual_floor_item) => Some(builder::message::create_individual_item(area_client, item.item_id, individual_floor_item)?), Box::pin(async move {
FloorItemDetail::Stacked(stacked_floor_item) => Some(builder::message::create_stacked_item(area_client, item.item_id, &stacked_floor_item.tool, stacked_floor_item.count())?), let (item, floor_type) = item_state.get_floor_item(&client.character.id, &ClientItemId(pickup_item.item_id)).await?;
FloorItemDetail::Meseta(_) => None, let remove_item = builder::message::remove_item_from_floor(area_client, &item)?;
}; let create_item = match &item.item {
FloorItemDetail::Individual(individual_floor_item) => Some(builder::message::create_individual_item(area_client, item.item_id, individual_floor_item)?),
match pick_up_item(item_state, &mut entity_gateway, &client.character, &ClientItemId(pickup_item.item_id)).await { FloorItemDetail::Stacked(stacked_floor_item) => Some(builder::message::create_stacked_item(area_client, item.item_id, &stacked_floor_item.tool, stacked_floor_item.count())?),
Ok(trigger_create_item) => { FloorItemDetail::Meseta(_) => None,
let remove_packets: Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send> = match floor_type {
FloorType::Local => {
Box::new(vec![(id, SendShipPacket::Message(Message::new(GameMessage::RemoveItemFromFloor(remove_item.clone()))))].into_iter())
},
FloorType::Shared => {
Box::new(clients_in_area.clone().into_iter()
.map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::RemoveItemFromFloor(remove_item.clone()))))
}))
},
}; };
Ok(Box::new(remove_packets match pick_up_item(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(pickup_item.item_id)).await {
.chain(clients_in_area.into_iter(). Ok(trigger_create_item) => {
filter_map(move |c| { let remove_packets: Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send> = match floor_type {
match trigger_create_item { FloorType::Local => {
TriggerCreateItem::Yes => create_item.clone().map(|ci| (c.client, SendShipPacket::Message(Message::new(GameMessage::CreateItem(ci))))), Box::new(vec![(id, SendShipPacket::Message(Message::new(GameMessage::RemoveItemFromFloor(remove_item.clone()))))].into_iter())
_ => None },
} FloorType::Shared => {
} Box::new(clients_in_area.clone().into_iter()
)))) .map(move |c| {
}, (c.client, SendShipPacket::Message(Message::new(GameMessage::RemoveItemFromFloor(remove_item.clone()))))
Err(err) => { }))
warn!("character {:?} could not pick up item: {:?}", client.character.id, err); },
Ok(Box::new(None.into_iter())) };
},
} Ok(remove_packets
.chain(clients_in_area.into_iter()
.filter_map(move |c| {
match trigger_create_item {
TriggerCreateItem::Yes => create_item.clone().map(|ci| (c.client, SendShipPacket::Message(Message::new(GameMessage::CreateItem(ci))))),
_ => None
}
}))
.collect())
},
Err(err) => {
warn!("character {:?} could not pick up item: {:?}", client.character.id, err);
Ok(Vec::new())
},
}
})}).await?
} }
pub async fn request_box_item<EG>(id: ClientId, pub async fn request_box_item<EG>(id: ClientId,
box_drop_request: &BoxDropRequest, box_drop_request: BoxDropRequest,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
rooms: &mut Rooms, rooms: &Rooms,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static
{ {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0) let box_object = rooms.with(room_id, |room| Box::pin(async move {
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))? room.maps.object_by_id(box_drop_request.object_id as usize)
.as_mut() })).await??;
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let box_object = room.maps.object_by_id(box_drop_request.object_id as usize)?;
if box_object.dropped_item { if box_object.dropped_item {
return Err(ShipError::BoxAlreadyDroppedItem(id, box_drop_request.object_id).into()) return Err(ShipError::BoxAlreadyDroppedItem(id, box_drop_request.object_id).into())
} }
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let client_and_drop = clients_in_area.into_iter() let client_and_drop = rooms.with_mut(room_id, |room| Box::pin(async move {
.filter_map(|area_client| { clients_in_area.into_iter()
room.drop_table.get_box_drop(&box_object.map, &box_object).map(|item_drop_type| { .filter_map(move |area_client| {
(area_client, item_drop_type) room.drop_table.get_box_drop(&box_object.map, &box_object).map(|item_drop_type| {
(area_client, item_drop_type)
})
}) })
}); .collect::<Vec<_>>()
})).await?;
let mut item_drop_packets = Vec::new(); let mut item_drop_packets = Vec::new();
for (area_client, item_drop) in client_and_drop { for (area_client, item_drop) in client_and_drop {
@ -215,94 +227,145 @@ where
z: box_drop_request.z, z: box_drop_request.z,
item: item_drop, item: item_drop,
}; };
let client = clients.get_mut(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client))?; //let client = clients.get_mut(&area_client.client).ok_or(ShipError::ClientNotFound(area_client.client))?;
let floor_item = enemy_drops_item(item_state, &mut entity_gateway, client.character.id, item_drop).await?; let character_id = clients.with(area_client.client, |client| Box::pin(async move {
client.character.id
})).await?;
let floor_item = enemy_drops_item(item_state, entity_gateway, character_id, item_drop).await?;
//let floor_item = enemy_drops_item(item_state, &mut entity_gateway, client.character.id, item_drop).await?;
let item_drop_msg = builder::message::item_drop(box_drop_request.client, box_drop_request.target, &floor_item)?; let item_drop_msg = builder::message::item_drop(box_drop_request.client, box_drop_request.target, &floor_item)?;
item_drop_packets.push((area_client.client, SendShipPacket::Message(Message::new(GameMessage::ItemDrop(item_drop_msg))))) item_drop_packets.push((area_client.client, SendShipPacket::Message(Message::new(GameMessage::ItemDrop(item_drop_msg)))))
} }
Ok(Box::new(item_drop_packets.into_iter())) Ok(item_drop_packets)
} }
// item_manager is not mutable in this, but for reasons I don't quite understand it requires the unique access of it to compile here
pub async fn send_bank_list(id: ClientId, pub async fn send_bank_list(id: ClientId,
clients: &Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{ {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; let bank = clients.with(id, |client| {
let bank = item_state.get_character_bank(&client.character)?; let item_state = item_state.clone();
let bank_items_pkt = builder::message::bank_item_list(bank); Box::pin(async move {
Ok(Box::new(vec![(id, SendShipPacket::BankItemList(bank_items_pkt))].into_iter())) item_state.get_character_bank(&client.character).await
})
}).await??;
let bank_items_pkt = builder::message::bank_item_list(&bank);
Ok(vec![(id, SendShipPacket::BankItemList(bank_items_pkt))])
} }
pub async fn bank_interaction<EG>(id: ClientId, pub async fn bank_interaction<EG>(id: ClientId,
bank_interaction: &BankInteraction, bank_interaction: BankInteraction,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let other_clients_in_area = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let other_clients_in_area = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let bank_action_pkts = match bank_interaction.action {
BANK_ACTION_DEPOSIT => { let bank_action_pkts = clients.with(id, |client| {
if bank_interaction.item_id == 0xFFFFFFFF { let mut entity_gateway = entity_gateway.clone();
deposit_meseta(item_state, &mut entity_gateway, &client.character, bank_interaction.meseta_amount).await?; let mut item_state = item_state.clone();
Vec::new() Box::pin(async move {
} Ok::<_, ShipError>(match bank_interaction.action {
else { BANK_ACTION_DEPOSIT => {
deposit_item(item_state, &mut entity_gateway, &client.character, &ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as u32).await?; if bank_interaction.item_id == 0xFFFFFFFF {
let player_no_longer_has_item = builder::message::player_no_longer_has_item(area_client, ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as u32); deposit_meseta(&mut item_state, &mut entity_gateway, &client.character, bank_interaction.meseta_amount).await?;
vec![SendShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)))] Vec::new()
} }
}, else {
BANK_ACTION_WITHDRAW => { deposit_item(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as u32).await?;
if bank_interaction.item_id == 0xFFFFFFFF { let player_no_longer_has_item = builder::message::player_no_longer_has_item(area_client, ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as u32);
withdraw_meseta(item_state, &mut entity_gateway, &client.character, bank_interaction.meseta_amount).await?; vec![SendShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)))]
Vec::new() }
} },
else { BANK_ACTION_WITHDRAW => {
let item_added_to_inventory = withdraw_item(item_state, &mut entity_gateway, &client.character, &ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as u32).await?; if bank_interaction.item_id == 0xFFFFFFFF {
let item_created = builder::message::create_withdrawn_inventory_item2(area_client, &item_added_to_inventory)?; withdraw_meseta(&mut item_state, &mut entity_gateway, &client.character, bank_interaction.meseta_amount).await?;
vec![SendShipPacket::Message(Message::new(GameMessage::CreateItem(item_created)))] Vec::new()
} }
}, else {
_ => { // TODO: error? let item_added_to_inventory = withdraw_item(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(bank_interaction.item_id), bank_interaction.item_amount as u32).await?;
Vec::new() let item_created = builder::message::create_withdrawn_inventory_item2(area_client, &item_added_to_inventory)?;
} vec![SendShipPacket::Message(Message::new(GameMessage::CreateItem(item_created)))]
}; }
},
Ok(Box::new(other_clients_in_area.into_iter() _ => { // TODO: error?
.flat_map(move |c| { Vec::new()
bank_action_pkts.clone().into_iter() }
.map(move |pkt| { })
(c.client, pkt) })
}) }).await??;
})
)) Ok(other_clients_in_area.into_iter()
.flat_map(move |c| {
bank_action_pkts.clone().into_iter()
.map(move |pkt| {
(c.client, pkt)
})
})
.collect()
)
} }
pub async fn shop_request(id: ClientId, pub async fn shop_request(id: ClientId,
shop_request: &ShopRequest, shop_request: ShopRequest,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
rooms: &Rooms, rooms: &Rooms,
shops: &mut ItemShops) shops: &ItemShops)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; //let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
/*
let room = rooms.get(room_id.0) let room = rooms.get(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))? .ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.as_ref() .as_ref()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; .ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let level = LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp) as usize; */
let difficulty = rooms.with(room_id, |room| Box::pin(async move {
room.mode.difficulty()
})).await?;
let shop_list = clients.with_mut(id, |client| {
let mut shops = shops.clone();
Box::pin(async move {
let level = LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp) as usize;
match shop_request.shop_type {
SHOP_OPTION_WEAPON => {
client.weapon_shop = shops.weapon_shop.get_mut(&(difficulty, client.character.section_id))
.ok_or(ShipError::ShopError)?
.lock()
.await
.generate_weapon_list(level);
Ok(builder::message::shop_list(shop_request.shop_type, &client.weapon_shop))
},
SHOP_OPTION_TOOL => {
client.tool_shop = shops.tool_shop
.lock()
.await
.generate_tool_list(level);
Ok(builder::message::shop_list(shop_request.shop_type, &client.tool_shop))
},
SHOP_OPTION_ARMOR => {
client.armor_shop = shops.armor_shop
.lock()
.await
.generate_armor_list(level);
Ok(builder::message::shop_list(shop_request.shop_type, &client.armor_shop))
},
_ => {
Err(ShipError::ShopError)
}
}
})}).await??;
/*
let shop_list = match shop_request.shop_type { let shop_list = match shop_request.shop_type {
SHOP_OPTION_WEAPON => { SHOP_OPTION_WEAPON => {
client.weapon_shop = shops.weapon_shop.get_mut(&(room.mode.difficulty(), client.character.section_id)) client.weapon_shop = shops.weapon_shop.get_mut(&(room.mode.difficulty(), client.character.section_id))
@ -322,64 +385,69 @@ pub async fn shop_request(id: ClientId,
return Err(ShipError::ShopError.into()) return Err(ShipError::ShopError.into())
} }
}; };
*/
Ok(Box::new(vec![(id, SendShipPacket::Message(Message::new(GameMessage::ShopList(shop_list))))].into_iter())) Ok(vec![(id, SendShipPacket::Message(Message::new(GameMessage::ShopList(shop_list))))])
} }
pub async fn buy_item<EG>(id: ClientId, pub async fn buy_item<EG>(id: ClientId,
buy_item: &BuyItem, buy_item: BuyItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let (item, remove): (&(dyn ShopItem + Send + Sync), bool) = match buy_item.shop_type { let create = clients.with_mut(id, |client| {
SHOP_OPTION_WEAPON => { let mut entity_gateway = entity_gateway.clone();
(client.weapon_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?, false) let mut item_state = item_state.clone();
}, Box::pin(async move {
SHOP_OPTION_TOOL => { let (item, remove): (&(dyn ShopItem + Send + Sync), bool) = match buy_item.shop_type {
let item = client.tool_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?; SHOP_OPTION_WEAPON => {
let remove = matches!(item, ToolShopItem::Tech(_)); (client.weapon_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?, false)
(item, remove) },
}, SHOP_OPTION_TOOL => {
SHOP_OPTION_ARMOR => { let item = client.tool_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?;
let item = client.armor_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?; let remove = matches!(item, ToolShopItem::Tech(_));
let remove = matches!(item, ArmorShopItem::Unit(_)); (item, remove)
(item, remove) },
}, SHOP_OPTION_ARMOR => {
_ => { let item = client.armor_shop.get(buy_item.shop_index as usize).ok_or(ShipError::ShopError)?;
return Err(ShipError::ShopError.into()) let remove = matches!(item, ArmorShopItem::Unit(_));
} (item, remove)
}; },
_ => {
return Err(ShipError::ShopError.into())
}
};
let inventory_item = buy_shop_item(item_state, &mut entity_gateway, &client.character, item, ClientItemId(buy_item.item_id), buy_item.amount as u32).await?; let inventory_item = buy_shop_item(&mut item_state, &mut entity_gateway, &client.character, item, ClientItemId(buy_item.item_id), buy_item.amount as u32).await?;
let create = builder::message::create_withdrawn_inventory_item(area_client, &inventory_item)?;
if remove { if remove {
match buy_item.shop_type { match buy_item.shop_type {
SHOP_OPTION_TOOL => { SHOP_OPTION_TOOL => {
client.tool_shop.remove(buy_item.shop_index as usize); client.tool_shop.remove(buy_item.shop_index as usize);
}, },
SHOP_OPTION_ARMOR => { SHOP_OPTION_ARMOR => {
client.armor_shop.remove(buy_item.shop_index as usize); client.armor_shop.remove(buy_item.shop_index as usize);
}, },
_ => {} _ => {}
} }
} }
builder::message::create_withdrawn_inventory_item(area_client, &inventory_item)
})}).await??;
let other_clients_in_area = client_location.get_client_neighbors(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let other_clients_in_area = client_location.get_client_neighbors(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(Box::new(other_clients_in_area.into_iter() Ok(other_clients_in_area.into_iter()
.map(move |c| { .map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::CreateItem(create.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::CreateItem(create.clone()))))
}))) })
.collect())
} }
@ -393,15 +461,15 @@ const TEK_PERCENT_MODIFIER: [item::weapon::TekPercentModifier; 5] = [item::weapo
item::weapon::TekPercentModifier::MinusMinus]; item::weapon::TekPercentModifier::MinusMinus];
pub async fn request_tek_item<EG>(id: ClientId, pub async fn request_tek_item<EG>(id: ClientId,
tek_request: &TekRequest, tek_request: TekRequest,
mut entity_gateway: EG, entity_gateway: &mut EG,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; //let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
// TODO: secids have different mod rates // TODO: secids have different mod rates
let (grind_mod, special_mod, percent_mod) = { let (grind_mod, special_mod, percent_mod) = {
@ -413,63 +481,73 @@ where
(grind_mod, special_mod, percent_mod) (grind_mod, special_mod, percent_mod)
}; };
client.tek = Some((ClientItemId(tek_request.item_id), special_mod, percent_mod, grind_mod)); let preview_pkt = clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
client.tek = Some((ClientItemId(tek_request.item_id), special_mod, percent_mod, grind_mod));
let inventory = item_state.get_character_inventory(&client.character)?; let inventory = item_state.get_character_inventory(&client.character).await?;
let item = inventory.get_by_client_id(&ClientItemId(tek_request.item_id)) let item = inventory.get_by_client_id(&ClientItemId(tek_request.item_id))
.ok_or(ItemStateError::WrongItemType(ClientItemId(tek_request.item_id)))?; .ok_or(ItemStateError::WrongItemType(ClientItemId(tek_request.item_id)))?;
let mut weapon = *item.item.as_individual() let mut weapon = *item.item.as_individual()
.ok_or(ItemStateError::WrongItemType(ClientItemId(tek_request.item_id)))? .ok_or(ItemStateError::WrongItemType(ClientItemId(tek_request.item_id)))?
.as_weapon() .as_weapon()
.ok_or(ItemStateError::WrongItemType(ClientItemId(tek_request.item_id)))?; .ok_or(ItemStateError::WrongItemType(ClientItemId(tek_request.item_id)))?;
weapon.apply_modifier(&item::weapon::WeaponModifier::Tekked { weapon.apply_modifier(&item::weapon::WeaponModifier::Tekked {
special: special_mod, special: special_mod,
percent: percent_mod, percent: percent_mod,
grind: grind_mod, grind: grind_mod,
}); });
take_meseta(item_state, &mut entity_gateway, &client.character.id, item::Meseta(100)).await?; take_meseta(&mut item_state, &mut entity_gateway, &client.character.id, item::Meseta(100)).await?;
builder::message::tek_preview(ClientItemId(tek_request.item_id), &weapon)
})}).await??;
let preview_pkt = builder::message::tek_preview(ClientItemId(tek_request.item_id), &weapon)?;
Ok(Box::new(vec![(id, SendShipPacket::Message(Message::new(GameMessage::TekPreview(preview_pkt))))].into_iter())) Ok(vec![(id, SendShipPacket::Message(Message::new(GameMessage::TekPreview(preview_pkt))))])
} }
pub async fn accept_tek_item<EG>(id: ClientId, pub async fn accept_tek_item<EG>(id: ClientId,
tek_accept: &TekAccept, tek_accept: TekAccept,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let neighbors = client_location.get_client_neighbors(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
if let Some((item_id, special_mod, percent_mod, grind_mod)) = client.tek { clients.with(id, |client| {
if item_id.0 != tek_accept.item_id { let mut entity_gateway = entity_gateway.clone();
return Err(MessageError::MismatchedTekIds(item_id, ClientItemId(tek_accept.item_id)).into()); let mut item_state = item_state.clone();
Box::pin(async move {
if let Some((item_id, special_mod, percent_mod, grind_mod)) = client.tek {
if item_id.0 != tek_accept.item_id {
return Err(MessageError::MismatchedTekIds(item_id, ClientItemId(tek_accept.item_id)).into());
}
let modifier = item::weapon::WeaponModifier::Tekked {
special: special_mod,
percent: percent_mod,
grind: grind_mod,
};
let weapon = apply_modifier(&mut item_state, &mut entity_gateway, &client.character, item_id, item::ItemModifier::WeaponModifier(modifier)).await?;
let create_item_pkt = builder::message::create_individual_item(area_client, item_id, &weapon)?;
Ok(neighbors.into_iter()
.map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::CreateItem(create_item_pkt.clone()))))
})
.collect())
} }
else {
let modifier = item::weapon::WeaponModifier::Tekked { Err(MessageError::InvalidTek(ClientItemId(tek_accept.item_id)).into())
special: special_mod, }
percent: percent_mod, })}).await?
grind: grind_mod,
};
let weapon = apply_modifier(item_state, &mut entity_gateway, &client.character, item_id, item::ItemModifier::WeaponModifier(modifier)).await?;
let create_item_pkt = builder::message::create_individual_item(area_client, item_id, &weapon)?;
let neighbors = client_location.get_client_neighbors(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(Box::new(neighbors.into_iter()
.map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::CreateItem(create_item_pkt.clone()))))
})))
}
else {
Err(MessageError::InvalidTek(ClientItemId(tek_accept.item_id)).into())
}
} }

View File

@ -1,57 +1,62 @@
use libpso::packet::ship::*; use libpso::packet::ship::*;
use crate::common::serverstate::ClientId; use crate::common::serverstate::ClientId;
use crate::common::leveltable::LEVEL_TABLE; use crate::common::leveltable::LEVEL_TABLE;
use crate::ship::ship::{SendShipPacket, ShipError, Clients, Rooms}; use crate::ship::ship::{SendShipPacket, ShipError, Clients};
use crate::ship::room::Rooms;
use crate::ship::character::{FullCharacterBytesBuilder}; use crate::ship::character::{FullCharacterBytesBuilder};
use crate::ship::location::{ClientLocation, LobbyId, RoomLobby, ClientLocationError, RoomId}; use crate::ship::location::{ClientLocation, LobbyId, RoomLobby, ClientLocationError, RoomId};
use crate::ship::packet; use crate::ship::packet;
use crate::ship::items::state::ItemState; use crate::ship::items::state::ItemState;
use crate::entity::gateway::EntityGateway; use crate::entity::gateway::EntityGateway;
use crate::ship::map::MapArea; use crate::ship::map::MapArea;
use futures::future::join_all;
// this function needs a better home // this function needs a better home
pub fn block_selected(id: ClientId, pub async fn block_selected(id: ClientId,
pkt: &MenuSelect, pkt: MenuSelect,
clients: &mut Clients, clients: &Clients,
item_state: &ItemState) item_state: &ItemState)
-> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; clients.with_mut(id, |client| {
client.block = pkt.item as usize - 1; let item_state = item_state.clone();
Box::pin(async move {
client.block = pkt.item as usize - 1;
let (level, stats) = LEVEL_TABLE.get_stats_from_exp(client.character.char_class, client.character.exp); let (level, stats) = LEVEL_TABLE.get_stats_from_exp(client.character.char_class, client.character.exp);
let inventory = item_state.get_character_inventory(&client.character).unwrap(); let inventory = item_state.get_character_inventory(&client.character).await?;
let bank = item_state.get_character_bank(&client.character).unwrap(); let bank = item_state.get_character_bank(&client.character).await?;
let fc = FullCharacterBytesBuilder::default() let fc = FullCharacterBytesBuilder::default()
.character(&client.character) .character(&client.character)
.stats(&stats) .stats(&stats)
.level(level) .level(level)
.meseta(inventory.meseta) .meseta(inventory.meseta)
.inventory(inventory) .inventory(&inventory)
.bank(bank) .bank(&bank)
.keyboard_config(&client.character.keyboard_config.as_bytes()) .keyboard_config(&client.character.keyboard_config.as_bytes())
.gamepad_config(&client.character.gamepad_config.as_bytes()) .gamepad_config(&client.character.gamepad_config.as_bytes())
.symbol_chat(&client.settings.settings.symbol_chats) .symbol_chat(&client.settings.settings.symbol_chats)
.tech_menu(&client.character.tech_menu.as_bytes()) .tech_menu(&client.character.tech_menu.as_bytes())
.option_flags(client.character.option_flags) .option_flags(client.character.option_flags)
.build(); .build();
Ok(vec![ Ok(vec![
(id, SendShipPacket::FullCharacter(Box::new(FullCharacter { (id, SendShipPacket::FullCharacter(Box::new(FullCharacter {
character: fc, character: fc,
}))), }))),
(id, SendShipPacket::CharDataRequest(CharDataRequest {})), (id, SendShipPacket::CharDataRequest(CharDataRequest {})),
(id, SendShipPacket::LobbyList(LobbyList::new())), (id, SendShipPacket::LobbyList(LobbyList::new())),
]) ])
})}).await?
} }
pub async fn send_player_to_lobby(id: ClientId, pub async fn send_player_to_lobby(id: ClientId,
_pkt: &CharData, _pkt: CharData,
client_location: &mut ClientLocation, client_location: &mut ClientLocation,
clients: &Clients, clients: &Clients,
item_state: &ItemState) item_state: &ItemState)
-> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let lobby = client_location.add_client_to_next_available_lobby(id, LobbyId(0)).await.map_err(|_| ShipError::TooManyClients)?; let lobby = client_location.add_client_to_next_available_lobby(id, LobbyId(0)).await.map_err(|_| ShipError::TooManyClients)?;
let join_lobby = packet::builder::lobby::join_lobby(id, lobby, client_location, clients, item_state).await?; let join_lobby = packet::builder::lobby::join_lobby(id, lobby, client_location, clients, item_state).await?;
let addto = packet::builder::lobby::add_to_lobby(id, lobby, client_location, clients, item_state).await?; let addto = packet::builder::lobby::add_to_lobby(id, lobby, client_location, clients, item_state).await?;
@ -63,15 +68,17 @@ pub async fn send_player_to_lobby(id: ClientId,
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub async fn change_lobby<EG: EntityGateway>(id: ClientId, pub async fn change_lobby<EG>(id: ClientId,
requested_lobby: u32, requested_lobby: u32,
client_location: &mut ClientLocation, client_location: &mut ClientLocation,
clients: &Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
ship_rooms: &mut Rooms, rooms: &Rooms,
mut entity_gateway: EG) entity_gateway: &mut EG)
-> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; where
EG: EntityGateway + Clone + 'static,
{
let prev_area = client_location.get_area(id).await.map_err(|err| -> ClientLocationError {err.into()})?; let prev_area = client_location.get_area(id).await.map_err(|err| -> ClientLocationError {err.into()})?;
match prev_area { match prev_area {
RoomLobby::Lobby(old_lobby) => { RoomLobby::Lobby(old_lobby) => {
@ -81,9 +88,13 @@ pub async fn change_lobby<EG: EntityGateway>(id: ClientId,
}, },
RoomLobby::Room(old_room) => { RoomLobby::Room(old_room) => {
if client_location.get_client_neighbors(id).await?.is_empty() { if client_location.get_client_neighbors(id).await?.is_empty() {
ship_rooms[old_room.0] = None; rooms.remove(old_room).await;
} }
item_state.remove_character_from_room(&client.character); clients.with(id, |client| {
let mut item_state = item_state.clone();
Box::pin(async move {
item_state.remove_character_from_room(&client.character).await;
})}).await?;
}, },
} }
let leave_lobby = packet::builder::lobby::remove_from_lobby(id, client_location).await?; let leave_lobby = packet::builder::lobby::remove_from_lobby(id, client_location).await?;
@ -100,10 +111,15 @@ pub async fn change_lobby<EG: EntityGateway>(id: ClientId,
} }
} }
} }
item_state.load_character(&mut entity_gateway, &client.character).await?; clients.with(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
item_state.load_character(&mut entity_gateway, &client.character).await
})}).await??;
let join_lobby = packet::builder::lobby::join_lobby(id, lobby, client_location, clients, item_state).await?; let join_lobby = packet::builder::lobby::join_lobby(id, lobby, client_location, clients, item_state).await?;
let addto = packet::builder::lobby::add_to_lobby(id, lobby, client_location, clients, item_state).await?; let addto = packet::builder::lobby::add_to_lobby(id, lobby, client_location, clients, item_state).await?;
let neighbors = client_location.get_client_neighbors(id).await.unwrap(); let neighbors = client_location.get_client_neighbors(id).await?;
Ok(vec![(id, SendShipPacket::JoinLobby(join_lobby))] Ok(vec![(id, SendShipPacket::JoinLobby(join_lobby))]
.into_iter() .into_iter()
.chain(neighbors.into_iter() .chain(neighbors.into_iter()
@ -115,24 +131,25 @@ pub async fn change_lobby<EG: EntityGateway>(id: ClientId,
pub async fn remove_from_lobby(id: ClientId, pub async fn remove_from_lobby(id: ClientId,
client_location: &mut ClientLocation) client_location: &mut ClientLocation)
-> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let area_client = client_location.get_local_client(id).await?; let area_client = client_location.get_local_client(id).await?;
let neighbors = client_location.get_client_neighbors(id).await?; let neighbors = client_location.get_client_neighbors(id).await?;
let leader = client_location.get_leader_by_client(id).await?; let leader = client_location.get_leader_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let leave_lobby_pkt = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), leader.local_client.id())); let leave_lobby_pkt = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), leader.local_client.id()));
client_location.remove_client_from_area(id).await?; client_location.remove_client_from_area(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(neighbors.into_iter().map(|n| { Ok(neighbors.into_iter().map(|n| {
(n.client, leave_lobby_pkt.clone()) (n.client, leave_lobby_pkt.clone())
}).collect()) }).collect())
} }
pub async fn get_room_tab_info(id: ClientId, pub async fn get_room_tab_info(id: ClientId,
pkt: &MenuDetail, pkt: MenuDetail,
client_location: &mut ClientLocation, client_location: &mut ClientLocation,
clients: &Clients, clients: &Clients,
rooms: &mut Rooms) rooms: &mut Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
/*
let room_id = RoomId(pkt.item as usize); let room_id = RoomId(pkt.item as usize);
if let Some(_room) = rooms.get(pkt.item as usize).ok_or(ShipError::InvalidRoom(pkt.item))? { if let Some(_room) = rooms.get(pkt.item as usize).ok_or(ShipError::InvalidRoom(pkt.item))? {
let mut room_info = String::new(); let mut room_info = String::new();
@ -151,4 +168,34 @@ pub async fn get_room_tab_info(id: ClientId,
} else { } else {
Ok(vec![(id, SendShipPacket::SmallLeftDialog(SmallLeftDialog::new("Game is no longer active".into())))]) Ok(vec![(id, SendShipPacket::SmallLeftDialog(SmallLeftDialog::new("Game is no longer active".into())))])
} }
*/
dbg!("a");
let room_id = RoomId(pkt.item as usize);
dbg!("b");
let clients_in_room = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
dbg!("c");
let room_info = if clients_in_room.len() == 0 {
dbg!("d");
String::from("Game is no longer active")
}
else {
dbg!("d2");
join_all(clients_in_room.iter()
.map(|clientl| async move {
dbg!("e");
clients.with(clientl.client, |client| Box::pin(async move {
dbg!("f");
format!("{} Lv{} {}\n{} {}",
client.character.name,
LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp),
client.user.guildcard,
client.character.char_class,
client.area.unwrap_or(MapArea::Pioneer2Ep1))
})).await
})).await
.into_iter()
.collect::<Result<Vec<_>, ShipError>>()?
.join("\n")
};
Ok(vec![(id, SendShipPacket::SmallLeftDialog(SmallLeftDialog::new(room_info)))])
} }

View File

@ -4,179 +4,218 @@ use crate::entity::gateway::EntityGateway;
use crate::entity::item::Meseta; use crate::entity::item::Meseta;
use crate::common::serverstate::ClientId; use crate::common::serverstate::ClientId;
use crate::common::leveltable::LEVEL_TABLE; use crate::common::leveltable::LEVEL_TABLE;
use crate::ship::ship::{SendShipPacket, ShipError, Rooms, Clients, ItemDropLocation}; use crate::ship::ship::{SendShipPacket, ShipError, Clients, ItemDropLocation};
use crate::ship::room::Rooms;
use crate::ship::location::{ClientLocation, ClientLocationError}; use crate::ship::location::{ClientLocation, ClientLocationError};
use crate::ship::items::ClientItemId; use crate::ship::items::ClientItemId;
use crate::ship::packet::builder; use crate::ship::packet::builder;
use crate::ship::items::state::ItemState; use crate::ship::items::state::ItemState;
use crate::ship::items::tasks::{drop_item, drop_partial_item, drop_meseta, equip_item, unequip_item, sort_inventory, use_item, feed_mag, sell_item, take_meseta}; use crate::ship::items::tasks::{drop_item, drop_partial_item, drop_meseta, equip_item, unequip_item, sort_inventory, use_item, feed_mag, sell_item, take_meseta};
pub async fn request_exp<EG: EntityGateway>(id: ClientId, pub async fn request_exp<EG>(id: ClientId,
request_exp: &RequestExp, request_exp: RequestExp,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
rooms: &mut Rooms) rooms: &Rooms)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; where
EG: EntityGateway + Clone + 'static,
{
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.as_mut()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let monster = room.maps.enemy_by_id(request_exp.enemy_id as usize)?; let enemy_id = request_exp.enemy_id as usize;
let monster_stats = room.monster_stats.get(&monster.monster).ok_or(ShipError::UnknownMonster(monster.monster))?; let enemy_exp = rooms.with(room_id, |room| Box::pin(async move {
let monster = room.maps.enemy_by_id(enemy_id)?;
let monster_stats = room.monster_stats.get(&monster.monster).ok_or(ShipError::UnknownMonster(monster.monster))?;
Ok::<_, ShipError>(monster_stats.exp)
})).await??;
let exp_gain = if request_exp.last_hitter == 1 { let exp_gain = if request_exp.last_hitter == 1 {
monster_stats.exp enemy_exp
} }
else { else {
((monster_stats.exp as f32) * 0.8) as u32 ((enemy_exp as f32) * 0.8) as u32
}; };
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let gain_exp_pkt = builder::message::character_gained_exp(area_client, exp_gain); let gain_exp_pkt = builder::message::character_gained_exp(area_client, exp_gain);
let mut exp_pkts: Box<dyn Iterator<Item = _> + Send> = Box::new(clients_in_area.clone().into_iter() let mut exp_pkts: Vec<_> = clients_in_area.clone().into_iter()
.map(move |c| { .map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::GiveCharacterExp(gain_exp_pkt.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::GiveCharacterExp(gain_exp_pkt.clone()))))
})); })
.collect();
let before_level = LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp); let (char_class, exp) = clients.with(id, |client| Box::pin(async move {
let after_level = LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp + exp_gain); (client.character.char_class, client.character.exp)
})).await?;
let before_level = LEVEL_TABLE.get_level_from_exp(char_class, exp);
let after_level = LEVEL_TABLE.get_level_from_exp(char_class, exp + exp_gain);
let level_up = before_level != after_level; let level_up = before_level != after_level;
if level_up { if level_up {
let (_, before_stats) = LEVEL_TABLE.get_stats_from_exp(client.character.char_class, client.character.exp); let (_, before_stats) = LEVEL_TABLE.get_stats_from_exp(char_class, exp);
let (after_level, after_stats) = LEVEL_TABLE.get_stats_from_exp(client.character.char_class, client.character.exp + exp_gain); let (after_level, after_stats) = LEVEL_TABLE.get_stats_from_exp(char_class, exp + exp_gain);
let level_up_pkt = builder::message::character_leveled_up(area_client, after_level, before_stats, after_stats); let level_up_pkt = builder::message::character_leveled_up(area_client, after_level, before_stats, after_stats);
exp_pkts = Box::new(exp_pkts.chain(clients_in_area.into_iter() exp_pkts.extend(clients_in_area.into_iter()
.map(move |c| { .map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerLevelUp(level_up_pkt.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerLevelUp(level_up_pkt.clone()))))
}))) }));
} }
client.character.exp += exp_gain; clients.with_mut(id, |client| {
entity_gateway.save_character(&client.character).await?; let mut entity_gateway = entity_gateway.clone();
Box::pin(async move {
client.character.exp += exp_gain;
entity_gateway.save_character(&client.character).await
})}).await??;
Ok(exp_pkts) Ok(exp_pkts)
} }
pub async fn player_drop_item<EG>(id: ClientId, pub async fn player_drop_item<EG>(id: ClientId,
player_drop_item: &PlayerDropItem, player_drop_item: PlayerDropItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
rooms: &mut Rooms, rooms: &Rooms,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0) let map_area = rooms.with(room_id, |room| Box::pin(async move {
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))? room.map_areas.get_area_map(player_drop_item.map_area)
.as_mut() })).await??;
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let area = room.map_areas.get_area_map(player_drop_item.map_area)?; clients.with(id, |client| {
drop_item(item_state, &mut entity_gateway, &client.character, &ClientItemId(player_drop_item.item_id), *area, (player_drop_item.x, player_drop_item.y, player_drop_item.z)).await?; let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
drop_item(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(player_drop_item.item_id), map_area, (player_drop_item.x, player_drop_item.y, player_drop_item.z)).await
})}).await??;
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let pdi = player_drop_item.clone(); let pdi = player_drop_item.clone();
Ok(Box::new(clients_in_area.into_iter() Ok(clients_in_area.into_iter()
.map(move |c| { .map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerDropItem(pdi.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerDropItem(pdi.clone()))))
}))) })
.collect())
} }
pub async fn drop_coordinates(id: ClientId, pub async fn drop_coordinates(id: ClientId,
drop_coordinates: &DropCoordinates, drop_coordinates: DropCoordinates,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
rooms: &Rooms) rooms: &Rooms)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get(room_id.0) let map_area = rooms.with(room_id, |room| Box::pin(async move {
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))? room.map_areas.get_area_map(drop_coordinates.map_area)
.as_ref() })).await??;
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
client.item_drop_location = Some(ItemDropLocation { clients.with_mut(id, |client| Box::pin(async move {
map_area: *room.map_areas.get_area_map(drop_coordinates.map_area)?, client.item_drop_location = Some(ItemDropLocation {
x: drop_coordinates.x, map_area,
z: drop_coordinates.z, x: drop_coordinates.x,
item_id: ClientItemId(drop_coordinates.item_id), z: drop_coordinates.z,
}); item_id: ClientItemId(drop_coordinates.item_id),
});
})).await?;
Ok(Box::new(None.into_iter())) // TODO: do we need to send a packet here? Ok(Vec::new()) // TODO: do we need to send a packet here?
} }
pub async fn no_longer_has_item<EG>(id: ClientId, pub async fn no_longer_has_item<EG>(id: ClientId,
no_longer_has_item: &PlayerNoLongerHasItem, no_longer_has_item: PlayerNoLongerHasItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; //let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
if let Some(drop_location) = client.item_drop_location {
let (drop_location, tek) = clients.with(id, |client| Box::pin(async move {
(client.item_drop_location, client.tek)
})).await?;
if let Some(drop_location) = drop_location {
if drop_location.item_id.0 != no_longer_has_item.item_id { if drop_location.item_id.0 != no_longer_has_item.item_id {
return Err(ShipError::DropInvalidItemId(no_longer_has_item.item_id).into()); return Err(ShipError::DropInvalidItemId(no_longer_has_item.item_id).into());
} }
if no_longer_has_item.item_id == 0xFFFFFFFF { if no_longer_has_item.item_id == 0xFFFFFFFF {
let dropped_meseta = drop_meseta(item_state, &mut entity_gateway, &client.character, drop_location.map_area, (drop_location.x, drop_location.z), no_longer_has_item.amount).await?; let dropped_meseta = clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
client.item_drop_location = None;
drop_meseta(&mut item_state, &mut entity_gateway, &client.character, drop_location.map_area, (drop_location.x, drop_location.z), no_longer_has_item.amount).await
})}).await??;
let dropped_meseta_pkt = builder::message::drop_split_meseta_stack(area_client, &dropped_meseta)?; let dropped_meseta_pkt = builder::message::drop_split_meseta_stack(area_client, &dropped_meseta)?;
let no_longer_has_meseta_pkt = builder::message::player_no_longer_has_meseta(area_client, no_longer_has_item.amount as u32); let no_longer_has_meseta_pkt = builder::message::player_no_longer_has_meseta(area_client, no_longer_has_item.amount as u32);
client.item_drop_location = None;
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(Box::new(clients_in_area.into_iter() Ok(clients_in_area.into_iter()
.flat_map(move |c| { .flat_map(move |c| {
std::iter::once((c.client, SendShipPacket::Message(Message::new(GameMessage::DropSplitStack(dropped_meseta_pkt.clone()))))) std::iter::once((c.client, SendShipPacket::Message(Message::new(GameMessage::DropSplitStack(dropped_meseta_pkt.clone())))))
.chain( .chain(
if c.client != id { if c.client != id {
Box::new(std::iter::once( Box::new(std::iter::once(
(c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(no_longer_has_meseta_pkt.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(no_longer_has_meseta_pkt.clone()))))
)) as Box<dyn Iterator<Item = _> + Send> )) as Box<dyn Iterator<Item = _> + Send>
} }
else { else {
Box::new(std::iter::empty()) as Box<dyn Iterator<Item = _> + Send> Box::new(std::iter::empty()) as Box<dyn Iterator<Item = _> + Send>
} }
) )
}) })
)) .collect()
)
} }
else { else {
let dropped_item = drop_partial_item(item_state, &mut entity_gateway, &client.character, &drop_location.item_id, drop_location.map_area, (drop_location.x, drop_location.z), no_longer_has_item.amount).await?; let dropped_item = clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
client.item_drop_location = None;
drop_partial_item(&mut item_state,
&mut entity_gateway,
&client.character,
&drop_location.item_id,
drop_location.map_area,
(drop_location.x, drop_location.z),
no_longer_has_item.amount)
.await
})}).await??;
let dropped_item_pkt = builder::message::drop_split_stack(area_client, &dropped_item)?; let dropped_item_pkt = builder::message::drop_split_stack(area_client, &dropped_item)?;
client.item_drop_location = None;
let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let clients_in_area = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(Box::new(clients_in_area.into_iter() Ok(clients_in_area.into_iter()
.map(move |c| { .map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::DropSplitStack(dropped_item_pkt.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::DropSplitStack(dropped_item_pkt.clone()))))
}))) })
.collect())
} }
} }
else if let Some(_tek) = client.tek { else if let Some(_tek) = tek {
let neighbors = client_location.get_client_neighbors(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let neighbors = client_location.get_client_neighbors(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let no_longer_has_item = no_longer_has_item.clone(); let no_longer_has_item = no_longer_has_item.clone();
Ok(Box::new(neighbors.into_iter() Ok(neighbors.into_iter()
.map(move |c| { .map(move |c| {
(c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(no_longer_has_item.clone())))) (c.client, SendShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(no_longer_has_item.clone()))))
}))) })
.collect())
} }
else { else {
Err(ShipError::InvalidItem(ClientItemId(no_longer_has_item.item_id)).into()) Err(ShipError::InvalidItem(ClientItemId(no_longer_has_item.item_id)).into())
@ -184,201 +223,233 @@ where
} }
pub async fn update_player_position(id: ClientId, pub async fn update_player_position(id: ClientId,
message: &Message, message: Message,
clients: &mut Clients, clients: &Clients,
client_location: &ClientLocation, client_location: &ClientLocation,
rooms: &Rooms) rooms: &Rooms)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?;
if let Ok(room_id) = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() }) { if let Ok(room_id) = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() }) {
let room = rooms.get(room_id.0) let msg = message.msg.clone();
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))? clients.with_mut(id, |client| {
.as_ref() let rooms = rooms.clone();
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; Box::pin(async move {
match msg {
match &message.msg { GameMessage::PlayerChangedMap(p) => {
GameMessage::PlayerChangedMap(p) => { client.x = p.x;
client.x = p.x; client.y = p.y;
client.y = p.y; client.z = p.z;
client.z = p.z; },
}, GameMessage::PlayerChangedMap2(p) => {
GameMessage::PlayerChangedMap2(p) => { client.area = rooms.with(room_id, |room| Box::pin(async move {
client.area = room.map_areas.get_area_map(p.map_area).ok().cloned(); room.map_areas.get_area_map(p.map_area).ok()
}, })).await?;
GameMessage::TellOtherPlayerMyLocation(p) => { },
client.x = p.x; GameMessage::TellOtherPlayerMyLocation(p) => {
client.y = p.y; client.x = p.x;
client.z = p.z; client.y = p.y;
client.area = room.map_areas.get_area_map(p.map_area).ok().cloned(); client.z = p.z;
}, client.area = rooms.with(room_id, |room| Box::pin(async move {
GameMessage::PlayerWarpingToFloor(p) => { room.map_areas.get_area_map(p.map_area).ok()
client.area = room.map_areas.get_area_map(p.area as u16).ok().cloned(); })).await?;
}, },
GameMessage::PlayerTeleported(p) => { GameMessage::PlayerWarpingToFloor(p) => {
client.x = p.x; client.area = rooms.with(room_id, |room| Box::pin(async move {
client.y = p.y; room.map_areas.get_area_map(p.area as u16).ok()
client.z = p.z; })).await?;
}, },
GameMessage::PlayerStopped(p) => { GameMessage::PlayerTeleported(p) => {
client.x = p.x; client.x = p.x;
client.y = p.y; client.y = p.y;
client.z = p.z; client.z = p.z;
}, },
GameMessage::PlayerLoadedIn(p) => { GameMessage::PlayerStopped(p) => {
client.x = p.x; client.x = p.x;
client.y = p.y; client.y = p.y;
client.z = p.z; client.z = p.z;
}, },
GameMessage::PlayerWalking(p) => { GameMessage::PlayerLoadedIn(p) => {
client.x = p.x; client.x = p.x;
client.z = p.z; client.y = p.y;
}, client.z = p.z;
GameMessage::PlayerRunning(p) => { },
client.x = p.x; GameMessage::PlayerWalking(p) => {
client.z = p.z; client.x = p.x;
}, client.z = p.z;
GameMessage::PlayerWarped(p) => { },
client.x = p.x; GameMessage::PlayerRunning(p) => {
client.y = p.y; client.x = p.x;
}, client.z = p.z;
// GameMessage::PlayerChangedFloor(p) => {client.area = MapArea::from_value(&room.mode.episode(), p.map).ok();}, },
GameMessage::InitializeSpeechNpc(p) => { GameMessage::PlayerWarped(p) => {
client.x = p.x; client.x = p.x;
client.z = p.z; client.y = p.y;
} },
_ => {}, // GameMessage::PlayerChangedFloor(p) => {client.area = MapArea::from_value(&room.mode.episode(), p.map).ok();},
} GameMessage::InitializeSpeechNpc(p) => {
} else {} client.x = p.x;
let m = message.clone(); client.z = p.z;
Ok(Box::new(client_location.get_client_neighbors(id).await.unwrap().into_iter() }
.map(move |client| { _ => {},
(client.client, SendShipPacket::Message(m.clone())) }
}))) Ok::<_, ShipError>(())
})}).await?;
}
Ok(client_location.get_client_neighbors(id).await?.into_iter()
.map(move |client| {
(client.client, SendShipPacket::Message(message.clone()))
})
.collect())
} }
pub async fn charge_attack<EG>(id: ClientId, pub async fn charge_attack<EG>(id: ClientId,
charge: &ChargeAttack, charge: ChargeAttack,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; let meseta = charge.meseta;
clients.with(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
// TODO: should probably validate this to be a legit number, I'd just hardcode 200 but vjaya
take_meseta(&mut item_state, &mut entity_gateway, &client.character.id, Meseta(meseta)).await
})}).await??;
// TODO: should probably validate this to be a legit number, I'd just hardcode 200 but vjaya Ok(client_location.get_client_neighbors(id).await.unwrap().into_iter()
take_meseta(item_state, &mut entity_gateway, &client.character.id, Meseta(charge.meseta)).await?; .map(move |client| {
(client.client, SendShipPacket::Message(Message::new(GameMessage::ChargeAttack(charge.clone()))))
let charge = charge.clone(); })
Ok(Box::new(client_location.get_client_neighbors(id).await.unwrap().into_iter() .collect())
.map(move |client| {
(client.client, SendShipPacket::Message(Message::new(GameMessage::ChargeAttack(charge.clone()))))
})))
} }
pub async fn player_uses_item<EG>(id: ClientId, pub async fn player_uses_item<EG>(id: ClientId,
player_use_tool: &PlayerUseItem, player_use_tool: PlayerUseItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
_client_location: &ClientLocation, _client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; clients.with_mut(id, |client| {
use_item(item_state, &mut entity_gateway, &mut client.character, &ClientItemId(player_use_tool.item_id), 1).await?; let mut entity_gateway = entity_gateway.clone();
Ok(Box::new(None.into_iter())) // TODO: should probably tell other players we used an item let mut item_state = item_state.clone();
Box::pin(async move {
use_item(&mut item_state, &mut entity_gateway, &mut client.character, &ClientItemId(player_use_tool.item_id), 1).await
})}).await??;
Ok(Vec::new())
} }
pub async fn player_used_medical_center<EG>(id: ClientId, pub async fn player_used_medical_center<EG>(id: ClientId,
pumc: &PlayerUsedMedicalCenter, pumc: PlayerUsedMedicalCenter,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; clients.with(id, |client| {
let mut entity_gateway = entity_gateway.clone();
take_meseta(item_state, &mut entity_gateway, &client.character.id, Meseta(10)).await?; let mut item_state = item_state.clone();
Box::pin(async move {
take_meseta(&mut item_state, &mut entity_gateway, &client.character.id, Meseta(10)).await
})}).await??;
let pumc = pumc.clone(); let pumc = pumc.clone();
Ok(Box::new(client_location.get_client_neighbors(id).await.unwrap().into_iter() Ok(client_location.get_client_neighbors(id).await.unwrap().into_iter()
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::Message(Message::new(GameMessage::PlayerUsedMedicalCenter(pumc.clone())))) (client.client, SendShipPacket::Message(Message::new(GameMessage::PlayerUsedMedicalCenter(pumc.clone()))))
}))) })
.collect())
} }
pub async fn player_feed_mag<EG>(id: ClientId, pub async fn player_feed_mag<EG>(id: ClientId,
mag_feed: &PlayerFeedMag, mag_feed: PlayerFeedMag,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?;
feed_mag(item_state, &mut entity_gateway, &client.character, &ClientItemId(mag_feed.mag_id), &ClientItemId(mag_feed.item_id)).await?;
let mag_feed = mag_feed.clone(); let cmag_feed = mag_feed.clone();
Ok(Box::new(client_location.get_client_neighbors(id).await.unwrap().into_iter() clients.with(id, |client| {
.map(move |client| { let mut entity_gateway = entity_gateway.clone();
(client.client, SendShipPacket::Message(Message::new(GameMessage::PlayerFeedMag(mag_feed.clone())))) let mut item_state = item_state.clone();
}))) Box::pin(async move {
feed_mag(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(cmag_feed.mag_id), &ClientItemId(cmag_feed.item_id)).await
})}).await??;
Ok(client_location.get_client_neighbors(id).await.unwrap().into_iter()
.map(move |client| {
(client.client, SendShipPacket::Message(Message::new(GameMessage::PlayerFeedMag(mag_feed.clone()))))
})
.collect())
} }
pub async fn player_equips_item<EG>(id: ClientId, pub async fn player_equips_item<EG>(id: ClientId,
pkt: &PlayerEquipItem, pkt: PlayerEquipItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
clients: &Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?;
let equip_slot = if pkt.sub_menu > 0 { let equip_slot = if pkt.sub_menu > 0 {
((pkt.sub_menu & 0x7) - 1) % 4 ((pkt.sub_menu & 0x7) - 1) % 4
} }
else { else {
0 0
}; };
equip_item(item_state, &mut entity_gateway, &client.character, &ClientItemId(pkt.item_id), equip_slot).await?;
Ok(Box::new(None.into_iter())) // TODO: tell other players you equipped an item clients.with(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
equip_item(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(pkt.item_id), equip_slot).await
})}).await??;
Ok(Vec::new()) // TODO: tell other players you equipped an item
} }
pub async fn player_unequips_item<EG>(id: ClientId, pub async fn player_unequips_item<EG>(id: ClientId,
pkt: &PlayerUnequipItem, pkt: PlayerUnequipItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
clients: &Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; clients.with(id, |client| {
unequip_item(item_state, &mut entity_gateway, &client.character, &ClientItemId(pkt.item_id)).await?; let mut entity_gateway = entity_gateway.clone();
Ok(Box::new(None.into_iter())) // TODO: tell other players if you unequip an item let mut item_state = item_state.clone();
Box::pin(async move {
unequip_item(&mut item_state, &mut entity_gateway, &client.character, &ClientItemId(pkt.item_id)).await
})}).await??;
Ok(Vec::new()) // TODO: tell other players if you unequip an item
} }
pub async fn player_sorts_items<EG>(id: ClientId, pub async fn player_sorts_items<EG>(id: ClientId,
pkt: &SortItems, pkt: SortItems,
mut entity_gateway: EG, entity_gateway: &mut EG,
clients: &Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?;
let item_ids = pkt.item_ids let item_ids = pkt.item_ids
.iter() .iter()
.filter_map(|item_id| { .filter_map(|item_id| {
@ -390,21 +461,30 @@ where
} }
}) })
.collect(); .collect();
sort_inventory(item_state, &mut entity_gateway, &client.character, item_ids).await?;
Ok(Box::new(None.into_iter())) // TODO: clients probably care about each others item orders clients.with(id, |client| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
sort_inventory(&mut item_state, &mut entity_gateway, &client.character, item_ids).await
})}).await??;
Ok(Vec::new()) // TODO: clients probably care about each others item orders
} }
pub async fn player_sells_item<EG> (id: ClientId, pub async fn player_sells_item<EG> (id: ClientId,
sold_item: &PlayerSoldItem, sold_item: PlayerSoldItem,
mut entity_gateway: EG, entity_gateway: &mut EG,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState) item_state: &mut ItemState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; clients.with(id, |client| {
sell_item(item_state, &mut entity_gateway, &client.character, ClientItemId(sold_item.item_id), sold_item.amount as u32).await?; let mut entity_gateway = entity_gateway.clone();
// TODO: send the packet to other clients let mut item_state = item_state.clone();
Ok(Box::new(None.into_iter())) Box::pin(async move {
sell_item(&mut item_state, &mut entity_gateway, &client.character, ClientItemId(sold_item.item_id), sold_item.amount as u32).await
})}).await??;
Ok(Vec::new()) // TODO: send the packet to other clients
} }

View File

@ -1,7 +1,9 @@
use std::io::{Cursor, Read, Seek, SeekFrom}; use std::io::{Cursor, Read, Seek, SeekFrom};
use futures::stream::{FuturesOrdered, StreamExt};
use libpso::packet::ship::*; use libpso::packet::ship::*;
use crate::common::serverstate::ClientId; use crate::common::serverstate::ClientId;
use crate::ship::ship::{SendShipPacket, ShipError, Clients, Rooms}; use crate::ship::ship::{SendShipPacket, ShipError, Clients};
use crate::ship::room::Rooms;
use crate::ship::location::{ClientLocation, ClientLocationError}; use crate::ship::location::{ClientLocation, ClientLocationError};
use crate::ship::packet::builder::quest; use crate::ship::packet::builder::quest;
use libpso::util::array_to_utf8; use libpso::util::array_to_utf8;
@ -36,165 +38,302 @@ fn parse_filename(filename_bytes: &[u8; 16]) -> Result<(u16, u16, QuestFileType)
} }
pub async fn send_quest_category_list(id: ClientId, rql: &RequestQuestList, client_location: &ClientLocation, rooms: &mut Rooms) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { pub async fn send_quest_category_list(id: ClientId,
rql: RequestQuestList,
client_location: &ClientLocation,
rooms: &Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0) /*
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut() let mut room = rooms.get_mut(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; .ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.write()
.await;
let qcl = quest::quest_category_list(&room.quests[rql.flag.clamp(0, (room.quests.len() - 1) as u32) as usize]); let qcl = quest::quest_category_list(&room.quests[rql.flag.clamp(0, (room.quests.len() - 1) as u32) as usize]);
room.set_quest_group(rql.flag as usize); room.set_quest_group(rql.flag as usize);
Ok(Box::new(vec![(id, SendShipPacket::QuestCategoryList(qcl))].into_iter())) Ok(Box::new(vec![(id, SendShipPacket::QuestCategoryList(qcl))].into_iter()))
*/
let rql = rql.clone();
rooms.with_mut(room_id, |room| Box::pin(async move {
let qcl = quest::quest_category_list(&room.quests[rql.flag.clamp(0, (room.quests.len() - 1) as u32) as usize]);
room.set_quest_group(rql.flag as usize);
Ok(vec![(id, SendShipPacket::QuestCategoryList(qcl))])
})).await?
} }
pub async fn select_quest_category(id: ClientId, menuselect: &MenuSelect, client_location: &ClientLocation, rooms: &mut Rooms) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { pub async fn select_quest_category(id: ClientId,
menuselect: MenuSelect,
client_location: &ClientLocation,
rooms: &Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0) rooms.with(room_id, |room| Box::pin(async move {
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut() let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; .nth(menuselect.item as usize)
let (_, category_quests) = room.quests[room.quest_group.value()].iter() .ok_or(ShipError::InvalidQuestCategory(menuselect.item))?;
.nth(menuselect.item as usize)
.ok_or(ShipError::InvalidQuestCategory(menuselect.item))?;
let ql = quest::quest_list(menuselect.item, category_quests); let ql = quest::quest_list(menuselect.item, category_quests);
for q in ql.quests.clone() { Ok(vec![(id, SendShipPacket::QuestOptionList(ql))])
println!("name: {:?} quest_id: {}", q.name, q.quest_id); })).await?
}
Ok(Box::new(vec![(id, SendShipPacket::QuestOptionList(ql))].into_iter()))
} }
pub async fn quest_detail(id: ClientId, questdetailrequest: &QuestDetailRequest, client_location: &ClientLocation, rooms: &mut Rooms) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { pub async fn quest_detail(id: ClientId,
questdetailrequest: QuestDetailRequest,
client_location: &ClientLocation,
rooms: &Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0) rooms.with(room_id, |room| Box::pin(async move {
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut() let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; .nth(questdetailrequest.category as usize)
let (_, category_quests) = room.quests[room.quest_group.value()].iter() .ok_or(ShipError::InvalidQuestCategory(questdetailrequest.category as u32))?;
.nth(questdetailrequest.category as usize)
.ok_or(ShipError::InvalidQuestCategory(questdetailrequest.category as u32))?;
let quest = category_quests.iter() let quest = category_quests.iter()
.find(|q| { .find(|q| {
q.id == questdetailrequest.quest as u16 q.id == questdetailrequest.quest as u16
}).ok_or(ShipError::InvalidQuest(questdetailrequest.quest as u32))?; }).ok_or(ShipError::InvalidQuest(questdetailrequest.quest as u32))?;
let qd = quest::quest_detail(quest); let qd = quest::quest_detail(quest);
Ok(Box::new(vec![(id, SendShipPacket::QuestDetail(qd))].into_iter())) Ok(vec![(id, SendShipPacket::QuestDetail(qd))])
})).await?
} }
pub async fn player_chose_quest(id: ClientId, questmenuselect: &QuestMenuSelect, clients: &mut Clients, client_location: &ClientLocation, rooms: &mut Rooms) pub async fn player_chose_quest(id: ClientId,
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { questmenuselect: QuestMenuSelect,
clients: &Clients,
client_location: &ClientLocation,
rooms: &Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut() let client_location = client_location.clone();
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; let questmenuselect = questmenuselect.clone();
let (_, category_quests) = room.quests[room.quest_group.value()].iter() rooms.with_mut(room_id, |room| {
let clients = clients.clone();
Box::pin(async move {
let quest = room.quests[room.quest_group.value()].iter()
.nth(questmenuselect.category as usize)
.ok_or(ShipError::InvalidQuestCategory(questmenuselect.category as u32))?
.1
.iter()
.find(|q| {
q.id == questmenuselect.quest as u16
})
.ok_or(ShipError::InvalidQuest(questmenuselect.quest as u32))?
.clone();
let rare_monster_drops = room.rare_monster_table.clone();
room.maps.set_quest_data(quest.enemies.clone(), quest.objects.clone(), &rare_monster_drops);
room.map_areas = quest.map_areas.clone();
let bin = quest::quest_header(&questmenuselect, &quest.bin_blob, "bin");
let dat = quest::quest_header(&questmenuselect, &quest.dat_blob, "dat");
let area_clients = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
for client in &area_clients {
clients.with_mut(client.client, |client| Box::pin(async move {
client.done_loading_quest = false;
})).await?;
}
//area_clients.iter().for_each(|c| {
//if let Some(client) = clients.get_mut(&c.client) {
// client.done_loading_quest = false;
//}
//});
Ok(area_clients
.into_iter()
.flat_map(move |c| {
vec![(c.client, SendShipPacket::QuestHeader(bin.clone())), (c.client, SendShipPacket::QuestHeader(dat.clone()))]
})
.collect())
})}).await?
/*
let mut room = rooms.get(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.as_ref()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.write()
.await;
/*
let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.nth(questmenuselect.category as usize) .nth(questmenuselect.category as usize)
.ok_or(ShipError::InvalidQuestCategory(questmenuselect.category as u32))?; .ok_or(ShipError::InvalidQuestCategory(questmenuselect.category as u32))?;
let quest = category_quests.iter() let quest = category_quests.iter()
.find(|q| { .find(|q| {
q.id == questmenuselect.quest as u16 q.id == questmenuselect.quest as u16
}).ok_or(ShipError::InvalidQuest(questmenuselect.quest as u32))?; }).ok_or(ShipError::InvalidQuest(questmenuselect.quest as u32))?
.clone();
*/
room.maps.set_quest_data(quest.enemies.clone(), quest.objects.clone(), &room.rare_monster_table); let quest = room.quests[room.quest_group.value()].iter()
room.map_areas = quest.map_areas.clone(); .nth(questmenuselect.category as usize)
.ok_or(ShipError::InvalidQuestCategory(questmenuselect.category as u32))?
.1
.iter()
.find(|q| {
q.id == questmenuselect.quest as u16
})
.ok_or(ShipError::InvalidQuest(questmenuselect.quest as u32))?
.clone();
let bin = quest::quest_header(questmenuselect, &quest.bin_blob, "bin"); let rare_monster_drops = room.rare_monster_table.clone();
let dat = quest::quest_header(questmenuselect, &quest.dat_blob, "dat"); room.maps.set_quest_data(quest.enemies.clone(), quest.objects.clone(), &rare_monster_drops);
room.map_areas = quest.map_areas.clone();
let area_clients = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let bin = quest::quest_header(questmenuselect, &quest.bin_blob, "bin");
area_clients.iter().for_each(|c| { let dat = quest::quest_header(questmenuselect, &quest.dat_blob, "dat");
let area_clients = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
area_clients.iter().for_each(|c| {
if let Some(client) = clients.get_mut(&c.client) { if let Some(client) = clients.get_mut(&c.client) {
client.done_loading_quest = false; client.done_loading_quest = false;
} }
}); });
Ok(Box::new(area_clients.into_iter().flat_map(move |c| { Ok(Box::new(area_clients.into_iter().flat_map(move |c| {
vec![(c.client, SendShipPacket::QuestHeader(bin.clone())), (c.client, SendShipPacket::QuestHeader(dat.clone()))] vec![(c.client, SendShipPacket::QuestHeader(bin.clone())), (c.client, SendShipPacket::QuestHeader(dat.clone()))]
}))) })))
*/
} }
pub async fn quest_file_request(id: ClientId, quest_file_request: &QuestFileRequest, client_location: &ClientLocation, rooms: &mut Rooms) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { pub async fn quest_file_request(id: ClientId,
quest_file_request: QuestFileRequest,
client_location: &ClientLocation,
rooms: &mut Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut() let quest_file_request = quest_file_request.clone();
rooms.with(room_id, |room| Box::pin(async move {
let (category_id, quest_id, datatype) = parse_filename(&quest_file_request.filename)?;
let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.nth(category_id as usize)
.ok_or(ShipError::InvalidQuestCategory(category_id as u32))?;
let quest = category_quests.iter()
.find(|q| {
q.id == quest_id as u16
}).ok_or(ShipError::InvalidQuest(quest_id as u32))?;
let blob = match datatype {
QuestFileType::Bin => &quest.bin_blob,
QuestFileType::Dat => &quest.dat_blob,
};
let mut blob_cursor = Cursor::new(&**blob);
let mut subblob = [0u8; 0x400];
let blob_length = blob_cursor.read(&mut subblob)?;
let qc = quest::quest_chunk(0, quest_file_request.filename, subblob, blob_length);
Ok(vec![(id, SendShipPacket::QuestChunk(qc))])
})).await?
}
pub async fn quest_chunk_ack(id: ClientId,
quest_chunk_ack: QuestChunkAck,
client_location: &ClientLocation,
rooms: &Rooms)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let quest_chunk_ack = quest_chunk_ack.clone();
rooms.with(room_id, |room| Box::pin(async move {
let (category_id, quest_id, datatype) = parse_filename(&quest_chunk_ack.filename)?;
let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.nth(category_id as usize)
.ok_or(ShipError::InvalidQuestCategory(category_id as u32))?;
let quest = category_quests.iter()
.find(|q| {
q.id == quest_id
}).ok_or(ShipError::InvalidQuest(quest_id as u32))?;
let blob = match datatype {
QuestFileType::Bin => &quest.bin_blob,
QuestFileType::Dat => &quest.dat_blob,
};
let mut blob_cursor = Cursor::new(&**blob);
blob_cursor.seek(SeekFrom::Start((quest_chunk_ack.chunk_num as u64 + 1) * 0x400))?;
let mut subblob = [0u8; 0x400];
let blob_length = blob_cursor.read(&mut subblob)?;
if blob_length == 0 {
return Ok(Vec::new());
}
let qc = quest::quest_chunk(quest_chunk_ack.chunk_num + 1, quest_chunk_ack.filename, subblob, blob_length);
Ok(vec![(id, SendShipPacket::QuestChunk(qc))])
})).await?
/*
let mut room = rooms.get(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.write()
.await
.as_ref()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?; .ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let (category_id, quest_id, datatype) = parse_filename(&quest_file_request.filename)?; let (category_id, quest_id, datatype) = parse_filename(&quest_chunk_ack.filename)?;
let (_, category_quests) = room.quests[room.quest_group.value()].iter() let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.nth(category_id as usize) .nth(category_id as usize)
.ok_or(ShipError::InvalidQuestCategory(category_id as u32))?; .ok_or(ShipError::InvalidQuestCategory(category_id as u32))?;
let quest = category_quests.iter() let quest = category_quests.iter()
.find(|q| { .find(|q| {
q.id == quest_id as u16 q.id == quest_id
}).ok_or(ShipError::InvalidQuest(quest_id as u32))?; }).ok_or(ShipError::InvalidQuest(quest_id as u32))?;
let blob = match datatype { let blob = match datatype {
QuestFileType::Bin => &quest.bin_blob, QuestFileType::Bin => &quest.bin_blob,
QuestFileType::Dat => &quest.dat_blob, QuestFileType::Dat => &quest.dat_blob,
}; };
let mut blob_cursor = Cursor::new(blob);
let mut subblob = [0u8; 0x400]; let mut blob_cursor = Cursor::new(&**blob);
let blob_length = blob_cursor.read(&mut subblob)?; blob_cursor.seek(SeekFrom::Start((quest_chunk_ack.chunk_num as u64 + 1) * 0x400))?;
let qc = quest::quest_chunk(0, quest_file_request.filename, subblob, blob_length); let mut subblob = [0u8; 0x400];
let blob_length = blob_cursor.read(&mut subblob)?;
Ok(Box::new(vec![(id, SendShipPacket::QuestChunk(qc))].into_iter())) if blob_length == 0 {
}
pub async fn quest_chunk_ack(id: ClientId, quest_chunk_ack: &QuestChunkAck, client_location: &ClientLocation, rooms: &mut Rooms) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> {
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let room = rooms.get_mut(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?.as_mut()
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?;
let (category_id, quest_id, datatype) = parse_filename(&quest_chunk_ack.filename)?;
let (_, category_quests) = room.quests[room.quest_group.value()].iter()
.nth(category_id as usize)
.ok_or(ShipError::InvalidQuestCategory(category_id as u32))?;
let quest = category_quests.iter()
.find(|q| {
q.id == quest_id
}).ok_or(ShipError::InvalidQuest(quest_id as u32))?;
let blob = match datatype {
QuestFileType::Bin => &quest.bin_blob,
QuestFileType::Dat => &quest.dat_blob,
};
let mut blob_cursor = Cursor::new(blob);
blob_cursor.seek(SeekFrom::Start((quest_chunk_ack.chunk_num as u64 + 1) * 0x400))?;
let mut subblob = [0u8; 0x400];
let blob_length = blob_cursor.read(&mut subblob)?;
if blob_length == 0 {
return Ok(Box::new(None.into_iter())); return Ok(Box::new(None.into_iter()));
} }
let qc = quest::quest_chunk(quest_chunk_ack.chunk_num + 1, quest_chunk_ack.filename, subblob, blob_length); let qc = quest::quest_chunk(quest_chunk_ack.chunk_num + 1, quest_chunk_ack.filename, subblob, blob_length);
Ok(Box::new(vec![(id, SendShipPacket::QuestChunk(qc))].into_iter())) Ok(Box::new(vec![(id, SendShipPacket::QuestChunk(qc))].into_iter()))
*/
} }
pub async fn done_loading_quest(id: ClientId, clients: &mut Clients, client_location: &ClientLocation) pub async fn done_loading_quest(id: ClientId,
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { clients: &Clients,
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id))?; client_location: &ClientLocation)
client.done_loading_quest = true; -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
clients.with_mut(id, |client| Box::pin(async move {
client.done_loading_quest = true;
})).await?;
let area_clients = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let area_clients = client_location.get_all_clients_by_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
let all_loaded = area_clients.iter().all(|c| {
clients.get(&c.client)
.map(|client| {
client.done_loading_quest
})
.unwrap_or(false)
});
let all_loaded = area_clients.iter()
.map(|client| async {
clients.with(client.client, |client| Box::pin(async move {
client.done_loading_quest
}))
})
.collect::<FuturesOrdered<_>>()
.all(|c| async move {
c.await.unwrap_or(false)
}).await;
if all_loaded { if all_loaded {
Ok(Box::new(area_clients.into_iter().map(|c| { Ok(area_clients
(c.client, SendShipPacket::DoneLoadingQuest(DoneLoadingQuest {})) .iter()
}))) .map(|c| {
(c.client, SendShipPacket::DoneLoadingQuest(DoneLoadingQuest {}))
})
.collect())
} }
else { else {
Ok(Box::new(None.into_iter())) Ok(Vec::new())
} }
} }

View File

@ -2,132 +2,186 @@ use libpso::packet::ship::*;
use libpso::packet::messages::*; use libpso::packet::messages::*;
use crate::common::serverstate::ClientId; use crate::common::serverstate::ClientId;
use crate::common::leveltable::LEVEL_TABLE; use crate::common::leveltable::LEVEL_TABLE;
use crate::ship::ship::{SendShipPacket, ShipError, Rooms, Clients}; use crate::ship::ship::{SendShipPacket, ShipError, Clients};
use crate::ship::location::{ClientLocation, RoomId, RoomLobby, ClientLocationError}; use crate::ship::room::Rooms;
use crate::ship::location::{ClientLocation, RoomId, RoomLobby, ClientLocationError, GetAreaError};
use crate::ship::packet::builder; use crate::ship::packet::builder;
use crate::ship::room; use crate::ship::room;
use crate::ship::items::state::ItemState; use crate::ship::items::state::ItemState;
use std::convert::{TryFrom}; use std::convert::{TryFrom, Into};
use futures::StreamExt; use async_std::sync::{Arc, RwLock};
use futures::stream::{FuturesOrdered, StreamExt};
pub async fn create_room(id: ClientId, pub async fn create_room(id: ClientId,
create_room: &CreateRoom, create_room: CreateRoom,
client_location: &mut ClientLocation, client_location: &mut ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
rooms: &mut Rooms) rooms: &Rooms)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; let level = clients.with(id, |client| Box::pin(async move {
let level = LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp); LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp)
})).await?;
match room::Difficulty::try_from(create_room.difficulty)? { match room::Difficulty::try_from(create_room.difficulty)? {
room::Difficulty::Ultimate => { room::Difficulty::Ultimate if level < 80 => {
if level < 80 { return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 80 \nto create Ultimate rooms.".into())))])
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 80 \nto create Ultimate rooms.".into())))].into_iter()))
}
}, },
room::Difficulty::VeryHard => { room::Difficulty::VeryHard if level < 40 => {
if level < 40 { return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 40 \nto create Very Hard rooms.".into())))])
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 40 \nto create Very Hard rooms.".into())))].into_iter()))
}
}, },
room::Difficulty::Hard => { room::Difficulty::Hard if level < 20 => {
if level < 20 { return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 20 \nto create Hard rooms.".into())))])
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 20 \nto create Hard rooms.".into())))].into_iter()))
}
}, },
room::Difficulty::Normal => {}, _ => {},
}; };
let area = client_location.get_area(id).await.unwrap(); let area = client_location.get_area(id).await?;
let area_client = client_location.get_local_client(id).await.unwrap(); let area_client = client_location.get_local_client(id).await?;
let lobby_neighbors = client_location.get_client_neighbors(id).await.unwrap(); let lobby_neighbors = client_location.get_client_neighbors(id).await?;
let room_id = client_location.create_new_room(id).await.unwrap();
let mut room = room::RoomState::from_create_room(create_room, client.character.section_id).unwrap();
room.bursting = true;
item_state.add_character_to_room(room_id, &client.character, area_client); //let room_id = client_location.create_new_room(id).await.map_err(Into::<ClientLocationError>::into)?;
let room_id = client_location.create_new_room(id).await?;
let room = clients.with(id, |client| {
let mut item_state = item_state.clone();
Box::pin(async move {
item_state.add_character_to_room(room_id, &client.character, area_client).await;
let mut room = room::RoomState::from_create_room(&create_room, client.character.section_id)?;
room.bursting = true;
Ok::<_, ShipError>(room)
})}).await??;
let join_room = builder::room::join_room(id, clients, client_location, room_id, &room).await?; let join_room = builder::room::join_room(id, clients, client_location, room_id, &room).await?;
rooms[room_id.0] = Some(room); rooms.add(room_id, room).await?;
let mut result: Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send> = Box::new( let mut result = vec![(id, SendShipPacket::JoinRoom(join_room))];
vec![(id, SendShipPacket::JoinRoom(join_room))].into_iter()
);
if let Ok(leader) = client_location.get_area_leader(area).await { if let Ok(leader) = client_location.get_area_leader(area).await {
let leave_lobby = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), leader.local_client.id())); let leave_lobby = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), leader.local_client.id()));
result = Box::new(result.chain(lobby_neighbors result.extend(lobby_neighbors
.into_iter() .into_iter()
.map(move |c| { .map(move |c| {
(c.client, leave_lobby.clone()) (c.client, leave_lobby.clone())
}))); }));
} }
Ok(result) Ok(result)
} }
// TODO: remove unwraps
pub async fn room_name_request(id: ClientId, pub async fn room_name_request(id: ClientId,
client_location: &ClientLocation, client_location: &ClientLocation,
rooms: &Rooms) rooms: &Rooms)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let area = client_location.get_area(id).await.unwrap(); let area = client_location.get_area(id).await?;
match area { match area {
RoomLobby::Room(room) => Box::new(vec![(id, SendShipPacket::RoomNameResponse(RoomNameResponse {name: rooms[room.0].as_ref().unwrap().name.clone()}))].into_iter()), RoomLobby::Room(room) => {
RoomLobby::Lobby(_) => panic!() rooms.with(room, |room| Box::pin(async move {
vec![(id, SendShipPacket::RoomNameResponse(RoomNameResponse {
name: room.name.clone()
}))]
})).await
},
RoomLobby::Lobby(_) => Err(GetAreaError::NotInRoom.into())
//RoomLobby::Lobby(_) => Err(ShipError::ClientLocationError(GetAreaError::NotInRoom))
} }
} }
pub async fn join_room(id: ClientId, pub async fn join_room(id: ClientId,
pkt: &MenuSelect, pkt: MenuSelect,
client_location: &mut ClientLocation, client_location: &mut ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
rooms: &mut Rooms) rooms: &Rooms)
-> Result<Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send>, ShipError> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; let room_id = RoomId(pkt.item as usize);
let level = LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp); if !rooms.exists(room_id).await {
// let room = rooms.get(pkt.item as usize).ok_or(ShipError::InvalidRoom(pkt.item))?.as_ref().unwrap(); // clippy look what you made me do return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("This room no longer exists!".into())))])
if let Some(room) = rooms.get(pkt.item as usize).ok_or(ShipError::InvalidRoom(pkt.item))? { }
let level = clients.with(id, |client| Box::pin(async move {
LEVEL_TABLE.get_level_from_exp(client.character.char_class, client.character.exp)
})).await?;
let (difficulty, bursting) = rooms.with(room_id, |room| Box::pin(async move {
(room.mode.difficulty(), room.bursting)
})).await?;
match room.mode.difficulty() { match difficulty {
room::Difficulty::Ultimate => { room::Difficulty::Ultimate if level < 80 => {
if level < 80 { return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 80 \nto join Ultimate rooms.".into())))])
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 80 \nto join Ultimate rooms.".into())))].into_iter())) },
} room::Difficulty::VeryHard if level < 40 => {
}, return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 40 \nto join Very Hard rooms.".into())))])
room::Difficulty::VeryHard => { },
if level < 40 { room::Difficulty::Hard if level < 20 => {
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 40 \nto join Very Hard rooms.".into())))].into_iter())) return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 20 \nto join Hard rooms.".into())))])
} },
}, _ => {},
room::Difficulty::Hard => { }
if level < 20 {
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("You must be at least level 20 \nto join Hard rooms.".into())))].into_iter()))
}
},
_ => {},
};
let original_area = client_location.get_area(id).await.unwrap(); if bursting {
let original_neighbors = client_location.get_client_neighbors(id).await.unwrap(); return Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("player is bursting\nplease wait".into())))])
if room.bursting { }
return Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("player is bursting\nplease wait".into())))].into_iter()))
}
let room_id = RoomId(pkt.item as usize);
let original_room_clients = client_location.get_clients_in_room(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?;
client_location.add_client_to_room(id, room_id).await.unwrap(); // TODO: show room full error or whatever
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; let original_area = client_location.get_area(id).await?;
let area_client = client_location.get_local_client(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let original_neighbors = client_location.get_client_neighbors(id).await?;
let original_room_clients = client_location.get_clients_in_room(room_id).await?;
client_location.add_client_to_room(id, room_id).await?;
let area_client = client_location.get_local_client(id).await?;
//let original_leader = client_location.get_area_leader(original_area).await.unwrap();
let room_leader = client_location.get_room_leader(room_id).await.unwrap();
item_state.add_character_to_room(room_id, &client.character, area_client); clients.with(id, |client| {
let mut item_state = item_state.clone();
Box::pin(async move {
item_state.add_character_to_room(room_id, &client.character, area_client).await;
})}).await?;
let leader = client_location.get_room_leader(room_id).await.map_err(|err| -> ClientLocationError { err.into() })?; let join_room = rooms.with(room_id, |room| {
let join_room = builder::room::join_room(id, clients, client_location, room_id, room).await?; let clients = clients.clone();
let add_to = builder::room::add_to_room(id, client, &area_client, &leader, item_state, room_id)?; let client_location = client_location.clone();
Box::pin(async move {
builder::room::join_room(id, &clients, &client_location, room_id, &room).await
})}).await??;
let add_to = clients.with(id, |client| {
let item_state = item_state.clone();
Box::pin(async move {
builder::room::add_to_room(id, client, &area_client, &room_leader, &item_state, room_id).await
})}).await??;
//let leave_lobby = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), original_leader.local_client.id()));
let room = rooms.get_mut(room_id.0).unwrap().as_mut().unwrap(); rooms.with_mut(room_id, |room| Box::pin(async move {
room.bursting = true; room.bursting = true;
})).await?;
Ok(vec![(id, SendShipPacket::JoinRoom(join_room))]
.into_iter()
.chain(original_room_clients.into_iter()
.map(move |c| (c.client, SendShipPacket::AddToRoom(add_to.clone()))))
.chain(futures::stream::iter(original_neighbors.into_iter())
.filter_map(|c| {
let client_location = client_location.clone();
async move {
client_location.get_area_leader(original_area).await.ok().map(|leader| {
let leave_lobby = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), leader.local_client.id()));
(c.client, leave_lobby.clone())
})
}
})
.collect::<Vec<_>>()
.await
)
.collect())
/*
if let Ok(leader) = client_location.get_area_leader(original_area).await {
let leave_lobby = SendShipPacket::LeaveLobby(LeaveLobby::new(area_client.local_client.id(), leader.local_client.id()));
result.extend(original_neighbors.into_iter()
.map(move |c| (c.client, leave_lobby.clone())))
}
*/
//Ok(result)
/*
if let Some(room) = &mut *rooms.get(pkt.item as usize).ok_or(ShipError::InvalidRoom(pkt.item))?.write().await {
let mut result: Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send> = Box::new( let mut result: Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send> = Box::new(
vec![(id, SendShipPacket::JoinRoom(join_room))] vec![(id, SendShipPacket::JoinRoom(join_room))]
.into_iter() .into_iter()
@ -141,64 +195,61 @@ pub async fn join_room(id: ClientId,
.map(move |c| (c.client, leave_lobby.clone())))) .map(move |c| (c.client, leave_lobby.clone()))))
} }
Ok(result) Ok(result.collect())
} else { } else {
Ok(Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("Game is no longer active".into())))].into_iter())) Ok(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("Game is no longer active".into())))])
} }
*/
} }
pub async fn done_bursting(id: ClientId, pub async fn done_bursting(id: ClientId,
client_location: &ClientLocation, client_location: &ClientLocation,
rooms: &mut Rooms) rooms: &Rooms)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let area = client_location.get_area(id).await.unwrap(); let room_id = client_location.get_room(id).await?;
let mut rare_monster_list: Option<Vec<u16>> = None; let rare_monster_list = rooms.with_mut(room_id, |room| Box::pin(async move {
if let RoomLobby::Room(room_id) = area { room.bursting = false;
if let Some(room) = rooms.get_mut(room_id.0).unwrap().as_mut() { room.maps.get_rare_monster_list()
room.bursting = false; })).await?;
rare_monster_list = Some(room.maps.get_rare_monster_list());
};
}
let area_client = client_location.get_local_client(id).await.unwrap(); // TODO: unwrap
let mut result: Box<dyn Iterator<Item=(ClientId, SendShipPacket)> + Send> = Box::new(
client_location.get_client_neighbors(id).await.unwrap().into_iter() // TODO: unwrap
.flat_map(move |client| {
vec![
(client.client, SendShipPacket::Message(Message::new(GameMessage::BurstDone(BurstDone {
client: area_client.local_client.id(),
target: 0
})))),
]
})
);
// TODO: check how often `done_bursting` is called. ie: make sure it's only used when joining a room and not each time a player warps in a pipe let area_client = client_location.get_local_client(id).await?;
if let Some(rare_list) = rare_monster_list { Ok(client_location.get_client_neighbors(id).await?.into_iter()
let rare_monster_packet = SendShipPacket::RareMonsterList(builder::room::build_rare_monster_list(rare_list)); .map(move |client| {
result = Box::new(result.chain(vec![(id, rare_monster_packet)])); // TODO: make sure we arent clobbering `result` here (client.client, SendShipPacket::Message(Message::new(GameMessage::BurstDone(BurstDone {
} client: area_client.local_client.id(),
target: 0
result }))))
})
.chain(std::iter::once_with(move || {
(id, SendShipPacket::RareMonsterList(builder::room::build_rare_monster_list(rare_monster_list)))
}))
.collect())
} }
pub async fn request_room_list(id: ClientId, pub async fn request_room_list(id: ClientId,
client_location: &ClientLocation, client_location: &ClientLocation,
rooms: &Rooms) rooms: &Rooms)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Vec<(ClientId, SendShipPacket)> {
let active_room_list = futures::stream::iter(rooms.iter()) //let active_room_list = futures::stream::iter(rooms.iter())
let active_room_list = rooms.stream()
.enumerate() .enumerate()
.filter_map(|(i, r)| async move { .filter_map(|(i, r)| async move {
r.as_ref().map(|room| async move { r.as_ref().map(|room| {
RoomList { let difficulty = room.get_difficulty_for_room_list();
menu_id: ROOM_MENU_ID, let name = libpso::utf8_to_utf16_array!(room.name, 16);
item_id: i as u32, let episode = room.get_episode_for_room_list();
difficulty: room.get_difficulty_for_room_list(), let flags = room.get_flags_for_room_list();
players: client_location.get_clients_in_room(RoomId(i)).await.unwrap().len() as u8, async move {
name: libpso::utf8_to_utf16_array!(room.name, 16), RoomList {
episode: room.get_episode_for_room_list(), menu_id: ROOM_MENU_ID,
flags: room.get_flags_for_room_list(), item_id: i as u32,
} difficulty,
}) players: client_location.get_clients_in_room(RoomId(i)).await.unwrap().len() as u8,
name,
episode,
flags,
}
}})
}); });
let baseroom: RoomList = RoomList { let baseroom: RoomList = RoomList {
menu_id: ROOM_MENU_ID, menu_id: ROOM_MENU_ID,
@ -210,21 +261,26 @@ pub async fn request_room_list(id: ClientId,
flags: 0, flags: 0,
}; };
Box::new(vec![(id, SendShipPacket::RoomListResponse(RoomListResponse { vec![(id, SendShipPacket::RoomListResponse(RoomListResponse {
baseroom, baseroom,
rooms: futures::future::join_all(active_room_list.collect::<Vec<_>>().await).await rooms: futures::future::join_all(active_room_list.collect::<Vec<_>>().await).await
}))].into_iter()) }))]
} }
pub async fn cool_62(id: ClientId, pub async fn cool_62(id: ClientId,
cool_62: &Like62ButCooler, cool_62: Like62ButCooler,
client_location: &ClientLocation) client_location: &ClientLocation)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Vec<(ClientId, SendShipPacket)> {
let target = cool_62.flag as u8; let target = cool_62.flag as u8;
let cool_62 = cool_62.clone(); let cool_62 = cool_62.clone();
Box::new(client_location.get_client_neighbors(id).await.unwrap().into_iter() client_location
.filter(move |client| client.local_client.id() == target) .get_client_neighbors(id)
.map(move |client| { .await
(client.client, SendShipPacket::Like62ButCooler(cool_62.clone())) .unwrap()
})) .into_iter()
.filter(move |client| client.local_client.id() == target)
.map(move |client| {
(client.client, SendShipPacket::Like62ButCooler(cool_62.clone()))
})
.collect()
} }

View File

@ -3,47 +3,70 @@ use crate::common::serverstate::ClientId;
use crate::ship::ship::{SendShipPacket, ShipError, Clients}; use crate::ship::ship::{SendShipPacket, ShipError, Clients};
use crate::entity::gateway::EntityGateway; use crate::entity::gateway::EntityGateway;
pub async fn update_config<EG: EntityGateway>(id: ClientId, pub async fn update_config<EG>(id: ClientId,
update_config: &UpdateConfig, update_config: UpdateConfig,
clients: &mut Clients, clients: &Clients,
mut entity_gateway: EG) entity_gateway: &mut EG)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); where
client.character.config.update(update_config); EG: EntityGateway + Clone + 'static,
entity_gateway.save_character(&client.character).await.unwrap(); {
Box::new(None.into_iter()) clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
Box::pin(async move {
client.character.config.update(&update_config);
entity_gateway.save_character(&client.character).await
})}).await??;
Ok(Vec::new())
} }
pub async fn save_options<EG: EntityGateway>(id: ClientId, pub async fn save_options<EG>(id: ClientId,
save_options: &SaveOptions, save_options: SaveOptions,
clients: &mut Clients, clients: &Clients,
mut entity_gateway: EG) entity_gateway: &mut EG)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
// TODO: don't unwrap? where
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); EG: EntityGateway + Clone + 'static,
client.character.option_flags = save_options.options; {
entity_gateway.save_character(&client.character).await.unwrap(); clients.with_mut(id, |client| {
Box::new(None.into_iter()) let mut entity_gateway = entity_gateway.clone();
Box::pin(async move {
client.character.option_flags = save_options.options;
entity_gateway.save_character(&client.character).await
})}).await??;
Ok(Vec::new())
} }
pub async fn keyboard_config<EG: EntityGateway>(id: ClientId, pub async fn keyboard_config<EG>(id: ClientId,
keyboard_config: &KeyboardConfig, keyboard_config: KeyboardConfig,
clients: &mut Clients, clients: &Clients,
mut entity_gateway: EG) entity_gateway: &mut EG)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); where
client.character.keyboard_config.update(keyboard_config); EG: EntityGateway + Clone + 'static,
entity_gateway.save_character(&client.character).await.unwrap(); {
Box::new(None.into_iter()) clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
Box::pin(async move {
client.character.keyboard_config.update(&keyboard_config);
entity_gateway.save_character(&client.character).await
})}).await??;
Ok(Vec::new())
} }
pub async fn gamepad_config<EG: EntityGateway>(id: ClientId, pub async fn gamepad_config<EG>(id: ClientId,
gamepad_config: &GamepadConfig, gamepad_config: GamepadConfig,
clients: &mut Clients, clients: &Clients,
mut entity_gateway: EG) entity_gateway: &mut EG)
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
let client = clients.get_mut(&id).ok_or(ShipError::ClientNotFound(id)).unwrap(); where
client.character.gamepad_config.update(gamepad_config); EG: EntityGateway + Clone + 'static,
entity_gateway.save_character(&client.character).await.unwrap(); {
Box::new(None.into_iter()) clients.with_mut(id, |client| {
let mut entity_gateway = entity_gateway.clone();
Box::pin(async move {
client.character.gamepad_config.update(&gamepad_config);
entity_gateway.save_character(&client.character).await
})}).await??;
Ok(Vec::new())
} }

View File

@ -5,19 +5,17 @@ use crate::common::interserver::Ship;
use crate::ship::ship::{SendShipPacket, ShipError}; use crate::ship::ship::{SendShipPacket, ShipError};
use crate::ship::packet::builder; use crate::ship::packet::builder;
pub fn ship_list(id: ClientId, ship_list: &[Ship]) pub fn ship_list(id: ClientId, ship_list: &[Ship]) -> Vec<(ClientId, SendShipPacket)> {
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { vec![(id, SendShipPacket::ShipList(builder::ship::ship_list(ship_list)))]
Box::new(vec![(id, SendShipPacket::ShipList(builder::ship::ship_list(ship_list)))].into_iter())
} }
pub fn block_list(id: ClientId, shipname: &str, num_blocks: usize) pub fn block_list(id: ClientId, shipname: &str, num_blocks: usize) -> Vec<(ClientId, SendShipPacket)> {
-> Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send> { vec![(id, SendShipPacket::ShipBlockList(ShipBlockList::new(shipname, num_blocks)))]
Box::new(vec![(id, SendShipPacket::ShipBlockList(ShipBlockList::new(shipname, num_blocks)))].into_iter())
} }
pub fn selected_ship(id: ClientId, menuselect: &MenuSelect, ship_list: &[Ship]) pub fn selected_ship(id: ClientId, menuselect: MenuSelect, ship_list: &[Ship])
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> { -> Result<Vec<(ClientId, SendShipPacket)>, ShipError> {
let ship = ship_list.get(menuselect.item as usize).ok_or(ShipError::InvalidShip(menuselect.item as usize))?; let ship = ship_list.get(menuselect.item as usize).ok_or(ShipError::InvalidShip(menuselect.item as usize))?;
let ip = u32::from_ne_bytes(ship.ip.octets()); let ip = u32::from_ne_bytes(ship.ip.octets());
Ok(Box::new(vec![(id, SendShipPacket::RedirectClient(RedirectClient::new(ip, ship.port)))].into_iter())) Ok(vec![(id, SendShipPacket::RedirectClient(RedirectClient::new(ip, ship.port)))])
} }

View File

@ -50,32 +50,35 @@ pub enum TradeError {
pub async fn do_trade_action<F>(id: ClientId, async fn do_trade_action<F>(id: ClientId,
pkt: TradeRequest, pkt: TradeRequest,
client_location: &ClientLocation, client_location: &ClientLocation,
target: u32, target: u32,
this: &mut ClientTradeState, this: &mut ClientTradeState,
other: &mut ClientTradeState, other: &mut ClientTradeState,
action: F) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> action: F)
-> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
F: Fn(&mut ClientTradeState, &mut ClientTradeState) -> Result<(), ShipError>, F: Fn(&mut ClientTradeState, &mut ClientTradeState) -> Result<(), ShipError>,
{ {
Ok(match action(this, other) { Ok(match action(this, other) {
Ok(_) => { Ok(_) => {
Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| client.local_client.id() == target as u8) .filter(move |client| client.local_client.id() == target as u8)
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::DirectMessage(DirectMessage::new(target, GameMessage::TradeRequest(pkt.clone())))) (client.client, SendShipPacket::DirectMessage(DirectMessage::new(target, GameMessage::TradeRequest(pkt.clone()))))
})) })
.collect()
}, },
Err(_) => { Err(_) => {
// TODO: some sort of error logging? // TODO: some sort of error logging?
Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| client.local_client.id() == target as u8) .filter(move |client| client.local_client.id() == target as u8)
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::CancelTrade(CancelTrade {})) (client.client, SendShipPacket::CancelTrade(CancelTrade {}))
}) })
.chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {}))))) .chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {}))))
.collect()
} }
}) })
} }
@ -83,13 +86,13 @@ where
// TODO: remove target // TODO: remove target
pub async fn trade_request(id: ClientId, pub async fn trade_request(id: ClientId,
trade_request: &TradeRequest, trade_request: TradeRequest,
target: u32, target: u32,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
trades: &mut TradeState) trades: &mut TradeState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{ {
let trade_request = trade_request.clone(); // TODO: make this function take ownership of packet let trade_request = trade_request.clone(); // TODO: make this function take ownership of packet
match trade_request.trade { match trade_request.trade {
@ -109,11 +112,12 @@ pub async fn trade_request(id: ClientId,
return Err(TradeError::OtherAlreadyInTrade.into()) return Err(TradeError::OtherAlreadyInTrade.into())
} }
trades.new_trade(&id, &trade_partner.client); trades.new_trade(&id, &trade_partner.client);
Ok(Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() Ok(client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| client.local_client.id() == target as u8) .filter(move |client| client.local_client.id() == target as u8)
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::DirectMessage(DirectMessage::new(target, GameMessage::TradeRequest(trade_request.clone())))) (client.client, SendShipPacket::DirectMessage(DirectMessage::new(target, GameMessage::TradeRequest(trade_request.clone()))))
}))) })
.collect())
}, },
TradeRequestInitializeCommand::Respond => { TradeRequestInitializeCommand::Respond => {
trades trades
@ -139,10 +143,13 @@ pub async fn trade_request(id: ClientId,
.with(&id, |mut this, mut other| { .with(&id, |mut this, mut other| {
let trade_request = trade_request.clone(); let trade_request = trade_request.clone();
async move { async move {
let inventory = clients.with(this.client(), |client| {
let item_state = item_state.clone();
Box::pin(async move {
item_state.get_character_inventory(&client.character).await
})}).await??;
do_trade_action(id, trade_request, client_location, target, &mut this, &mut other, |this, other| { do_trade_action(id, trade_request, client_location, target, &mut this, &mut other, |this, other| {
if this.status == TradeStatus::Trading && other.status == TradeStatus::Trading { if this.status == TradeStatus::Trading && other.status == TradeStatus::Trading {
let client = clients.get(&this.client()).ok_or_else(|| ShipError::ClientNotFound(this.client()))?;
let inventory = item_state.get_character_inventory(&client.character)?;
if ClientItemId(item_id) == MESETA_ITEM_ID { if ClientItemId(item_id) == MESETA_ITEM_ID {
this.meseta += amount as usize; this.meseta += amount as usize;
} }
@ -174,10 +181,13 @@ pub async fn trade_request(id: ClientId,
.with(&id, |mut this, mut other| { .with(&id, |mut this, mut other| {
let trade_request = trade_request.clone(); let trade_request = trade_request.clone();
async move { async move {
let inventory = clients.with(this.client(), |client| {
let item_state = item_state.clone();
Box::pin(async move {
item_state.get_character_inventory(&client.character).await
})}).await??;
do_trade_action(id, trade_request, client_location, target, &mut this, &mut other, |this, other| { do_trade_action(id, trade_request, client_location, target, &mut this, &mut other, |this, other| {
if this.status == TradeStatus::Trading && other.status == TradeStatus::Trading { if this.status == TradeStatus::Trading && other.status == TradeStatus::Trading {
let client = clients.get(&this.client()).ok_or_else(|| ShipError::ClientNotFound(this.client()))?;
let inventory = item_state.get_character_inventory(&client.character)?;
if ClientItemId(item_id) == MESETA_ITEM_ID { if ClientItemId(item_id) == MESETA_ITEM_ID {
this.meseta -= amount as usize; this.meseta -= amount as usize;
} }
@ -256,13 +266,14 @@ pub async fn trade_request(id: ClientId,
}).await? }).await?
}, },
TradeRequestCommand::Cancel => { TradeRequestCommand::Cancel => {
trades.remove_trade(&id); trades.remove_trade(&id).await;
Ok(Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() Ok(client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| client.local_client.id() == target as u8) .filter(move |client| client.local_client.id() == target as u8)
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::CancelTrade(CancelTrade {})) (client.client, SendShipPacket::CancelTrade(CancelTrade {}))
}) })
.chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {})))))) .chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {}))))
.collect())
} }
} }
} }
@ -276,23 +287,32 @@ fn status_is_not<const N: usize>(status: &TradeStatus, statuses: &[TradeStatus;
!status_is(status, statuses) !status_is(status, statuses)
} }
pub async fn inner_items_to_trade(id: ClientId, async fn inner_items_to_trade(id: ClientId,
items_to_trade: &ItemsToTrade, items_to_trade: ItemsToTrade,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
trades: &mut TradeState) trades: &mut TradeState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{ {
let pkts: Result<Box<dyn Iterator<Item=_> + Send>, ShipError> = trades let pkts = trades
.with(&id, |mut this, other| async move { .with(&id, |mut this, other| async move {
if status_is_not(&this.status, &[TradeStatus::FinalConfirm]) || status_is_not(&other.status, &[TradeStatus::FinalConfirm, TradeStatus::ItemsChecked]) { if status_is_not(&this.status, &[TradeStatus::FinalConfirm]) || status_is_not(&other.status, &[TradeStatus::FinalConfirm, TradeStatus::ItemsChecked]) {
return Err(TradeError::MismatchedStatus.into()) return Err(ShipError::from(TradeError::MismatchedStatus))
} }
let other_client = other.client();
let client = clients.get(&this.client()).ok_or_else(|| ShipError::ClientNotFound(this.client()))?; let (this_inventory, other_inventory) = clients.with(this.client(), |client| {
let other_client = clients.get(&other.client()).ok_or_else(|| ShipError::ClientNotFound(other.client()))?; let item_state = item_state.clone();
let inventory = item_state.get_character_inventory(&client.character)?; let clients = clients.clone();
Box::pin(async move {
let this = item_state.get_character_inventory(&client.character).await?;
let other_inventory = clients.with(other_client, |client| {
let item_state = item_state.clone();
Box::pin(async move {
item_state.get_character_inventory(&client.character).await
})}).await??;
Ok::<_, ShipError>((this, other_inventory))
})}).await??;
if items_to_trade.count as usize != (this.items.len() + (if this.meseta != 0 { 1 } else { 0 })) { if items_to_trade.count as usize != (this.items.len() + (if this.meseta != 0 { 1 } else { 0 })) {
return Err(TradeError::MismatchedTradeItems.into()) return Err(TradeError::MismatchedTradeItems.into())
@ -307,8 +327,8 @@ pub async fn inner_items_to_trade(id: ClientId,
return Err(TradeError::InvalidItemId(ClientItemId(item.item_id)).into()) return Err(TradeError::InvalidItemId(ClientItemId(item.item_id)).into())
} }
let amount = u32::from_le_bytes(item.item_data2); let amount = u32::from_le_bytes(item.item_data2);
let character_meseta = item_state.get_character_inventory(&client.character).map_err(|_| TradeError::InvalidMeseta)?.meseta; let character_meseta = this_inventory.meseta;
let other_character_meseta = item_state.get_character_inventory(&other_client.character).map_err(|_| TradeError::InvalidMeseta)?.meseta; let other_character_meseta = other_inventory.meseta;
if amount > character_meseta.0 { if amount > character_meseta.0 {
return Err(TradeError::InvalidMeseta.into()) return Err(TradeError::InvalidMeseta.into())
} }
@ -321,7 +341,7 @@ pub async fn inner_items_to_trade(id: ClientId,
Ok(()) Ok(())
} }
else { else {
let real_item = inventory.get_by_client_id(&ClientItemId(item.item_id)) let real_item = this_inventory.get_by_client_id(&ClientItemId(item.item_id))
.ok_or(ItemStateError::InvalidItemId(ClientItemId(item.item_id)))?; .ok_or(ItemStateError::InvalidItemId(ClientItemId(item.item_id)))?;
let real_trade_item = this.items let real_trade_item = this.items
.iter() .iter()
@ -367,69 +387,73 @@ pub async fn inner_items_to_trade(id: ClientId,
this.status = TradeStatus::ItemsChecked; this.status = TradeStatus::ItemsChecked;
if this.status == TradeStatus::ItemsChecked && other.status == TradeStatus::ItemsChecked { if this.status == TradeStatus::ItemsChecked && other.status == TradeStatus::ItemsChecked {
Ok(Box::new(vec![ Ok(vec![
(this.client(), SendShipPacket::AcknowledgeTrade(AcknowledgeTrade {})), (this.client(), SendShipPacket::AcknowledgeTrade(AcknowledgeTrade {})),
(other.client(), SendShipPacket::AcknowledgeTrade(AcknowledgeTrade {})), (other.client(), SendShipPacket::AcknowledgeTrade(AcknowledgeTrade {})),
].into_iter()) as Box<dyn Iterator<Item=_> + Send>) ])
} }
else { else {
Ok(Box::new(Vec::new().into_iter()) as Box<dyn Iterator<Item=_> + Send>) Ok(Vec::new())
} }
}).await?; }).await?;
match pkts { match pkts {
Ok(pkts) => Ok(pkts), Ok(pkts) => Ok(pkts),
Err(err) => { Err(err) => {
log::warn!("trade error: {:?}", err); log::warn!("trade error: {:?}", err);
let (_this, other) = trades.remove_trade(&id); let (_this, other) = trades.remove_trade(&id).await;
Ok(Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() Ok(client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| other.as_ref().map(|other| client.client == other.client() ).unwrap_or_else(|| false)) .filter(move |client| other.as_ref().map(|other| client.client == other.client() ).unwrap_or_else(|| false))
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::CancelTrade(CancelTrade {})) (client.client, SendShipPacket::CancelTrade(CancelTrade {}))
}) })
.chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {})))))) .chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {}))))
.collect())
} }
} }
} }
pub async fn items_to_trade(id: ClientId, pub async fn items_to_trade(id: ClientId,
items_to_trade_pkt: &ItemsToTrade, items_to_trade_pkt: ItemsToTrade,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
trades: &mut TradeState) trades: &mut TradeState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
{ {
let t = inner_items_to_trade(id, items_to_trade_pkt, client_location, clients, item_state, trades).await; let t = inner_items_to_trade(id, items_to_trade_pkt, client_location, clients, item_state, trades).await;
match t { match t {
Ok(p) => Ok(p), Ok(p) => Ok(p),
Err(err) => { Err(err) => {
log::warn!("atrade error: {:?}", err); log::warn!("atrade error: {:?}", err);
let (_this, other) = trades.remove_trade(&id); let (_this, other) = trades.remove_trade(&id).await;
Ok(Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() Ok(client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| other.as_ref().map(|other| client.client == other.client()).unwrap_or_else(|| false)) .filter(move |client| other.as_ref().map(|other| client.client == other.client()).unwrap_or_else(|| false))
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::CancelTrade(CancelTrade {})) (client.client, SendShipPacket::CancelTrade(CancelTrade {}))
}) })
.chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {})))))) .chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {}))))
.collect())
} }
} }
} }
pub async fn trade_confirmed_inner<EG>(id: ClientId, async fn trade_confirmed_inner<EG>(id: ClientId,
mut entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
trades: &mut TradeState) trades: &mut TradeState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
enum TradeReady<'a> { enum TradeReady/*<'a>*/ {
OnePlayer, OnePlayer,
BothPlayers(RoomId, BothPlayers(RoomId,
(AreaClient, &'a crate::ship::ship::ClientState, crate::ship::trade::ClientTradeState), (AreaClient, crate::ship::trade::ClientTradeState),
(AreaClient, &'a crate::ship::ship::ClientState, crate::ship::trade::ClientTradeState)), (AreaClient, crate::ship::trade::ClientTradeState)),
//(AreaClient, &'a crate::ship::ship::ClientState, crate::ship::trade::ClientTradeState),
//(AreaClient, &'a crate::ship::ship::ClientState, crate::ship::trade::ClientTradeState)),
} }
let trade = trades let trade = trades
@ -441,15 +465,13 @@ where
this.status = TradeStatus::TradeComplete; this.status = TradeStatus::TradeComplete;
if this.status == TradeStatus::TradeComplete && other.status == TradeStatus::TradeComplete { if this.status == TradeStatus::TradeComplete && other.status == TradeStatus::TradeComplete {
let this_client = clients.get(&this.client()).ok_or_else(|| ShipError::ClientNotFound(this.client()))?;
let other_client = clients.get(&other.client()).ok_or_else(|| ShipError::ClientNotFound(other.client()))?;
let this_local_client = client_location.get_local_client(this.client()).await?; let this_local_client = client_location.get_local_client(this.client()).await?;
let other_local_client = client_location.get_local_client(other.client()).await?; let other_local_client = client_location.get_local_client(other.client()).await?;
let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?; let room_id = client_location.get_room(id).await.map_err(|err| -> ClientLocationError { err.into() })?;
Ok(TradeReady::BothPlayers(room_id, Ok(TradeReady::BothPlayers(room_id,
(this_local_client, this_client, this.clone()), (this_local_client, /*this_client, */this.clone()),
(other_local_client, other_client, other.clone()))) (other_local_client, /*other_client, */other.clone())))
} }
else { else {
Ok(TradeReady::OnePlayer) Ok(TradeReady::OnePlayer)
@ -459,9 +481,9 @@ where
match trade { match trade {
TradeReady::OnePlayer => { TradeReady::OnePlayer => {
Ok(Box::new(None.into_iter()) as Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>) Ok(Vec::new())
}, },
TradeReady::BothPlayers(_room_id, (this_local_client, this_client, this), (other_local_client, other_client, other)) => { TradeReady::BothPlayers(_room_id, (this_local_client, /*this_client,*/ this), (other_local_client, /*other_client,*/ other)) => {
let remove_item_packets = this.items let remove_item_packets = this.items
.clone() .clone()
.into_iter() .into_iter()
@ -478,11 +500,20 @@ where
GameMessage::PlayerNoLongerHasItem(builder::message::player_no_longer_has_item(client, item.item_id(), item.amount() as u32)) GameMessage::PlayerNoLongerHasItem(builder::message::player_no_longer_has_item(client, item.item_id(), item.amount() as u32))
}); });
let (this_new_items, other_new_items) = trade_items(item_state, let this_items = this.items.clone();
&mut entity_gateway, let other_items = other.items.clone();
(&this_local_client, &this_client.character, &this.items, Meseta(this.meseta as u32)), let (this_new_items, other_new_items) = clients.with_many(
(&other_local_client, &other_client.character, &other.items, Meseta(other.meseta as u32))).await?; [this_local_client.client, other_local_client.client],
|[this_client, other_client]| {
let mut entity_gateway = entity_gateway.clone();
let mut item_state = item_state.clone();
Box::pin(async move {
trade_items(&mut item_state,
&mut entity_gateway,
(&this_local_client, &this_client.character, &this_items, Meseta(this.meseta as u32)),
(&other_local_client, &other_client.character, &other_items, Meseta(other.meseta as u32))).await
})}).await??;
let create_item_packets = this_new_items let create_item_packets = this_new_items
.into_iter() .into_iter()
.map(move |item| { .map(move |item| {
@ -541,32 +572,33 @@ where
(this.client(), SendShipPacket::TradeSuccessful(TradeSuccessful::default())), (this.client(), SendShipPacket::TradeSuccessful(TradeSuccessful::default())),
(other.client(), SendShipPacket::TradeSuccessful(TradeSuccessful::default())) (other.client(), SendShipPacket::TradeSuccessful(TradeSuccessful::default()))
].into_iter(); ].into_iter();
Ok(Box::new(traded_item_packets.chain(close_trade))) Ok(traded_item_packets.chain(close_trade).collect())
} }
} }
} }
pub async fn trade_confirmed<EG>(id: ClientId, pub async fn trade_confirmed<EG>(id: ClientId,
entity_gateway: EG, entity_gateway: &mut EG,
client_location: &ClientLocation, client_location: &ClientLocation,
clients: &mut Clients, clients: &Clients,
item_state: &mut ItemState, item_state: &mut ItemState,
trades: &mut TradeState) trades: &mut TradeState)
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, ShipError> -> Result<Vec<(ClientId, SendShipPacket)>, ShipError>
where where
EG: EntityGateway EG: EntityGateway + Clone + 'static,
{ {
match trade_confirmed_inner(id, entity_gateway, client_location, clients, item_state, trades).await { match trade_confirmed_inner(id, entity_gateway, client_location, clients, item_state, trades).await {
Ok(result) => Ok(result), Ok(result) => Ok(result),
Err(_err) => { Err(_err) => {
let (_this, other) = trades.remove_trade(&id); let (_this, other) = trades.remove_trade(&id).await;
Ok(Box::new(client_location.get_all_clients_by_client(id).await?.into_iter() Ok(client_location.get_all_clients_by_client(id).await?.into_iter()
.filter(move |client| other.as_ref().map(|other| client.client == other.client()).unwrap_or_else(|| false)) .filter(move |client| other.as_ref().map(|other| client.client == other.client()).unwrap_or_else(|| false))
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::CancelTrade(CancelTrade {})) (client.client, SendShipPacket::CancelTrade(CancelTrade {}))
}) })
.chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {})))))) .chain(std::iter::once((id, SendShipPacket::CancelTrade(CancelTrade {}))))
.collect())
} }
} }
} }

View File

@ -4,6 +4,7 @@ use std::fs::File;
use std::io::{Read, Write, Cursor, Seek, SeekFrom}; use std::io::{Read, Write, Cursor, Seek, SeekFrom};
use std::path::PathBuf; use std::path::PathBuf;
use std::convert::TryInto; use std::convert::TryInto;
use async_std::sync::Arc;
use thiserror::Error; use thiserror::Error;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use ages_prs::{LegacyPrsDecoder, LegacyPrsEncoder}; use ages_prs::{LegacyPrsDecoder, LegacyPrsEncoder};
@ -76,7 +77,7 @@ fn read_dat_section_header<T: Read + Seek>(cursor: &mut T, episode: &Episode, ma
cursor.read_exact(&mut obj_data)?; cursor.read_exact(&mut obj_data)?;
let mut obj_cursor = Cursor::new(obj_data); let mut obj_cursor = Cursor::new(obj_data);
let objects = objects_from_stream(&mut obj_cursor, episode, map_area); let objects = objects_from_stream(&mut obj_cursor, episode, &map_area);
Ok(DatBlock::Object(objects)) Ok(DatBlock::Object(objects))
}, },
DAT_ENEMY_HEADER_ID => { DAT_ENEMY_HEADER_ID => {
@ -84,7 +85,7 @@ fn read_dat_section_header<T: Read + Seek>(cursor: &mut T, episode: &Episode, ma
cursor.read_exact(&mut enemy_data)?; cursor.read_exact(&mut enemy_data)?;
let mut enemy_cursor = Cursor::new(enemy_data); let mut enemy_cursor = Cursor::new(enemy_data);
let enemies = enemy_data_from_stream(&mut enemy_cursor, map_area, episode); let enemies = enemy_data_from_stream(&mut enemy_cursor, &map_area, episode);
Ok(DatBlock::Enemy(enemies)) Ok(DatBlock::Enemy(enemies))
}, },
@ -159,18 +160,18 @@ pub enum QuestLoadError {
CouldNotLoadConfigFile, CouldNotLoadConfigFile,
} }
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct Quest { pub struct Quest {
pub name: String, pub name: String,
pub description: String, pub description: String,
pub full_description: String, pub full_description: String,
pub language: u16, pub language: u16,
pub id: u16, pub id: u16,
pub bin_blob: Vec<u8>, pub bin_blob: Arc<Vec<u8>>,
pub dat_blob: Vec<u8>, pub dat_blob: Arc<Vec<u8>>,
pub enemies: Vec<Option<MapEnemy>>, pub enemies: Vec<Option<MapEnemy>>, // TODO: Arc?
pub objects: Vec<Option<MapObject>>, pub objects: Vec<Option<MapObject>>, // TODO: Arc?
pub map_areas: MapAreaLookup, pub map_areas: MapAreaLookup, // TODO: Arc?
} }
impl Quest { impl Quest {
@ -196,8 +197,8 @@ impl Quest {
full_description, full_description,
id, id,
language, language,
bin_blob: prs_bin.into_inner().map_err(|_| QuestLoadError::CouldNotReadMetadata)?, bin_blob: Arc::new(prs_bin.into_inner().map_err(|_| QuestLoadError::CouldNotReadMetadata)?),
dat_blob: prs_dat.into_inner().map_err(|_| QuestLoadError::CouldNotReadMetadata)?, dat_blob: Arc::new(prs_dat.into_inner().map_err(|_| QuestLoadError::CouldNotReadMetadata)?),
enemies, enemies,
objects, objects,
map_areas, map_areas,
@ -232,7 +233,7 @@ pub fn load_quest(bin_path: PathBuf, dat_path: PathBuf, quest_path: PathBuf) ->
} }
pub fn load_quests(quest_path: &mut PathBuf) -> Result<QuestList, QuestLoadError> { pub fn load_quests(mut quest_path: PathBuf) -> Result<QuestList, QuestLoadError> {
let mut f = File::open(quest_path.clone()).map_err(|_| QuestLoadError::CouldNotLoadConfigFile)?; let mut f = File::open(quest_path.clone()).map_err(|_| QuestLoadError::CouldNotLoadConfigFile)?;
let mut s = String::new(); let mut s = String::new();
f.read_to_string(&mut s)?; f.read_to_string(&mut s)?;
@ -270,7 +271,7 @@ pub fn load_quests(quest_path: &mut PathBuf) -> Result<QuestList, QuestLoadError
#[cfg(test)] #[cfg(test)]
mod test { mod tests {
use super::*; use super::*;
// the quest phantasmal world 4 uses the tower map twice, to do this it had to remap // the quest phantasmal world 4 uses the tower map twice, to do this it had to remap

View File

@ -1,7 +1,14 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::{From, Into, TryFrom, TryInto}; use std::convert::{From, Into, TryFrom, TryInto};
use std::path::PathBuf;
use async_std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::future::Future;
use futures::stream::{Stream, StreamExt, FuturesOrdered};
use futures::future::BoxFuture;
use thiserror::Error; use thiserror::Error;
use std::ops::Deref;
use rand::Rng; use rand::Rng;
use crate::ship::map::Maps; use crate::ship::map::Maps;
@ -11,7 +18,127 @@ use crate::ship::monster::{load_monster_stats_table, MonsterType, MonsterStats};
use crate::ship::map::area::MapAreaLookup; use crate::ship::map::area::MapAreaLookup;
use crate::ship::map::enemy::RareMonsterAppearTable; use crate::ship::map::enemy::RareMonsterAppearTable;
use crate::ship::quests; use crate::ship::quests;
use std::path::PathBuf; use crate::ship::ship::ShipError;
use crate::ship::location::{ClientLocation, RoomLobby, MAX_ROOMS, ClientLocationError, GetNeighborError, GetClientsError, GetAreaError, RoomId};
#[derive(Clone)]
pub struct Rooms([Arc<RwLock<Option<RoomState>>>; MAX_ROOMS]);
impl Default for Rooms {
fn default() -> Rooms {
Rooms(core::array::from_fn(|_| Arc::new(RwLock::new(None))))
}
}
/*
#[derive(escher::Rebindable)]
struct BorrowedRoom<'a> {
lock: RwLockReadGuard<'a, Option<RoomState>>,
room: &'a Option<RoomState>,
}
impl<'a> std::ops::Deref for BorrowedRoom<'a> {
type Target = RoomState;
fn deref(&self) -> &Self::Target {
&self.room
}
}
*/
impl Rooms {
pub async fn add(&self, room_id: RoomId, room: RoomState) -> Result<(), ShipError> {
*self.0
.get(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.write()
.await = Some(room);
Ok(())
}
pub async fn remove(&self, room_id: RoomId) {
if let Some(room) = self.0.get(room_id.0) {
*room
.write()
.await = None;
}
}
pub async fn exists(&self, room_id: RoomId) -> bool {
match self.0.get(room_id.0) {
Some(room) => {
room
.read()
.await
.is_some()
},
None => false,
}
}
pub async fn with<'a, T, F>(&'a self, room_id: RoomId, func: F) -> Result<T, ShipError>
where
T: Send,
F: for<'b> FnOnce(&'b RoomState) -> BoxFuture<'b, T> + Send + 'a
{
let room = self.0
.get(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.read()
.await;
if let Some(room) = room.as_ref() {
Ok(func(room).await)
}
else {
Err(ShipError::InvalidRoom(room_id.0 as u32))
}
}
pub async fn with_mut<'a, T, F>(&'a self, room_id: RoomId, func: F) -> Result<T, ShipError>
where
T: Send,
F: for<'b> FnOnce(&'b mut RoomState) -> BoxFuture<'b, T> + Send + 'a
{
let mut room = self.0
.get(room_id.0)
.ok_or(ShipError::InvalidRoom(room_id.0 as u32))?
.write()
.await;
if let Some(room) = room.as_mut() {
Ok(func(room).await)
}
else {
Err(ShipError::InvalidRoom(room_id.0 as u32))
}
}
pub async fn get<'a>(&'a self, room_id: RoomId) -> RwLockReadGuard<'a, Option<RoomState>> {
self.0
.get(room_id.0)
.unwrap()
.read()
.await
}
pub fn stream<'a>(&'a self) -> impl Stream<Item = RwLockReadGuard<'a, Option<RoomState>>> + 'a {
self.0
.iter()
.map(|room| async move {
room
.read()
.await
})
.collect::<FuturesOrdered<_>>()
}
}
#[derive(Debug, Error)] #[derive(Debug, Error)]
@ -279,7 +406,7 @@ impl RoomState {
qpath.push(room_mode.to_string()); qpath.push(room_mode.to_string());
qpath.push("quests.toml"); qpath.push("quests.toml");
let mut room_quests = Vec::new(); let mut room_quests = Vec::new();
let quest_list = match quests::load_quests(&mut qpath) { let quest_list = match quests::load_quests(qpath) {
Ok(qlist) => qlist, Ok(qlist) => qlist,
Err(_) => return Err(RoomCreationError::CouldNotLoadQuests), Err(_) => return Err(RoomCreationError::CouldNotLoadQuests),
}; };
@ -292,7 +419,7 @@ impl RoomState {
qpath.push(room_mode.episode().to_string()); qpath.push(room_mode.episode().to_string());
qpath.push("government/quests.toml"); qpath.push("government/quests.toml");
let quest_list = match quests::load_quests(&mut qpath) { let quest_list = match quests::load_quests(qpath) {
Ok(qlist) => qlist, Ok(qlist) => qlist,
Err(_) => return Err(RoomCreationError::CouldNotLoadQuests), Err(_) => return Err(RoomCreationError::CouldNotLoadQuests),
}; };

View File

@ -2,6 +2,9 @@
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::collections::HashMap; use std::collections::HashMap;
use async_std::channel;
use async_std::sync::{Arc, Mutex};
use rand::Rng; use rand::Rng;
use thiserror::Error; use thiserror::Error;
@ -13,6 +16,7 @@ use libpso::crypto::bb::PSOBBCipher;
use libpso::packet::ship::{BLOCK_MENU_ID, ROOM_MENU_ID}; use libpso::packet::ship::{BLOCK_MENU_ID, ROOM_MENU_ID};
use crate::common::cipherkeys::{ELSEWHERE_PRIVATE_KEY, ELSEWHERE_PARRAY}; use crate::common::cipherkeys::{ELSEWHERE_PRIVATE_KEY, ELSEWHERE_PARRAY};
use crate::common::serverstate::{SendServerPacket, RecvServerPacket, ServerState, OnConnect, ClientId}; use crate::common::serverstate::{SendServerPacket, RecvServerPacket, ServerState, OnConnect, ClientId};
use crate::common::interserver::{AuthToken, Ship, ServerId, InterserverActor, LoginMessage, ShipMessage}; use crate::common::interserver::{AuthToken, Ship, ServerId, InterserverActor, LoginMessage, ShipMessage};
@ -24,7 +28,7 @@ use crate::entity::account::{UserAccountEntity, UserSettingsEntity};
use crate::entity::character::{CharacterEntity, SectionID}; use crate::entity::character::{CharacterEntity, SectionID};
use crate::entity::item; use crate::entity::item;
use crate::ship::location::{ClientLocation, RoomLobby, MAX_ROOMS, ClientLocationError, GetNeighborError, GetClientsError, GetAreaError}; use crate::ship::location::{ClientLocation, RoomLobby, MAX_ROOMS, ClientLocationError, GetNeighborError, GetClientsError, GetAreaError, RoomId};
use crate::ship::items; use crate::ship::items;
use crate::ship::room; use crate::ship::room;
@ -33,11 +37,13 @@ use crate::ship::packet::handler;
use crate::ship::shops::{WeaponShop, ToolShop, ArmorShop, WeaponShopItem, ToolShopItem, ArmorShopItem}; use crate::ship::shops::{WeaponShop, ToolShop, ArmorShop, WeaponShopItem, ToolShopItem, ArmorShopItem};
use crate::ship::trade::TradeState; use crate::ship::trade::TradeState;
// TODO: remove once stuff settles down
pub use crate::ship::client::*;
pub const SHIP_PORT: u16 = 23423; pub const SHIP_PORT: u16 = 23423;
pub const QUEST_CATEGORY_MENU_ID: u32 = 0xA2; pub const QUEST_CATEGORY_MENU_ID: u32 = 0xA2;
pub const QUEST_SELECT_MENU_ID: u32 = 0xA3; pub const QUEST_SELECT_MENU_ID: u32 = 0xA3;
pub type Rooms = [Option<room::RoomState>; MAX_ROOMS];
pub type Clients = HashMap<ClientId, ClientState>;
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum ShipError { pub enum ShipError {
@ -50,13 +56,16 @@ pub enum ShipError {
#[error("too many clients")] #[error("too many clients")]
TooManyClients, TooManyClients,
#[error("client error location {0}")] #[error("client error location {0}")]
ClientLocationError(#[from] ClientLocationError), //ClientLocationError(#[from] ClientLocationError),
ClientLocationError(ClientLocationError),
/*
#[error("get neighbor error {0}")] #[error("get neighbor error {0}")]
GetNeighborError(#[from] GetNeighborError), GetNeighborError(#[from] GetNeighborError),
#[error("get clients error {0}")] #[error("get clients error {0}")]
GetClientsError(#[from] GetClientsError), GetClientsError(#[from] GetClientsError),
#[error("get area error {0}")] #[error("get area error {0}")]
GetAreaError(#[from] GetAreaError), GetAreaError(#[from] GetAreaError),
*/
#[error("maps error {0}")] #[error("maps error {0}")]
MapsError(#[from] MapsError), MapsError(#[from] MapsError),
#[error("map area error {0}")] #[error("map area error {0}")]
@ -105,8 +114,35 @@ pub enum ShipError {
TradeError(#[from] crate::ship::packet::handler::trade::TradeError), TradeError(#[from] crate::ship::packet::handler::trade::TradeError),
#[error("trade state error {0}")] #[error("trade state error {0}")]
TradeStateError(#[from] crate::ship::trade::TradeStateError), TradeStateError(#[from] crate::ship::trade::TradeStateError),
#[error("message error {0}")]
MessageError(#[from] crate::ship::packet::handler::direct_message::MessageError),
#[error("room creation error {0}")]
RoomCreationError(#[from] room::RoomCreationError),
} }
/*
impl From<ClientLocationError> for ShipError {
fn from(other: &ClientLocationError) -> ShipError {
}
}
*/
/*
impl<I: Into<ClientLocationError>> Into<ShipError> for I {
fn into(other: I) -> ShipError {
ShipError::ClientLocationError(other.into())
}
}
*/
impl<I: Into<ClientLocationError>> From<I> for ShipError {
fn from(other: I) -> ShipError {
ShipError::ClientLocationError(other.into())
}
}
#[derive(Debug)] #[derive(Debug)]
pub enum RecvShipPacket { pub enum RecvShipPacket {
Login(Login), Login(Login),
@ -275,79 +311,11 @@ impl SendServerPacket for SendShipPacket {
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Clone)]
pub struct ItemDropLocation {
pub map_area: MapArea,
pub x: f32,
pub z: f32,
pub item_id: items::ClientItemId,
}
pub struct LoadingQuest {
pub header_bin: Option<QuestHeader>,
pub header_dat: Option<QuestHeader>,
//pub quest_chunk_bin: Option<Box<dyn Iterator<Item = >>>,
}
pub struct ClientState {
pub user: UserAccountEntity,
pub settings: UserSettingsEntity,
pub character: CharacterEntity,
session: Session,
//guildcard: GuildCard,
pub block: usize,
pub item_drop_location: Option<ItemDropLocation>,
pub done_loading_quest: bool,
//pub loading_quest: Option<LoadingQuest>,
pub area: Option<MapArea>,
pub x: f32,
pub y: f32,
pub z: f32,
pub weapon_shop: Vec<WeaponShopItem>,
pub tool_shop: Vec<ToolShopItem>,
pub armor_shop: Vec<ArmorShopItem>,
pub tek: Option<(items::ClientItemId, item::weapon::TekSpecialModifier, item::weapon::TekPercentModifier, i32)>,
pub character_playtime: chrono::Duration,
pub log_on_time: chrono::DateTime<chrono::Utc>,
}
impl ClientState {
pub fn new(user: UserAccountEntity, settings: UserSettingsEntity, character: CharacterEntity, session: Session) -> ClientState {
let character_playtime = chrono::Duration::seconds(character.playtime as i64);
ClientState {
user,
settings,
character,
session,
block: 0,
item_drop_location: None,
done_loading_quest: false,
area: None,
x: 0.0,
y: 0.0,
z: 0.0,
weapon_shop: Vec::new(),
tool_shop: Vec::new(),
armor_shop: Vec::new(),
tek: None,
character_playtime,
log_on_time: chrono::Utc::now(),
}
}
fn update_playtime(&mut self) {
let additional_playtime = chrono::Utc::now() - self.log_on_time;
self.character.playtime = (self.character_playtime + additional_playtime).num_seconds() as u32;
}
}
pub struct ItemShops { pub struct ItemShops {
pub weapon_shop: HashMap<(room::Difficulty, SectionID), WeaponShop<rand_chacha::ChaCha20Rng>>, pub weapon_shop: HashMap<(room::Difficulty, SectionID), Arc<Mutex<WeaponShop<rand_chacha::ChaCha20Rng>>>>,
pub tool_shop: ToolShop<rand_chacha::ChaCha20Rng>, pub tool_shop: Arc<Mutex<ToolShop<rand_chacha::ChaCha20Rng>>>,
pub armor_shop: ArmorShop<rand_chacha::ChaCha20Rng>, pub armor_shop: Arc<Mutex<ArmorShop<rand_chacha::ChaCha20Rng>>>,
} }
impl Default for ItemShops { impl Default for ItemShops {
@ -359,20 +327,20 @@ impl Default for ItemShops {
let mut weapon_shop = HashMap::new(); let mut weapon_shop = HashMap::new();
for d in difficulty.iter() { for d in difficulty.iter() {
for id in section_id.iter() { for id in section_id.iter() {
weapon_shop.insert((*d, *id), WeaponShop::new(*d, *id)); weapon_shop.insert((*d, *id), Arc::new(Mutex::new(WeaponShop::new(*d, *id))));
} }
} }
ItemShops { ItemShops {
weapon_shop, weapon_shop,
tool_shop: ToolShop::default(), tool_shop: Arc::new(Mutex::new(ToolShop::default())),
armor_shop: ArmorShop::default(), armor_shop: Arc::new(Mutex::new(ArmorShop::default())),
} }
} }
} }
pub struct ShipServerStateBuilder<EG: EntityGateway + Clone> { pub struct ShipServerStateBuilder<EG: EntityGateway + Clone + 'static> {
entity_gateway: Option<EG>, entity_gateway: Option<EG>,
name: Option<String>, name: Option<String>,
ip: Option<Ipv4Addr>, ip: Option<Ipv4Addr>,
@ -381,7 +349,7 @@ pub struct ShipServerStateBuilder<EG: EntityGateway + Clone> {
num_blocks: usize, num_blocks: usize,
} }
impl<EG: EntityGateway + Clone> Default for ShipServerStateBuilder<EG> { impl<EG: EntityGateway + Clone + 'static> Default for ShipServerStateBuilder<EG> {
fn default() -> ShipServerStateBuilder<EG> { fn default() -> ShipServerStateBuilder<EG> {
ShipServerStateBuilder { ShipServerStateBuilder {
entity_gateway: None, entity_gateway: None,
@ -394,7 +362,7 @@ impl<EG: EntityGateway + Clone> Default for ShipServerStateBuilder<EG> {
} }
} }
impl<EG: EntityGateway + Clone> ShipServerStateBuilder<EG> { impl<EG: EntityGateway + Clone + 'static> ShipServerStateBuilder<EG> {
#[must_use] #[must_use]
pub fn gateway(mut self, entity_gateway: EG) -> ShipServerStateBuilder<EG> { pub fn gateway(mut self, entity_gateway: EG) -> ShipServerStateBuilder<EG> {
self.entity_gateway = Some(entity_gateway); self.entity_gateway = Some(entity_gateway);
@ -435,12 +403,12 @@ impl<EG: EntityGateway + Clone> ShipServerStateBuilder<EG> {
let blocks = std::iter::repeat_with(Block::default).take(self.num_blocks).collect(); // Block doesn't have a Clone impl which limits the easy ways to init this let blocks = std::iter::repeat_with(Block::default).take(self.num_blocks).collect(); // Block doesn't have a Clone impl which limits the easy ways to init this
ShipServerState { ShipServerState {
entity_gateway: self.entity_gateway.unwrap(), entity_gateway: self.entity_gateway.unwrap(),
clients: HashMap::new(), clients: Clients::default(),
name: self.name.unwrap_or_else(|| "NAMENOTSET".into()), name: self.name.unwrap_or_else(|| "NAMENOTSET".into()),
item_state: items::state::ItemState::default(), item_state: items::state::ItemState::default(),
ip: self.ip.unwrap_or_else(|| Ipv4Addr::new(127,0,0,1)), ip: self.ip.unwrap_or_else(|| Ipv4Addr::new(127,0,0,1)),
port: self.port.unwrap_or(SHIP_PORT), port: self.port.unwrap_or(SHIP_PORT),
shops: Box::new(ItemShops::default()), shops: ItemShops::default(),
blocks: Blocks(blocks), blocks: Blocks(blocks),
auth_token: self.auth_token.unwrap_or_else(|| AuthToken("".into())), auth_token: self.auth_token.unwrap_or_else(|| AuthToken("".into())),
@ -451,37 +419,57 @@ impl<EG: EntityGateway + Clone> ShipServerStateBuilder<EG> {
} }
} }
#[derive(Clone)]
pub struct Block { pub struct Block {
client_location: Box<ClientLocation>, client_location: ClientLocation,
pub rooms: Box<Rooms>, pub rooms: room::Rooms,
} }
impl Default for Block { impl Default for Block {
fn default() -> Block { fn default() -> Block {
const SNONE: Option<room::RoomState> = None;
const NONE: Rooms = [SNONE; MAX_ROOMS];
Block { Block {
client_location: Box::new(ClientLocation::default()), client_location: ClientLocation::default(),
rooms: Box::new(NONE), rooms: room::Rooms::default(),
//rooms: core::array::from_fn(|_| Arc::new(RwLock::new(None))),
} }
} }
} }
/*
impl Block {
fn with<F, T>(&self, func: F) -> T
where
T: Send,
F: FnOnce(&Block) -> T,
{
func(self)
}
}
*/
#[derive(Clone)]
pub struct Blocks(pub Vec<Block>); pub struct Blocks(pub Vec<Block>);
impl Blocks { impl Blocks {
fn with_client(&mut self, id: ClientId, clients: &Clients) -> Result<&mut Block, ShipError> { async fn from_client(&mut self, id: ClientId, clients: &Clients) -> Result<&mut Block, ShipError> {
let client = clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; let block = clients.with(id, |client| Box::pin(async move {
self.0.get_mut(client.block).ok_or(ShipError::InvalidBlock(client.block)) client.block
})).await?;
self.0
.get_mut(block)
.ok_or(ShipError::InvalidBlock(block))
} }
} }
pub struct ShipServerState<EG: EntityGateway + Clone> { #[derive(Clone)]
pub struct ShipServerState<EG: EntityGateway + Clone + 'static> {
entity_gateway: EG, entity_gateway: EG,
pub clients: Clients, pub clients: Clients,
name: String, name: String,
item_state: items::state::ItemState, item_state: items::state::ItemState,
shops: Box<ItemShops>, shops: ItemShops,
pub blocks: Blocks, pub blocks: Blocks,
ip: Ipv4Addr, ip: Ipv4Addr,
@ -489,127 +477,126 @@ pub struct ShipServerState<EG: EntityGateway + Clone> {
auth_token: AuthToken, auth_token: AuthToken,
ship_list: Vec<Ship>, ship_list: Vec<Ship>,
shipgate_sender: Option<Box<dyn Fn(ShipMessage) + Send + Sync>>, //shipgate_sender: Option<Box<dyn Fn(ShipMessage) + Send + Sync>>,
shipgate_sender: Option<channel::Sender<ShipMessage>>,
trades: TradeState, trades: TradeState,
} }
impl<EG: EntityGateway + Clone> ShipServerState<EG> { impl<EG: EntityGateway + Clone + 'static> ShipServerState<EG> {
pub fn builder() -> ShipServerStateBuilder<EG> { pub fn builder() -> ShipServerStateBuilder<EG> {
ShipServerStateBuilder::default() ShipServerStateBuilder::default()
} }
pub fn set_sender(&mut self, sender: Box<dyn Fn(ShipMessage) + Send + Sync>) { async fn message(&mut self, id: ClientId, msg: Message) -> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> {
self.shipgate_sender = Some(sender); Ok(match msg.msg {
}
async fn message(&mut self, id: ClientId, msg: &Message) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> {
Ok(match &msg.msg {
GameMessage::RequestExp(request_exp) => { GameMessage::RequestExp(request_exp) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::request_exp(id, request_exp, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut block.rooms).await? handler::message::request_exp(id, request_exp, &mut self.entity_gateway, &block.client_location, &self.clients, &block.rooms).await?
}, },
GameMessage::PlayerDropItem(player_drop_item) => { GameMessage::PlayerDropItem(player_drop_item) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::player_drop_item(id, player_drop_item, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_state).await? handler::message::player_drop_item(id, player_drop_item, &mut self.entity_gateway, &block.client_location, &self.clients, &block.rooms, &mut self.item_state).await?
}, },
GameMessage::DropCoordinates(drop_coordinates) => { GameMessage::DropCoordinates(drop_coordinates) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::drop_coordinates(id, drop_coordinates, &block.client_location, &mut self.clients, &block.rooms).await? handler::message::drop_coordinates(id, drop_coordinates, &block.client_location, &mut self.clients, &block.rooms).await?
}, },
GameMessage::PlayerNoLongerHasItem(no_longer_has_item) => { GameMessage::PlayerNoLongerHasItem(no_longer_has_item) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::no_longer_has_item(id, no_longer_has_item, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::message::no_longer_has_item(id, no_longer_has_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerChangedMap(_) | GameMessage::PlayerChangedMap2(_) | GameMessage::TellOtherPlayerMyLocation(_) | GameMessage::PlayerChangedMap(_) | GameMessage::PlayerChangedMap2(_) | GameMessage::TellOtherPlayerMyLocation(_) |
GameMessage::PlayerWarpingToFloor(_) | GameMessage::PlayerTeleported(_) | GameMessage::PlayerStopped(_) | GameMessage::PlayerWarpingToFloor(_) | GameMessage::PlayerTeleported(_) | GameMessage::PlayerStopped(_) |
GameMessage::PlayerLoadedIn(_) | GameMessage::PlayerWalking(_) | GameMessage::PlayerRunning(_) | GameMessage::PlayerLoadedIn(_) | GameMessage::PlayerWalking(_) | GameMessage::PlayerRunning(_) |
GameMessage::PlayerWarped(_) | GameMessage::PlayerChangedFloor(_) | GameMessage::InitializeSpeechNpc(_) => { GameMessage::PlayerWarped(_) | GameMessage::PlayerChangedFloor(_) | GameMessage::InitializeSpeechNpc(_) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::update_player_position(id, msg, &mut self.clients, &block.client_location, &block.rooms).await? handler::message::update_player_position(id, msg, &mut self.clients, &block.client_location, &block.rooms).await?
}, },
GameMessage::ChargeAttack(charge_attack) => { GameMessage::ChargeAttack(charge_attack) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::charge_attack(id, charge_attack, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::message::charge_attack(id, charge_attack, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerUseItem(player_use_item) => { GameMessage::PlayerUseItem(player_use_item) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::player_uses_item(id, player_use_item, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::message::player_uses_item(id, player_use_item, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerUsedMedicalCenter(player_used_medical_center) => { GameMessage::PlayerUsedMedicalCenter(player_used_medical_center) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::player_used_medical_center(id, player_used_medical_center, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::message::player_used_medical_center(id, player_used_medical_center, &mut self.entity_gateway, &block.client_location, &mut self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerFeedMag(player_feed_mag) => { GameMessage::PlayerFeedMag(player_feed_mag) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::message::player_feed_mag(id, player_feed_mag, self.entity_gateway.clone(), &block.client_location, &self.clients, &mut self.item_state).await? handler::message::player_feed_mag(id, player_feed_mag, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerEquipItem(player_equip_item) => { GameMessage::PlayerEquipItem(player_equip_item) => {
handler::message::player_equips_item(id, player_equip_item, self.entity_gateway.clone(), &self.clients, &mut self.item_state).await? handler::message::player_equips_item(id, player_equip_item, &mut self.entity_gateway, &self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerUnequipItem(player_unequip_item) => { GameMessage::PlayerUnequipItem(player_unequip_item) => {
handler::message::player_unequips_item(id, player_unequip_item, self.entity_gateway.clone(), &self.clients, &mut self.item_state).await? handler::message::player_unequips_item(id, player_unequip_item, &mut self.entity_gateway, &self.clients, &mut self.item_state).await?
}, },
GameMessage::SortItems(sort_items) => { GameMessage::SortItems(sort_items) => {
handler::message::player_sorts_items(id, sort_items, self.entity_gateway.clone(), &self.clients, &mut self.item_state).await? handler::message::player_sorts_items(id, sort_items, &mut self.entity_gateway, &self.clients, &mut self.item_state).await?
}, },
GameMessage::PlayerSoldItem(player_sold_item) => { GameMessage::PlayerSoldItem(player_sold_item) => {
handler::message::player_sells_item(id, player_sold_item, self.entity_gateway.clone(), &mut self.clients, &mut self.item_state).await? handler::message::player_sells_item(id, player_sold_item, &mut self.entity_gateway, &mut self.clients, &mut self.item_state).await?
}, },
_ => { _ => {
let cmsg = msg.clone(); let cmsg = msg.clone();
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
Box::new(block.client_location.get_client_neighbors(id).await.unwrap().into_iter() block.client_location.get_client_neighbors(id).await.unwrap().into_iter()
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::Message(cmsg.clone())) (client.client, SendShipPacket::Message(cmsg.clone()))
})) })
.collect()
}, },
}) })
} }
async fn direct_message(&mut self, id: ClientId, msg: &DirectMessage) -> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> { async fn direct_message(&mut self, id: ClientId, msg: DirectMessage) -> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> {
let target = msg.flag; let target = msg.flag;
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
Ok(match &msg.msg { Ok(match msg.msg {
GameMessage::GuildcardSend(guildcard_send) => { GameMessage::GuildcardSend(guildcard_send) => {
handler::direct_message::guildcard_send(id, guildcard_send, target, &block.client_location, &self.clients).await handler::direct_message::guildcard_send(id, guildcard_send, target, &block.client_location, &self.clients).await?
}, },
GameMessage::RequestItem(request_item) => { GameMessage::RequestItem(request_item) => {
handler::direct_message::request_item(id, request_item, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_state).await? handler::direct_message::request_item(id, request_item, &mut self.entity_gateway, &block.client_location, &self.clients, &block.rooms, &mut self.item_state).await?
}, },
GameMessage::PickupItem(pickup_item) => { GameMessage::PickupItem(pickup_item) => {
handler::direct_message::pickup_item(id, pickup_item, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::direct_message::pickup_item(id, pickup_item, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_state).await?
}, },
GameMessage::BoxDropRequest(box_drop_request) => { GameMessage::BoxDropRequest(box_drop_request) => {
handler::direct_message::request_box_item(id, box_drop_request, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut block.rooms, &mut self.item_state).await? handler::direct_message::request_box_item(id, box_drop_request, &mut self.entity_gateway, &block.client_location, &self.clients, &block.rooms, &mut self.item_state).await?
}, },
GameMessage::BankRequest(_bank_request) => { GameMessage::BankRequest(_bank_request) => {
handler::direct_message::send_bank_list(id, &self.clients, &mut self.item_state).await? handler::direct_message::send_bank_list(id, &self.clients, &mut self.item_state).await?
}, },
GameMessage::BankInteraction(bank_interaction) => { GameMessage::BankInteraction(bank_interaction) => {
handler::direct_message::bank_interaction(id, bank_interaction, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::direct_message::bank_interaction(id, bank_interaction, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_state).await?
}, },
GameMessage::ShopRequest(shop_request) => { GameMessage::ShopRequest(shop_request) => {
handler::direct_message::shop_request(id, shop_request, &block.client_location, &mut self.clients, &block.rooms, &mut self.shops).await? handler::direct_message::shop_request(id, shop_request, &block.client_location, &self.clients, &block.rooms, &mut self.shops).await?
}, },
GameMessage::BuyItem(buy_item) => { GameMessage::BuyItem(buy_item) => {
handler::direct_message::buy_item(id, buy_item, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::direct_message::buy_item(id, buy_item, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_state).await?
}, },
GameMessage::TekRequest(tek_request) => { GameMessage::TekRequest(tek_request) => {
handler::direct_message::request_tek_item(id, tek_request, self.entity_gateway.clone(), &mut self.clients, &mut self.item_state).await? handler::direct_message::request_tek_item(id, tek_request, &mut self.entity_gateway, &self.clients, &mut self.item_state).await?
}, },
GameMessage::TekAccept(tek_accept) => { GameMessage::TekAccept(tek_accept) => {
handler::direct_message::accept_tek_item(id, tek_accept, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state).await? handler::direct_message::accept_tek_item(id, tek_accept, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_state).await?
}, },
GameMessage::TradeRequest(trade_request) => { GameMessage::TradeRequest(trade_request) => {
handler::trade::trade_request(id, trade_request, target, &block.client_location, &mut self.clients, &mut self.item_state, &mut self.trades).await? handler::trade::trade_request(id, trade_request, target, &block.client_location, &self.clients, &mut self.item_state, &mut self.trades).await?
}, },
_ => { _ => {
let cmsg = msg.clone(); let cmsg = msg.clone();
Box::new(block.client_location.get_all_clients_by_client(id).await.unwrap().into_iter() block.client_location.get_all_clients_by_client(id).await.unwrap().into_iter()
.filter(move |client| client.local_client.id() == target as u8) .filter(move |client| client.local_client.id() == target as u8)
.map(move |client| { .map(move |client| {
(client.client, SendShipPacket::DirectMessage(cmsg.clone())) (client.client, SendShipPacket::DirectMessage(cmsg.clone()))
})) })
.collect()
}, },
}) })
} }
@ -619,9 +606,10 @@ impl<EG: EntityGateway + Clone> ShipServerState<EG> {
impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> { impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> {
type SendPacket = SendShipPacket; type SendPacket = SendShipPacket;
type RecvPacket = RecvShipPacket; type RecvPacket = RecvShipPacket;
type Cipher = PSOBBCipher;
type PacketError = anyhow::Error; type PacketError = anyhow::Error;
async fn on_connect(&mut self, _id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket>>, anyhow::Error> { async fn on_connect(&mut self, _id: ClientId) -> Result<Vec<OnConnect<Self::SendPacket, Self::Cipher>>, anyhow::Error> {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let mut server_key = [0u8; 48]; let mut server_key = [0u8; 48];
@ -630,59 +618,104 @@ impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> {
rng.fill(&mut client_key[..]); rng.fill(&mut client_key[..]);
Ok(vec![OnConnect::Packet(SendShipPacket::ShipWelcome(ShipWelcome::new(server_key, client_key))), Ok(vec![OnConnect::Packet(SendShipPacket::ShipWelcome(ShipWelcome::new(server_key, client_key))),
OnConnect::Cipher((Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key)), OnConnect::Cipher(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, client_key),
Box::new(PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key)))) PSOBBCipher::new(ELSEWHERE_PARRAY, ELSEWHERE_PRIVATE_KEY, server_key))
]) ])
} }
async fn handle(&mut self, id: ClientId, pkt: &RecvShipPacket) async fn handle(&mut self, id: ClientId, pkt: RecvShipPacket) -> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> {
-> Result<Box<dyn Iterator<Item = (ClientId, SendShipPacket)> + Send>, anyhow::Error> { if let Ok((char_id, char_playtime)) = self.clients.with_mut(id, |client| Box::pin(async move {
client.update_playtime();
(client.character.id, client.character.playtime)
})).await {
self.entity_gateway.set_character_playtime(&char_id, char_playtime).await?;
}
/*
if let Some(client) = self.clients.get_mut(&id) { if let Some(client) = self.clients.get_mut(&id) {
client.update_playtime(); client.update_playtime();
self.entity_gateway.set_character_playtime(&client.character.id, client.character.playtime).await?; self.entity_gateway.set_character_playtime(&client.character.id, client.character.playtime).await?;
} }*/
Ok(match pkt { Ok(match pkt {
RecvShipPacket::Login(login) => { RecvShipPacket::Login(login) => {
Box::new(handler::auth::validate_login(id, login, self.entity_gateway.clone(), &mut self.clients, &mut self.item_state, &self.shipgate_sender, &self.name, self.blocks.0.len()) handler::auth::validate_login(id, login, &mut self.entity_gateway, &mut self.clients, &mut self.item_state, &self.shipgate_sender, &self.name, self.blocks.0.len())
.await?.into_iter().map(move |pkt| (id, pkt))) .await?
.into_iter()
.map(move |pkt| (id, pkt))
.collect()
}, },
RecvShipPacket::QuestDetailRequest(questdetailrequest) => { RecvShipPacket::QuestDetailRequest(questdetailrequest) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
match questdetailrequest.menu { match questdetailrequest.menu {
QUEST_SELECT_MENU_ID => handler::quest::quest_detail(id, questdetailrequest, &block.client_location, &mut block.rooms).await?, QUEST_SELECT_MENU_ID => handler::quest::quest_detail(id, questdetailrequest, &block.client_location, &mut block.rooms).await?,
_ => unreachable!(), _ => unreachable!(),
} }
}, },
RecvShipPacket::MenuSelect(menuselect) => { RecvShipPacket::MenuSelect(menuselect) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
match menuselect.menu { match menuselect.menu {
SHIP_MENU_ID => { SHIP_MENU_ID => {
let leave_lobby = handler::lobby::remove_from_lobby(id, &mut block.client_location).await.into_iter().into_iter().flatten(); let leave_lobby = handler::lobby::remove_from_lobby(id, &mut block.client_location).await.into_iter().into_iter().flatten();
let select_ship = handler::ship::selected_ship(id, menuselect, &self.ship_list)?; let select_ship = handler::ship::selected_ship(id, menuselect, &self.ship_list)?;
Box::new(leave_lobby.chain(select_ship)) leave_lobby.chain(select_ship).collect()
} }
BLOCK_MENU_ID => { BLOCK_MENU_ID => {
let leave_lobby = handler::lobby::remove_from_lobby(id, &mut block.client_location).await.into_iter().into_iter().flatten(); let leave_lobby = handler::lobby::remove_from_lobby(id, &mut block.client_location).await.into_iter().into_iter().flatten();
let select_block = handler::lobby::block_selected(id, menuselect, &mut self.clients, &self.item_state)?.into_iter(); let select_block = handler::lobby::block_selected(id, menuselect, &self.clients, &self.item_state).await?.into_iter();
Box::new(leave_lobby.chain(select_block)) leave_lobby.chain(select_block).collect()
} }
ROOM_MENU_ID => handler::room::join_room(id, menuselect, &mut block.client_location, &mut self.clients, &mut self.item_state, &mut block.rooms).await?, ROOM_MENU_ID => handler::room::join_room(id, menuselect, &mut block.client_location, &self.clients, &mut self.item_state, &mut block.rooms).await?,
QUEST_CATEGORY_MENU_ID => handler::quest::select_quest_category(id, menuselect, &block.client_location, &mut block.rooms).await?, QUEST_CATEGORY_MENU_ID => handler::quest::select_quest_category(id, menuselect, &block.client_location, &mut block.rooms).await?,
_ => unreachable!(), _ => unreachable!(),
} }
}, },
RecvShipPacket::QuestMenuSelect(questmenuselect) => { RecvShipPacket::QuestMenuSelect(questmenuselect) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::quest::player_chose_quest(id, questmenuselect, &mut self.clients, &block.client_location, &mut block.rooms).await? handler::quest::player_chose_quest(id, questmenuselect, &mut self.clients, &block.client_location, &mut block.rooms).await?
}, },
RecvShipPacket::MenuDetail(menudetail) => { RecvShipPacket::MenuDetail(menudetail) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
Box::new(handler::lobby::get_room_tab_info(id, menudetail, &mut block.client_location, &self.clients, &mut block.rooms).await?.into_iter()) handler::lobby::get_room_tab_info(id, menudetail, &mut block.client_location, &self.clients, &mut block.rooms).await?
}, },
RecvShipPacket::RoomPasswordReq(room_password_req) => { RecvShipPacket::RoomPasswordReq(room_password_req) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
if room_password_req.password == block.rooms[room_password_req.item as usize].as_ref()
/*
let password = room_password_req.password;
let correct_password = block.rooms.with(RoomId(room_password_req.item as usize), |room| Box::pin(async move {
password == room.password
})).await?;
*/
let room_password = block.rooms.with(RoomId(room_password_req.item as usize), |room| Box::pin(async move {
room.password
})).await?;
/*
let correct_password = room_password_req.password == block.rooms
.get(RoomId(room_password_req.item as usize))
.await
.map(|room| room.password)
.unwrap_or_else(false);
*/
//if correct_password {
if room_password_req.password == room_password {
let menuselect = MenuSelect {
menu: room_password_req.menu,
item: room_password_req.item,
};
handler::room::join_room(id, menuselect, &mut block.client_location, &mut self.clients, &mut self.item_state, &mut block.rooms).await?
}
else {
vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("Incorrect password".into())))]
}
/*
if room_password_req.password == block.rooms[room_password_req.item as usize]
.read()
.await
.as_ref()
.ok_or(ShipError::InvalidRoom(room_password_req.item))? .ok_or(ShipError::InvalidRoom(room_password_req.item))?
.password { .password {
let menuselect = MenuSelect { let menuselect = MenuSelect {
@ -694,10 +727,11 @@ impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> {
else { else {
Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("Incorrect password".into())))].into_iter()) Box::new(vec![(id, SendShipPacket::SmallDialog(SmallDialog::new("Incorrect password".into())))].into_iter())
} }
*/
}, },
RecvShipPacket::CharData(chardata) => { RecvShipPacket::CharData(chardata) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
Box::new(handler::lobby::send_player_to_lobby(id, chardata, &mut block.client_location, &self.clients, &self.item_state).await?.into_iter()) handler::lobby::send_player_to_lobby(id, chardata, &mut block.client_location, &self.clients, &self.item_state).await?
}, },
RecvShipPacket::Message(msg) => { RecvShipPacket::Message(msg) => {
self.message(id, msg).await? self.message(id, msg).await?
@ -706,72 +740,72 @@ impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> {
self.direct_message(id, msg).await? self.direct_message(id, msg).await?
}, },
RecvShipPacket::PlayerChat(msg) => { RecvShipPacket::PlayerChat(msg) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
Box::new(handler::communication::player_chat(id, msg, &block.client_location, &self.clients).await?) handler::communication::player_chat(id, msg, &block.client_location, &self.clients).await?
}, },
RecvShipPacket::CreateRoom(create_room) => { RecvShipPacket::CreateRoom(create_room) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::room::create_room(id, create_room, &mut block.client_location, &mut self.clients, &mut self.item_state, &mut block.rooms).await? handler::room::create_room(id, create_room, &mut block.client_location, &mut self.clients, &mut self.item_state, &mut block.rooms).await?
}, },
RecvShipPacket::RoomNameRequest(_req) => { RecvShipPacket::RoomNameRequest(_req) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::room::room_name_request(id, &block.client_location, &block.rooms).await handler::room::room_name_request(id, &block.client_location, &block.rooms).await?
}, },
RecvShipPacket::UpdateConfig(pkt) => { RecvShipPacket::UpdateConfig(pkt) => {
handler::settings::update_config(id, pkt, &mut self.clients, self.entity_gateway.clone()).await handler::settings::update_config(id, pkt, &mut self.clients, &mut self.entity_gateway).await?
}, },
RecvShipPacket::ViewInfoboardRequest(_pkt) => { RecvShipPacket::ViewInfoboardRequest(_pkt) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::communication::request_infoboard(id, &block.client_location, &self.clients).await handler::communication::request_infoboard(id, &block.client_location, &self.clients).await?
}, },
RecvShipPacket::WriteInfoboard(pkt) => { RecvShipPacket::WriteInfoboard(pkt) => {
handler::communication::write_infoboard(id, pkt, &mut self.clients, self.entity_gateway.clone()).await handler::communication::write_infoboard(id, pkt, &self.clients, &mut self.entity_gateway).await?
}, },
RecvShipPacket::RoomListRequest(_req) => { RecvShipPacket::RoomListRequest(_req) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::room::request_room_list(id, &block.client_location, &block.rooms).await handler::room::request_room_list(id, &block.client_location, &block.rooms).await
}, },
RecvShipPacket::Like62ButCooler(cool62) => { RecvShipPacket::Like62ButCooler(cool62) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::room::cool_62(id, cool62, &block.client_location).await handler::room::cool_62(id, cool62, &block.client_location).await
}, },
RecvShipPacket::ClientCharacterData(_) => { RecvShipPacket::ClientCharacterData(_) => {
// TOOD: validate this in some way? // TOOD: validate this in some way?
Box::new(None.into_iter()) Vec::new()
}, },
RecvShipPacket::DoneBursting(_) => { RecvShipPacket::DoneBursting(_) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::room::done_bursting(id, &block.client_location, &mut block.rooms).await handler::room::done_bursting(id, &block.client_location, &mut block.rooms).await?
}, },
RecvShipPacket::DoneBursting2(_) => { RecvShipPacket::DoneBursting2(_) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::room::done_bursting(id, &block.client_location, &mut block.rooms).await handler::room::done_bursting(id, &block.client_location, &mut block.rooms).await?
}, },
RecvShipPacket::LobbySelect(pkt) => { RecvShipPacket::LobbySelect(pkt) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
Box::new(handler::lobby::change_lobby(id, pkt.lobby, &mut block.client_location, &self.clients, &mut self.item_state, &mut block.rooms, self.entity_gateway.clone()).await?.into_iter()) handler::lobby::change_lobby(id, pkt.lobby, &mut block.client_location, &self.clients, &mut self.item_state, &mut block.rooms, &mut self.entity_gateway).await?
}, },
RecvShipPacket::RequestQuestList(rql) => { RecvShipPacket::RequestQuestList(rql) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::quest::send_quest_category_list(id, rql, &block.client_location, &mut block.rooms).await? handler::quest::send_quest_category_list(id, rql, &block.client_location, &mut block.rooms).await?
}, },
RecvShipPacket::QuestFileRequest(quest_file_request) => { RecvShipPacket::QuestFileRequest(quest_file_request) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::quest::quest_file_request(id, quest_file_request, &block.client_location, &mut block.rooms).await? handler::quest::quest_file_request(id, quest_file_request, &block.client_location, &mut block.rooms).await?
}, },
RecvShipPacket::QuestChunkAck(quest_chunk_ack) => { RecvShipPacket::QuestChunkAck(quest_chunk_ack) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::quest::quest_chunk_ack(id, quest_chunk_ack, &block.client_location, &mut block.rooms).await? handler::quest::quest_chunk_ack(id, quest_chunk_ack, &block.client_location, &mut block.rooms).await?
}, },
RecvShipPacket::DoneLoadingQuest(_) => { RecvShipPacket::DoneLoadingQuest(_) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::quest::done_loading_quest(id, &mut self.clients, &block.client_location).await? handler::quest::done_loading_quest(id, &self.clients, &block.client_location).await?
}, },
RecvShipPacket::FullCharacterData(_full_character_data) => { RecvShipPacket::FullCharacterData(_full_character_data) => {
Box::new(None.into_iter()) Vec::new()
}, },
RecvShipPacket::SaveOptions(save_options) => { RecvShipPacket::SaveOptions(save_options) => {
handler::settings::save_options(id, save_options, &mut self.clients, self.entity_gateway.clone()).await handler::settings::save_options(id, save_options, &self.clients, &mut self.entity_gateway).await?
}, },
RecvShipPacket::RequestShipList(_) => { RecvShipPacket::RequestShipList(_) => {
handler::ship::ship_list(id, &self.ship_list) handler::ship::ship_list(id, &self.ship_list)
@ -780,32 +814,32 @@ impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> {
handler::ship::block_list(id, &self.name, self.blocks.0.len()) handler::ship::block_list(id, &self.name, self.blocks.0.len())
}, },
RecvShipPacket::ItemsToTrade(items_to_trade) => { RecvShipPacket::ItemsToTrade(items_to_trade) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::trade::items_to_trade(id, items_to_trade, &block.client_location, &mut self.clients, &mut self.item_state, &mut self.trades).await? handler::trade::items_to_trade(id, items_to_trade, &block.client_location, &self.clients, &mut self.item_state, &mut self.trades).await?
}, },
RecvShipPacket::TradeConfirmed(_) => { RecvShipPacket::TradeConfirmed(_) => {
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
handler::trade::trade_confirmed(id, self.entity_gateway.clone(), &block.client_location, &mut self.clients, &mut self.item_state, &mut self.trades).await? handler::trade::trade_confirmed(id, &mut self.entity_gateway, &block.client_location, &self.clients, &mut self.item_state, &mut self.trades).await?
}, },
RecvShipPacket::KeyboardConfig(keyboard_config) => { RecvShipPacket::KeyboardConfig(keyboard_config) => {
handler::settings::keyboard_config(id, keyboard_config, &mut self.clients, self.entity_gateway.clone()).await handler::settings::keyboard_config(id, keyboard_config, &self.clients, &mut self.entity_gateway).await?
}, },
RecvShipPacket::GamepadConfig(gamepad_config) => { RecvShipPacket::GamepadConfig(gamepad_config) => {
handler::settings::gamepad_config(id, gamepad_config, &mut self.clients, self.entity_gateway.clone()).await handler::settings::gamepad_config(id, gamepad_config, &self.clients, &mut self.entity_gateway).await?
}, },
}) })
} }
async fn on_disconnect(&mut self, id: ClientId) -> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> { async fn on_disconnect(&mut self, id: ClientId) -> Result<Vec<(ClientId, SendShipPacket)>, anyhow::Error> {
let client = self.clients.get(&id).ok_or(ShipError::ClientNotFound(id))?; //let client = self.clients.get(&id).ok_or(ShipError::ClientNotFound(id))?;
let block = self.blocks.with_client(id, &self.clients)?; let block = self.blocks.from_client(id, &self.clients).await?;
let area_client = block.client_location.get_local_client(id).await?; let area_client = block.client_location.get_local_client(id).await?;
let neighbors = block.client_location.get_client_neighbors(id).await?; let neighbors = block.client_location.get_client_neighbors(id).await?;
let pkt = match block.client_location.get_area(id).await? { let pkt = match block.client_location.get_area(id).await? {
RoomLobby::Room(room) => { RoomLobby::Room(room) => {
if neighbors.is_empty() { if neighbors.is_empty() {
block.rooms[room.0] = None; block.rooms.remove(room).await;
} }
let leader = block.client_location.get_room_leader(room).await?; let leader = block.client_location.get_room_leader(room).await?;
SendShipPacket::LeaveRoom(LeaveRoom::new(area_client.local_client.id(), leader.local_client.id())) SendShipPacket::LeaveRoom(LeaveRoom::new(area_client.local_client.id(), leader.local_client.id()))
@ -816,16 +850,24 @@ impl<EG: EntityGateway + Clone> ServerState for ShipServerState<EG> {
} }
}; };
/*
if let Some(shipgate_sender) = self.shipgate_sender.as_ref() { if let Some(shipgate_sender) = self.shipgate_sender.as_ref() {
shipgate_sender(ShipMessage::RemoveUser(client.user.id)); shipgate_sender.send(ShipMessage::RemoveUser(client.user.id)).await;
} }
block.client_location.remove_client_from_area(id).await; block.client_location.remove_client_from_area(id).await;
self.item_state.remove_character_from_room(&client.character); self.clients.with(id, |client| Box::pin(async move {
self.item_state.remove_character_from_room(&client.character).await
})).await?;
*/
if let Some(mut client) = self.clients.remove(&id) { if let Some(mut client) = self.clients.remove(&id).await {
client.user.at_ship = false; client.user.at_ship = false;
self.entity_gateway.save_user(&client.user).await; self.entity_gateway.save_user(&client.user).await;
if let Some(shipgate_sender) = self.shipgate_sender.as_ref() {
shipgate_sender.send(ShipMessage::RemoveUser(client.user.id)).await;
}
self.item_state.remove_character_from_room(&client.character).await
} }
Ok(neighbors.into_iter().map(|n| { Ok(neighbors.into_iter().map(|n| {
@ -854,7 +896,7 @@ impl<EG: EntityGateway + Clone> InterserverActor for ShipServerState<EG> {
] ]
} }
async fn action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error> { async fn on_action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error> {
match msg { match msg {
LoginMessage::SendMail{..} => { LoginMessage::SendMail{..} => {
Ok(Vec::new()) Ok(Vec::new())
@ -864,11 +906,15 @@ impl<EG: EntityGateway + Clone> InterserverActor for ShipServerState<EG> {
Ok(Vec::new()) Ok(Vec::new())
}, },
LoginMessage::RequestUsers => { LoginMessage::RequestUsers => {
/*
Ok(self.clients.iter() Ok(self.clients.iter()
.map(|(_, client)| { .map(|(_, client)| {
(id, ShipMessage::AddUser(client.user.id)) (id, ShipMessage::AddUser(client.user.id))
}) })
.collect()) .collect())
*/
// TODO
Ok(Vec::new())
} }
} }
} }
@ -876,4 +922,8 @@ impl<EG: EntityGateway + Clone> InterserverActor for ShipServerState<EG> {
async fn on_disconnect(&mut self, _id: ServerId) -> Vec<(ServerId, Self::SendMessage)> { async fn on_disconnect(&mut self, _id: ServerId) -> Vec<(ServerId, Self::SendMessage)> {
Vec::new() Vec::new()
} }
fn set_sender(&mut self, _server_id: ServerId, sender: channel::Sender<Self::SendMessage>) {
self.shipgate_sender = Some(sender);
}
} }

View File

@ -1,8 +1,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::common::serverstate::ClientId; use crate::common::serverstate::ClientId;
use crate::ship::items; use crate::ship::items;
use async_std::sync::{Mutex, MutexGuard}; use async_std::sync::{Arc, Mutex, MutexGuard};
use futures::future::Future; use futures::future::{Future, OptionFuture};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum TradeItem { pub enum TradeItem {
@ -81,9 +81,9 @@ pub enum TradeStateError {
MismatchedTrade(ClientId, ClientId), MismatchedTrade(ClientId, ClientId),
} }
#[derive(Default, Debug)] #[derive(Default, Debug, Clone)]
pub struct TradeState { pub struct TradeState {
trades: HashMap<ClientId, Mutex<ClientTradeState>>, trades: HashMap<ClientId, Arc<Mutex<ClientTradeState>>>,
} }
impl TradeState { impl TradeState {
@ -95,7 +95,7 @@ impl TradeState {
meseta: 0, meseta: 0,
status: TradeStatus::SentRequest, status: TradeStatus::SentRequest,
}; };
self.trades.insert(*sender, Mutex::new(state)); self.trades.insert(*sender, Arc::new(Mutex::new(state)));
let state = ClientTradeState { let state = ClientTradeState {
client: *receiver, client: *receiver,
@ -104,13 +104,14 @@ impl TradeState {
meseta: 0, meseta: 0,
status: TradeStatus::ReceivedRequest, status: TradeStatus::ReceivedRequest,
}; };
self.trades.insert(*receiver, Mutex::new(state)); self.trades.insert(*receiver, Arc::new(Mutex::new(state)));
} }
pub fn in_trade(&self, client: &ClientId) -> bool { pub fn in_trade(&self, client: &ClientId) -> bool {
self.trades.contains_key(client) self.trades.contains_key(client)
} }
/*
pub async fn with<'a, T, F, Fut> (&'a self, client: &ClientId, func: F) -> Result<T, TradeStateError> pub async fn with<'a, T, F, Fut> (&'a self, client: &ClientId, func: F) -> Result<T, TradeStateError>
where where
F: FnOnce(MutexGuard<'a, ClientTradeState>, MutexGuard<'a, ClientTradeState>) -> Fut + 'a, F: FnOnce(MutexGuard<'a, ClientTradeState>, MutexGuard<'a, ClientTradeState>) -> Fut + 'a,
@ -125,12 +126,38 @@ impl TradeState {
} }
Ok(func(c1, c2).await) Ok(func(c1, c2).await)
} }
*/
pub async fn with<'a, T, F, Fut> (&'a self, client: &ClientId, func: F) -> Result<T, TradeStateError>
where
T: Send,
//F: for<'b> FnOnce(&'b mut ClientTradeState, &'b mut ClientTradeState) -> BoxFuture<'b, T> + Send + 'a
//F: for<'b> FnOnce(&'b mut ClientTradeState, &'b mut ClientTradeState) -> Fut + Send + 'a,
F: FnOnce(MutexGuard<'a, ClientTradeState>, MutexGuard<'a, ClientTradeState>) -> Fut + 'a,
Fut: Future<Output = T>,
{
let c1 = self.trades
.get(client)
.ok_or(TradeStateError::ClientNotInTrade(*client))?
.lock()
.await;
let c2 = self.trades
.get(&c1.other_client)
.ok_or(TradeStateError::ClientNotInTrade(c1.other_client))?
.lock()
.await;
if c1.client != c2.other_client {
return Err(TradeStateError::MismatchedTrade(c1.client, c2.client));
}
Ok(func(c1, c2).await)
}
// TODO: is it possible for this to not return Options? // TODO: is it possible for this to not return Options?
pub fn remove_trade(&mut self, client: &ClientId) -> (Option<ClientTradeState>, Option<ClientTradeState>) { pub async fn remove_trade(&mut self, client: &ClientId) -> (Option<ClientTradeState>, Option<ClientTradeState>) {
let c1 = self.trades.remove(client).map(|c| c.into_inner()); let c1 = OptionFuture::from(self.trades.remove(client).map(|c| async move {c.lock().await.clone()} )).await;
let c2 = if let Some(ref state) = c1 { let c2 = if let Some(ref state) = c1 {
self.trades.remove(&state.other_client).map(|c| c.into_inner()) OptionFuture::from(self.trades.remove(&state.other_client).map(|c| async move {c.lock().await.clone()})).await
} }
else { else {
None None

View File

@ -37,7 +37,7 @@ pub async fn new_user_character<EG: EntityGateway + Clone>(entity_gateway: &mut
pub async fn log_in_char<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, username: &str, password: &str) { pub async fn log_in_char<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, username: &str, password: &str) {
let username = username.to_string(); let username = username.to_string();
let password = password.to_string(); let password = password.to_string();
ship.handle(id, &RecvShipPacket::Login(Login { ship.handle(id, RecvShipPacket::Login(Login {
tag: 0, tag: 0,
guildcard: 0, guildcard: 0,
version: 0, version: 0,
@ -49,13 +49,13 @@ pub async fn log_in_char<EG: EntityGateway + Clone>(ship: &mut ShipServerState<E
unknown3: [0; 40], unknown3: [0; 40],
hwinfo: [0; 8], hwinfo: [0; 8],
session: Session::new(), session: Session::new(),
})).await.unwrap().for_each(drop); })).await.unwrap();
} }
pub async fn join_lobby<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId) { pub async fn join_lobby<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId) {
ship.handle(id, &RecvShipPacket::CharData(CharData { ship.handle(id, RecvShipPacket::CharData(CharData {
_unknown: [0; 0x828] _unknown: [0; 0x828]
})).await.unwrap().for_each(drop); })).await.unwrap();
} }
pub async fn create_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, name: &str, password: &str) { pub async fn create_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, name: &str, password: &str) {
@ -63,14 +63,14 @@ pub async fn create_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<E
} }
pub async fn leave_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId) { pub async fn leave_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId) {
ship.handle(id, &RecvShipPacket::LobbySelect(LobbySelect { ship.handle(id, RecvShipPacket::LobbySelect(LobbySelect {
menu: 3, menu: 3,
lobby: 0, lobby: 0,
})).await.unwrap().for_each(drop); })).await.unwrap();
} }
pub async fn create_room_with_difficulty<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, name: &str, password: &str, difficulty: Difficulty) { pub async fn create_room_with_difficulty<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, name: &str, password: &str, difficulty: Difficulty) {
ship.handle(id, &RecvShipPacket::CreateRoom(CreateRoom { ship.handle(id, RecvShipPacket::CreateRoom(CreateRoom {
unknown: [0; 2], unknown: [0; 2],
name: utf8_to_utf16_array!(name, 16), name: utf8_to_utf16_array!(name, 16),
password: utf8_to_utf16_array!(password, 16), password: utf8_to_utf16_array!(password, 16),
@ -80,14 +80,14 @@ pub async fn create_room_with_difficulty<EG: EntityGateway + Clone>(ship: &mut S
episode: 1, episode: 1,
single_player: 0, single_player: 0,
padding: [0; 3], padding: [0; 3],
})).await.unwrap().for_each(drop); })).await.unwrap();
ship.handle(id, &RecvShipPacket::DoneBursting(DoneBursting {})).await.unwrap().for_each(drop); ship.handle(id, RecvShipPacket::DoneBursting(DoneBursting {})).await.unwrap();
} }
pub async fn join_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, room_id: u32) { pub async fn join_room<EG: EntityGateway + Clone>(ship: &mut ShipServerState<EG>, id: ClientId, room_id: u32) {
ship.handle(id, &RecvShipPacket::MenuSelect(MenuSelect { ship.handle(id, RecvShipPacket::MenuSelect(MenuSelect {
menu: ROOM_MENU_ID, menu: ROOM_MENU_ID,
item: room_id, item: room_id,
})).await.unwrap().for_each(drop); })).await.unwrap();
ship.handle(id, &RecvShipPacket::DoneBursting(DoneBursting {})).await.unwrap().for_each(drop); ship.handle(id, RecvShipPacket::DoneBursting(DoneBursting {})).await.unwrap();
} }

View File

@ -38,10 +38,10 @@ async fn test_bank_items_sent_in_character_login() {
.build()); .build());
log_in_char(&mut ship, ClientId(1), "a1", "a").await; log_in_char(&mut ship, ClientId(1), "a1", "a").await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::MenuSelect(MenuSelect { let packets = ship.handle(ClientId(1), RecvShipPacket::MenuSelect(MenuSelect {
menu: BLOCK_MENU_ID, menu: BLOCK_MENU_ID,
item: 1, item: 1,
})).await.unwrap().collect::<Vec<_>>(); })).await.unwrap();
assert!(matches!(&packets[0], (_, SendShipPacket::FullCharacter(fc)) if fc.character.bank.items[0].data1[0..3] == [0x00, 0x08, 0x04] )); assert!(matches!(&packets[0], (_, SendShipPacket::FullCharacter(fc)) if fc.character.bank.items[0].data1[0..3] == [0x00, 0x08, 0x04] ));
} }
@ -78,11 +78,11 @@ async fn test_request_bank_items() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(matches!(&packets[0], (_, SendShipPacket::BankItemList (bank_item_list)) assert!(matches!(&packets[0], (_, SendShipPacket::BankItemList (bank_item_list))
if bank_item_list.item_count == 3 if bank_item_list.item_count == 3
@ -122,11 +122,11 @@ async fn test_request_stacked_bank_items() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(matches!(&packets[0], (_, SendShipPacket::BankItemList (bank_item_list)) assert!(matches!(&packets[0], (_, SendShipPacket::BankItemList (bank_item_list))
if bank_item_list.item_count == 1 if bank_item_list.item_count == 1
@ -187,11 +187,11 @@ async fn test_request_bank_items_sorted() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(matches!(&packets[0], (_, SendShipPacket::BankItemList (bank_item_list)) assert!(matches!(&packets[0], (_, SendShipPacket::BankItemList (bank_item_list))
if bank_item_list.item_count == 3 if bank_item_list.item_count == 3
@ -247,13 +247,13 @@ async fn test_deposit_individual_item() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10001, item_id: 0x10001,
@ -261,7 +261,7 @@ async fn test_deposit_individual_item() {
item_amount: 0, item_amount: 0,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)}))
@ -313,13 +313,13 @@ async fn test_deposit_stacked_item() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -327,7 +327,7 @@ async fn test_deposit_stacked_item() {
item_amount: 3, item_amount: 3,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)}))
@ -374,13 +374,13 @@ async fn test_deposit_partial_stacked_item() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -388,7 +388,7 @@ async fn test_deposit_partial_stacked_item() {
item_amount: 2, item_amount: 2,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)}))
@ -455,13 +455,13 @@ async fn test_deposit_stacked_item_with_stack_already_in_bank() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -469,7 +469,7 @@ async fn test_deposit_stacked_item_with_stack_already_in_bank() {
item_amount: 2, item_amount: 2,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::PlayerNoLongerHasItem(player_no_longer_has_item)}))
@ -525,13 +525,13 @@ async fn test_deposit_stacked_item_with_full_stack_in_bank() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -603,13 +603,13 @@ async fn test_deposit_individual_item_in_full_bank() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -675,13 +675,13 @@ async fn test_deposit_stacked_item_in_full_bank() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -761,13 +761,13 @@ async fn test_deposit_stacked_item_in_full_bank_with_partial_stack() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -775,7 +775,7 @@ async fn test_deposit_stacked_item_in_full_bank_with_partial_stack() {
item_amount: 2, item_amount: 2,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let bank_items = entity_gateway.get_character_bank(&char1.id, &item::BankName("".into())).await.unwrap(); let bank_items = entity_gateway.get_character_bank(&char1.id, &item::BankName("".into())).await.unwrap();
assert_eq!(bank_items.items.len(), 200); assert_eq!(bank_items.items.len(), 200);
@ -801,13 +801,13 @@ async fn test_deposit_meseta() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -815,7 +815,7 @@ async fn test_deposit_meseta() {
item_amount: 0, item_amount: 0,
meseta_amount: 23, meseta_amount: 23,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
let c1_bank_meseta = entity_gateway.get_bank_meseta(&char1.id, &item::BankName("".into())).await.unwrap(); let c1_bank_meseta = entity_gateway.get_bank_meseta(&char1.id, &item::BankName("".into())).await.unwrap();
@ -838,13 +838,13 @@ async fn test_deposit_too_much_meseta() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -877,13 +877,13 @@ async fn test_deposit_meseta_when_bank_is_maxed() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -935,13 +935,13 @@ async fn test_withdraw_individual_item() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -949,7 +949,7 @@ async fn test_withdraw_individual_item() {
item_amount: 0, item_amount: 0,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)}))
@ -995,13 +995,13 @@ async fn test_withdraw_stacked_item() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1009,7 +1009,7 @@ async fn test_withdraw_stacked_item() {
item_amount: 3, item_amount: 3,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)}))
@ -1054,13 +1054,13 @@ async fn test_withdraw_partial_stacked_item() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1068,7 +1068,7 @@ async fn test_withdraw_partial_stacked_item() {
item_amount: 2, item_amount: 2,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)}))
@ -1132,13 +1132,13 @@ async fn test_withdraw_stacked_item_with_stack_already_in_inventory() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1146,7 +1146,7 @@ async fn test_withdraw_stacked_item_with_stack_already_in_inventory() {
item_amount: 2, item_amount: 2,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 2); assert!(packets.len() == 2);
assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)})) assert!(matches!(&packets[1], (ClientId(2), SendShipPacket::Message(Message {msg: GameMessage::CreateItem(create_item)}))
@ -1204,13 +1204,13 @@ async fn test_withdraw_stacked_item_with_full_stack_in_inventory() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1282,13 +1282,13 @@ async fn test_withdraw_individual_item_in_full_inventory() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1350,13 +1350,13 @@ async fn test_withdraw_stacked_item_in_full_inventory() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1437,13 +1437,13 @@ async fn test_withdraw_stacked_item_in_full_inventory_with_partial_stack() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x20000, item_id: 0x20000,
@ -1451,7 +1451,7 @@ async fn test_withdraw_stacked_item_in_full_inventory_with_partial_stack() {
item_amount: 2, item_amount: 2,
meseta_amount: 0, meseta_amount: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let bank_items = entity_gateway.get_character_bank(&char1.id, &item::BankName("".into())).await.unwrap(); let bank_items = entity_gateway.get_character_bank(&char1.id, &item::BankName("".into())).await.unwrap();
assert!(bank_items.items.len() == 0); assert!(bank_items.items.len() == 0);
@ -1480,13 +1480,13 @@ async fn test_withdraw_meseta() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -1494,7 +1494,7 @@ async fn test_withdraw_meseta() {
item_amount: 0, item_amount: 0,
meseta_amount: 23, meseta_amount: 23,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
let c1_bank_meseta = entity_gateway.get_bank_meseta(&char1.id, &item::BankName("".into())).await.unwrap(); let c1_bank_meseta = entity_gateway.get_bank_meseta(&char1.id, &item::BankName("".into())).await.unwrap();
@ -1517,13 +1517,13 @@ async fn test_withdraw_too_much_meseta() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packet = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packet = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -1556,13 +1556,13 @@ async fn test_withdraw_meseta_inventory_is_maxed() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankRequest(BankRequest {
client: 0, client: 0,
target: 0, target: 0,
unknown: 0, unknown: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packet = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction { let packet = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BankInteraction(BankInteraction {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,

View File

@ -21,9 +21,9 @@ async fn test_save_options() {
log_in_char(&mut ship, ClientId(1), "a1", "a").await; log_in_char(&mut ship, ClientId(1), "a1", "a").await;
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
ship.handle(ClientId(1), &RecvShipPacket::SaveOptions(SaveOptions{ ship.handle(ClientId(1), RecvShipPacket::SaveOptions(SaveOptions{
options: 12345, options: 12345,
})).await.unwrap().for_each(drop); })).await.unwrap();
let characters = entity_gateway.get_characters_by_user(&user1).await.unwrap(); let characters = entity_gateway.get_characters_by_user(&user1).await.unwrap();
let char = characters[0].as_ref().unwrap(); let char = characters[0].as_ref().unwrap();
@ -67,7 +67,7 @@ async fn test_change_keyboard_mappings() {
// update from default2 to default4 // update from default2 to default4
// the client simply sends the full 364 bytes... // the client simply sends the full 364 bytes...
ship.handle(ClientId(1), &RecvShipPacket::KeyboardConfig(KeyboardConfig{ ship.handle(ClientId(1), RecvShipPacket::KeyboardConfig(KeyboardConfig{
keyboard_config: [ keyboard_config: [
0, 0, 0, 0, 117, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 117, 0, 0, 0, 0, 0, 0, 0, 105, 0, 0, 0,
0, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 115, 0, 0, 0, 0, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 115, 0, 0, 0,
@ -93,7 +93,7 @@ async fn test_change_keyboard_mappings() {
0, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0,
0, 0, 0, 0, 51, 0, 0, 0, 1, 0, 0, 0 0, 0, 0, 0, 51, 0, 0, 0, 1, 0, 0, 0
], ],
})).await.unwrap().for_each(drop); })).await.unwrap();
let characters = entity_gateway.get_characters_by_user(&user1).await.unwrap(); let characters = entity_gateway.get_characters_by_user(&user1).await.unwrap();
let char = characters[0].as_ref().unwrap(); let char = characters[0].as_ref().unwrap();

View File

@ -0,0 +1,18 @@
/*
use elseware::common::serverstate::{ClientId, ServerState};
use elseware::entity::gateway::{EntityGateway, InMemoryGateway};
use elseware::entity::item;
use elseware::ship::ship::{ShipServerState, RecvShipPacket};
use libpso::packet::ship::*;
use libpso::packet::messages::*;
#[path = "common.rs"]
mod common;
use common::*;
#[async_std::test]
async fn test_character_data_includes_material_usage() {
}
*/

View File

@ -3,6 +3,7 @@ use elseware::entity::gateway::{EntityGateway, InMemoryGateway};
use elseware::common::leveltable::CharacterLevelTable; use elseware::common::leveltable::CharacterLevelTable;
use elseware::ship::ship::{ShipServerState, SendShipPacket, RecvShipPacket}; use elseware::ship::ship::{ShipServerState, SendShipPacket, RecvShipPacket};
use elseware::ship::monster::MonsterType; use elseware::ship::monster::MonsterType;
use elseware::ship::location::RoomId;
use libpso::packet::ship::*; use libpso::packet::ship::*;
use libpso::packet::messages::*; use libpso::packet::messages::*;
@ -25,27 +26,30 @@ async fn test_character_gains_exp() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let (enemy_id, exp) = { let (enemy_id, exp) = {
let room = ship.blocks.0[0].rooms[0].as_ref().unwrap(); //let room = ship.blocks.0[0].rooms.get(RoomId(0)).as_ref().unwrap();
let (enemy_id, map_enemy) = (0..).filter_map(|i| { ship.blocks.0[0].rooms.with(RoomId(0), |room| Box::pin(async move {
room.maps.enemy_by_id(i).map(|enemy| { let (enemy_id, map_enemy) = (0..).filter_map(|i| {
(i, enemy) room.maps.enemy_by_id(i).map(|enemy| {
}).ok() (i, enemy)
}).next().unwrap(); }).ok()
let map_enemy_stats = room.monster_stats.get(&map_enemy.monster).unwrap(); }).next().unwrap();
(enemy_id, map_enemy_stats.exp) let map_enemy_stats = room.monster_stats.get(&map_enemy.monster).unwrap();
(enemy_id, map_enemy_stats.exp)
})).await.unwrap()
}; };
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp{ ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp {
client: enemy_id as u8, client: enemy_id as u8,
target: 16, target: 16,
enemy_id: enemy_id as u16, enemy_id: enemy_id as u16,
client_id: 0, client_id: 0,
unused: 0, unused: 0,
last_hitter: 1, last_hitter: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1 = ship.clients.get(&ClientId(1)).unwrap(); ship.clients.with(ClientId(1), |client| Box::pin(async move {
assert!(exp == c1.character.exp); assert!(exp == client.character.exp);
})).await;
} }
#[async_std::test] #[async_std::test]
@ -63,29 +67,29 @@ async fn test_character_levels_up() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let enemy_id = { let enemy_id = ship.blocks.0[0].rooms.with(RoomId(0), |room| Box::pin(async move {
let room = ship.blocks.0[0].rooms[0].as_ref().unwrap();
(0..).filter_map(|i| { (0..).filter_map(|i| {
room.maps.enemy_by_id(i).map(|_| { room.maps.enemy_by_id(i).map(|_| {
i i
}).ok() }).ok()
}).next().unwrap() }).next().unwrap()
}; })).await.unwrap();
let levelup_pkt = ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp{ let levelup_pkt = ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp {
client: enemy_id as u8, client: enemy_id as u8,
target: 16, target: 16,
enemy_id: enemy_id as u16, enemy_id: enemy_id as u16,
client_id: 0, client_id: 0,
unused: 0, unused: 0,
last_hitter: 1, last_hitter: 1,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(matches!(levelup_pkt[1].1, SendShipPacket::Message(Message {msg: GameMessage::PlayerLevelUp(PlayerLevelUp {lvl: 2, ..})}))); assert!(matches!(levelup_pkt[1].1, SendShipPacket::Message(Message {msg: GameMessage::PlayerLevelUp(PlayerLevelUp {lvl: 2, ..})})));
let leveltable = CharacterLevelTable::default(); let leveltable = CharacterLevelTable::default();
let c1 = ship.clients.get(&ClientId(1)).unwrap(); ship.clients.with(ClientId(1), |client| Box::pin(async move {
assert!(leveltable.get_level_from_exp(c1.character.char_class, c1.character.exp) == 2); assert!(leveltable.get_level_from_exp(client.character.char_class, client.character.exp) == 2)
})).await.unwrap();
} }
#[async_std::test] #[async_std::test]
@ -102,34 +106,36 @@ async fn test_character_levels_up_multiple_times() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let (enemy_id, exp) = { let (enemy_id, exp) = {
let room = ship.blocks.0[0].rooms[0].as_ref().unwrap(); ship.blocks.0[0].rooms.with(RoomId(0), |room| Box::pin(async move {
let (enemy_id, map_enemy) = (0..).filter_map(|i| { let (enemy_id, map_enemy) = (0..).filter_map(|i| {
room.maps.enemy_by_id(i).ok().and_then(|enemy| { room.maps.enemy_by_id(i).ok().and_then(|enemy| {
if enemy.monster == MonsterType::DarkFalz2 { if enemy.monster == MonsterType::DarkFalz2 {
Some((i, enemy)) Some((i, enemy))
} }
else { else {
None None
} }
}) })
}).next().unwrap(); }).next().unwrap();
let map_enemy_stats = room.monster_stats.get(&map_enemy.monster).unwrap(); let map_enemy_stats = room.monster_stats.get(&map_enemy.monster).unwrap();
(enemy_id, map_enemy_stats.exp) (enemy_id, map_enemy_stats.exp)
})).await.unwrap()
}; };
let levelup_pkt = ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp{ let levelup_pkt = ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp {
client: enemy_id as u8, client: enemy_id as u8,
target: 16, target: 16,
enemy_id: enemy_id as u16, enemy_id: enemy_id as u16,
client_id: 0, client_id: 0,
unused: 0, unused: 0,
last_hitter: 1, last_hitter: 1,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(matches!(levelup_pkt[1].1, SendShipPacket::Message(Message {msg: GameMessage::PlayerLevelUp(PlayerLevelUp {lvl: 8, ..})}))); assert!(matches!(levelup_pkt[1].1, SendShipPacket::Message(Message {msg: GameMessage::PlayerLevelUp(PlayerLevelUp {lvl: 8, ..})})));
let c1 = ship.clients.get(&ClientId(1)).unwrap(); let c1 = ship.clients.with(ClientId(1), |client| Box::pin(async move {
assert!(exp == c1.character.exp); assert!(exp == client.character.exp);
})).await;
} }
#[async_std::test] #[async_std::test]
@ -151,8 +157,7 @@ async fn test_one_character_gets_full_exp_and_other_attacker_gets_partial() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
let (enemy_id, exp) = { let (enemy_id, exp) = ship.blocks.0[0].rooms.with(RoomId(0), |room| Box::pin(async move {
let room = ship.blocks.0[0].rooms[0].as_ref().unwrap();
let (enemy_id, map_enemy) = (0..).filter_map(|i| { let (enemy_id, map_enemy) = (0..).filter_map(|i| {
room.maps.enemy_by_id(i).ok().and_then(|enemy| { room.maps.enemy_by_id(i).ok().and_then(|enemy| {
if enemy.monster == MonsterType::DarkFalz2 { if enemy.monster == MonsterType::DarkFalz2 {
@ -165,28 +170,30 @@ async fn test_one_character_gets_full_exp_and_other_attacker_gets_partial() {
}).next().unwrap(); }).next().unwrap();
let map_enemy_stats = room.monster_stats.get(&map_enemy.monster).unwrap(); let map_enemy_stats = room.monster_stats.get(&map_enemy.monster).unwrap();
(enemy_id, map_enemy_stats.exp) (enemy_id, map_enemy_stats.exp)
}; })).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp{ ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp {
client: enemy_id as u8, client: enemy_id as u8,
target: 16, target: 16,
enemy_id: enemy_id as u16, enemy_id: enemy_id as u16,
client_id: 0, client_id: 0,
unused: 0, unused: 0,
last_hitter: 1, last_hitter: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp{ ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::RequestExp(RequestExp {
client: enemy_id as u8, client: enemy_id as u8,
target: 16, target: 16,
enemy_id: enemy_id as u16, enemy_id: enemy_id as u16,
client_id: 0, client_id: 0,
unused: 0, unused: 0,
last_hitter: 0, last_hitter: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1 = ship.clients.get(&ClientId(1)).unwrap(); ship.clients.with(ClientId(1), |client| Box::pin(async move {
let c2 = ship.clients.get(&ClientId(2)).unwrap(); assert!(client.character.exp == exp);
assert!(c1.character.exp == exp); })).await.unwrap();
assert!(c2.character.exp == (exp as f32 * 0.8) as u32); ship.clients.with(ClientId(2), |client| Box::pin(async move {
assert!(client.character.exp == (exp as f32 * 0.8) as u32);
})).await.unwrap();
} }

View File

@ -63,22 +63,22 @@ async fn test_equip_unit_from_equip_menu() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerEquipItem(PlayerEquipItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerEquipItem(PlayerEquipItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10001, item_id: 0x10001,
sub_menu: 9, sub_menu: 9,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
// case when someone tries to send invalid submenu? submenu is 9-12 in normal gameplay // case when someone tries to send invalid submenu? submenu is 9-12 in normal gameplay
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerEquipItem(PlayerEquipItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerEquipItem(PlayerEquipItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10002, item_id: 0x10002,
sub_menu: 14, sub_menu: 14,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let equips = entity_gateway.get_character_equips(&char1.id).await.unwrap(); let equips = entity_gateway.get_character_equips(&char1.id).await.unwrap();
assert_eq!(equips.unit[0].unwrap(), item::ItemEntityId(2)); assert_eq!(equips.unit[0].unwrap(), item::ItemEntityId(2));
@ -140,12 +140,12 @@ async fn test_unequip_armor_with_units() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUnequipItem(PlayerUnequipItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUnequipItem(PlayerUnequipItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let equips = entity_gateway.get_character_equips(&char1.id).await.unwrap(); let equips = entity_gateway.get_character_equips(&char1.id).await.unwrap();
assert!(equips.armor.is_none()); assert!(equips.armor.is_none());
@ -213,13 +213,13 @@ async fn test_sort_items() {
}).unwrap(); }).unwrap();
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::SortItems(SortItems { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::SortItems(SortItems {
client: 255, client: 255,
target: 255, target: 255,
item_ids: [0x10001u32, 0x10002, 0x10000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, item_ids: [0x10001u32, 0x10002, 0x10000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF], 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF],
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 3); assert_eq!(inventory_items.items.len(), 3);

View File

@ -51,7 +51,7 @@ async fn test_pick_up_individual_item() {
let p2_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap(); let p2_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap();
assert_eq!(p2_items.items.len(), 0); assert_eq!(p2_items.items.len(), 0);
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -60,20 +60,20 @@ async fn test_pick_up_individual_item() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(p1_items.items.len(), 0); assert_eq!(p1_items.items.len(), 0);
let p2_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap(); let p2_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap();
assert_eq!(p2_items.items.len(), 0); assert_eq!(p2_items.items.len(), 0);
ship.handle(ClientId(2), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(2), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(p1_items.items.len(), 0); assert_eq!(p1_items.items.len(), 0);
@ -129,7 +129,7 @@ async fn test_pick_up_item_stack_of_items_already_in_inventory() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -138,15 +138,15 @@ async fn test_pick_up_item_stack_of_items_already_in_inventory() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x210000, item_id: 0x210000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 1); assert_eq!(inventory_items.items.len(), 1);
@ -188,7 +188,7 @@ async fn test_pick_up_item_stack_of_items_not_already_held() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -197,15 +197,15 @@ async fn test_pick_up_item_stack_of_items_not_already_held() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x210000, item_id: 0x210000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 1); assert_eq!(inventory_items.items.len(), 1);
@ -254,7 +254,7 @@ async fn test_pick_up_meseta_when_inventory_full() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -262,22 +262,22 @@ async fn test_pick_up_meseta_when_inventory_full() {
room: 0, room: 0,
x: 0.0, x: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
amount: 23, amount: 23,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x00810001, item_id: 0x00810001,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 30); assert_eq!(inventory_items.items.len(), 30);
@ -345,7 +345,7 @@ async fn test_pick_up_partial_stacked_item_when_inventory_is_otherwise_full() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -354,15 +354,15 @@ async fn test_pick_up_partial_stacked_item_when_inventory_is_otherwise_full() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x210000, item_id: 0x210000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 30); assert_eq!(inventory_items.items.len(), 30);
@ -423,7 +423,7 @@ async fn test_can_not_pick_up_item_when_inventory_full() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -432,28 +432,28 @@ async fn test_can_not_pick_up_item_when_inventory_full() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x210000, item_id: 0x210000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(p1_items.items.len(), 30); assert_eq!(p1_items.items.len(), 30);
let p2_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap(); let p2_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap();
assert_eq!(p2_items.items.len(), 0); assert_eq!(p2_items.items.len(), 0);
ship.handle(ClientId(2), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(2), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x210000, item_id: 0x210000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(p1_items.items.len(), 30); assert_eq!(p1_items.items.len(), 30);
@ -478,7 +478,7 @@ async fn test_can_not_drop_more_meseta_than_is_held() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -486,9 +486,9 @@ async fn test_can_not_drop_more_meseta_than_is_held() {
room: 0, room: 0,
x: 0.0, x: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let split_attempt = ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem { let split_attempt = ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -545,7 +545,7 @@ async fn test_pick_up_stack_that_would_exceed_stack_limit() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -554,15 +554,15 @@ async fn test_pick_up_stack_that_would_exceed_stack_limit() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x210000, item_id: 0x210000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 0); assert!(packets.len() == 0);
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
@ -596,7 +596,7 @@ async fn test_can_not_pick_up_meseta_when_full() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -604,22 +604,22 @@ async fn test_can_not_pick_up_meseta_when_full() {
room: 0, room: 0,
x: 0.0, x: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
amount: 23, amount: 23,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x00810001, item_id: 0x00810001,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert!(packets.len() == 0); assert!(packets.len() == 0);
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
@ -650,7 +650,7 @@ async fn test_meseta_caps_at_999999_when_trying_to_pick_up_more() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
@ -658,22 +658,22 @@ async fn test_meseta_caps_at_999999_when_trying_to_pick_up_more() {
room: 0, room: 0,
x: 0.0, x: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem { ship.handle(ClientId(2), RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0xFFFFFFFF, item_id: 0xFFFFFFFF,
amount: 23, amount: 23,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x00810001, item_id: 0x00810001,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
let c2_meseta = entity_gateway.get_character_meseta(&char2.id).await.unwrap(); let c2_meseta = entity_gateway.get_character_meseta(&char2.id).await.unwrap();
@ -714,7 +714,7 @@ async fn test_player_drops_partial_stack_and_other_player_picks_it_up() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::DropCoordinates(DropCoordinates {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
@ -722,22 +722,22 @@ async fn test_player_drops_partial_stack_and_other_player_picks_it_up() {
room: 0, room: 0,
x: 0.0, x: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerNoLongerHasItem(PlayerNoLongerHasItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 2, amount: 2,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(2), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10003, item_id: 0x10003,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 1); assert_eq!(inventory_items.items.len(), 1);

View File

@ -43,11 +43,11 @@ async fn test_use_monomate() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 2); assert_eq!(inventory_items.items.len(), 2);
@ -90,16 +90,16 @@ async fn test_use_monomate_twice() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 2); assert_eq!(inventory_items.items.len(), 2);
@ -138,11 +138,11 @@ async fn test_use_last_monomate() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
@ -178,11 +178,11 @@ async fn test_use_nonstackable_tool() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 0); assert_eq!(inventory_items.items.len(), 0);
@ -219,21 +219,21 @@ async fn test_use_materials() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10001, item_id: 0x10001,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10001, item_id: 0x10001,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 2); assert_eq!(inventory_items.items.len(), 2);

View File

@ -58,12 +58,12 @@ async fn test_mag_feed() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
for _ in 0..7usize { for _ in 0..7usize {
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerFeedMag(PlayerFeedMag { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerFeedMag(PlayerFeedMag {
client: 0, client: 0,
target: 0, target: 0,
mag_id: 0x10000, mag_id: 0x10000,
item_id: 0x10001, item_id: 0x10001,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
} }
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
@ -115,7 +115,7 @@ async fn test_mag_change_owner() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerDropItem(PlayerDropItem {
client: 0, client: 0,
target: 0, target: 0,
unknown1: 0, unknown1: 0,
@ -124,15 +124,15 @@ async fn test_mag_change_owner() {
x: 0.0, x: 0.0,
y: 0.0, y: 0.0,
z: 0.0, z: 0.0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem { ship.handle(ClientId(2), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::PickupItem(PickupItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
map_area: 0, map_area: 0,
unknown: [0; 3] unknown: [0; 3]
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char2.id).await.unwrap();
assert_eq!(inventory_items.items.len(), 1); assert_eq!(inventory_items.items.len(), 1);
@ -198,11 +198,11 @@ async fn test_mag_cell() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerUseItem(PlayerUseItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10001, item_id: 0x10001,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let inventory_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
inventory_items.items[0].with_individual(|item| { inventory_items.items[0].with_individual(|item| {

View File

@ -2,6 +2,7 @@ use elseware::common::serverstate::{ClientId, ServerState};
use elseware::entity::gateway::{EntityGateway, InMemoryGateway}; use elseware::entity::gateway::{EntityGateway, InMemoryGateway};
use elseware::entity::item; use elseware::entity::item;
use elseware::ship::ship::{ShipServerState, RecvShipPacket, SendShipPacket}; use elseware::ship::ship::{ShipServerState, RecvShipPacket, SendShipPacket};
use elseware::ship::location::RoomId;
use libpso::packet::ship::*; use libpso::packet::ship::*;
//use libpso::packet::messages::*; //use libpso::packet::messages::*;
@ -63,11 +64,11 @@ async fn test_item_ids_reset_when_rejoining_rooms() {
join_lobby(&mut ship, ClientId(2)).await; join_lobby(&mut ship, ClientId(2)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let p = ship.handle(ClientId(2), &RecvShipPacket::MenuSelect(MenuSelect { let p = ship.handle(ClientId(2), RecvShipPacket::MenuSelect(MenuSelect {
menu: ROOM_MENU_ID, menu: ROOM_MENU_ID,
item: 0, item: 0,
})).await.unwrap().collect::<Vec<_>>(); })).await.unwrap();
ship.handle(ClientId(2), &RecvShipPacket::DoneBursting(DoneBursting {})).await.unwrap().for_each(drop); ship.handle(ClientId(2), RecvShipPacket::DoneBursting(DoneBursting {})).await.unwrap();
match &p[1].1 { match &p[1].1 {
SendShipPacket::AddToRoom(add_to) => { SendShipPacket::AddToRoom(add_to) => {
@ -81,10 +82,10 @@ async fn test_item_ids_reset_when_rejoining_rooms() {
leave_room(&mut ship, ClientId(2)).await; leave_room(&mut ship, ClientId(2)).await;
let p = ship.handle(ClientId(2), &RecvShipPacket::MenuSelect(MenuSelect { let p = ship.handle(ClientId(2), RecvShipPacket::MenuSelect(MenuSelect {
menu: ROOM_MENU_ID, menu: ROOM_MENU_ID,
item: 0, item: 0,
})).await.unwrap().collect::<Vec<_>>(); })).await.unwrap();
match &p[1].1 { match &p[1].1 {
SendShipPacket::AddToRoom(add_to) => { SendShipPacket::AddToRoom(add_to) => {
@ -108,12 +109,12 @@ async fn test_load_rare_monster_default_appear_rates() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
// assume episode 1 // assume episode 1
let room = ship.blocks.0[0].rooms[0].as_ref().unwrap(); ship.blocks.0[0].rooms.with(RoomId(0), |room| Box::pin(async move {
println!("rare monster table: {:?}", room.rare_monster_table); let rates = &*room.rare_monster_table;
let rates = &*room.rare_monster_table; for (_monster, rate) in rates.clone().appear_rate {
for (_monster, rate) in rates.clone().appear_rate { assert_eq!(rate, 0.001953125f32); // 1/512 = 0.001953125
assert_eq!(rate, 0.001953125f32); // 1/512 = 0.001953125 }
} })).await.unwrap();
} }
#[async_std::test] #[async_std::test]
@ -127,7 +128,7 @@ async fn test_set_valid_quest_group() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::RequestQuestList(RequestQuestList{flag: 0})).await.unwrap().collect::<Vec<_>>(); let packets = ship.handle(ClientId(1), RecvShipPacket::RequestQuestList(RequestQuestList{flag: 0})).await.unwrap();
match &packets[0].1 { match &packets[0].1 {
SendShipPacket::QuestCategoryList(quest_cat) => { SendShipPacket::QuestCategoryList(quest_cat) => {
assert!(String::from_utf16_lossy(&quest_cat.quest_categories[0].name).starts_with("Retrieval")); assert!(String::from_utf16_lossy(&quest_cat.quest_categories[0].name).starts_with("Retrieval"));
@ -147,7 +148,7 @@ async fn test_set_invalid_quest_group() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::RequestQuestList(RequestQuestList{flag: 100})).await.unwrap().collect::<Vec<_>>(); let packets = ship.handle(ClientId(1), RecvShipPacket::RequestQuestList(RequestQuestList{flag: 100})).await.unwrap();
match &packets[0].1 { match &packets[0].1 {
SendShipPacket::QuestCategoryList(quest_cat) => { SendShipPacket::QuestCategoryList(quest_cat) => {
// flag > quest category length should take the highest value allowed for quest category which is 1 in multimode (for govt quests) and 0 in other modes. // flag > quest category length should take the highest value allowed for quest category which is 1 in multimode (for govt quests) and 0 in other modes.
@ -174,7 +175,7 @@ async fn test_get_room_info() {
join_lobby(&mut ship, ClientId(2)).await; join_lobby(&mut ship, ClientId(2)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let _expectedmsg = String::from("1 Lv1 GODmar\nHUmar Pioneer 2\n"); let _expectedmsg = String::from("1 Lv1 GODmar\nHUmar Pioneer 2\n");
let packets = ship.handle(ClientId(2), &RecvShipPacket::MenuDetail(MenuDetail{menu: 3, item: 0})).await.unwrap().collect::<Vec<_>>(); let packets = ship.handle(ClientId(2), RecvShipPacket::MenuDetail(MenuDetail{menu: 3, item: 0})).await.unwrap();
assert!(matches!(&packets[0], (ClientId(2), SendShipPacket::SmallLeftDialog(SmallLeftDialog{ assert!(matches!(&packets[0], (ClientId(2), SendShipPacket::SmallLeftDialog(SmallLeftDialog{
padding: [17664, 1157645568], padding: [17664, 1157645568],
msg: _expectedmsg, msg: _expectedmsg,
@ -196,7 +197,7 @@ async fn test_cannot_get_room_info_after_room_is_closed() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
leave_room(&mut ship, ClientId(1)).await; leave_room(&mut ship, ClientId(1)).await;
let _expectedmsg = String::from("Game is no longer active!\0"); let _expectedmsg = String::from("Game is no longer active!\0");
let packets = ship.handle(ClientId(2), &RecvShipPacket::MenuDetail(MenuDetail{menu: 3, item: 0})).await.unwrap().collect::<Vec<_>>(); let packets = ship.handle(ClientId(2), RecvShipPacket::MenuDetail(MenuDetail{menu: 3, item: 0})).await.unwrap();
assert!(matches!(&packets[0], (ClientId(2), SendShipPacket::SmallLeftDialog(SmallLeftDialog{ assert!(matches!(&packets[0], (ClientId(2), SendShipPacket::SmallLeftDialog(SmallLeftDialog{
padding: [17664, 1157645568], padding: [17664, 1157645568],
msg: _expectedmsg, msg: _expectedmsg,
@ -218,7 +219,7 @@ async fn test_cannot_join_room_after_its_closed() {
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
leave_room(&mut ship, ClientId(1)).await; leave_room(&mut ship, ClientId(1)).await;
let _expectedmsg = String::from("This room no longer exists!\0"); let _expectedmsg = String::from("This room no longer exists!\0");
let packets = ship.handle(ClientId(2), &RecvShipPacket::MenuSelect(MenuSelect{menu: 3, item: 0})).await.unwrap().collect::<Vec<_>>(); let packets = ship.handle(ClientId(2), RecvShipPacket::MenuSelect(MenuSelect{menu: 3, item: 0})).await.unwrap();
assert!(matches!(&packets[0], (ClientId(2), SendShipPacket::SmallDialog(SmallDialog{ assert!(matches!(&packets[0], (ClientId(2), SendShipPacket::SmallDialog(SmallDialog{
padding: [0,0], padding: [0,0],
msg: _expectedmsg, // wow yes cool rust is so great literally the best i can't put a String::from() directly in here. msg: _expectedmsg, // wow yes cool rust is so great literally the best i can't put a String::from() directly in here.

View File

@ -1,7 +1,7 @@
use elseware::common::serverstate::{ClientId, ServerState}; use elseware::common::serverstate::{ClientId, ServerState};
use elseware::entity::gateway::{EntityGateway, InMemoryGateway}; use elseware::entity::gateway::{EntityGateway, InMemoryGateway};
use elseware::entity::item; use elseware::entity::item;
use elseware::ship::ship::{ShipServerState, RecvShipPacket, SendShipPacket}; use elseware::ship::ship::{ShipServerState, RecvShipPacket, SendShipPacket, ShipError};
use elseware::ship::room::Difficulty; use elseware::ship::room::Difficulty;
use elseware::ship::items::state::ItemStateError; use elseware::ship::items::state::ItemStateError;
@ -27,11 +27,11 @@ async fn test_player_opens_weapon_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 1 shop_type: 1
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert_eq!(packets.len(), 1); assert_eq!(packets.len(), 1);
match &packets[0].1 { match &packets[0].1 {
@ -57,11 +57,11 @@ async fn test_player_opens_tool_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 0 shop_type: 0
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert_eq!(packets.len(), 1); assert_eq!(packets.len(), 1);
match &packets[0].1 { match &packets[0].1 {
@ -87,11 +87,11 @@ async fn test_player_opens_armor_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 2 shop_type: 2
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert_eq!(packets.len(), 1); assert_eq!(packets.len(), 1);
match &packets[0].1 { match &packets[0].1 {
@ -118,12 +118,12 @@ async fn test_player_buys_from_weapon_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 1 shop_type: 1
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -131,7 +131,7 @@ async fn test_player_buys_from_weapon_shop() {
shop_index: 0, shop_index: 0,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert!(c1_meseta.0 < 999999); assert!(c1_meseta.0 < 999999);
@ -156,12 +156,12 @@ async fn test_player_buys_from_tool_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 0, shop_type: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -169,7 +169,7 @@ async fn test_player_buys_from_tool_shop() {
shop_index: 0, shop_index: 0,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert!(c1_meseta.0 < 999999); assert!(c1_meseta.0 < 999999);
@ -193,12 +193,12 @@ async fn test_player_buys_multiple_from_tool_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 0, shop_type: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -206,7 +206,7 @@ async fn test_player_buys_multiple_from_tool_shop() {
shop_index: 0, shop_index: 0,
amount: 5, amount: 5,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 999749); assert_eq!(c1_meseta.0, 999749);
@ -234,12 +234,12 @@ async fn test_player_buys_from_armor_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 2 shop_type: 2
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -247,7 +247,7 @@ async fn test_player_buys_from_armor_shop() {
shop_index: 0, shop_index: 0,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert!(c1_meseta.0 < 999999); assert!(c1_meseta.0 < 999999);
@ -288,12 +288,12 @@ async fn test_player_sells_3_attr_weapon_to_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 4406); assert_eq!(c1_meseta.0, 4406);
@ -319,12 +319,12 @@ async fn test_other_clients_see_purchase() {
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Normal).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Normal).await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 1 shop_type: 1
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -332,7 +332,7 @@ async fn test_other_clients_see_purchase() {
shop_index: 0, shop_index: 0,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert_eq!(packets.len(), 1); assert_eq!(packets.len(), 1);
assert_eq!(packets[0].0, ClientId(2)); assert_eq!(packets[0].0, ClientId(2));
@ -370,12 +370,12 @@ async fn test_other_clients_see_stacked_purchase() {
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Normal).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Normal).await;
join_room(&mut ship, ClientId(2), 0).await; join_room(&mut ship, ClientId(2), 0).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 1 shop_type: 1
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -383,7 +383,7 @@ async fn test_other_clients_see_stacked_purchase() {
shop_index: 0, shop_index: 0,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
assert_eq!(packets.len(), 1); assert_eq!(packets.len(), 1);
assert_eq!(packets[0].0, ClientId(2)); assert_eq!(packets[0].0, ClientId(2));
@ -406,12 +406,12 @@ async fn test_buying_item_without_enough_mseseta() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Normal).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Normal).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 1 shop_type: 1
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -444,12 +444,12 @@ async fn test_player_double_buys_from_tool_shop() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 0, shop_type: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -457,8 +457,8 @@ async fn test_player_double_buys_from_tool_shop() {
shop_index: 0, shop_index: 0,
amount: 3, amount: 3,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10001, item_id: 0x10001,
@ -466,8 +466,8 @@ async fn test_player_double_buys_from_tool_shop() {
shop_index: 1, shop_index: 1,
amount: 2, amount: 2,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10002, item_id: 0x10002,
@ -475,7 +475,7 @@ async fn test_player_double_buys_from_tool_shop() {
shop_index: 0, shop_index: 0,
amount: 4, amount: 4,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert!(c1_meseta.0 < 999999); assert!(c1_meseta.0 < 999999);
@ -509,11 +509,11 @@ async fn test_techs_disappear_from_shop_when_bought() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 0, shop_type: 0,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
let first_tech = match &packets[0].1 { let first_tech = match &packets[0].1 {
SendShipPacket::Message(Message {msg: GameMessage::ShopList(shop_list)}) => { SendShipPacket::Message(Message {msg: GameMessage::ShopList(shop_list)}) => {
@ -527,7 +527,7 @@ async fn test_techs_disappear_from_shop_when_bought() {
_ => panic!(""), _ => panic!(""),
}; };
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -535,8 +535,8 @@ async fn test_techs_disappear_from_shop_when_bought() {
shop_index: first_tech as u8, shop_index: first_tech as u8,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10001, item_id: 0x10001,
@ -544,7 +544,7 @@ async fn test_techs_disappear_from_shop_when_bought() {
shop_index: first_tech as u8, shop_index: first_tech as u8,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
p1_items.items[0].with_individual(|item1| { p1_items.items[0].with_individual(|item1| {
@ -571,11 +571,11 @@ async fn test_units_disappear_from_shop_when_bought() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await; create_room_with_difficulty(&mut ship, ClientId(1), "room", "", Difficulty::Ultimate).await;
let packets = ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest { let packets = ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::ShopRequest(ShopRequest {
client: 255, client: 255,
target: 255, target: 255,
shop_type: 2, shop_type: 2,
})))).await.unwrap().collect::<Vec<_>>(); })))).await.unwrap();
let first_unit = match &packets[0].1 { let first_unit = match &packets[0].1 {
SendShipPacket::Message(Message {msg: GameMessage::ShopList(shop_list)}) => { SendShipPacket::Message(Message {msg: GameMessage::ShopList(shop_list)}) => {
@ -589,7 +589,7 @@ async fn test_units_disappear_from_shop_when_bought() {
_ => panic!(""), _ => panic!(""),
}; };
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10000, item_id: 0x10000,
@ -597,8 +597,8 @@ async fn test_units_disappear_from_shop_when_bought() {
shop_index: first_unit as u8, shop_index: first_unit as u8,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
ship.handle(ClientId(1), &RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem { ship.handle(ClientId(1), RecvShipPacket::DirectMessage(DirectMessage::new(0, GameMessage::BuyItem(BuyItem {
client: 255, client: 255,
target: 255, target: 255,
item_id: 0x10001, item_id: 0x10001,
@ -606,7 +606,7 @@ async fn test_units_disappear_from_shop_when_bought() {
shop_index: first_unit as u8, shop_index: first_unit as u8,
amount: 1, amount: 1,
unknown1: 0, unknown1: 0,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap(); let p1_items = entity_gateway.get_character_inventory(&char1.id).await.unwrap();
p1_items.items[0].with_individual(|item1| { p1_items.items[0].with_individual(|item1| {
@ -649,12 +649,12 @@ async fn test_player_sells_untekked_weapon() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 1); assert_eq!(c1_meseta.0, 1);
@ -693,12 +693,12 @@ async fn test_player_sells_rare_item() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 10); assert_eq!(c1_meseta.0, 10);
@ -736,12 +736,12 @@ async fn test_player_sells_partial_photon_drop_stack() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 3, amount: 3,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 3000); assert_eq!(c1_meseta.0, 3000);
@ -777,12 +777,12 @@ async fn test_player_sells_basic_frame() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 24); assert_eq!(c1_meseta.0, 24);
@ -818,12 +818,12 @@ async fn test_player_sells_max_frame() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 74); assert_eq!(c1_meseta.0, 74);
@ -858,12 +858,12 @@ async fn test_player_sells_basic_barrier() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 69); assert_eq!(c1_meseta.0, 69);
@ -898,12 +898,12 @@ async fn test_player_sells_max_barrier() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 122); assert_eq!(c1_meseta.0, 122);
@ -937,12 +937,12 @@ async fn test_player_sells_1_star_minusminus_unit() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 125); assert_eq!(c1_meseta.0, 125);
@ -976,12 +976,12 @@ async fn test_player_sells_5_star_plusplus_unit() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 625); assert_eq!(c1_meseta.0, 625);
@ -1017,12 +1017,12 @@ async fn test_player_sells_rare_frame() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 10); assert_eq!(c1_meseta.0, 10);
@ -1057,12 +1057,12 @@ async fn test_player_sells_rare_barrier() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 10); assert_eq!(c1_meseta.0, 10);
@ -1096,12 +1096,12 @@ async fn test_player_sells_rare_unit() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.unwrap().for_each(drop); })))).await.unwrap();
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 10); assert_eq!(c1_meseta.0, 10);
@ -1136,13 +1136,14 @@ async fn test_player_cant_sell_if_meseta_would_go_over_max() {
join_lobby(&mut ship, ClientId(1)).await; join_lobby(&mut ship, ClientId(1)).await;
create_room(&mut ship, ClientId(1), "room", "").await; create_room(&mut ship, ClientId(1), "room", "").await;
let ack = ship.handle(ClientId(1), &RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem { let ack = ship.handle(ClientId(1), RecvShipPacket::Message(Message::new(GameMessage::PlayerSoldItem(PlayerSoldItem {
client: 0, client: 0,
target: 0, target: 0,
item_id: 0x10000, item_id: 0x10000,
amount: 1, amount: 1,
})))).await.err().unwrap(); })))).await.err().unwrap();
assert!(matches!(ack.downcast::<ItemStateError>().unwrap(), ItemStateError::FullOfMeseta)); //assert_eq!(ack, ShipError::ItemStateError(ItemStateError::FullOfMeseta));
assert!(matches!(ack.downcast::<ShipError>().unwrap(), ShipError::ItemStateError(ItemStateError::FullOfMeseta)));
let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap(); let c1_meseta = entity_gateway.get_character_meseta(&char1.id).await.unwrap();
assert_eq!(c1_meseta.0, 999995); assert_eq!(c1_meseta.0, 999995);

File diff suppressed because it is too large Load Diff