mirror of
https://github.com/bevyengine/bevy
synced 2025-02-17 06:28:34 +00:00
# Objective A common pattern in Rust is the [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html). This is an especially useful pattern in Bevy as it allows us to give common/foreign types different semantics (such as allowing it to implement `Component` or `FromWorld`) or to simply treat them as a "new type" (clever). For example, it allows us to wrap a common `Vec<String>` and do things like: ```rust #[derive(Component)] struct Items(Vec<String>); fn give_sword(query: Query<&mut Items>) { query.single_mut().0.push(String::from("Flaming Poisoning Raging Sword of Doom")); } ``` > We could then define another struct that wraps `Vec<String>` without anything clashing in the query. However, one of the worst parts of this pattern is the ugly `.0` we have to write in order to access the type we actually care about. This is why people often implement `Deref` and `DerefMut` in order to get around this. Since it's such a common pattern, especially for Bevy, it makes sense to add a derive macro to automatically add those implementations. ## Solution Added a derive macro for `Deref` and another for `DerefMut` (both exported into the prelude). This works on all structs (including tuple structs) as long as they only contain a single field: ```rust #[derive(Deref)] struct Foo(String); #[derive(Deref, DerefMut)] struct Bar { name: String, } ``` This allows us to then remove that pesky `.0`: ```rust #[derive(Component, Deref, DerefMut)] struct Items(Vec<String>); fn give_sword(query: Query<&mut Items>) { query.single_mut().push(String::from("Flaming Poisoning Raging Sword of Doom")); } ``` ### Alternatives There are other alternatives to this such as by using the [`derive_more`](https://crates.io/crates/derive_more) crate. However, it doesn't seem like we need an entire crate just yet since we only need `Deref` and `DerefMut` (for now). ### Considerations One thing to consider is that the Rust std library recommends _not_ using `Deref` and `DerefMut` for things like this: "`Deref` should only be implemented for smart pointers to avoid confusion" ([reference](https://doc.rust-lang.org/std/ops/trait.Deref.html)). Personally, I believe it makes sense to use it in the way described above, but others may disagree. ### Additional Context Discord: https://discord.com/channels/691052431525675048/692572690833473578/956648422163746827 (controversiality discussed [here](https://discord.com/channels/691052431525675048/692572690833473578/956711911481835630)) --- ## Changelog - Add `Deref` derive macro (exported to prelude) - Add `DerefMut` derive macro (exported to prelude) - Updated most newtypes in examples to use one or both derives Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
91 lines
2.8 KiB
Rust
91 lines
2.8 KiB
Rust
use bevy::prelude::*;
|
|
// Using crossbeam_channel instead of std as std `Receiver` is `!Sync`
|
|
use crossbeam_channel::{bounded, Receiver};
|
|
use rand::Rng;
|
|
use std::time::{Duration, Instant};
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_event::<StreamEvent>()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_startup_system(setup)
|
|
.add_system(read_stream)
|
|
.add_system(spawn_text)
|
|
.add_system(move_text)
|
|
.run();
|
|
}
|
|
|
|
#[derive(Deref)]
|
|
struct StreamReceiver(Receiver<u32>);
|
|
struct StreamEvent(u32);
|
|
|
|
#[derive(Deref)]
|
|
struct LoadedFont(Handle<Font>);
|
|
|
|
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
|
|
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
|
|
|
|
let (tx, rx) = bounded::<u32>(10);
|
|
std::thread::spawn(move || loop {
|
|
// Everything here happens in another thread
|
|
// This is where you could connect to an external data source
|
|
let mut rng = rand::thread_rng();
|
|
let start_time = Instant::now();
|
|
let duration = Duration::from_secs_f32(rng.gen_range(0.0..0.2));
|
|
while Instant::now() - start_time < duration {
|
|
// Spinning for 'duration', simulating doing hard work!
|
|
}
|
|
|
|
tx.send(rng.gen_range(0..2000)).unwrap();
|
|
});
|
|
|
|
commands.insert_resource(StreamReceiver(rx));
|
|
commands.insert_resource(LoadedFont(asset_server.load("fonts/FiraSans-Bold.ttf")));
|
|
}
|
|
|
|
// This system reads from the receiver and sends events to Bevy
|
|
fn read_stream(receiver: ResMut<StreamReceiver>, mut events: EventWriter<StreamEvent>) {
|
|
for from_stream in receiver.try_iter() {
|
|
events.send(StreamEvent(from_stream));
|
|
}
|
|
}
|
|
|
|
fn spawn_text(
|
|
mut commands: Commands,
|
|
mut reader: EventReader<StreamEvent>,
|
|
loaded_font: Res<LoadedFont>,
|
|
) {
|
|
let text_style = TextStyle {
|
|
font: loaded_font.clone(),
|
|
font_size: 20.0,
|
|
color: Color::WHITE,
|
|
};
|
|
let text_alignment = TextAlignment {
|
|
vertical: VerticalAlign::Center,
|
|
horizontal: HorizontalAlign::Center,
|
|
};
|
|
for (per_frame, event) in reader.iter().enumerate() {
|
|
commands.spawn_bundle(Text2dBundle {
|
|
text: Text::with_section(format!("{}", event.0), text_style.clone(), text_alignment),
|
|
transform: Transform::from_xyz(
|
|
per_frame as f32 * 100.0 + rand::thread_rng().gen_range(-40.0..40.0),
|
|
300.0,
|
|
0.0,
|
|
),
|
|
..default()
|
|
});
|
|
}
|
|
}
|
|
|
|
fn move_text(
|
|
mut commands: Commands,
|
|
mut texts: Query<(Entity, &mut Transform), With<Text>>,
|
|
time: Res<Time>,
|
|
) {
|
|
for (entity, mut position) in texts.iter_mut() {
|
|
position.translation -= Vec3::new(0.0, 100.0 * time.delta_seconds(), 0.0);
|
|
if position.translation.y < -300.0 {
|
|
commands.entity(entity).despawn();
|
|
}
|
|
}
|
|
}
|