Prefer Display over Debug (#16112)

# Objective

Fixes #16104

## Solution

I removed all instances of `:?` and put them back one by one where it
caused an error.

I removed some bevy_utils helper functions that were only used in 2
places and don't add value. See: #11478

## Testing

CI should catch the mistakes

## Migration Guide

`bevy::utils::{dbg,info,warn,error}` were removed. Use
`bevy::utils::tracing::{debug,info,warn,error}` instead.

---------

Co-authored-by: SpecificProtagonist <vincentjunge@posteo.net>
This commit is contained in:
Benjamin Brienen 2024-12-27 01:40:06 +01:00 committed by GitHub
parent 80094c6030
commit 64efd08e13
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
59 changed files with 155 additions and 170 deletions

View File

@ -1057,8 +1057,8 @@ pub fn animate_targets(
(player, graph_handle.id())
} else {
trace!(
"Either an animation player {:?} or a graph was missing for the target \
entity {:?} ({:?}); no animations will play this frame",
"Either an animation player {} or a graph was missing for the target \
entity {} ({:?}); no animations will play this frame",
player_id,
entity_mut.id(),
entity_mut.get::<Name>(),

View File

@ -49,9 +49,9 @@ impl AssetWatcher for FileWatcher {}
pub(crate) fn get_asset_path(root: &Path, absolute_path: &Path) -> (PathBuf, bool) {
let relative_path = absolute_path.strip_prefix(root).unwrap_or_else(|_| {
panic!(
"FileWatcher::get_asset_path() failed to strip prefix from absolute path: absolute_path={:?}, root={:?}",
absolute_path,
root
"FileWatcher::get_asset_path() failed to strip prefix from absolute path: absolute_path={}, root={}",
absolute_path.display(),
root.display()
)
});
let is_meta = relative_path

View File

@ -78,8 +78,9 @@ impl FileAssetWriter {
if create_root {
if let Err(e) = std::fs::create_dir_all(&root_path) {
error!(
"Failed to create root directory {:?} for file asset writer: {:?}",
root_path, e
"Failed to create root directory {} for file asset writer: {}",
root_path.display(),
e
);
}
}

View File

@ -1684,9 +1684,9 @@ mod tests {
);
}
}
_ => panic!("Unexpected error type {:?}", read_error),
_ => panic!("Unexpected error type {}", read_error),
},
_ => panic!("Unexpected error type {:?}", error.error),
_ => panic!("Unexpected error type {}", error.error),
}
}
}

View File

@ -381,7 +381,7 @@ impl AssetProcessor {
// Therefore, we shouldn't automatically delete the asset ... that is a
// user-initiated action.
debug!(
"Meta for asset {:?} was removed. Attempting to re-process",
"Meta for asset {} was removed. Attempting to re-process",
AssetPath::from_path(&path).with_source(source.id())
);
self.process_asset(source, path).await;
@ -389,7 +389,10 @@ impl AssetProcessor {
/// Removes all processed assets stored at the given path (respecting transactionality), then removes the folder itself.
async fn handle_removed_folder(&self, source: &AssetSource, path: &Path) {
debug!("Removing folder {:?} because source was removed", path);
debug!(
"Removing folder {} because source was removed",
path.display()
);
let processed_reader = source.processed_reader().unwrap();
match processed_reader.read_directory(path).await {
Ok(mut path_stream) => {
@ -739,7 +742,7 @@ impl AssetProcessor {
) -> Result<ProcessResult, ProcessError> {
// TODO: The extension check was removed now that AssetPath is the input. is that ok?
// TODO: check if already processing to protect against duplicate hot-reload events
debug!("Processing {:?}", asset_path);
debug!("Processing {}", asset_path);
let server = &self.server;
let path = asset_path.path();
let reader = source.reader();
@ -1237,7 +1240,7 @@ impl ProcessorAssetInfos {
) {
match result {
Ok(ProcessResult::Processed(processed_info)) => {
debug!("Finished processing \"{:?}\"", asset_path);
debug!("Finished processing \"{}\"", asset_path);
// clean up old dependents
let old_processed_info = self
.infos
@ -1260,7 +1263,7 @@ impl ProcessorAssetInfos {
}
}
Ok(ProcessResult::SkippedNotChanged) => {
debug!("Skipping processing (unchanged) \"{:?}\"", asset_path);
debug!("Skipping processing (unchanged) \"{}\"", asset_path);
let info = self.get_mut(&asset_path).expect("info should exist");
// NOTE: skipping an asset on a given pass doesn't mean it won't change in the future as a result
// of a dependency being re-processed. This means apps might receive an "old" (but valid) asset first.
@ -1271,7 +1274,7 @@ impl ProcessorAssetInfos {
info.update_status(ProcessStatus::Processed).await;
}
Ok(ProcessResult::Ignored) => {
debug!("Skipping processing (ignored) \"{:?}\"", asset_path);
debug!("Skipping processing (ignored) \"{}\"", asset_path);
}
Err(ProcessError::ExtensionRequired) => {
// Skip assets without extensions

View File

@ -443,7 +443,7 @@ impl AssetInfos {
} else {
// the dependency id does not exist, which implies it was manually removed or never existed in the first place
warn!(
"Dependency {:?} from asset {:?} is unknown. This asset's dependency load status will not switch to 'Loaded' until the unknown dependency is loaded.",
"Dependency {} from asset {} is unknown. This asset's dependency load status will not switch to 'Loaded' until the unknown dependency is loaded.",
dep_id, loaded_asset_id
);
true

View File

@ -906,7 +906,7 @@ impl AssetServer {
.spawn(async move {
let Ok(source) = server.get_source(path.source()) else {
error!(
"Failed to load {path}. AssetSource {:?} does not exist",
"Failed to load {path}. AssetSource {} does not exist",
path.source()
);
return;
@ -918,7 +918,7 @@ impl AssetServer {
Ok(reader) => reader,
Err(_) => {
error!(
"Failed to load {path}. AssetSource {:?} does not have a processed AssetReader",
"Failed to load {path}. AssetSource {} does not have a processed AssetReader",
path.source()
);
return;

View File

@ -130,7 +130,7 @@ pub(crate) fn play_queued_audio_system<Source: Asset + Decodable>(
// the user may have made a mistake.
if ear_positions.multiple_listeners() {
warn!(
"Multiple SpatialListeners found. Using {:?}.",
"Multiple SpatialListeners found. Using {}.",
ear_positions.query.iter().next().unwrap().0
);
}

View File

@ -4,7 +4,7 @@ macro_rules! assert_approx_eq {
if ($x - $y).abs() >= $d {
panic!(
"assertion failed: `(left !== right)` \
(left: `{:?}`, right: `{:?}`, tolerance: `{:?}`)",
(left: `{}`, right: `{}`, tolerance: `{}`)",
$x, $y, $d
);
}

View File

@ -80,7 +80,7 @@ struct Position { x: f32, y: f32 }
fn print_position(query: Query<(Entity, &Position)>) {
for (entity, position) in &query {
println!("Entity {:?} is at position: x {}, y {}", entity, position.x, position.y);
println!("Entity {} is at position: x {}, y {}", entity, position.x, position.y);
}
}
```
@ -172,7 +172,7 @@ struct Player;
struct Alive;
// Gets the Position component of all Entities with Player component and without the Alive
// component.
// component.
fn system(query: Query<&Position, (With<Player>, Without<Alive>)>) {
for position in &query {
}
@ -340,7 +340,7 @@ let mut world = World::new();
let entity = world.spawn_empty().id();
world.add_observer(|trigger: Trigger<Explode>, mut commands: Commands| {
println!("Entity {:?} goes BOOM!", trigger.target());
println!("Entity {} goes BOOM!", trigger.target());
commands.entity(trigger.target()).despawn();
});

View File

@ -80,10 +80,10 @@ fn print_changed_entities(
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
) {
for entity in &entity_with_added_component {
println!(" {entity:?} has it's first birthday!");
println!(" {entity} has it's first birthday!");
}
for (entity, value) in &entity_with_mutated_component {
println!(" {entity:?} is now {value:?} frames old");
println!(" {entity} is now {value:?} frames old");
}
}
@ -98,7 +98,7 @@ fn age_all_entities(mut entities: Query<&mut Age>) {
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
for (entity, age) in &entities {
if age.frames > 2 {
println!(" despawning {entity:?} due to age > 2");
println!(" despawning {entity} due to age > 2");
commands.entity(entity).despawn();
}
}

View File

@ -57,7 +57,7 @@ fn sending_system(mut event_writer: EventWriter<MyEvent>) {
fn receiving_system(mut event_reader: EventReader<MyEvent>) {
for my_event in event_reader.read() {
println!(
" Received message {:?}, with random value of {}",
" Received message {}, with random value of {}",
my_event.message, my_event.random_value
);
}

View File

@ -198,7 +198,7 @@ pub type ObserverRunner = fn(DeferredWorld, ObserverTrigger, PtrMut, propagate:
/// struct Explode;
///
/// world.add_observer(|trigger: Trigger<Explode>, mut commands: Commands| {
/// println!("Entity {:?} goes BOOM!", trigger.target());
/// println!("Entity {} goes BOOM!", trigger.target());
/// commands.entity(trigger.target()).despawn();
/// });
///

View File

@ -356,7 +356,7 @@ unsafe impl<T: Component> QueryFilter for Without<T> {
/// #
/// fn print_cool_entity_system(query: Query<Entity, Or<(Changed<Color>, Changed<Node>)>>) {
/// for entity in &query {
/// println!("Entity {:?} got a new style or color", entity);
/// println!("Entity {} got a new style or color", entity);
/// }
/// }
/// # bevy_ecs::system::assert_is_system(print_cool_entity_system);

View File

@ -134,7 +134,7 @@ impl RemovedComponentEvents {
/// # #[derive(Component)]
/// # struct MyComponent;
/// fn react_on_removal(mut removed: RemovedComponents<MyComponent>) {
/// removed.read().for_each(|removed_entity| println!("{:?}", removed_entity));
/// removed.read().for_each(|removed_entity| println!("{}", removed_entity));
/// }
/// # bevy_ecs::system::assert_is_system(react_on_removal);
/// ```

View File

@ -452,7 +452,7 @@ impl<'w, 's> Commands<'w, 's> {
#[track_caller]
fn panic_no_entity(entities: &Entities, entity: Entity) -> ! {
panic!(
"Attempting to create an EntityCommands for entity {entity:?}, which {}",
"Attempting to create an EntityCommands for entity {entity}, which {}",
entities.entity_does_not_exist_error_details_message(entity)
);
}
@ -1405,7 +1405,7 @@ impl<'a> EntityCommands<'a> {
entity.insert_by_id(component_id, ptr);
});
} else {
panic!("error[B0003]: {caller}: Could not insert a component {component_id:?} (with type {}) for entity {entity:?}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<T>(), world.entities().entity_does_not_exist_error_details_message(entity));
panic!("error[B0003]: {caller}: Could not insert a component {component_id:?} (with type {}) for entity {entity}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<T>(), world.entities().entity_does_not_exist_error_details_message(entity));
}
})
}
@ -1739,7 +1739,7 @@ impl<'a> EntityCommands<'a> {
/// .spawn_empty()
/// // Closures with this signature implement `EntityCommand`.
/// .queue(|entity: EntityWorldMut| {
/// println!("Executed an EntityCommand for {:?}", entity.id());
/// println!("Executed an EntityCommand for {}", entity.id());
/// });
/// # }
/// # bevy_ecs::system::assert_is_system(my_system);
@ -2119,7 +2119,7 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
caller,
);
} else {
panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for {entity:?}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<T>(), world.entities().entity_does_not_exist_error_details_message(entity) );
panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for {entity}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<T>(), world.entities().entity_does_not_exist_error_details_message(entity) );
}
});
self
@ -2225,7 +2225,7 @@ fn insert<T: Bundle>(bundle: T, mode: InsertMode) -> impl EntityCommand {
caller,
);
} else {
panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for entity {entity:?}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<T>(), world.entities().entity_does_not_exist_error_details_message(entity));
panic!("error[B0003]: {caller}: Could not insert a bundle (of type `{}`) for entity {entity}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<T>(), world.entities().entity_does_not_exist_error_details_message(entity));
}
}
}

View File

@ -1652,9 +1652,10 @@ mod tests {
assert_is_system(returning::<&str>.map(u64::from_str).map(Result::unwrap));
assert_is_system(static_system_param);
assert_is_system(
exclusive_in_out::<(), Result<(), std::io::Error>>.map(|result| {
if let Err(error) = result {
log::error!("{:?}", error);
exclusive_in_out::<(), Result<(), std::io::Error>>.map(|_out| {
#[cfg(feature = "trace")]
if let Err(error) = _out {
tracing::error!("{}", error);
}
}),
);

View File

@ -620,7 +620,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
/// ) {
/// for friends in &friends_query {
/// for counter in counter_query.iter_many(&friends.list) {
/// println!("Friend's counter: {:?}", counter.value);
/// println!("Friend's counter: {}", counter.value);
/// }
/// }
/// }
@ -674,7 +674,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
/// for friends in &friends_query {
/// let mut iter = counter_query.iter_many_mut(&friends.list);
/// while let Some(mut counter) = iter.fetch_next() {
/// println!("Friend's counter: {:?}", counter.value);
/// println!("Friend's counter: {}", counter.value);
/// counter.value += 1;
/// }
/// }

View File

@ -710,7 +710,7 @@ impl World {
#[track_caller]
fn panic_no_entity(world: &World, entity: Entity) -> ! {
panic!(
"Entity {entity:?} {}",
"Entity {entity} {}",
world
.entities
.entity_does_not_exist_error_details_message(entity)
@ -862,7 +862,7 @@ impl World {
let entity_location = self
.entities()
.get(entity)
.unwrap_or_else(|| panic!("Entity {entity:?} does not exist"));
.unwrap_or_else(|| panic!("Entity {entity} does not exist"));
let archetype = self
.archetypes()
@ -1336,7 +1336,7 @@ impl World {
true
} else {
if log_warning {
warn!("error[B0003]: {caller}: Could not despawn entity {entity:?}, which {}. See: https://bevyengine.org/learn/errors/b0003", self.entities.entity_does_not_exist_error_details_message(entity));
warn!("error[B0003]: {caller}: Could not despawn entity {entity}, which {}. See: https://bevyengine.org/learn/errors/b0003", self.entities.entity_does_not_exist_error_details_message(entity));
}
false
}
@ -2498,11 +2498,11 @@ impl World {
)
};
} else {
panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {entity:?}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>(), self.entities.entity_does_not_exist_error_details_message(entity));
panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {entity}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>(), self.entities.entity_does_not_exist_error_details_message(entity));
}
}
} else {
panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {first_entity:?}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>(), self.entities.entity_does_not_exist_error_details_message(first_entity));
panic!("error[B0003]: Could not insert a bundle (of type `{}`) for entity {first_entity}, which {}. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::<B>(), self.entities.entity_does_not_exist_error_details_message(first_entity));
}
}
}

View File

@ -213,7 +213,7 @@ pub enum GetComponentReflectError {
NoCorrespondingComponentId(TypeId),
/// The given [`Entity`] does not have a [`Component`] corresponding to the given [`TypeId`].
#[error("The given `Entity` {entity:?} does not have a `{component_name:?}` component ({component_id:?}, which corresponds to {type_id:?})")]
#[error("The given `Entity` {entity} does not have a `{component_name:?}` component ({component_id:?}, which corresponds to {type_id:?})")]
EntityDoesNotHaveComponent {
/// The given [`Entity`].
entity: Entity,

View File

@ -646,13 +646,13 @@ async fn load_gltf<'a, 'b, 'c>(
if [Semantic::Joints(0), Semantic::Weights(0)].contains(&semantic) {
if !meshes_on_skinned_nodes.contains(&gltf_mesh.index()) {
warn!(
"Ignoring attribute {:?} for skinned mesh {:?} used on non skinned nodes (NODE_SKINNED_MESH_WITHOUT_SKIN)",
"Ignoring attribute {:?} for skinned mesh {} used on non skinned nodes (NODE_SKINNED_MESH_WITHOUT_SKIN)",
semantic,
primitive_label
);
continue;
} else if meshes_on_non_skinned_nodes.contains(&gltf_mesh.index()) {
error!("Skinned mesh {:?} used on both skinned and non skin nodes, this is likely to cause an error (NODE_SKINNED_MESH_WITHOUT_SKIN)", primitive_label);
error!("Skinned mesh {} used on both skinned and non skin nodes, this is likely to cause an error (NODE_SKINNED_MESH_WITHOUT_SKIN)", primitive_label);
}
}
match convert_attribute(
@ -737,9 +737,9 @@ async fn load_gltf<'a, 'b, 'c>(
generate_tangents_span.in_scope(|| {
if let Err(err) = mesh.generate_tangents() {
warn!(
"Failed to generate vertex tangents using the mikktspace algorithm: {:?}",
err
);
"Failed to generate vertex tangents using the mikktspace algorithm: {}",
err
);
}
});
}
@ -1912,7 +1912,7 @@ impl<'a> GltfTreeIterator<'a> {
if skin.joints().len() > MAX_JOINTS && warned_about_max_joints.insert(skin.index())
{
warn!(
"The glTF skin {:?} has {} joints, but the maximum supported is {}",
"The glTF skin {} has {} joints, but the maximum supported is {}",
skin.name()
.map(ToString::to_string)
.unwrap_or_else(|| skin.index().to_string()),

View File

@ -51,10 +51,10 @@ fn despawn_with_children_recursive_inner(world: &mut World, entity: Entity, warn
if warn {
if !world.despawn(entity) {
debug!("Failed to despawn entity {:?}", entity);
debug!("Failed to despawn entity {}", entity);
}
} else if !world.try_despawn(entity) {
debug!("Failed to despawn entity {:?}", entity);
debug!("Failed to despawn entity {}", entity);
}
}

View File

@ -1346,7 +1346,7 @@ pub fn gamepad_connection_system(
product_id,
} => {
let Some(mut gamepad) = commands.get_entity(id) else {
warn!("Gamepad {:} removed before handling connection event.", id);
warn!("Gamepad {} removed before handling connection event.", id);
continue;
};
gamepad.insert((
@ -1357,18 +1357,18 @@ pub fn gamepad_connection_system(
..Default::default()
},
));
info!("Gamepad {:?} connected.", id);
info!("Gamepad {} connected.", id);
}
GamepadConnection::Disconnected => {
let Some(mut gamepad) = commands.get_entity(id) else {
warn!("Gamepad {:} removed before handling disconnection event. You can ignore this if you manually removed it.", id);
warn!("Gamepad {} removed before handling disconnection event. You can ignore this if you manually removed it.", id);
continue;
};
// Gamepad entities are left alive to preserve their state (e.g. [`GamepadSettings`]).
// Instead of despawning, we remove Gamepad components that don't need to preserve state
// and re-add them if they ever reconnect.
gamepad.remove::<Gamepad>();
info!("Gamepad {:} disconnected.", id);
info!("Gamepad {} disconnected.", id);
}
}
}

View File

@ -61,7 +61,7 @@ pub trait ShapeSample {
/// let square = Rectangle::new(2.0, 2.0);
///
/// // Returns a Vec2 with both x and y between -1 and 1.
/// println!("{:?}", square.sample_interior(&mut rand::thread_rng()));
/// println!("{}", square.sample_interior(&mut rand::thread_rng()));
/// ```
fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output;
@ -76,7 +76,7 @@ pub trait ShapeSample {
///
/// // Returns a Vec2 where one of the coordinates is at ±1,
/// // and the other is somewhere between -1 and 1.
/// println!("{:?}", square.sample_boundary(&mut rand::thread_rng()));
/// println!("{}", square.sample_boundary(&mut rand::thread_rng()));
/// ```
fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output;
@ -92,7 +92,7 @@ pub trait ShapeSample {
///
/// // Iterate over points randomly drawn from `square`'s interior:
/// for random_val in square.interior_dist().sample_iter(rng).take(5) {
/// println!("{:?}", random_val);
/// println!("{}", random_val);
/// }
/// ```
fn interior_dist(self) -> impl Distribution<Self::Output>
@ -114,7 +114,7 @@ pub trait ShapeSample {
///
/// // Iterate over points randomly drawn from `square`'s boundary:
/// for random_val in square.boundary_dist().sample_iter(rng).take(5) {
/// println!("{:?}", random_val);
/// println!("{}", random_val);
/// }
/// ```
fn boundary_dist(self) -> impl Distribution<Self::Output>

View File

@ -38,7 +38,7 @@ pub struct StandardMaterial {
///
/// Doubles as diffuse albedo for non-metallic, specular for metallic and a mix for everything
/// in between. If used together with a `base_color_texture`, this is factored into the final
/// base color as `base_color * base_color_texture_value`
/// base color as `base_color * base_color_texture_value`.
///
/// Defaults to [`Color::WHITE`].
pub base_color: Color,

View File

@ -54,7 +54,7 @@
//! transform.rotate_local_y(drag.delta.x / 50.0);
//! })
//! .observe(|trigger: Trigger<Pointer<Click>>, mut commands: Commands| {
//! println!("Entity {:?} goes BOOM!", trigger.target());
//! println!("Entity {} goes BOOM!", trigger.target());
//! commands.entity(trigger.target()).despawn();
//! })
//! .observe(|trigger: Trigger<Pointer<Over>>, mut events: EventWriter<Greeting>| {

View File

@ -173,7 +173,7 @@ impl FunctionRegistry {
/// .register_with_name(core::any::type_name_of_val(&mul), mul)?
/// // Registering an existing function with a custom name
/// .register_with_name("my_crate::mul", mul)?;
///
///
/// // Be careful not to register anonymous functions with their type name.
/// // This code works but registers the function with a non-unique name like `foo::bar::{{closure}}`
/// registry.register_with_name(core::any::type_name_of_val(&div), div)?;

View File

@ -75,7 +75,7 @@ impl<T: Reflect + SerializeWithRegistry> FromType<T> for ReflectSerializeWithReg
serialize: |value: &dyn Reflect, registry| {
let value = value.downcast_ref::<T>().unwrap_or_else(|| {
panic!(
"Expected value to be of type {:?} but received {:?}",
"Expected value to be of type {} but received {}",
core::any::type_name::<T>(),
value.reflect_type_path()
)

View File

@ -339,7 +339,7 @@ fn map_buffers(mut readbacks: ResMut<GpuReadbacks>) {
drop(data);
buffer.unmap();
if let Err(e) = tx.try_send((entity, buffer, result)) {
warn!("Failed to send readback result: {:?}", e);
warn!("Failed to send readback result: {}", e);
}
});
readbacks.mapped.push(readback);

View File

@ -785,7 +785,7 @@ impl MeshAllocator {
slab_to_grow: SlabToReallocate,
) {
let Some(Slab::General(slab)) = self.slabs.get_mut(&slab_id) else {
error!("Couldn't find slab {:?} to grow", slab_id);
error!("Couldn't find slab {} to grow", slab_id);
return;
};

View File

@ -238,7 +238,7 @@ pub struct NodeState {
impl Debug for NodeState {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "{:?} ({:?})", self.label, self.type_name)
writeln!(f, "{:?} ({})", self.label, self.type_name)
}
}

View File

@ -264,7 +264,7 @@ impl ShaderCache {
));
debug!(
"processing shader {:?}, with shader defs {:?}",
"processing shader {}, with shader defs {:?}",
id, shader_defs
);
let shader_source = match &shader.source {

View File

@ -239,7 +239,7 @@ fn extract_screenshots(
};
if seen_targets.contains(&render_target) {
warn!(
"Duplicate render target for screenshot, skipping entity {:?}: {:?}",
"Duplicate render target for screenshot, skipping entity {}: {:?}",
entity, render_target
);
// If we don't despawn the entity here, it will be captured again in the next frame
@ -273,7 +273,7 @@ fn prepare_screenshots(
NormalizedRenderTarget::Window(window) => {
let window = window.entity();
let Some(surface_data) = window_surfaces.surfaces.get(&window) else {
warn!("Unknown window for screenshot, skipping: {:?}", window);
warn!("Unknown window for screenshot, skipping: {}", window);
continue;
};
let format = surface_data.configuration.format.add_srgb_suffix();
@ -690,7 +690,7 @@ pub(crate) fn collect_screenshots(world: &mut World) {
RenderAssetUsages::RENDER_WORLD,
),
)) {
error!("Failed to send screenshot: {:?}", e);
error!("Failed to send screenshot: {}", e);
}
};

View File

@ -935,7 +935,7 @@ mod tests {
.entities
.iter()
.find(|dynamic_entity| dynamic_entity.entity == expected.entity)
.unwrap_or_else(|| panic!("missing entity (expected: `{:?}`)", expected.entity));
.unwrap_or_else(|| panic!("missing entity (expected: `{}`)", expected.entity));
assert_eq!(expected.entity, received.entity, "entities did not match");

View File

@ -443,7 +443,7 @@ pub fn detect_text_needs_rerender<Root: Component>(
// - Root children changed (can include additions and removals).
for root in changed_roots.iter() {
let Ok((_, Some(mut computed), _)) = computed.get_mut(root) else {
warn_once!("found entity {:?} with a root text component ({}) but no ComputedTextBlock; this warning only \
warn_once!("found entity {} with a root text component ({}) but no ComputedTextBlock; this warning only \
prints once", root, core::any::type_name::<Root>());
continue;
};
@ -456,14 +456,14 @@ pub fn detect_text_needs_rerender<Root: Component>(
// - Span children changed (can include additions and removals).
for (entity, maybe_span_parent, has_text_block) in changed_spans.iter() {
if has_text_block {
warn_once!("found entity {:?} with a TextSpan that has a TextLayout, which should only be on root \
warn_once!("found entity {} with a TextSpan that has a TextLayout, which should only be on root \
text entities (that have {}); this warning only prints once",
entity, core::any::type_name::<Root>());
}
let Some(span_parent) = maybe_span_parent else {
warn_once!(
"found entity {:?} with a TextSpan that has no parent; it should have an ancestor \
"found entity {} with a TextSpan that has no parent; it should have an ancestor \
with a root text component ({}); this warning only prints once",
entity,
core::any::type_name::<Root>()
@ -477,8 +477,8 @@ pub fn detect_text_needs_rerender<Root: Component>(
// is outweighed by the expense of tracking visited spans.
loop {
let Ok((maybe_parent, maybe_computed, has_span)) = computed.get_mut(parent) else {
warn_once!("found entity {:?} with a TextSpan that is part of a broken hierarchy with a Parent \
component that points at non-existent entity {:?}; this warning only prints once",
warn_once!("found entity {} with a TextSpan that is part of a broken hierarchy with a Parent \
component that points at non-existent entity {}; this warning only prints once",
entity, parent);
break;
};
@ -487,14 +487,14 @@ pub fn detect_text_needs_rerender<Root: Component>(
break;
}
if !has_span {
warn_once!("found entity {:?} with a TextSpan that has an ancestor ({}) that does not have a text \
warn_once!("found entity {} with a TextSpan that has an ancestor ({}) that does not have a text \
span component or a ComputedTextBlock component; this warning only prints once",
entity, parent);
break;
}
let Some(next_parent) = maybe_parent else {
warn_once!(
"found entity {:?} with a TextSpan that has no ancestor with the root text \
"found entity {} with a TextSpan that has no ancestor with the root text \
component ({}); this warning only prints once",
entity,
core::any::type_name::<Root>()

View File

@ -27,7 +27,7 @@ pub fn print_ui_layout_tree(ui_surface: &UiSurface) {
&mut out,
);
}
bevy_utils::tracing::info!("Layout tree for camera entity: {entity:?}\n{out}");
bevy_utils::tracing::info!("Layout tree for camera entity: {entity}\n{out}");
}
}
@ -62,7 +62,7 @@ fn print_node(
};
writeln!(
acc,
"{lines}{fork} {display} [x: {x:<4} y: {y:<4} width: {width:<4} height: {height:<4}] ({entity:?}) {measured}",
"{lines}{fork} {display} [x: {x:<4} y: {y:<4} width: {width:<4} height: {height:<4}] ({entity}) {measured}",
lines = lines_string,
fork = fork_string,
display = display_variant,

View File

@ -171,7 +171,7 @@ pub fn ui_layout_system(
Some(camera_entity) => {
let Ok((_, camera)) = cameras.get(camera_entity) else {
warn!(
"TargetCamera (of root UI node {entity:?}) is pointing to a camera {:?} which doesn't exist",
"TargetCamera (of root UI node {entity}) is pointing to a camera {} which doesn't exist",
camera_entity
);
return;
@ -187,7 +187,7 @@ pub fn ui_layout_system(
} else {
warn!(
"Multiple cameras found, causing UI target ambiguity. \
To fix this, add an explicit `TargetCamera` component to the root UI node {:?}",
To fix this, add an explicit `TargetCamera` component to the root UI node {}",
entity
);
}
@ -876,12 +876,12 @@ mod tests {
);
assert!(
current_rect.height().abs() + current_rect.width().abs() > 0.,
"root ui node {entity:?} doesn't have a logical size"
"root ui node {entity} doesn't have a logical size"
);
assert_ne!(
global_transform.affine(),
GlobalTransform::default().affine(),
"root ui node {entity:?} global transform is not populated"
"root ui node {entity} global transform is not populated"
);
let Some((rect, is_overlapping)) = option_rect else {
return Some((current_rect, false));

View File

@ -400,34 +400,6 @@ impl<F: FnOnce()> Drop for OnDrop<F> {
}
}
/// Calls the [`tracing::info!`] macro on a value.
#[cfg(feature = "tracing")]
pub fn info<T: Debug>(data: T) {
tracing::info!("{:?}", data);
}
/// Calls the [`tracing::debug!`] macro on a value.
#[cfg(feature = "tracing")]
pub fn dbg<T: Debug>(data: T) {
tracing::debug!("{:?}", data);
}
/// Processes a [`Result`] by calling the [`tracing::warn!`] macro in case of an [`Err`] value.
#[cfg(feature = "tracing")]
pub fn warn<E: Debug>(result: Result<(), E>) {
if let Err(warn) = result {
tracing::warn!("{:?}", warn);
}
}
/// Processes a [`Result`] by calling the [`tracing::error!`] macro in case of an [`Err`] value.
#[cfg(feature = "tracing")]
pub fn error<E: Debug>(result: Result<(), E>) {
if let Err(error) = result {
tracing::error!("{:?}", error);
}
}
/// Like [`tracing::trace`], but conditional on cargo feature `detailed_trace`.
#[cfg(feature = "tracing")]
#[macro_export]

View File

@ -61,11 +61,7 @@ pub fn create_windows<F: QueryFilter + 'static>(
continue;
}
info!(
"Creating new window {:?} ({:?})",
window.title.as_str(),
entity
);
info!("Creating new window {} ({})", window.title.as_str(), entity);
let winit_window = winit_windows.create_window(
event_loop,
@ -209,7 +205,7 @@ pub fn create_monitors(
idx += 1;
true
} else {
info!("Monitor removed {:?}", entity);
info!("Monitor removed {}", entity);
commands.entity(*entity).despawn();
idx += 1;
false
@ -234,7 +230,7 @@ pub(crate) fn despawn_windows(
closing_events.send(WindowClosing { window });
}
for window in closed.read() {
info!("Closing window {:?}", window);
info!("Closing window {}", window);
// Guard to verify that the window is in fact actually gone,
// rather than having the component added
// and removed in the same frame.
@ -390,7 +386,7 @@ pub(crate) fn changed_windows(
let position = PhysicalPosition::new(physical_position.x, physical_position.y);
if let Err(err) = winit_window.set_cursor_position(position) {
error!("could not set cursor position: {:?}", err);
error!("could not set cursor position: {}", err);
}
}
}
@ -410,7 +406,7 @@ pub(crate) fn changed_windows(
if let Err(err) = winit_window.set_cursor_hittest(window.cursor_options.hit_test) {
window.cursor_options.hit_test = cache.window.cursor_options.hit_test;
warn!(
"Could not set cursor hit test for window {:?}: {:?}",
"Could not set cursor hit test for window {}: {}",
window.title, err
);
}

View File

@ -290,7 +290,7 @@ impl WinitWindows {
if !window.cursor_options.hit_test {
if let Err(err) = winit_window.set_cursor_hittest(window.cursor_options.hit_test) {
warn!(
"Could not set cursor hit test for window {:?}: {:?}",
"Could not set cursor hit test for window {}: {}",
window.title, err
);
}

View File

@ -228,7 +228,7 @@ fn create_texture_atlas(
let id = handle.id().typed_unchecked::<Image>();
let Some(texture) = textures.get(id) else {
warn!(
"{:?} did not resolve to an `Image` asset.",
"{} did not resolve to an `Image` asset.",
handle.path().unwrap()
);
continue;

View File

@ -15,9 +15,9 @@ impl<S: Subscriber> Layer<S> for CustomLayer {
_ctx: bevy::log::tracing_subscriber::layer::Context<'_, S>,
) {
println!("Got event!");
println!(" level={:?}", event.metadata().level());
println!(" target={:?}", event.metadata().target());
println!(" name={:?}", event.metadata().name());
println!(" level={}", event.metadata().level());
println!(" target={}", event.metadata().target());
println!(" name={}", event.metadata().name());
}
}

View File

@ -149,7 +149,7 @@ fn print_on_load(
info!("Custom asset loaded: {:?}", custom_asset.unwrap());
info!("Custom asset loaded: {:?}", other_custom_asset.unwrap());
info!("Blob Size: {:?} Bytes", blob.unwrap().bytes.len());
info!("Blob Size: {} Bytes", blob.unwrap().bytes.len());
// Once printed, we won't print again
state.printed = true;

View File

@ -16,7 +16,7 @@ struct CustomAssetReader(Box<dyn ErasedAssetReader>);
impl AssetReader for CustomAssetReader {
async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
info!("Reading {:?}", path);
info!("Reading {}", path.display());
self.0.read(path).await
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {

View File

@ -36,7 +36,7 @@ fn change_component(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)
for (entity, mut component) in &mut query {
if rand::thread_rng().gen_bool(0.1) {
let new_component = MyComponent(time.elapsed_secs().round());
info!("New value: {new_component:?} {entity:?}");
info!("New value: {new_component:?} {entity}");
// Change detection occurs on mutable dereference, and does not consider whether or not
// a value is actually equal. To avoid triggering change detection when nothing has
// actually changed, you can use the `set_if_neq` method on any component or resource
@ -53,7 +53,7 @@ fn change_component_2(time: Res<Time>, mut query: Query<(Entity, &mut MyComponen
for (entity, mut component) in &mut query {
if rand::thread_rng().gen_bool(0.1) {
let new_component = MyComponent(time.elapsed_secs().round());
info!("New value: {new_component:?} {entity:?}");
info!("New value: {new_component:?} {entity}");
component.set_if_neq(new_component);
}
}

View File

@ -72,7 +72,7 @@ fn setup(world: &mut World) {
.on_add(|mut world, entity, component_id| {
// You can access component data from within the hook
let value = world.get::<MyComponent>(entity).unwrap().0;
println!("Component: {component_id:?} added to: {entity:?} with value {value:?}");
println!("Component: {component_id:?} added to: {entity} with value {value:?}");
// Or access resources
world
.resource_mut::<MyComponentIndex>()
@ -96,7 +96,7 @@ fn setup(world: &mut World) {
// since it runs before the component is removed you can still access the component data
.on_remove(|mut world, entity, component_id| {
let value = world.get::<MyComponent>(entity).unwrap().0;
println!("Component: {component_id:?} removed from: {entity:?} with value {value:?}");
println!("Component: {component_id:?} removed from: {entity} with value {value:?}");
// You can also issue commands through `.commands()`
world.commands().entity(entity).despawn();
});

View File

@ -66,7 +66,7 @@ fn print_components_read_only(
) {
println!("Print components (read_only):");
for e in &query {
println!("Entity: {:?}", e.entity);
println!("Entity: {}", e.entity);
println!("A: {:?}", e.a);
println!("B: {:?}", e.b);
println!("Nested: {:?}", e.nested);
@ -138,7 +138,7 @@ fn print_components_iter_mut(
for e in &mut query {
// Re-declaring the variable to illustrate the type of the actual iterator item.
let e: CustomQueryItem<'_, _, _> = e;
println!("Entity: {:?}", e.entity);
println!("Entity: {}", e.entity);
println!("A: {:?}", e.a);
println!("B: {:?}", e.b);
println!("Optional nested: {:?}", e.optional_nested);
@ -156,7 +156,7 @@ fn print_components_iter(
for e in &query {
// Re-declaring the variable to illustrate the type of the actual iterator item.
let e: CustomQueryReadOnlyItem<'_, _, _> = e;
println!("Entity: {:?}", e.entity);
println!("Entity: {}", e.entity);
println!("A: {:?}", e.a);
println!("B: {:?}", e.b);
println!("Nested: {:?}", e.nested);
@ -186,7 +186,7 @@ fn print_components_tuple(
) {
println!("Print components (tuple):");
for (entity, a, b, nested, (generic_c, generic_d)) in &query {
println!("Entity: {entity:?}");
println!("Entity: {entity}");
println!("A: {a:?}");
println!("B: {b:?}");
println!("Nested: {:?} {:?}", nested.0, nested.1);

View File

@ -98,7 +98,7 @@ fn main() {
};
component_names.insert(name.to_string(), id);
component_info.insert(id, info.clone());
println!("Component {} created with id: {:?}", name, id.index());
println!("Component {} created with id: {}", name, id.index());
});
}
"s" => {
@ -142,7 +142,7 @@ fn main() {
entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
}
println!("Entity spawned with id: {:?}", entity.id());
println!("Entity spawned with id: {}", entity.id());
}
"q" => {
let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
@ -182,7 +182,7 @@ fn main() {
.collect::<Vec<_>>()
.join(", ");
println!("{:?}: {}", filtered_entity.id(), terms);
println!("{}: {}", filtered_entity.id(), terms);
});
}
_ => continue,

View File

@ -147,7 +147,7 @@ fn explode_mine(trigger: Trigger<Explode>, query: Query<&Mine>, mut commands: Co
let Some(mut entity) = commands.get_entity(id) else {
return;
};
info!("Boom! {:?} exploded.", id.index());
info!("Boom! {} exploded.", id.index());
entity.despawn();
let mine = query.get(id).unwrap();
// Trigger another explosion cascade.

View File

@ -71,7 +71,7 @@ struct DebugEvent {
/// A system that sends all combinations of events.
fn send_events(mut events: EventWriter<DebugEvent>, frame_count: Res<FrameCount>) {
println!("Sending events for frame {:?}", frame_count.0);
println!("Sending events for frame {}", frame_count.0);
events.send(DebugEvent {
resend_from_param_set: false,

View File

@ -12,13 +12,13 @@ fn main() {
// create a closure, with an 'input' value.
let complex_closure = |mut value: String| {
move || {
info!("Hello from a complex closure! {:?}", value);
info!("Hello from a complex closure! {}", value);
// we can modify the value inside the closure. this will be saved between calls.
value = format!("{value} - updated");
// you could also use an outside variable like presented in the inlined closures
// info!("outside_variable! {:?}", outside_variable);
// info!("outside_variable! {}", outside_variable);
}
};
@ -37,7 +37,7 @@ fn main() {
// or use variables outside a closure
.add_systems(Update, move || {
info!(
"Hello from an inlined closure that captured the 'outside_variable'! {:?}",
"Hello from an inlined closure that captured the 'outside_variable'! {}",
outside_variable
);
// you can use outside_variable, or any other variables inside this closure.

View File

@ -6,7 +6,7 @@ use std::num::ParseIntError;
use bevy::{
log::LogPlugin,
utils::{dbg, error, info, tracing::Level, warn},
utils::tracing::{debug, error, info, Level},
};
fn main() {
@ -22,10 +22,18 @@ fn main() {
Update,
(
parse_message_system.pipe(handler_system),
data_pipe_system.map(info),
parse_message_system.map(dbg),
warning_pipe_system.map(warn),
parse_error_message_system.map(error),
data_pipe_system.map(|out| info!("{out}")),
parse_message_system.map(|out| debug!("{out:?}")),
warning_pipe_system.map(|out| {
if let Err(err) = out {
error!("{err}");
}
}),
parse_error_message_system.map(|out| {
if let Err(err) = out {
error!("{err}");
}
}),
parse_message_system.map(drop),
),
)

View File

@ -12,19 +12,19 @@ fn main() {
fn gamepad_system(gamepads: Query<(Entity, &Gamepad)>) {
for (entity, gamepad) in &gamepads {
if gamepad.just_pressed(GamepadButton::South) {
info!("{:?} just pressed South", entity);
info!("{} just pressed South", entity);
} else if gamepad.just_released(GamepadButton::South) {
info!("{:?} just released South", entity);
info!("{} just released South", entity);
}
let right_trigger = gamepad.get(GamepadButton::RightTrigger2).unwrap();
if right_trigger.abs() > 0.01 {
info!("{:?} RightTrigger2 value is {}", entity, right_trigger);
info!("{} RightTrigger2 value is {}", entity, right_trigger);
}
let left_stick_x = gamepad.get(GamepadAxis::LeftStickX).unwrap();
if left_stick_x.abs() > 0.01 {
info!("{:?} LeftStickX value is {}", entity, left_stick_x);
info!("{} LeftStickX value is {}", entity, left_stick_x);
}
}
}

View File

@ -31,13 +31,13 @@ fn gamepad_events(
}
for axis_changed_event in axis_changed_events.read() {
info!(
"{:?} of {:?} is changed to {}",
"{:?} of {} is changed to {}",
axis_changed_event.axis, axis_changed_event.entity, axis_changed_event.value
);
}
for button_changed_event in button_changed_events.read() {
info!(
"{:?} of {:?} is changed to {}",
"{:?} of {} is changed to {}",
button_changed_event.button, button_changed_event.entity, button_changed_event.value
);
}

View File

@ -12,7 +12,7 @@ fn main() {
fn touch_system(touches: Res<Touches>) {
for touch in touches.iter_just_pressed() {
info!(
"just pressed touch with id: {:?}, at: {:?}",
"just pressed touch with id: {}, at: {}",
touch.id(),
touch.position()
);
@ -20,19 +20,19 @@ fn touch_system(touches: Res<Touches>) {
for touch in touches.iter_just_released() {
info!(
"just released touch with id: {:?}, at: {:?}",
"just released touch with id: {}, at: {}",
touch.id(),
touch.position()
);
}
for touch in touches.iter_just_canceled() {
info!("canceled touch with id: {:?}", touch.id());
info!("canceled touch with id: {}", touch.id());
}
// you can also iterate all current touches and retrieve their state like this:
for touch in touches.iter() {
info!("active touch: {:?}", touch);
info!("active touch: {touch:?}");
info!(" just_pressed: {}", touches.just_pressed(touch.id()));
}
}

View File

@ -114,14 +114,14 @@ fn assign_clips(
let Some(ancestor_player) = ancestor_player else {
warn!(
"Unexpected animation hierarchy for animation clip {:?}; ignoring.",
"Unexpected animation hierarchy for animation clip {}; ignoring.",
clip_id
);
continue;
};
let Some(clip_handle) = assets.get_id_handle(clip_id) else {
warn!("Clip {:?} wasn't loaded.", clip_id);
warn!("Clip {} wasn't loaded.", clip_id);
continue;
};
@ -156,7 +156,7 @@ fn handle_inputs(
for (mut player, mut clips, entity, name) in &mut animation_player {
let display_entity_name = match name {
Some(name) => name.to_string(),
None => format!("entity {entity:?}"),
None => format!("entity {entity}"),
};
if keyboard_input.just_pressed(KeyCode::Space) {
if player.all_paused() {

View File

@ -115,9 +115,9 @@ struct Target {
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.name.as_ref(), self.entity_name.as_ref()) {
(None, None) => write!(f, "animation{} of {:?}", self.index, self.entity),
(None, None) => write!(f, "animation{} of {}", self.index, self.entity),
(None, Some(entity)) => write!(f, "animation{} of {entity}", self.index),
(Some(target), None) => write!(f, "{target} of {:?}", self.entity),
(Some(target), None) => write!(f, "{target} of {}", self.entity),
(Some(target), Some(entity)) => write!(f, "{target} of {entity}"),
}?;
write!(f, ": {}", self.weight)

View File

@ -27,10 +27,14 @@ fn basic_config(root_dir: impl Into<PathBuf>, args: &Args) -> ui_test::Result<Co
match root_dir.try_exists() {
Ok(true) => { /* success */ }
Ok(false) => {
return Err(eyre!("path does not exist: {:?}", root_dir));
return Err(eyre!("path does not exist: {}", root_dir.display()));
}
Err(error) => {
return Err(eyre!("failed to read path: {:?} ({:?})", root_dir, error));
return Err(eyre!(
"failed to read path: {} ({})",
root_dir.display(),
error
));
}
}

View File

@ -353,7 +353,7 @@ fn main() {
.join(format!("{}.png", to_run.technical_name)),
);
if let Err(err) = renamed_screenshot {
println!("Failed to rename screenshot: {:?}", err);
println!("Failed to rename screenshot: {}", err);
no_screenshot_examples.push((to_run, duration));
} else {
successful_examples.push((to_run, duration));