1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
//! Vector image is used to create images, that consists from a fixed set of basic primitives, such as lines,
//! triangles, rectangles, etc. It could be used to create simple images that can be infinitely scaled without
//! aliasing issues. See [`VectorImage`] docs for more info and usage examples.
#![warn(missing_docs)]
use crate::{
core::{
algebra::Vector2, color::Color, math::Rect, math::Vector2Ext, pool::Handle,
reflect::prelude::*, type_traits::prelude::*, visitor::prelude::*,
},
draw::{CommandTexture, Draw, DrawingContext},
message::UiMessage,
widget::{Widget, WidgetBuilder},
BuildContext, Control, UiNode, UserInterface,
};
use fyrox_core::uuid_provider;
use std::ops::{Deref, DerefMut};
use strum_macros::{AsRefStr, EnumString, EnumVariantNames};
/// Primitive is a simplest shape, that consists of one or multiple lines of the same thickness.
#[derive(Clone, Debug, Visit, Reflect, AsRefStr, EnumString, EnumVariantNames)]
pub enum Primitive {
/// Solid triangle primitive.
Triangle {
/// Points of the triangle in local coordinates.
points: [Vector2<f32>; 3],
},
/// A line of fixed thickness between two points.
Line {
/// Beginning of the line in local coordinates.
begin: Vector2<f32>,
/// End of the line in local coordinates.
end: Vector2<f32>,
/// Thickness of the line in absolute units.
thickness: f32,
},
/// Solid circle primitive.
Circle {
/// Center of the circle in local coordinates.
center: Vector2<f32>,
/// Radius of the circle in absolute units.
radius: f32,
/// Amount of segments that is used to approximate the circle using triangles. The higher the value, the smoother the
/// circle and vice versa.
segments: usize,
},
/// Wireframe rectangle primitive.
Rectangle {
/// Rectangle bounds in local coordinates.
rect: Rect<f32>,
/// Thickness of the lines on the rectangle in absolute units.
thickness: f32,
},
/// Solid rectangle primitive.
RectangleFilled {
/// Rectangle bounds in local coordinates.
rect: Rect<f32>,
},
}
uuid_provider!(Primitive = "766be1b3-6d1c-4466-bcf3-7093017c9e31");
impl Default for Primitive {
fn default() -> Self {
Self::Line {
begin: Default::default(),
end: Default::default(),
thickness: 0.0,
}
}
}
fn line_thickness_vector(a: Vector2<f32>, b: Vector2<f32>, thickness: f32) -> Vector2<f32> {
if let Some(dir) = (b - a).try_normalize(f32::EPSILON) {
Vector2::new(dir.y, -dir.x).scale(thickness * 0.5)
} else {
Vector2::default()
}
}
impl Primitive {
/// Returns current bounds of the primitive as `min, max` tuple.
pub fn bounds(&self) -> (Vector2<f32>, Vector2<f32>) {
match self {
Primitive::Triangle { points } => {
let min = points[0]
.per_component_min(&points[1])
.per_component_min(&points[2]);
let max = points[0]
.per_component_max(&points[1])
.per_component_max(&points[2]);
(min, max)
}
Primitive::Line {
begin,
end,
thickness,
} => {
let tv = line_thickness_vector(*begin, *end, *thickness);
let mut min = begin + tv;
let mut max = min;
for v in &[begin - tv, end + tv, end - tv] {
min = min.per_component_min(v);
max = max.per_component_max(v);
}
(min, max)
}
Primitive::Circle { radius, center, .. } => {
let radius = Vector2::new(*radius, *radius);
(center - radius, center + radius)
}
Primitive::Rectangle { rect, .. } | Primitive::RectangleFilled { rect } => {
(rect.left_top_corner(), rect.right_bottom_corner())
}
}
}
}
/// Vector image is used to create images, that consists from a fixed set of basic primitives, such as lines,
/// triangles, rectangles, etc. It could be used to create simple images that can be infinitely scaled without
/// aliasing issues.
///
/// ## Examples
///
/// The following example creates a cross shape with given size and thickness:
///
/// ```rust
/// # use fyrox_ui::{
/// # core::{algebra::Vector2, pool::Handle},
/// # vector_image::{Primitive, VectorImageBuilder},
/// # widget::WidgetBuilder,
/// # BuildContext, UiNode, BRUSH_BRIGHT,
/// # };
/// #
/// fn make_cross_vector_image(
/// ctx: &mut BuildContext,
/// size: f32,
/// thickness: f32,
/// ) -> Handle<UiNode> {
/// VectorImageBuilder::new(
/// WidgetBuilder::new()
/// // Color of the image is defined by the foreground brush of the base widget.
/// .with_foreground(BRUSH_BRIGHT),
/// )
/// .with_primitives(vec![
/// Primitive::Line {
/// begin: Vector2::new(0.0, 0.0),
/// end: Vector2::new(size, size),
/// thickness,
/// },
/// Primitive::Line {
/// begin: Vector2::new(size, 0.0),
/// end: Vector2::new(0.0, size),
/// thickness,
/// },
/// ])
/// .build(ctx)
/// }
/// ```
///
/// Keep in mind that all primitives located in local coordinates. The color of the vector image can be changed by
/// setting a new foreground brush.
#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
pub struct VectorImage {
/// Base widget of the image.
pub widget: Widget,
/// Current set of primitives that will be drawn.
pub primitives: Vec<Primitive>,
}
crate::define_widget_deref!(VectorImage);
uuid_provider!(VectorImage = "7e535b65-0178-414e-b310-e208afc0eeb5");
impl Control for VectorImage {
fn measure_override(&self, _ui: &UserInterface, _available_size: Vector2<f32>) -> Vector2<f32> {
if self.primitives.is_empty() {
Default::default()
} else {
let mut max = Vector2::new(-f32::MAX, -f32::MAX);
let mut min = Vector2::new(f32::MAX, f32::MAX);
for primitive in self.primitives.iter() {
let (pmin, pmax) = primitive.bounds();
min = min.per_component_min(&pmin);
max = max.per_component_max(&pmax);
}
max - min
}
}
fn draw(&self, drawing_context: &mut DrawingContext) {
let bounds = self.widget.bounding_rect();
for primitive in self.primitives.iter() {
match primitive {
Primitive::Triangle { points } => {
let pts = [
bounds.position + points[0],
bounds.position + points[1],
bounds.position + points[2],
];
drawing_context.push_triangle_filled(pts);
}
Primitive::Line {
begin,
end,
thickness,
} => {
drawing_context.push_line(
bounds.position + *begin,
bounds.position + *end,
*thickness,
);
}
Primitive::Circle {
center,
radius,
segments,
} => drawing_context.push_circle(
bounds.position + *center,
*radius,
*segments,
Color::WHITE,
),
Primitive::RectangleFilled { rect } => drawing_context.push_rect_filled(rect, None),
Primitive::Rectangle { rect, thickness } => {
drawing_context.push_rect(rect, *thickness)
}
}
}
drawing_context.commit(
self.clip_bounds(),
self.widget.foreground(),
CommandTexture::None,
None,
);
}
fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
self.widget.handle_routed_message(ui, message);
}
}
/// Vector image builder creates [`VectorImage`] instances and adds them to the user interface.
pub struct VectorImageBuilder {
widget_builder: WidgetBuilder,
primitives: Vec<Primitive>,
}
impl VectorImageBuilder {
/// Creates new vector image builder.
pub fn new(widget_builder: WidgetBuilder) -> Self {
Self {
widget_builder,
primitives: Default::default(),
}
}
/// Sets the desired set of primitives.
pub fn with_primitives(mut self, primitives: Vec<Primitive>) -> Self {
self.primitives = primitives;
self
}
/// Builds the vector image widget.
pub fn build_node(self) -> UiNode {
let image = VectorImage {
widget: self.widget_builder.build(),
primitives: self.primitives,
};
UiNode::new(image)
}
/// Finishes vector image building and adds it to the user interface.
pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
ctx.add_node(self.build_node())
}
}