Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UI node outlines #9931

Merged
merged 15 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions crates/bevy_ui/src/layout/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
mod convert;
pub mod debug;

use crate::{ContentSize, Node, Style, UiScale};
use crate::{ContentSize, Node, Outline, Style, UiScale};
use bevy_ecs::{
change_detection::DetectChanges,
change_detection::{DetectChanges, DetectChangesMut},
entity::Entity,
event::EventReader,
query::{With, Without},
Expand Down Expand Up @@ -383,6 +383,27 @@ pub fn ui_layout_system(
}
}

/// Resolve and update the widths of Node outlines
pub fn resolve_outlines_system(
primary_window: Query<&Window, With<PrimaryWindow>>,
ui_scale: Res<UiScale>,
mut outlines_query: Query<(&Outline, &mut Node)>,
) {
let viewport_size = primary_window
.get_single()
.map(|window| Vec2::new(window.resolution.width(), window.resolution.height()))
.unwrap_or(Vec2::ZERO)
/ ui_scale.0 as f32;

for (outline, mut node) in outlines_query.iter_mut() {
node.bypass_change_detection().outline_width = outline
.width
.resolve(node.size().x, viewport_size)
.unwrap_or(0.)
.max(0.);
}
}

#[inline]
/// Round `value` to the nearest whole integer, with ties (values with a fractional part equal to 0.5) rounded towards positive infinity.
fn round_ties_up(value: f32) -> f32 {
Expand Down
6 changes: 6 additions & 0 deletions crates/bevy_ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ pub enum UiSystem {
Focus,
/// After this label, the [`UiStack`] resource has been updated
Stack,
/// After this label, node outline widths have been updated
Outlines,
}

/// The current scale of the UI.
Expand Down Expand Up @@ -122,6 +124,7 @@ impl Plugin for UiPlugin {
.register_type::<widget::Button>()
.register_type::<widget::Label>()
.register_type::<ZIndex>()
.register_type::<Outline>()
.add_systems(
PreUpdate,
ui_focus_system.in_set(UiSystem::Focus).after(InputSystem),
Expand Down Expand Up @@ -172,6 +175,9 @@ impl Plugin for UiPlugin {
ui_layout_system
.in_set(UiSystem::Layout)
.before(TransformSystem::TransformPropagate),
resolve_outlines_system
.in_set(UiSystem::Outlines)
.after(UiSystem::Layout),
ui_stack_system.in_set(UiSystem::Stack),
update_clipping_system.after(TransformSystem::TransformPropagate),
),
Expand Down
94 changes: 94 additions & 0 deletions crates/bevy_ui/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use bevy_window::{PrimaryWindow, Window};
pub use pipeline::*;
pub use render_pass::*;

use crate::Outline;
use crate::{
prelude::UiCameraConfig, BackgroundColor, BorderColor, CalculatedClip, ContentSize, Node,
Style, UiImage, UiScale, UiStack, UiTextureAtlasImage, Val,
Expand Down Expand Up @@ -85,6 +86,7 @@ pub fn build_ui_render(app: &mut App) {
extract_uinode_borders.after(RenderUiSystem::ExtractAtlasNode),
#[cfg(feature = "bevy_text")]
extract_text_uinodes.after(RenderUiSystem::ExtractAtlasNode),
extract_uinode_outlines.after(RenderUiSystem::ExtractAtlasNode),
),
)
.add_systems(
Expand Down Expand Up @@ -389,6 +391,98 @@ pub fn extract_uinode_borders(
}
}

pub fn extract_uinode_outlines(
mut commands: Commands,
mut extracted_uinodes: ResMut<ExtractedUiNodes>,
ui_stack: Extract<Res<UiStack>>,
uinode_query: Extract<
Query<(
&Node,
&GlobalTransform,
&Outline,
&ViewVisibility,
Option<&Parent>,
)>,
>,
clip_query: Query<&CalculatedClip>,
) {
let image = AssetId::<Image>::default();

for (stack_index, entity) in ui_stack.uinodes.iter().enumerate() {
if let Ok((node, global_transform, outline, view_visibility, maybe_parent)) =
uinode_query.get(*entity)
{
// Skip invisible outlines
if !view_visibility.get() || outline.color.a() == 0. || node.outline_width == 0. {
continue;
}

// Outline's are drawn outside of a node's borders, so they are clipped using the clipping Rect of their UI node entity's parent.
let clip = maybe_parent
.and_then(|parent| clip_query.get(parent.get()).ok().map(|clip| clip.clip));

// Calculate the outline rects.
let inner_rect = Rect::from_center_size(Vec2::ZERO, node.size());
let outer_rect = inner_rect.inset(node.outline_width());
let outline_edges = [
// Left edge
Rect::new(
outer_rect.min.x,
outer_rect.min.y,
inner_rect.min.x,
outer_rect.max.y,
),
// Right edge
Rect::new(
inner_rect.max.x,
outer_rect.min.y,
outer_rect.max.x,
outer_rect.max.y,
),
// Top edge
Rect::new(
inner_rect.min.x,
outer_rect.min.y,
inner_rect.max.x,
inner_rect.min.y,
),
// Bottom edge
Rect::new(
inner_rect.min.x,
inner_rect.max.y,
inner_rect.max.x,
outer_rect.max.y,
),
];

let transform = global_transform.compute_matrix();

for edge in outline_edges {
if edge.min.x < edge.max.x && edge.min.y < edge.max.y {
extracted_uinodes.uinodes.insert(
commands.spawn_empty().id(),
ExtractedUiNode {
stack_index,
// This translates the uinode's transform to the center of the current border rectangle
transform: transform * Mat4::from_translation(edge.center().extend(0.)),
color: outline.color,
rect: Rect {
max: edge.size(),
..Default::default()
},
image,
atlas_size: None,
clip,
flip_x: false,
flip_y: false,
},
);
}
}
}
}
}

pub fn extract_uinodes(
mut extracted_uinodes: ResMut<ExtractedUiNodes>,
images: Extract<Res<Assets<Image>>>,
Expand Down
40 changes: 40 additions & 0 deletions crates/bevy_ui/src/ui_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ pub struct Node {
/// The size of the node as width and height in logical pixels
/// automatically calculated by [`super::layout::ui_layout_system`]
pub(crate) calculated_size: Vec2,
/// The width of this node's outline
/// If this value is `Auto`, negative or `0.` then no outline will be rendered
/// automatically calculated by [`super::layout::resolve_outlines_system`]
pub(crate) outline_width: f32,
}

impl Node {
Expand Down Expand Up @@ -61,11 +65,19 @@ impl Node {
),
}
}

#[inline]
/// Returns the thickness of the UI node's outline.
/// If this value is negative or `0.` then no outline will be rendered.
pub fn outline_width(&self) -> f32 {
self.outline_width
}
}

impl Node {
pub const DEFAULT: Self = Self {
calculated_size: Vec2::ZERO,
outline_width: 0.,
};
}

Expand Down Expand Up @@ -1448,6 +1460,34 @@ impl Default for BorderColor {
}
}

#[derive(Component, Copy, Clone, Default, Debug, Reflect)]
#[reflect(Component, Default)]
/// The `Outline` component adds an outline outside the border of a UI node.
/// Outlines do not take up space in the layout
pub struct Outline {
/// The width of the outline
///
/// Percentage `Val` values are resolved based on the width of the outlined [`Node`]
pub width: Val,
/// Color of the outline
pub color: Color,
}

impl Outline {
/// Create a new outline
pub fn new(width: Val, color: Color) -> Self {
Self { width, color }
}

/// Create a new outline with width in logical pixels
pub fn px(width: f32, color: Color) -> Self {
Self {
width: Val::Px(width),
color,
}
}
}

/// The 2D texture displayed for this UI node
#[derive(Component, Clone, Debug, Reflect, Default)]
#[reflect(Component, Default)]
Expand Down
30 changes: 18 additions & 12 deletions examples/ui/borders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,20 +97,26 @@ fn setup(mut commands: Commands) {
})
.id();
let bordered_node = commands
.spawn(NodeBundle {
style: Style {
width: Val::Px(50.),
height: Val::Px(50.),
border: borders[i % borders.len()],
margin: UiRect::all(Val::Px(2.)),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
.spawn((
NodeBundle {
style: Style {
width: Val::Px(50.),
height: Val::Px(50.),
border: borders[i % borders.len()],
margin: UiRect::all(Val::Px(2.)),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..Default::default()
},
background_color: Color::BLUE.into(),
border_color: Color::WHITE.with_a(0.5).into(),
..Default::default()
},
background_color: Color::BLUE.into(),
border_color: Color::WHITE.with_a(0.5).into(),
..Default::default()
})
Outline {
width: Val::Px(1.),
color: Color::PURPLE,
},
))
.add_child(inner_spot)
.id();
commands.entity(root).add_child(bordered_node);
Expand Down