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 shapes #114

Merged
merged 19 commits into from
Sep 14, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
446 changes: 446 additions & 0 deletions examples/ui.rs

Large diffs are not rendered by default.

49 changes: 48 additions & 1 deletion src/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@ use bevy::{
},
sprite::QUAD_HANDLE,
transform::components::{GlobalTransform, Transform},
ui::{Node, Style},
};
use lyon_tessellation::{path::Path, FillOptions};

use crate::{render::SHAPE_PIPELINE_HANDLE, utils::DrawMode};
use crate::{
render::{SHAPE_PIPELINE_HANDLE, UI_SHAPE_PIPELINE_HANDLE},
utils::DrawMode,
};

/// The colors assigned to a shape.
pub struct ShapeColors {
Expand Down Expand Up @@ -86,3 +90,46 @@ impl Default for ShapeBundle {
}
}
}

/// A Bevy `Bundle` to represent a shape visible by a UI camera.
#[allow(missing_docs)]
#[derive(Bundle)]
pub struct UiShapeBundle {
pub node: Node,
pub style: Style,
pub path: Path,
pub mode: DrawMode,
pub mesh: Handle<Mesh>,
pub colors: ShapeColors,
pub draw: Draw,
pub visible: Visible,
pub render_pipelines: RenderPipelines,
pub transform: Transform,
pub global_transform: GlobalTransform,
}

impl Default for UiShapeBundle {
fn default() -> Self {
Self {
node: Node::default(),
style: Style::default(),
path: Path::new(),
mode: DrawMode::Fill(FillOptions::default()),
mesh: QUAD_HANDLE.typed(),
render_pipelines: RenderPipelines::from_pipelines(vec![RenderPipeline::new(
UI_SHAPE_PIPELINE_HANDLE.typed(),
)]),
visible: Visible {
is_transparent: true,
..Visible::default()
},
draw: Draw::default(),
colors: ShapeColors {
main: Color::WHITE,
outline: Color::BLACK,
},
transform: Transform::default(),
global_transform: GlobalTransform::default(),
}
}
}
34 changes: 31 additions & 3 deletions src/geometry.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Types for defining and using geometries.

use bevy::transform::components::Transform;
use bevy::{transform::components::Transform, ui::Style};
use lyon_tessellation::path::{path::Builder, Path};

use crate::{
entity::{ShapeBundle, ShapeColors},
entity::{ShapeBundle, ShapeColors, UiShapeBundle},
utils::DrawMode,
};

Expand Down Expand Up @@ -101,7 +101,7 @@ impl GeometryBuilder {
self
}

/// Generates a [`ShapeBundle`] using the data contained in the path
/// Returns a [`ShapeBundle`] using the data contained in the path
/// builder.
#[must_use]
pub fn build(self, colors: ShapeColors, mode: DrawMode, transform: Transform) -> ShapeBundle {
Expand All @@ -114,7 +114,21 @@ impl GeometryBuilder {
}
}

/// Returns a [`UiShapeBundle`] using the data contained in the path
/// builder.
#[must_use]
pub fn build_ui(self, colors: ShapeColors, mode: DrawMode, style: Style) -> UiShapeBundle {
UiShapeBundle {
path: self.0.build(),
colors,
mode,
style,
..UiShapeBundle::default()
}
}

/// Generates a [`ShapeBundle`] with only one geometry.
///
/// Adds a geometry to the path builder.
///
/// # Example
Expand Down Expand Up @@ -143,6 +157,20 @@ impl GeometryBuilder {
multishape.add(shape);
multishape.build(colors, mode, transform)
}

/// Generates a [`UiShapeBundle`] with only one geometry.
///
/// Adds a geometry to the path builder.
pub fn build_ui_as(
shape: &impl Geometry,
colors: ShapeColors,
mode: DrawMode,
style: Style,
) -> UiShapeBundle {
let mut multishape = Self::new();
multishape.add(shape);
multishape.build_ui(colors, mode, style)
}
}

impl Default for GeometryBuilder {
Expand Down
7 changes: 5 additions & 2 deletions src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use bevy::{
app::{App, Plugin},
asset::{Assets, Handle},
ecs::{
query::{Added, Changed, Or},
query::{Changed, Or},
schedule::{StageLabel, SystemStage},
system::{Query, ResMut},
},
Expand Down Expand Up @@ -99,6 +99,7 @@ impl Plugin for ShapePlugin {
.add_system_to_stage(Stage::Shape, complete_shape_bundle_system);

crate::render::add_shape_pipeline(&mut app.world);
crate::render::add_ui_shape_pipeline(&mut app.world);
}
}

Expand All @@ -111,9 +112,11 @@ fn complete_shape_bundle_system(
mut stroke_tess: ResMut<StrokeTessellator>,
mut query: Query<
(&DrawMode, &Path, &mut Handle<Mesh>, &ShapeColors),
Or<(Added<Path>, Changed<ShapeColors>, Changed<DrawMode>)>,
Or<(Changed<Path>, Changed<ShapeColors>, Changed<DrawMode>)>,
>,
) {
// TODO: Handle `Shape` component changed.

for (tess_mode, path, mut mesh, colors) in query.iter_mut() {
let mut buffers = VertexBuffers::new();

Expand Down
75 changes: 74 additions & 1 deletion src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ use bevy::{

#[allow(missing_docs, clippy::unreadable_literal)]
pub const SHAPE_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 3868147544761532180);
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 0x35ae6bb2984f7f14);

#[allow(missing_docs, clippy::unreadable_literal)]
pub const UI_SHAPE_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 0x158745fbe65cbe34);

#[allow(clippy::too_many_lines)]
fn build_shape_pipeline(shaders: &mut Assets<Shader>) -> PipelineDescriptor {
Expand Down Expand Up @@ -93,3 +97,72 @@ pub(crate) fn add_shape_pipeline(world: &mut World) {
let mut shaders = world.get_resource_mut::<Assets<Shader>>().unwrap();
pipelines.set_untracked(SHAPE_PIPELINE_HANDLE, build_shape_pipeline(&mut shaders));
}

#[allow(clippy::too_many_lines)]
fn build_ui_shape_pipeline(shaders: &mut Assets<Shader>) -> PipelineDescriptor {
PipelineDescriptor {
depth_stencil: Some(DepthStencilState {
format: TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: CompareFunction::Less,
stencil: StencilState {
front: StencilFaceState::IGNORE,
back: StencilFaceState::IGNORE,
read_mask: 0,
write_mask: 0,
},
bias: DepthBiasState {
constant: 0,
slope_scale: 0.0,
clamp: 0.0,
},
}),
color_target_states: vec![ColorTargetState {
format: TextureFormat::default(),
blend: Some(BlendState {
color: BlendComponent {
src_factor: BlendFactor::SrcAlpha,
dst_factor: BlendFactor::OneMinusSrcAlpha,
operation: BlendOperation::Add,
},
alpha: BlendComponent {
src_factor: BlendFactor::One,
dst_factor: BlendFactor::One,
operation: BlendOperation::Add,
},
}),
write_mask: ColorWrite::ALL,
}],
primitive: PrimitiveState {
topology: PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: FrontFace::Cw,
cull_mode: Some(Face::Back),
polygon_mode: PolygonMode::Fill,
clamp_depth: false,
conservative: false,
},
..PipelineDescriptor::new(ShaderStages {
vertex: shaders.add(Shader::from_glsl(
ShaderStage::Vertex,
include_str!("ui_shape.vert"),
)),
fragment: Some(shaders.add(Shader::from_glsl(
ShaderStage::Fragment,
include_str!("ui_shape.frag"),
))),
})
}
}

pub(crate) fn add_ui_shape_pipeline(world: &mut World) {
let world = world.cell();
let mut pipelines = world
.get_resource_mut::<Assets<PipelineDescriptor>>()
.unwrap();
let mut shaders = world.get_resource_mut::<Assets<Shader>>().unwrap();
pipelines.set_untracked(
UI_SHAPE_PIPELINE_HANDLE,
build_ui_shape_pipeline(&mut shaders),
);
}
9 changes: 9 additions & 0 deletions src/render/ui_shape.frag
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#version 450

layout(location = 0) in vec4 v_color;

layout(location = 0) out vec4 o_Target;

void main() {
o_Target = v_color;
}
20 changes: 20 additions & 0 deletions src/render/ui_shape.vert
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#version 450

layout(location = 0) in vec2 Vertex_Position_2D;
layout(location = 1) in vec4 Vertex_Color;

layout(location = 0) out vec4 v_color;

layout(set = 0, binding = 0) uniform CameraViewProj {
mat4 ViewProj;
};

layout(set = 1, binding = 0) uniform Transform {
mat4 Object;
};

void main() {
v_color = Vertex_Color;
vec2 position = Vertex_Position_2D;
gl_Position = ViewProj * Object * vec4(position, 0.0, 1.0);
}
3 changes: 3 additions & 0 deletions src/shapes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ impl Default for RectangleOrigin {
}
}

// TODO: Implement Rectangle::square(f32). Also use extents: Vec2 instead of
// width/height

#[allow(missing_docs)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rectangle {
Expand Down
2 changes: 2 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use lyon_tessellation::{
FillOptions, StrokeOptions,
};

// TODO: Include shape color(s) in DrawMode (Rename to DrawOptions).

/// Determines how a shape will be drawn.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DrawMode {
Expand Down