Skip to content

Commit

Permalink
Merge branch 'dev' of https://github.com/SkyUOI/Zenith into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
wlywlywlywly committed Jun 23, 2024
2 parents b17fad5 + 7e68215 commit b5b596b
Show file tree
Hide file tree
Showing 15 changed files with 269 additions and 104 deletions.
7 changes: 7 additions & 0 deletions gdrust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions gdrust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ base = { path = "base" }
prost = "0"
prost-types = { version = "0", optional = true }
bytes = "1"
collection_literals = "1"

[dev-dependencies]
assert_cmd = "2"
Expand Down
11 changes: 10 additions & 1 deletion gdrust/proto/proto/connect.proto
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,13 @@ message Response {
string message = 2;
}

message CreateObj { string path = 1; }
message CreateObj {
string path = 1;
int32 id = 2;
}

message UpdateObj {
int32 id = 1;
int32 attr = 2;
bytes val = 3;
}
6 changes: 3 additions & 3 deletions gdrust/src/fight_items/block_drawer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl INode2D for BlockDrawer {
];
let mut staticbody = self.get_staticbody();
for i in 0..4 {
let mut colliison_obj = CollisionPolygon2D::new_alloc();
let mut collision_obj = CollisionPolygon2D::new_alloc();
let mut line = PackedVector2Array::new();
let start_point = points[i % 4];
let end_point = points[(i + 1) % 4];
Expand All @@ -66,8 +66,8 @@ impl INode2D for BlockDrawer {
let end_near = end_point + offset_vec;
line.push(end_near);
line.push(end_point);
colliison_obj.set_polygon(line);
staticbody.add_child(colliison_obj.upcast());
collision_obj.set_polygon(line);
staticbody.add_child(collision_obj.upcast());
}
}

Expand Down
4 changes: 2 additions & 2 deletions gdrust/src/fight_items/health_bar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ impl INode2D for HealthBar {
}
}

fn ready(&mut self) {}

fn draw(&mut self) {
// godot_print!("again!");
let start_pos = Vector2::new(Self::START_POSITION_X, Self::START_POSITION_Y);
Expand All @@ -47,6 +45,8 @@ impl INode2D for HealthBar {
.width(Self::WIDTH)
.done();
}

fn ready(&mut self) {}
}

#[godot_api()]
Expand Down
87 changes: 65 additions & 22 deletions gdrust/src/multi.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,27 @@
use crate::{get_multi_single, get_tokio_runtime, MultiSingle};
use ::proto::ProtoRequest;
use anyhow::anyhow;
use bytes::{Bytes, BytesMut};
use godot::classes::{INode, Node};
use godot::prelude::*;
use prost::Message;
use proto::connect::Join;
use std::collections::HashMap;
use std::process::{Child, Command};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::TcpStream;
use tokio::sync::mpsc;

use crate::{get_multi_single, get_tokio_runtime, MultiSingle};

pub struct MultiPlayerConnection {}

impl MultiPlayerConnection {}

enum Requests {
Proto(ProtoRequest),
Wrong(String),
ExitSuccess,
}

pub struct MultiManagerImpl {
clients: HashMap<usize, MultiPlayerConnection>,
/// 发送器
socket: Option<mpsc::Sender<Bytes>>,
receiver: Option<std::sync::mpsc::Receiver<Requests>>,
/// 接收读取到的指令
receiver: Option<std::sync::mpsc::Receiver<ProtoRequest>>,
is_host: bool,
}

async fn send(sender: mpsc::Sender<Bytes>, data: BytesMut) -> anyhow::Result<()> {
Expand All @@ -46,7 +41,7 @@ async fn write_loop(
}

async fn read_loop(
send_channel: std::sync::mpsc::Sender<Requests>,
send_channel: std::sync::mpsc::Sender<ProtoRequest>,
mut read_socket: OwnedReadHalf,
) -> anyhow::Result<()> {
let mut buf = BytesMut::new();
Expand All @@ -60,22 +55,20 @@ async fn read_loop(
if n == 0 {
if buf.is_empty() {
godot_print!("Connection closed");
send_channel.send(Requests::ExitSuccess)?;
break;
} else {
let err_msg = "Connection reset by peer";
godot_error!("{}", err_msg);
send_channel.send(Requests::Wrong(err_msg.to_string()))?;
return Err(anyhow::anyhow!(err_msg));
}
}
}
Ok(())
}

fn parse_request(buf: &BytesMut) -> Option<Requests> {
fn parse_request(buf: &BytesMut) -> Option<ProtoRequest> {
match Join::decode(&buf[..]) {
Ok(v) => Some(Requests::Proto(ProtoRequest::Join(v))),
Ok(v) => Some(ProtoRequest::Join(v)),
Err(_) => None,
}
}
Expand Down Expand Up @@ -123,14 +116,45 @@ impl MultiManagerImpl {
pub fn close(&mut self) {
self.socket = None;
}

pub fn send_data(&mut self, data: Bytes) {
let socket = self.socket.clone();
get_tokio_runtime().spawn(async {
match socket {
Some(socket) => {
socket.send(data).await?;
}
None => {
// Ignore in single mode
}
}
anyhow::Ok(())
});
}

pub fn alloc_id(&mut self) -> usize {
let socket = self.socket.clone();
// socket.unwrap().blocking_send(value);
// get_tokio_runtime().spawn(async {
// match socket {
// Some(socket) => {}
// None => {}
// }
// })
todo!()
}

pub fn is_host(&mut self, val: bool) {
self.is_host = val;
}
}

impl MultiManagerImpl {
pub fn new() -> Self {
Self {
clients: HashMap::new(),
socket: None,
receiver: None,
is_host: false,
}
}
}
Expand All @@ -139,21 +163,40 @@ impl MultiManagerImpl {
#[class(base = Node)]
pub struct MultiManager {
base: Base<Node>,
multi_impl: MultiSingle,
server: Option<Child>,
}

#[godot_api()]
impl INode for MultiManager {
fn init(base: Base<Node>) -> Self {
Self {
base,
multi_impl: get_multi_single().clone(),
}
Self { base, server: None }
}
}

#[godot_api()]
impl MultiManager {
#[func]
fn add_new_player(&mut self) {}

#[func]
fn set_up_server(&mut self) {
get_multi_single().lock().unwrap().is_host(true);
self.server = Some(
Command::new("your_command")
.spawn()
.expect("Failed to start process"),
);
}
}

impl Drop for MultiManager {
fn drop(&mut self) {
match &mut self.server {
None => {}
Some(data) => {
data.kill().expect("Stop server failed");
data.wait().expect("Waited failed");
}
}
}
}
8 changes: 4 additions & 4 deletions gdrust/src/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,6 @@ impl ICharacterBody2D for Player {
}
}

fn ready(&mut self) {
debug_check!(self)
}

fn physics_process(&mut self, delta: f64) {
let input_obj = Input::singleton();
let mut down_rate = 1.0;
Expand Down Expand Up @@ -148,6 +144,10 @@ impl ICharacterBody2D for Player {
}
}
}

fn ready(&mut self) {
debug_check!(self)
}
}

#[godot_api]
Expand Down
6 changes: 3 additions & 3 deletions gdrust/src/ui/multi_enter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ impl IButton for MultiEnter {
impl MultiEnter {
#[func]
fn connect_to_server(&mut self, ip: String) -> bool {
let mult_manager = get_multi_single();
let mut lock = mult_manager.lock().unwrap();
let multi_manager = get_multi_single();
let mut lock = multi_manager.lock().unwrap();
match lock.connect_to_server(ip) {
Ok(_) => true,
Err(err) => {
Expand All @@ -50,4 +50,4 @@ impl MultiEnter {
dialog.set_text(text.into());
dialog.popup_centered()
}
}
}
29 changes: 22 additions & 7 deletions gdrust/src/weapons/enchanted_sword.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,49 @@
use crate::get_multi_single;
use godot::{
classes::{ISprite2D, Sprite2D},
prelude::*,
};
use proto::connect;
use std::collections::HashMap;

#[derive(GodotClass)]
#[class(init, base = Sprite2D)]
#[class(base = Sprite2D)]
struct EnchantedSword {
properties: HashMap<String, Callable>,
properties: HashMap<String, Box<dyn Fn()>>,
base: Base<Sprite2D>,
}

#[godot_api]
impl ISprite2D for EnchantedSword {
fn init(base: Base<Sprite2D>) -> Self {
let mut properties = HashMap::new();
properties.insert(
"position".to_string(),
Box::new(|| {
// let data = connect::UpdateObj {};
let data = todo!();
get_multi_single().lock().unwrap().send_data(data)
}),
);
Self {
base,
properties: HashMap::new(),
}
}

fn get_property(&self, name: StringName) -> Option<Variant> {
match self.properties.get(&name.to_string()) {
None => {}
Some(val) => {
val.callv((&[self.base().to_variant()]).into());
}
Some(val) => val(),
}
None
}
}

#[godot_api]
impl EnchantedSword {
#[func]
/// 设置要检测的属性
fn set_monitor(&mut self, property_name: String, func: Callable) {
fn set_monitor(&mut self, property_name: String, func: Box<dyn Fn()>) {
self.properties.insert(property_name, func);
}
}
30 changes: 15 additions & 15 deletions gdrust/src/weapons/star_wrath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,6 @@ impl IArea2D for StarWrath {
}
}

fn ready(&mut self) {
// for debug
// 检查是否是当前场景
debug_check!(self);
if self.base().get_tree().unwrap().get_current_scene().unwrap()
== self.base().clone().upcast()
{
let mut fight_time = self.get_fight_timer();
fight_time.start();
self.start();
} else {
self.base_mut().hide();
}
}

fn process(&mut self, delta: f64) {
let mut animation = self.get_animation();
// animation.play_ex().name("Wave".into()).done();
Expand All @@ -61,6 +46,21 @@ impl IArea2D for StarWrath {
}
if self.state == State::Wave1 {}
}

fn ready(&mut self) {
// for debug
// 检查是否是当前场景
debug_check!(self);
if self.base().get_tree().unwrap().get_current_scene().unwrap()
== self.base().clone().upcast()
{
let mut fight_time = self.get_fight_timer();
fight_time.start();
self.start();
} else {
self.base_mut().hide();
}
}
}

#[godot_api]
Expand Down
Loading

0 comments on commit b5b596b

Please sign in to comment.