Initial commit
This commit is contained in:
commit
47f61c9eab
16 changed files with 8455 additions and 0 deletions
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
*.ktx filter=lfs diff=lfs merge=lfs -text
|
||||
*.blend filter=lfs diff=lfs merge=lfs -text
|
||||
*.ktx2 filter=lfs diff=lfs merge=lfs -text
|
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/target
|
7311
Cargo.lock
generated
Normal file
7311
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
38
Cargo.toml
Normal file
38
Cargo.toml
Normal file
|
@ -0,0 +1,38 @@
|
|||
[package]
|
||||
name = "politburo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
async-std = { version = "1.12.0", default-features = false, features = ["async-io", "std"] }
|
||||
bevy = { version = "0.13.0", features = ["wayland"] }
|
||||
bevy_asset_loader = "0.20.0"
|
||||
bevy_editor_pls = "0.8.0"
|
||||
bevy_egui = { version = "0.25.0", features = ["manage_clipboard"] }
|
||||
flume = "0.11.0"
|
||||
futures = "0.3.30"
|
||||
futures-timer = "3.0.2"
|
||||
keyframe = { version = "1.1.1", default-features = false }
|
||||
libp2p = { version = "0.53.2", features = ["async-std", "dns", "dcutr", "identify", "macros", "noise", "ping", "relay", "rendezvous", "tcp", "yamux", "gossipsub"] }
|
||||
postcard = { version = "1.0.8", features = ["use-std"] }
|
||||
rand = "0.8.5"
|
||||
serde = { version = "1.0.195", features = ["derive"] }
|
||||
tracing = "0.1.40"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||
yoke = { version = "0.7.3", features = ["derive"] }
|
||||
|
||||
# Enable a small amount of optimization in debug mode
|
||||
[profile.dev]
|
||||
opt-level = 1
|
||||
|
||||
# Enable high optimizations for dependencies (incl. Bevy), but not for our code:
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 3
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = true
|
73
LICENSE
Normal file
73
LICENSE
Normal file
|
@ -0,0 +1,73 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
Copyright 2024 Politburo
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
3
README.md
Normal file
3
README.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
# politburo
|
||||
|
||||
A social deduction, historically based card game
|
212
Retrograde interactive.svg
Normal file
212
Retrograde interactive.svg
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 5.3 MiB |
6
assets/credits.txt
Normal file
6
assets/credits.txt
Normal file
|
@ -0,0 +1,6 @@
|
|||
[Special Thanks]
|
||||
Planet by Quaternius
|
||||
Executive Desk by Zsky [CC-BY] via Poly Pizza
|
||||
Dry Erase Board by Jarlan Perez [CC-BY] via Poly Pizza
|
||||
Marker by Poly by Google [CC-BY] via Poly Pizza
|
||||
Walkie talkie by Poly by Google [CC-BY] via Poly Pizza
|
BIN
assets/logo.ktx2
(Stored with Git LFS)
Normal file
BIN
assets/logo.ktx2
(Stored with Git LFS)
Normal file
Binary file not shown.
BIN
assets/logo_bw.ktx2
(Stored with Git LFS)
Normal file
BIN
assets/logo_bw.ktx2
(Stored with Git LFS)
Normal file
Binary file not shown.
77
placeholder.svg
Normal file
77
placeholder.svg
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 195 KiB |
116
src/logo.rs
Normal file
116
src/logo.rs
Normal file
|
@ -0,0 +1,116 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use bevy::{prelude::*, utils::Instant};
|
||||
use bevy_asset_loader::asset_collection::AssetCollection;
|
||||
use keyframe::functions::*;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
const FADE_IN_TIME: f32 = 2.5;
|
||||
const ZOOM_OUT_TIME: f32 = 2.0;
|
||||
const FULL_FADE_FINISHED: f32 = 4.0;
|
||||
const FADE_OUT_TIME: f32 = 1.0;
|
||||
const QUIT_TIME: f32 = 0.5;
|
||||
const LOGO_FINISHED_SCALE: f32 = 0.2;
|
||||
|
||||
pub struct LogoPlugin;
|
||||
|
||||
#[derive(AssetCollection, Resource)]
|
||||
pub struct LogoAssets {
|
||||
#[asset(path = "logo.ktx2")]
|
||||
logo_texture: Handle<Image>,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct LogoData {
|
||||
logo_entity: Entity,
|
||||
}
|
||||
|
||||
impl Plugin for LogoPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(OnEnter(AppState::Logo), load_logo)
|
||||
.add_systems(Update, fade_in_logo.run_if(in_state(AppState::Logo)))
|
||||
.add_systems(OnExit(AppState::Logo), cleanup_logo);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct LogoTimer(Instant, Instant);
|
||||
|
||||
impl LogoTimer {
|
||||
fn elapsed_secs(&self) -> f32 {
|
||||
self.0.elapsed().as_secs_f32()
|
||||
}
|
||||
|
||||
fn finished(&self) -> bool {
|
||||
Instant::now() > self.1
|
||||
}
|
||||
}
|
||||
|
||||
fn load_logo(mut commands: Commands, assets: Res<LogoAssets>) {
|
||||
let now = Instant::now();
|
||||
commands.insert_resource(ClearColor(Color::BLACK));
|
||||
let sprite_entity = commands
|
||||
.spawn((
|
||||
SpriteBundle {
|
||||
texture: assets.logo_texture.clone(),
|
||||
sprite: Sprite {
|
||||
color: Color::rgba(1.0, 1.0, 1.0, 0.0),
|
||||
..Default::default()
|
||||
},
|
||||
transform: Transform::from_scale(Vec3::ONE),
|
||||
..Default::default()
|
||||
},
|
||||
LogoTimer(
|
||||
now,
|
||||
now + Duration::from_secs_f32(QUIT_TIME + FULL_FADE_FINISHED + FADE_OUT_TIME),
|
||||
),
|
||||
))
|
||||
.id();
|
||||
commands.spawn(Camera2dBundle::default());
|
||||
commands.insert_resource(LogoData {
|
||||
logo_entity: sprite_entity,
|
||||
});
|
||||
}
|
||||
|
||||
fn fade_in_logo(
|
||||
mut query: Query<(&mut Sprite, &mut Transform, &LogoTimer)>,
|
||||
mut next_state: ResMut<NextState<AppState>>,
|
||||
keyboard_input: Res<ButtonInput<KeyCode>>,
|
||||
) {
|
||||
let (mut sprite, mut transform, timer) = query.single_mut();
|
||||
let elapsed = timer.elapsed_secs();
|
||||
|
||||
if timer.finished() || keyboard_input.get_pressed().len() > 0 {
|
||||
next_state.set(AppState::LoadingMenu);
|
||||
} else if elapsed > FULL_FADE_FINISHED {
|
||||
sprite.color.set_a(keyframe::ease_with_scaled_time(
|
||||
EaseInCubic,
|
||||
FULL_FADE_FINISHED,
|
||||
0.0,
|
||||
elapsed,
|
||||
FADE_OUT_TIME + FULL_FADE_FINISHED,
|
||||
));
|
||||
} else {
|
||||
sprite.color.set_a(keyframe::ease_with_scaled_time(
|
||||
Linear,
|
||||
0.0,
|
||||
1.0,
|
||||
elapsed,
|
||||
FADE_IN_TIME,
|
||||
));
|
||||
transform.scale = Vec3::splat(keyframe::ease_with_scaled_time(
|
||||
EaseOutQuint,
|
||||
2.0,
|
||||
LOGO_FINISHED_SCALE,
|
||||
elapsed,
|
||||
ZOOM_OUT_TIME,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_logo(mut commands: Commands, logo_data: Res<LogoData>) {
|
||||
commands.entity(logo_data.logo_entity).despawn_recursive();
|
||||
commands.remove_resource::<LogoData>();
|
||||
commands.remove_resource::<LogoAssets>();
|
||||
}
|
49
src/main.rs
Normal file
49
src/main.rs
Normal file
|
@ -0,0 +1,49 @@
|
|||
use bevy::prelude::*;
|
||||
use bevy_asset_loader::loading_state::{
|
||||
config::ConfigureLoadingState, LoadingState, LoadingStateAppExt,
|
||||
};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
mod logo;
|
||||
mod menu;
|
||||
mod networking;
|
||||
mod rooms;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
|
||||
pub enum AppState {
|
||||
#[default]
|
||||
LoadingLogo,
|
||||
Logo,
|
||||
LoadingMenu,
|
||||
Menu,
|
||||
Rooms,
|
||||
InGame,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.try_init();
|
||||
|
||||
App::new()
|
||||
.init_state::<AppState>()
|
||||
.add_loading_state(
|
||||
LoadingState::new(AppState::LoadingLogo)
|
||||
.continue_to_state(AppState::Logo)
|
||||
.load_collection::<logo::LogoAssets>(),
|
||||
)
|
||||
.add_loading_state(
|
||||
LoadingState::new(AppState::LoadingMenu)
|
||||
.continue_to_state(AppState::Menu)
|
||||
.load_collection::<menu::MenuAssets>(),
|
||||
)
|
||||
.add_plugins((
|
||||
DefaultPlugins,
|
||||
logo::LogoPlugin,
|
||||
menu::MenuPlugin,
|
||||
rooms::RoomsPlugin,
|
||||
))
|
||||
.add_plugins(bevy_egui::EguiPlugin)
|
||||
// .add_plugins(EditorPlugin::default())
|
||||
.run();
|
||||
}
|
175
src/menu.rs
Normal file
175
src/menu.rs
Normal file
|
@ -0,0 +1,175 @@
|
|||
use bevy::{app::AppExit, prelude::*};
|
||||
use bevy_asset_loader::asset_collection::AssetCollection;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
pub struct MenuPlugin;
|
||||
|
||||
#[derive(Resource, AssetCollection)]
|
||||
pub struct MenuAssets {
|
||||
#[asset(path = "logo_bw.ktx2")]
|
||||
pub logo: Handle<Image>,
|
||||
}
|
||||
|
||||
const NORMAL_BUTTON: Color = Color::BLACK;
|
||||
|
||||
impl Plugin for MenuPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(OnEnter(AppState::Menu), setup_menu)
|
||||
.add_systems(Update, menu.run_if(in_state(AppState::Menu)))
|
||||
.add_systems(OnExit(AppState::Menu), cleanup_menu);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
enum MenuButton {
|
||||
Play,
|
||||
Quit,
|
||||
}
|
||||
|
||||
#[derive(Resource, Clone, Copy)]
|
||||
pub struct MenuData {
|
||||
pub button_entity: Entity,
|
||||
pub logo_bw_entity: Entity,
|
||||
}
|
||||
|
||||
fn cleanup_menu(mut commands: Commands, menu_data: Res<MenuData>) {
|
||||
commands.entity(menu_data.button_entity).despawn_recursive();
|
||||
}
|
||||
|
||||
fn menu(
|
||||
mut next_state: ResMut<NextState<AppState>>,
|
||||
mut interaction_query: Query<(&Interaction, &MenuButton), Changed<Interaction>>,
|
||||
mut app_exit_events: EventWriter<AppExit>,
|
||||
) {
|
||||
for (interaction, button_type) in &mut interaction_query {
|
||||
match *interaction {
|
||||
Interaction::Pressed => match *button_type {
|
||||
MenuButton::Play => next_state.set(AppState::Rooms),
|
||||
MenuButton::Quit => {
|
||||
app_exit_events.send(AppExit);
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_menu(
|
||||
mut commands: Commands,
|
||||
assets: Res<MenuAssets>,
|
||||
mut clear_color: ResMut<ClearColor>,
|
||||
) {
|
||||
clear_color.0 = Color::GRAY;
|
||||
let logo_bw_entity = commands
|
||||
.spawn(NodeBundle {
|
||||
style: Style {
|
||||
// center button
|
||||
width: Val::Percent(100.),
|
||||
height: Val::Percent(100.),
|
||||
justify_content: JustifyContent::FlexStart,
|
||||
align_items: AlignItems::End,
|
||||
..default()
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
.with_children(|parent| {
|
||||
parent.spawn(ImageBundle {
|
||||
style: Style {
|
||||
width: Val::Auto,
|
||||
height: Val::Auto,
|
||||
justify_content: JustifyContent::FlexStart,
|
||||
align_items: AlignItems::Start,
|
||||
..Default::default()
|
||||
},
|
||||
image: UiImage {
|
||||
texture: assets.logo.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
});
|
||||
})
|
||||
.id();
|
||||
let button_entity = commands
|
||||
.spawn(NodeBundle {
|
||||
style: Style {
|
||||
// center button
|
||||
width: Val::Percent(100.),
|
||||
height: Val::Percent(100.),
|
||||
justify_content: JustifyContent::Center,
|
||||
align_items: AlignItems::Center,
|
||||
flex_direction: FlexDirection::Column,
|
||||
..default()
|
||||
},
|
||||
..default()
|
||||
})
|
||||
.with_children(|parent| {
|
||||
parent
|
||||
.spawn((
|
||||
ButtonBundle {
|
||||
style: Style {
|
||||
width: Val::Px(150.),
|
||||
height: Val::Px(65.),
|
||||
// horizontally center child text
|
||||
justify_content: JustifyContent::Center,
|
||||
// vertically center child text
|
||||
align_items: AlignItems::Center,
|
||||
margin: UiRect {
|
||||
bottom: Val::Px(16.0),
|
||||
..Default::default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
background_color: NORMAL_BUTTON.into(),
|
||||
..default()
|
||||
},
|
||||
MenuButton::Play,
|
||||
))
|
||||
.with_children(|parent| {
|
||||
parent.spawn(TextBundle::from_section(
|
||||
"Play",
|
||||
TextStyle {
|
||||
font_size: 40.0,
|
||||
color: Color::rgb(0.9, 0.9, 0.9),
|
||||
..default()
|
||||
},
|
||||
));
|
||||
});
|
||||
parent
|
||||
.spawn((
|
||||
ButtonBundle {
|
||||
style: Style {
|
||||
width: Val::Px(150.),
|
||||
height: Val::Px(65.),
|
||||
// horizontally center child text
|
||||
justify_content: JustifyContent::Center,
|
||||
// vertically center child text
|
||||
align_items: AlignItems::Center,
|
||||
margin: UiRect {
|
||||
bottom: Val::Px(16.0),
|
||||
..Default::default()
|
||||
},
|
||||
..default()
|
||||
},
|
||||
background_color: NORMAL_BUTTON.into(),
|
||||
..default()
|
||||
},
|
||||
MenuButton::Quit,
|
||||
))
|
||||
.with_children(|parent| {
|
||||
parent.spawn(TextBundle::from_section(
|
||||
"Quit",
|
||||
TextStyle {
|
||||
font_size: 40.0,
|
||||
color: Color::rgb(0.9, 0.9, 0.9),
|
||||
..default()
|
||||
},
|
||||
));
|
||||
});
|
||||
})
|
||||
.id();
|
||||
commands.insert_resource(MenuData {
|
||||
button_entity,
|
||||
logo_bw_entity,
|
||||
});
|
||||
}
|
238
src/networking.rs
Normal file
238
src/networking.rs
Normal file
|
@ -0,0 +1,238 @@
|
|||
use async_std::io;
|
||||
use bevy::ecs::system::Resource;
|
||||
use flume::{Receiver, Sender};
|
||||
use futures::{executor::block_on, future::FutureExt, stream::StreamExt};
|
||||
use libp2p::{
|
||||
core::multiaddr::{Multiaddr, Protocol},
|
||||
dcutr, gossipsub, identify, identity, noise, ping, relay,
|
||||
swarm::{NetworkBehaviour, SwarmEvent},
|
||||
tcp, yamux, PeerId,
|
||||
};
|
||||
use rand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{borrow::Cow, hash::Hash};
|
||||
use std::{cell::OnceCell, sync::OnceLock, time::Duration};
|
||||
use std::{collections::hash_map::DefaultHasher, hash::Hasher};
|
||||
use yoke::{Yoke, Yokeable};
|
||||
|
||||
#[derive(NetworkBehaviour)]
|
||||
pub struct Behaviour {
|
||||
relay_client: relay::client::Behaviour,
|
||||
ping: ping::Behaviour,
|
||||
identify: identify::Behaviour,
|
||||
gossipsub: gossipsub::Behaviour,
|
||||
dcutr: dcutr::Behaviour,
|
||||
}
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct NetworkManager {
|
||||
pub events: Receiver<NetworkEvent>,
|
||||
pub command_sender: Sender<NetworkCommand>,
|
||||
pub peer_id: OnceLock<String>,
|
||||
}
|
||||
|
||||
pub enum NetworkCommand {
|
||||
Dial(PeerId),
|
||||
Publish(Message<'static>),
|
||||
}
|
||||
|
||||
pub enum NetworkEvent {
|
||||
Event(SwarmEvent<BehaviourEvent>),
|
||||
Message(PeerId, Yoke<(u32, Message<'static>), Vec<u8>>),
|
||||
LocalPeerID(PeerId),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Yokeable, Debug)]
|
||||
pub enum Message<'a> {
|
||||
Chat { content: Cow<'a, str> },
|
||||
}
|
||||
|
||||
const RELAY_ID: &'static str =
|
||||
"/dns4/nations.lol/tcp/4001/p2p/12D3KooWMh5tkGf7NDKD2FbKypGBbMyyv4TVmkXRAbWwvyftixU6";
|
||||
|
||||
pub async fn open_network(
|
||||
command_rx: flume::Receiver<NetworkCommand>,
|
||||
event_tx: flume::Sender<NetworkEvent>,
|
||||
) {
|
||||
let relay_address: Multiaddr = RELAY_ID.parse().unwrap();
|
||||
let mut command_rx = command_rx.into_stream();
|
||||
let mut swarm = libp2p::SwarmBuilder::with_existing_identity(generate_ed25519(1))
|
||||
.with_async_std()
|
||||
.with_tcp(
|
||||
tcp::Config::default().port_reuse(true).nodelay(true),
|
||||
noise::Config::new,
|
||||
yamux::Config::default,
|
||||
)
|
||||
.unwrap()
|
||||
.with_dns()
|
||||
.await
|
||||
.unwrap()
|
||||
.with_relay_client(noise::Config::new, yamux::Config::default)
|
||||
.unwrap()
|
||||
.with_behaviour(|keypair, relay_behaviour| {
|
||||
// To content-address message, we can take the hash of message and use it as an ID.
|
||||
let message_id_fn = |message: &gossipsub::Message| {
|
||||
let mut s = DefaultHasher::new();
|
||||
message.data.hash(&mut s);
|
||||
gossipsub::MessageId::from(s.finish().to_string())
|
||||
};
|
||||
// Set a custom gossipsub configuration
|
||||
let gossipsub_config = gossipsub::ConfigBuilder::default()
|
||||
.heartbeat_interval(Duration::from_secs(10)) // This is set to aid debugging by not cluttering the log space
|
||||
.validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)
|
||||
.message_id_fn(message_id_fn) // content-address messages. No two messages of the same content will be propagated.
|
||||
.build()
|
||||
.map_err(|msg| io::Error::new(io::ErrorKind::Other, msg))?; // Temporary hack because `build` does not return a proper `std::error::Error`.
|
||||
|
||||
// build a gossipsub network behaviour
|
||||
let gossipsub = gossipsub::Behaviour::new(
|
||||
gossipsub::MessageAuthenticity::Signed(keypair.clone()),
|
||||
gossipsub_config,
|
||||
)?;
|
||||
|
||||
Ok(Behaviour {
|
||||
relay_client: relay_behaviour,
|
||||
ping: ping::Behaviour::new(ping::Config::new()),
|
||||
identify: identify::Behaviour::new(identify::Config::new(
|
||||
"/TODO/0.0.1".to_string(),
|
||||
keypair.public(),
|
||||
)),
|
||||
gossipsub,
|
||||
dcutr: dcutr::Behaviour::new(keypair.public().to_peer_id()),
|
||||
})
|
||||
})
|
||||
.unwrap()
|
||||
.with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
|
||||
.build();
|
||||
|
||||
// Create a Gossipsub topic
|
||||
let topic = gossipsub::IdentTopic::new("test-net");
|
||||
// subscribes to our topic
|
||||
swarm.behaviour_mut().gossipsub.subscribe(&topic).unwrap();
|
||||
|
||||
swarm
|
||||
.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap())
|
||||
.unwrap();
|
||||
|
||||
// Wait to listen on all interfaces.
|
||||
block_on(async {
|
||||
let mut delay = futures_timer::Delay::new(std::time::Duration::from_secs(1)).fuse();
|
||||
loop {
|
||||
futures::select! {
|
||||
event = swarm.next() => {
|
||||
match event.unwrap() {
|
||||
SwarmEvent::NewListenAddr { address, .. } => {
|
||||
tracing::info!(%address, "Listening on address");
|
||||
}
|
||||
event => panic!("{event:?}"),
|
||||
}
|
||||
}
|
||||
_ = delay => {
|
||||
// Likely listening on all interfaces now, thus continuing by breaking the loop.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Connect to the relay server. Not for the reservation or relayed connection, but to (a) learn
|
||||
// our local public address and (b) enable a freshly started relay to learn its public address.
|
||||
swarm.dial(relay_address.clone()).unwrap();
|
||||
block_on(async {
|
||||
let mut learned_observed_addr = false;
|
||||
let mut told_relay_observed_addr = false;
|
||||
|
||||
loop {
|
||||
match swarm.next().await.unwrap() {
|
||||
SwarmEvent::NewListenAddr { .. } => {}
|
||||
SwarmEvent::Dialing { .. } => {}
|
||||
SwarmEvent::ConnectionEstablished { .. } => {}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Ping(_)) => {}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Identify(identify::Event::Sent {
|
||||
..
|
||||
})) => {
|
||||
tracing::info!("Told relay its public address");
|
||||
told_relay_observed_addr = true;
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Identify(identify::Event::Received {
|
||||
info: identify::Info { observed_addr, .. },
|
||||
..
|
||||
})) => {
|
||||
tracing::info!(address=%observed_addr, "Relay told us our observed address");
|
||||
learned_observed_addr = true;
|
||||
}
|
||||
// event => panic!("{event:?}"),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if learned_observed_addr && told_relay_observed_addr {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
swarm
|
||||
.listen_on(relay_address.clone().with(Protocol::P2pCircuit))
|
||||
.unwrap();
|
||||
// match opts.mode {
|
||||
// Mode::Dial => {
|
||||
// swarm
|
||||
// .dial(
|
||||
// opts.relay_address
|
||||
// .with(Protocol::P2pCircuit)
|
||||
// .with(Protocol::P2p(opts.remote_peer_id.unwrap())),
|
||||
// )
|
||||
// .unwrap();
|
||||
// }
|
||||
// Mode::Listen => {
|
||||
// }
|
||||
// }
|
||||
|
||||
event_tx
|
||||
.send(NetworkEvent::LocalPeerID(swarm.local_peer_id().clone()))
|
||||
.unwrap();
|
||||
|
||||
block_on(async {
|
||||
loop {
|
||||
futures::select! {
|
||||
command = command_rx.select_next_some() => match command {
|
||||
NetworkCommand::Dial(addr) => swarm.dial(
|
||||
relay_address.clone()
|
||||
.with(Protocol::P2pCircuit)
|
||||
.with(Protocol::P2p(addr)),
|
||||
).unwrap(),
|
||||
NetworkCommand::Publish(data) => swarm.behaviour_mut().gossipsub.publish(topic.clone(), postcard::to_stdvec(&(rand::thread_rng().gen::<u32>(), data)).unwrap()).map(|_| ()).unwrap(),
|
||||
},
|
||||
event = swarm.select_next_some() => match event {
|
||||
SwarmEvent::ConnectionEstablished {
|
||||
peer_id, endpoint, ..
|
||||
} => {
|
||||
tracing::info!(peer=%peer_id, ?endpoint, "Established new connection");
|
||||
swarm.behaviour_mut().gossipsub.add_explicit_peer(&peer_id);
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Gossipsub(gossipsub::Event::Message { message, .. })) => {
|
||||
let peer_id = message.source.unwrap();
|
||||
let message: Yoke<(u32, Message<'static>), Vec<u8>> = Yoke::try_attach_to_cart(message.data, |c| postcard::from_bytes(c)).unwrap();
|
||||
event_tx.send(NetworkEvent::Message(peer_id, message)).unwrap();
|
||||
}
|
||||
event => event_tx.send(NetworkEvent::Event(event)).unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn generate_ed25519(key_id: u8) -> identity::Keypair {
|
||||
match std::fs::read(format!("key-{}.protobuf", key_id)) {
|
||||
Ok(key) => identity::Keypair::from_protobuf_encoding(&key).unwrap(),
|
||||
Err(_) => {
|
||||
let key = identity::Keypair::generate_ed25519();
|
||||
std::fs::write(
|
||||
format!("key-{}.protobuf", key_id),
|
||||
key.to_protobuf_encoding().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
key
|
||||
}
|
||||
}
|
||||
}
|
147
src/rooms.rs
Normal file
147
src/rooms.rs
Normal file
|
@ -0,0 +1,147 @@
|
|||
use std::sync::OnceLock;
|
||||
|
||||
use bevy::{prelude::*, tasks::IoTaskPool};
|
||||
use bevy_egui::egui::Align2;
|
||||
use bevy_egui::EguiContexts;
|
||||
use bevy_egui::{egui, EguiClipboard};
|
||||
use libp2p::{relay, swarm::SwarmEvent, PeerId};
|
||||
|
||||
use crate::{
|
||||
menu::{MenuAssets, MenuData},
|
||||
networking::{BehaviourEvent, NetworkEvent, NetworkManager},
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub struct RoomsPlugin;
|
||||
|
||||
impl Plugin for RoomsPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(OnEnter(AppState::Rooms), setup_rooms)
|
||||
.add_systems(Update, rooms.run_if(in_state(AppState::Rooms)))
|
||||
.add_systems(OnExit(AppState::Rooms), cleanup_rooms);
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_rooms(mut commands: Commands, menu_data: Res<MenuData>) {
|
||||
commands
|
||||
.entity(menu_data.logo_bw_entity)
|
||||
.despawn_recursive();
|
||||
commands.remove_resource::<MenuAssets>();
|
||||
}
|
||||
|
||||
#[derive(Resource, Default)]
|
||||
struct ChatBuffer {
|
||||
buffer: String,
|
||||
history: String,
|
||||
}
|
||||
|
||||
fn rooms(
|
||||
mut next_state: ResMut<NextState<AppState>>,
|
||||
mut text_buffer: ResMut<ChatBuffer>,
|
||||
net_manager: Res<NetworkManager>,
|
||||
mut clipboard_ctx: ResMut<EguiClipboard>,
|
||||
mut contexts: EguiContexts,
|
||||
) {
|
||||
egui::Window::new("Chat room")
|
||||
.anchor(Align2::CENTER_CENTER, egui::Vec2::ZERO)
|
||||
.movable(false)
|
||||
.show(contexts.ctx_mut(), |ui| {
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
ui.label(&text_buffer.history);
|
||||
});
|
||||
ui.text_edit_singleline(&mut text_buffer.buffer);
|
||||
if ui.button("Send").clicked() {
|
||||
if text_buffer.buffer.starts_with("/dial") {
|
||||
let address: PeerId = text_buffer
|
||||
.buffer
|
||||
.split(' ')
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap();
|
||||
|
||||
net_manager
|
||||
.command_sender
|
||||
.send(crate::networking::NetworkCommand::Dial(address))
|
||||
.unwrap();
|
||||
} else {
|
||||
let mut buffer = String::new();
|
||||
core::mem::swap(&mut buffer, &mut text_buffer.buffer);
|
||||
net_manager
|
||||
.command_sender
|
||||
.send(crate::networking::NetworkCommand::Publish(
|
||||
crate::networking::Message::Chat {
|
||||
content: std::borrow::Cow::Owned(buffer),
|
||||
},
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
text_buffer.buffer.clear();
|
||||
}
|
||||
if ui.button("Copy Peer ID").clicked() {
|
||||
clipboard_ctx.set_contents(net_manager.peer_id.get().unwrap().as_str());
|
||||
}
|
||||
});
|
||||
|
||||
if let Ok(event) = net_manager.events.try_recv() {
|
||||
match event {
|
||||
NetworkEvent::Event(event) => match event {
|
||||
SwarmEvent::NewListenAddr { address, .. } => {
|
||||
tracing::info!(%address, "Listening on address");
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::RelayClient(
|
||||
relay::client::Event::ReservationReqAccepted { .. },
|
||||
)) => {
|
||||
// assert!(opts.mode == Mode::Listen);
|
||||
tracing::info!("Relay accepted our reservation request");
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::RelayClient(event)) => {
|
||||
tracing::info!(?event)
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Dcutr(event)) => {
|
||||
tracing::info!(?event)
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Identify(event)) => {
|
||||
tracing::info!(?event)
|
||||
}
|
||||
SwarmEvent::Behaviour(BehaviourEvent::Ping(_)) => {}
|
||||
SwarmEvent::OutgoingConnectionError { peer_id, error, .. } => {
|
||||
tracing::info!(peer=?peer_id, "Outgoing connection failed: {error}");
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
NetworkEvent::LocalPeerID(id) => {
|
||||
std::fmt::Write::write_fmt(
|
||||
&mut text_buffer.history,
|
||||
format_args!("Peer ID: {}\n", id),
|
||||
)
|
||||
.unwrap();
|
||||
let mut peer_id = String::new();
|
||||
std::fmt::Write::write_fmt(&mut peer_id, format_args!("{}", id)).unwrap();
|
||||
net_manager.peer_id.set(peer_id).unwrap();
|
||||
}
|
||||
NetworkEvent::Message(p, m) => {
|
||||
std::fmt::Write::write_fmt(
|
||||
&mut text_buffer.history,
|
||||
format_args!("{:#?}\n", (p, m)),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_rooms(mut commands: Commands) {
|
||||
let task_pool = IoTaskPool::get();
|
||||
let (command_tx, command_rx) = flume::unbounded::<super::networking::NetworkCommand>();
|
||||
let (event_tx, event_rx) = flume::unbounded::<super::networking::NetworkEvent>();
|
||||
task_pool
|
||||
.spawn(super::networking::open_network(command_rx, event_tx))
|
||||
.detach();
|
||||
commands.insert_resource(NetworkManager {
|
||||
events: event_rx,
|
||||
command_sender: command_tx,
|
||||
peer_id: OnceLock::new(),
|
||||
});
|
||||
commands.insert_resource(ChatBuffer::default());
|
||||
}
|
Loading…
Reference in a new issue