CrystalServer

Struct CrystalServer 

Source
pub struct CrystalServer { /* private fields */ }
Expand description

A “bridge” between a server and the client.

First, you need to define (and connect to at any time)

let mut cs = CrystalServer::init("your-game-id");
// Setup here things like game version, callbacks, etc...
cs.connect().await?; // Connecting requires a mutable reference

Since you need to continuously call the cs.update() function, you can do this on a separate async task, but you need to do so after connecting to the server:

let cs = Arc::new(cs);
{
    let cs = cs.clone();
    tokio::spawn(async {
        loop {
            cs.update().await?; // Update client data...
            tokio::time::sleep(Duration::from_secs_f64(1.0 / 60.0)).await;
        }
    });
}

Or in a single rust task, which is easier to handle:

// On a new frame
cs.update().await?;
You shouldn't update this faster than once in a frame, this may have unintended consequences on the network usage of your game.

After making sure you’re always triggering this function once in a frame (at most), you may do anything else with the other functions.

Implementations§

Source§

impl CrystalServer

Source

pub fn init(game_id: &str) -> Self

Source

pub async fn connect(&mut self)

Try to establish a connection between the client and the server.

Source

pub async fn update(&self) -> IoResult<()>

Update the Crystal Server runtime. This ensures that things are kept up-to-date between the server and the client.

Source

pub async fn callback_set_room( &self, callback: Box<dyn FnMut() -> String + Sync + Send>, )

This is where you tell the other clients in which room you are The function receives 0 arguments and must return a String

static CURRENT_ROOM: LazyLock<Mutex<String>> = LazyLock::new(|| Mutex::new(String::from("kitchen")));

/// ...now I am in the living room
*CURRENT_ROOM.lock().unwrap() = String::from("living room");

And you’d tell that to the server through this function:

cs.callback_set_room(Box::new(|| CURRENT_ROOM.lock().unwrap().clone())).await;
Source

pub async fn callback_set_p2p( &self, callback: Box<dyn FnMut(Option<u64>, i16, Vec<Value>) + Sync + Send>, )

This is the callback when the client receives data from the server or another player. The function receives 3 arguments: Player ID: Option, Message ID: i64, Payload/Data: Vec, and must return nothing.

Source

pub async fn callback_set_register( &self, callback: Box<dyn FnMut(RegistrationCode) + Sync + Send>, )

This is the callback when a registration event has been carried out. The function receives 1 argument: Result: RegistrationCode, and must return nothing.

Source

pub async fn callback_set_login( &self, callback: Box<dyn FnMut(LoginCode, Option<DateTime<Utc>>, Option<String>) + Sync + Send>, )

This is the callback when a login event has been carried out. The function receives 1 argument: Result: LoginCode, and must return nothing.

Source

pub async fn callback_set_banned( &self, callback: Box<dyn FnMut(String, DateTime<Utc>) + Sync + Send>, )

This is the callback when the player has been banned while playing. The function receives 2 arguments: Reason: String, Unban Time: DateTime, and must return nothing.

Source

pub async fn callback_set_kicked( &self, callback: Box<dyn FnMut(String) + Sync + Send>, )

This is the callback when the player has been kicked while playing. The function receives 2 arguments: Reason: String, and must return nothing.

Source

pub async fn callback_set_disconnected( &self, callback: Box<dyn FnMut() + Sync + Send>, )

This is the callback when the client has disconnected from the server. The function receives 0 arguments and must return nothing.

Source

pub async fn callback_set_login_token( &self, callback: Box<dyn FnMut(String) + Sync + Send>, )

This is the callback when the client has disconnected from the server. The function receives 0 arguments and must return nothing.

The login-token is only valid once and only works for the game it was generated on.

Source

pub async fn callback_set_data_update( &self, callback: Box<dyn FnMut(DataUpdate) + Sync + Send>, )

This is the callback when an event has been triggered by the server. This may work as a replacement for all of the other callback functions except CrystalServer::callback_set_room. The function receives 1 argument, Data: DataUpdate and must return nothing.

Source

pub async fn is_connected(&self) -> bool

Checks if the client has an active connection to the server.

Source

pub async fn is_connecting(&self) -> bool

Checks if the client is trying to establish an active connection to the server.

Source

pub async fn is_loggedin(&self) -> bool

Check if the client is currently logged in.

Source

pub async fn get_ping(&self) -> f64

Obtain the ping between the client and the server in ms.

Source

pub async fn set_game_token(&self, token: &str)

Sets the Game Token so that the client may be able to log in.

The Game Token is like a “password” for your game and that the game the player is playing on must be the same one as the one in the server.

Source

pub async fn disconnect(&self)

Disconnects the client from an active connection with the server.

Source

pub async fn login(&self, username: &str, passw: &str) -> IoResult<()>

Try to log into an existing account.

The login result will be sent as a callback event. Use CrystalServer::callback_set_login and CrystalServer::callback_set_login_token respectively to obtain data from the login attempt.

Source

pub async fn login_with_token( &self, username: &str, token: &str, ) -> IoResult<()>

Try to log into an existing account using a login-token.

The login result will be sent as a callback event. Use CrystalServer::callback_set_login and CrystalServer::callback_set_login_token respectively to obtain data from the login attempt.

Source

pub async fn register( &self, username: &str, email: &str, passw: &str, repeat_passw: &str, ) -> IoResult<()>

Try to register a new account.

The register result will be sent as a callback event. Use CrystalServer::callback_set_login to obtain data from the registration attempt.

Source

pub async fn get_player_id(&self) -> Option<u64>

Obtain the current Player ID. Note that this will only return something if the player is logged in.

Source

pub async fn get_player_name(&self) -> Option<String>

Obtain the current Player Name. Note that this will only return something if the player is logged in.

Source

pub async fn set_variable(&self, name: &str, value: Value)

Sets a variable with the name and value provided.

Source

pub async fn remove_variable(&self, name: &str)

Removes a variable with the provided name.

Source

pub async fn iter_other_players(&self) -> impl Stream<Item = (u64, Player)>

An iterator to obtain the other connected players data. (data such as syncs, variables, etc.)

Source

pub async fn other_player_count(&self) -> usize

Gets the current amount of other players.

Source

pub async fn get_other_player(&self, pid: u64) -> Option<Player>

Gets the data of a player from the Player ID if the player is connected. If the player is not found, it returns None.

Source

pub async fn get_other_player_name(&self, name: &str) -> Option<(u64, Player)>

Gets the data of a player from the Player Name if the player is connected. /// If the player is not found, it returns None.

Source

pub async fn request_other_player_variable( &self, pid: u64, name: &str, callback: Option<PlayerVariableServerUpdate>, ) -> IoResult<()>

Force an update of a variable, note that this will only be useful if the player is not in the same room as you.

The result will be saved as normal and will be sent as a callback event. Use CrystalServer::callback_set_data_update or the callback variable to fetch it.

Source

pub async fn p2p( &self, target: PlayerRequest, message_id: i16, payload: Vec<Value>, ) -> IoResult<()>

Sends a message “peer-to-peer” to the requested target. The Message ID will allow you to quickly differentiate what message it’s supposed to be.

Source

pub async fn set_version(&self, version: f64) -> IoResult<()>

Sets the current game version.

Source

pub async fn get_version(&self) -> f64

Gets the current set version.

Source

pub async fn get_server_version(&self) -> f64

Gets the registered server version.

Source

pub async fn set_session(&self, session: &str) -> IoResult<()>

Sets the current game session.

Source

pub async fn get_session(&self) -> String

Gets the current set session.

Source

pub async fn get_open_playerini(&self) -> String

Gets the currently open playerini file. The result will be empty is no files are open.

Source

pub async fn open_playerini(&self, file: &str)

Opens a playerini file.

Source

pub async fn close_playerini(&self)

Closes the currently open playerini file.

Source

pub async fn has_playerini(&self, section: &str, key: &str) -> bool

Checks if the requested section & key exists in the currently open playerini file.

Source

pub async fn get_playerini(&self, section: &str, key: &str) -> Option<Value>

Returns the saved value in the section & key of the currently open playerini file. If the value is not found, it returns None.

Source

pub async fn set_playerini(&self, section: &str, key: &str, value: Value)

Saves a new value for the requested section & key of the currently open playerini file.

Source

pub async fn remove_playerini(&self, section: &str, key: &str)

Removes the saved value for the requested section & key of the currently open playerini file.

Source

pub async fn get_open_gameini(&self) -> String

Gets the currently open gameini file. The result will be empty is no files are open.

Source

pub async fn open_gameini(&self, file: &str)

Opens a gameini file.

Source

pub async fn close_gameini(&self)

Closes the currently open gameini file.

Source

pub async fn has_gameini(&self, section: &str, key: &str) -> bool

Checks if the requested section & key exists in the currently open gameini file.

Source

pub async fn get_gameini(&self, section: &str, key: &str) -> Option<Value>

Returns the saved value in the section & key of the currently open gameini file. If the value is not found, it returns None.

Source

pub async fn set_gameini(&self, section: &str, key: &str, value: Value)

Saves a new value for the requested section & key of the currently open gameini file.

Source

pub async fn remove_gameini(&self, section: &str, key: &str)

Removes the saved value for the requested section & key of the currently open gameini file.

Source

pub async fn has_achievement(&self, aid: u64) -> bool

Checks if an achievement exists.

Source

pub async fn get_achievement(&self, aid: u64) -> Option<Achievement>

Gets an achievement data. If it doesn’t exist it returns None.

Source

pub async fn has_reached_achievement(&self, aid: u64) -> bool

Checks if the player has reached an achievement.

Source

pub async fn get_reached_achievement(&self, aid: u64) -> Option<i64>

Get the timestamp (on Unix UTC) of when the achievement was unlocked. If the player hasn’t unlocked the achievement yet, it returns None.

Source

pub async fn reach_achievement(&self, aid: u64) -> IoResult<()>

Make the current player reach an achievement.

Source

pub async fn has_highscore(&self, hid: u64) -> bool

Checks if a highscore exists.

Source

pub async fn get_highscore(&self, hid: u64) -> Option<Highscore>

Gets a highscore data. If the highscore doesn’t exist, it returns None.

Source

pub async fn has_score_highscore(&self, hid: u64) -> bool

Checks if the player has a score on a highscore.

Source

pub async fn get_score_highscore(&self, hid: u64) -> Option<f64>

Gets the last recorded score from the player on this highscore. If the highscore doesn’t exist, it returns None.

Source

pub async fn set_score_highscore(&self, hid: u64, score: f64) -> IoResult<()>

Records a new player score on the specified highscore.

Source

pub async fn create_sync(&self, sync_type: SyncType, kind: i16) -> usize

Creates a new sync.

Source

pub async fn destroy_sync(&self, sync: usize)

Destroys a created sync.

Source

pub async fn set_variable_sync(&self, sync: usize, name: &str, value: Value)

Set a sync variable with the specified name and value.

Source

pub async fn remove_variable_sync(&self, sync: usize, name: &str)

Remove a sync variable with the specified name.

Source

pub async fn get_variable_other_sync( &self, pid: u64, sync: usize, name: &str, ) -> Option<Value>

Gets a sync variable from another player with the specified Sync ID and name.

Source

pub async fn has_variable_other_sync( &self, pid: u64, sync: usize, name: &str, ) -> Option<bool>

Checks if a sync variable exists of another player with the specified Sync ID and name. If the player or sync is not found, it returns None.

Source

pub async fn iter_other_syncs(&self) -> impl Stream<Item = SyncIter>

An iterator to obtain all the other players’ sync data. (data such as variables, current event, etc.)

Source

pub async fn is_player_admin(&self, pid: u64) -> bool

Checks if a player is an administrator.

Source

pub async fn get_player_admin(&self, pid: u64) -> Option<Administrator>

Obtains the administrator data of a player. If the player is not an administrator, it returns None.

Source

pub async fn player_kick(&self, pid: u64, reason: &str) -> IoResult<bool>

Kicks the specified player from the game. If the player doesn’t have permission to kick the player, the function will return false and nothing will happen. You can kick yourself with this function without any checks.

Source

pub async fn player_ban( &self, pid: u64, reason: &str, unban_time: DateTime<Utc>, ) -> IoResult<bool>

Bans the specified player from the game. If the player doesn’t have permission to ban the player, the function will return false and nothing will happen. You can ban yourself with this function without any checks.

Source

pub async fn player_unban(&self, pid: u64) -> IoResult<bool>

Unbans the specified player from the game. If the player doesn’t have permission to unban the player, the function will return false and nothing will happen.

Source

pub async fn logout(&self) -> IoResult<bool>

Logs out from the account currently playing in.

Source

pub async fn request_other_sync_variable( &self, pid: u64, slot: usize, name: &str, callback: Option<SyncVariableServerUpdate>, ) -> IoResult<()>

Force an update of a variable from a sync, note that this will only be useful if the player is not in the same room as you.

The result will be saved as normal and will be sent as a callback event. Use CrystalServer::callback_set_data_update or the callback variable to fetch it.

Source

pub async fn fetch_bdb( &self, name: &str, callback: Option<FetchBdbServerUpdate>, ) -> IoResult<()>

Get the data of a Binary Data Block.

The result will be saved as normal and will be sent as a callback event. Use CrystalServer::callback_set_data_update or the callback variable to fetch it.

Source

pub async fn set_bdb(&self, name: &str, data: Vec<u8>) -> IoResult<()>

Update the data of a Binary Data Block.

Source

pub async fn get_incoming_friends(&self) -> Option<IntSet<u64>>

Obtain the player’s incoming friend requests. If the player is not logged in, it returns None.

Source

pub async fn get_outgoing_friends(&self) -> Option<IntSet<u64>>

Obtain the player’s outgoing friend requests. If the player is not logged in, it returns None.

Source

pub async fn get_friends(&self) -> Option<IntSet<u64>>

Obtain the player’s current friends. If the player is not logged in, it returns None.

Source

pub async fn send_outgoing_friend(&self, pid: u64) -> IoResult<()>

Send a friend request to a player.

Source

pub async fn remove_outgoing_friend(&self, pid: u64) -> IoResult<()>

Cancel the sent friend request of a player.

Source

pub async fn deny_incoming_friend(&self, pid: u64) -> IoResult<()>

Deny the received friend request of a player.

Source

pub async fn accept_incoming_friend(&self, pid: u64) -> IoResult<()>

Accept the received the friend request of a player.

Source

pub async fn remove_friend(&self, pid: u64) -> IoResult<()>

Remove a friend from the player’s friend list.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V