Skip to content

Instantly share code, notes, and snippets.

@RJ
Last active July 1, 2021 11:48
Show Gist options
  • Save RJ/6e713213fec89318e772642e324f81a7 to your computer and use it in GitHub Desktop.
Save RJ/6e713213fec89318e772642e324f81a7 to your computer and use it in GitHub Desktop.
bevy span lifetime
// idea is to call enter_span at the start of a stage, so the span is in scope for all systems in the stage
// next tick, the span is replaced, so the old one is dropped (ie, old span exited).
//
use bevy::{core::{FixedTimestep, FixedTimesteps}, prelude::*};
use bevy::utils::tracing::span;
#[derive(Default)]
pub struct TickSpan<'a> {
pub n: u32,
pub guard: Option<span::Entered<'a>>,
pub span: Option<span::Span>,
}
impl TickSpan<'_> {
pub fn inc(&mut self) {
self.n += 1;
self.guard = None;
let span = info_span!("tick", n = self.n);
self.guard = Some(span.enter());
self.span = Some(span);
}
}
fn enter_span(mut ts: ResMut<TickSpan>) {
ts.inc();
}
const LABEL: &str = "my_fixed_timestep";
#[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)]
struct FixedUpdateStage;
fn main() {
App::build()
.add_plugins(DefaultPlugins)
// this system will run once every update (it should match your screen's refresh rate)
.add_system(update.system())
.insert_resource(TickSpan::default())
// add a new stage that runs every two seconds
.add_stage_after(
CoreStage::Update,
FixedUpdateStage,
SystemStage::parallel()
.with_run_criteria(
FixedTimestep::step(1.0)
// labels are optional. they provide a way to access the current
// FixedTimestep state from within a system
.with_label(LABEL),
)
.with_system(fixed_update.system().label("do_stuff"))
.with_system(enter_span.system().before("do_stuff"))
)
.run();
}
fn update(mut last_time: Local<f64>, time: Res<Time>) {
// info!("update: {}", time.seconds_since_startup() - *last_time);
*last_time = time.seconds_since_startup();
}
fn fixed_update(mut last_time: Local<f64>, time: Res<Time>, fixed_timesteps: Res<FixedTimesteps>,
) {
info!(
"fixed_update: {}",
time.seconds_since_startup() - *last_time,
);
let fixed_timestep = fixed_timesteps.get(LABEL).unwrap();
info!(
" overstep_percentage: {}",
fixed_timestep.overstep_percentage()
);
*last_time = time.seconds_since_startup();
}
[package]
name = "bevylog"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bevy = "0.5"
@RJ
Copy link
Author

RJ commented Jul 1, 2021

$ cargo run
   Compiling bevylog v0.1.0 (/Users/rj/src/bevylog)
error[E0621]: explicit lifetime required in the type of `ts`
  --> src/main.rs:25:8
   |
25 |     ts.inc();
   |        ^^^ lifetime `'static` required

error: aborting due to previous error

For more information about this error, try `rustc --explain E0621`.
error: could not compile `bevylog`

To learn more, run the command again with --verbose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment