Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/async_tasks/external_source_external_thread.rs
6593 views
1
//! How to use an external thread to run an infinite task and communicate with a channel.
2
3
use bevy::prelude::*;
4
// Using crossbeam_channel instead of std as std `Receiver` is `!Sync`
5
use crossbeam_channel::{bounded, Receiver};
6
use rand::{Rng, SeedableRng};
7
use rand_chacha::ChaCha8Rng;
8
9
fn main() {
10
App::new()
11
.add_event::<StreamEvent>()
12
.add_plugins(DefaultPlugins)
13
.add_systems(Startup, setup)
14
.add_systems(Update, (spawn_text, move_text))
15
.add_systems(FixedUpdate, read_stream)
16
.insert_resource(Time::<Fixed>::from_seconds(0.5))
17
.run();
18
}
19
20
#[derive(Resource, Deref)]
21
struct StreamReceiver(Receiver<u32>);
22
23
#[derive(BufferedEvent)]
24
struct StreamEvent(u32);
25
26
fn setup(mut commands: Commands) {
27
commands.spawn(Camera2d);
28
29
let (tx, rx) = bounded::<u32>(1);
30
std::thread::spawn(move || {
31
// We're seeding the PRNG here to make this example deterministic for testing purposes.
32
// This isn't strictly required in practical use unless you need your app to be deterministic.
33
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
34
loop {
35
// Everything here happens in another thread
36
// This is where you could connect to an external data source
37
38
// This will block until the previous value has been read in system `read_stream`
39
tx.send(rng.random_range(0..2000)).unwrap();
40
}
41
});
42
43
commands.insert_resource(StreamReceiver(rx));
44
}
45
46
// This system reads from the receiver and sends events to Bevy
47
fn read_stream(receiver: Res<StreamReceiver>, mut events: EventWriter<StreamEvent>) {
48
for from_stream in receiver.try_iter() {
49
events.write(StreamEvent(from_stream));
50
}
51
}
52
53
fn spawn_text(mut commands: Commands, mut reader: EventReader<StreamEvent>) {
54
for (per_frame, event) in reader.read().enumerate() {
55
commands.spawn((
56
Text2d::new(event.0.to_string()),
57
TextLayout::new_with_justify(Justify::Center),
58
Transform::from_xyz(per_frame as f32 * 100.0, 300.0, 0.0),
59
));
60
}
61
}
62
63
fn move_text(
64
mut commands: Commands,
65
mut texts: Query<(Entity, &mut Transform), With<Text2d>>,
66
time: Res<Time>,
67
) {
68
for (entity, mut position) in &mut texts {
69
position.translation -= Vec3::new(0.0, 100.0 * time.delta_secs(), 0.0);
70
if position.translation.y < -300.0 {
71
commands.entity(entity).despawn();
72
}
73
}
74
}
75
76