Skip to content

Commit

Permalink
Rename Handle::as_weak() to cast_weak() (#5321)
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
manokara committed Oct 28, 2022
1 parent 71f8b4a commit 306c1ac
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
10 changes: 8 additions & 2 deletions crates/bevy_asset/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,15 @@ impl<T: Asset> Handle<T> {
}

/// Recasts this handle as a weak handle of an Asset `U`.
pub fn as_weak<U: Asset>(&self) -> Handle<U> {
pub fn cast_weak<U: Asset>(&self) -> Handle<U> {
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,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_text/src/glyph_brush.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<FontAtlasSet> = section_data.0.as_weak();
let handle_font_atlas: Handle<FontAtlasSet> = section_data.0.cast_weak();
let font_atlas_set = font_atlas_set_storage
.get_or_insert_with(handle_font_atlas, FontAtlasSet::default);

Expand Down
2 changes: 1 addition & 1 deletion examples/ui/font_atlas_debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn atlas_render_system(
font_atlas_sets: Res<Assets<FontAtlasSet>>,
texture_atlases: Res<Assets<TextureAtlas>>,
) {
if let Some(set) = font_atlas_sets.get(&state.handle.as_weak::<FontAtlasSet>()) {
if let Some(set) = font_atlas_sets.get(&state.handle.cast_weak::<FontAtlasSet>()) {
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 {
Expand Down

0 comments on commit 306c1ac

Please sign in to comment.