From 306c1ac6177d8ff55c07410b8aaac5ff4cf84020 Mon Sep 17 00:00:00 2001 From: Mark Nokalt Date: Fri, 28 Oct 2022 22:43:14 +0000 Subject: [PATCH] Rename Handle::as_weak() to cast_weak() (#5321) # Objective Following discussion on #3536 and #3522, `Handle::as_weak()` takes a type `U`, reinterpreting the handle as of another asset type while keeping the same ID. This is mainly used today in font atlas code. This PR does two things: - Rename the method to `cast_weak()` to make its intent more clear - Actually change the type uuid in the handle if it's not an asset path variant. ## Migration Guide - Rename `Handle::as_weak` uses to `Handle::cast_weak` The method now properly sets the associated type uuid if the handle is a direct reference (e.g. not a reference to an `AssetPath`), so adjust you code accordingly if you relied on the previous behavior. --- crates/bevy_asset/src/handle.rs | 10 ++++++++-- crates/bevy_text/src/glyph_brush.rs | 2 +- examples/ui/font_atlas_debug.rs | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/bevy_asset/src/handle.rs b/crates/bevy_asset/src/handle.rs index 1ef5116d43..677f1e053e 100644 --- a/crates/bevy_asset/src/handle.rs +++ b/crates/bevy_asset/src/handle.rs @@ -160,9 +160,15 @@ impl Handle { } /// Recasts this handle as a weak handle of an Asset `U`. - pub fn as_weak(&self) -> Handle { + pub fn cast_weak(&self) -> Handle { + let id = if let HandleId::Id(_, id) = self.id { + HandleId::Id(U::TYPE_UUID, id) + } else { + self.id + }; + Handle { - id: self.id, + id, handle_type: HandleType::Weak, marker: PhantomData, } diff --git a/crates/bevy_text/src/glyph_brush.rs b/crates/bevy_text/src/glyph_brush.rs index 80b47dd57c..476b806460 100644 --- a/crates/bevy_text/src/glyph_brush.rs +++ b/crates/bevy_text/src/glyph_brush.rs @@ -106,7 +106,7 @@ impl GlyphBrush { let section_data = sections_data[sg.section_index]; if let Some(outlined_glyph) = section_data.1.font.outline_glyph(glyph) { let bounds = outlined_glyph.px_bounds(); - let handle_font_atlas: Handle = section_data.0.as_weak(); + let handle_font_atlas: Handle = section_data.0.cast_weak(); let font_atlas_set = font_atlas_set_storage .get_or_insert_with(handle_font_atlas, FontAtlasSet::default); diff --git a/examples/ui/font_atlas_debug.rs b/examples/ui/font_atlas_debug.rs index e2ea358d66..8dd72311c4 100644 --- a/examples/ui/font_atlas_debug.rs +++ b/examples/ui/font_atlas_debug.rs @@ -37,7 +37,7 @@ fn atlas_render_system( font_atlas_sets: Res>, texture_atlases: Res>, ) { - if let Some(set) = font_atlas_sets.get(&state.handle.as_weak::()) { + if let Some(set) = font_atlas_sets.get(&state.handle.cast_weak::()) { if let Some((_size, font_atlas)) = set.iter().next() { let x_offset = state.atlas_count as f32; if state.atlas_count == font_atlas.len() as u32 {