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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// plotters-conrod
//
// Conrod backend for Plotters
// Copyright: 2020, Valerian Saliou <valerian@valeriansaliou.name>
// License: MIT

use std::convert::From;

use conrod_core::{self as conrod, position::Scalar as ConrodScalar, Positionable, Widget};
use plotters_backend::{
    text_anchor, BackendColor, BackendCoord, BackendStyle, BackendTextStyle, DrawingBackend,
    DrawingErrorKind,
};

use crate::error::ConrodBackendError;
use crate::graph::ConrodBackendReusableGraph;
use crate::triangulate;
use crate::utils::{color, convert, path, position, shape};

/// The Conrod drawing backend
pub struct ConrodBackend<'a, 'b> {
    ui: &'a mut conrod::UiCell<'b>,
    size: (u32, u32),
    parent: conrod::widget::Id,
    font: conrod::text::font::Id,
    graph: &'a mut ConrodBackendReusableGraph,
}

impl<'a, 'b> ConrodBackend<'a, 'b> {
    /// Create a new Conrod backend drawer, with:
    /// - `ui`: the `UiCell` that was derived from `Ui` for this frame
    /// - `(plot_width, plot_height)`: the size of your plot in pixels (make sure it matches its parent canvas size)
    /// - `ids.parent`: the `widget::Id` of the canvas that contains your plot (of the same size than the plot itself)
    /// - `fonts.regular`: the `font::Id` of the font to use to draw text (ie. a Conrod font identifier)
    /// - `conrod_graph`: a mutable reference to the graph instance you built outside of the drawing loop (pass it as a mutable reference)
    pub fn new(
        ui: &'a mut conrod::UiCell<'b>,
        size: (u32, u32),
        parent: conrod::widget::Id,
        font: conrod::text::font::Id,
        graph: &'a mut ConrodBackendReusableGraph,
    ) -> Self {
        // Important: prepare the IDs graph, and reset all incremented IDs counters back to zero; \
        //   if we do not do that, counts will increment forever and the graph will be enlarged \
        //   infinitely, which would result in a huge memory leak.
        graph.prepare();

        Self {
            ui,
            parent,
            font,
            size,
            graph,
        }
    }
}

impl<'a, 'b> DrawingBackend for ConrodBackend<'a, 'b> {
    type ErrorType = ConrodBackendError;

    fn get_size(&self) -> (u32, u32) {
        self.size
    }

    fn ensure_prepared(&mut self) -> Result<(), DrawingErrorKind<ConrodBackendError>> {
        Ok(())
    }

    fn present(&mut self) -> Result<(), DrawingErrorKind<ConrodBackendError>> {
        Ok(())
    }

    fn draw_pixel(
        &mut self,
        _point: BackendCoord,
        _color: BackendColor,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Not supported yet (rendering ignored)
        // Notice: doing this efficiently would require building an internal buffer on 'self', and \
        //   rendering it as a Conrod image widget when the final call to 'present()' is done. \
        //   doing it solely by drawing Conrod rectangle primitives from there has been deemed \
        //   super inefficient. Note that this buffer would be shared with 'blit_bitmap()', and \
        //   thus alpha-channel pixels would need to be blended accordingly.

        Ok(())
    }

    fn draw_line<S: BackendStyle>(
        &mut self,
        from: BackendCoord,
        to: BackendCoord,
        style: &S,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Acquire absolute position generator (in parent container)
        if let Some(position) = position::PositionParent::from(&self.ui, self.parent) {
            // Generate line style
            let line_style = conrod::widget::primitive::line::Style::solid()
                .color(color::Color::from(&style.color()).into())
                .thickness(style.stroke_width() as ConrodScalar);

            // Render line widget
            conrod::widget::line::Line::abs_styled(
                position.abs_point_conrod_scalar(&from),
                position.abs_point_conrod_scalar(&to),
                line_style,
            )
            .top_left_of(self.parent)
            .set(self.graph.line.next(&mut self.ui), &mut self.ui);

            Ok(())
        } else {
            Err(DrawingErrorKind::DrawingError(
                ConrodBackendError::NoParentPosition,
            ))
        }
    }

    fn draw_rect<S: BackendStyle>(
        &mut self,
        upper_left: BackendCoord,
        bottom_right: BackendCoord,
        style: &S,
        fill: bool,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Generate rectangle style
        let rectangle_style = if fill {
            conrod::widget::primitive::shape::Style::fill_with(
                color::Color::from(&style.color()).into(),
            )
        } else {
            conrod::widget::primitive::shape::Style::outline_styled(
                conrod::widget::primitive::line::Style::new()
                    .color(color::Color::from(&style.color()).into())
                    .thickness(style.stroke_width() as ConrodScalar),
            )
        };

        // Render rectangle widget
        conrod::widget::rectangle::Rectangle::styled(
            [
                (bottom_right.0 - upper_left.0) as ConrodScalar,
                (bottom_right.1 - upper_left.1) as ConrodScalar,
            ],
            rectangle_style,
        )
        .top_left_with_margins_on(
            self.parent,
            upper_left.1 as ConrodScalar,
            upper_left.0 as ConrodScalar,
        )
        .set(self.graph.rect.next(&mut self.ui), &mut self.ui);

        Ok(())
    }

    fn draw_path<S: BackendStyle, I: IntoIterator<Item = BackendCoord>>(
        &mut self,
        path: I,
        style: &S,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Acquire absolute position generator (in parent container)
        if let Some(position) = position::PositionParent::from(&self.ui, self.parent) {
            // Generate line style
            let line_style = conrod::widget::primitive::line::Style::solid()
                .color(color::Color::from(&style.color()).into())
                .thickness(style.stroke_width() as ConrodScalar);

            // Render point path widget
            conrod::widget::point_path::PointPath::abs_styled(
                path.into_iter()
                    .map(|point| position.abs_point_conrod_scalar(&point))
                    .collect::<Vec<conrod::position::Point>>(),
                line_style,
            )
            .top_left_of(self.parent)
            .set(self.graph.path.next(&mut self.ui), &mut self.ui);

            Ok(())
        } else {
            Err(DrawingErrorKind::DrawingError(
                ConrodBackendError::NoParentPosition,
            ))
        }
    }

    fn draw_circle<S: BackendStyle>(
        &mut self,
        center: BackendCoord,
        radius: u32,
        style: &S,
        fill: bool,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Generate circle style
        let circle_style = if fill {
            conrod::widget::primitive::shape::Style::fill_with(
                color::Color::from(&style.color()).into(),
            )
        } else {
            conrod::widget::primitive::shape::Style::outline_styled(
                conrod::widget::primitive::line::Style::new()
                    .color(color::Color::from(&style.color()).into())
                    .thickness(style.stroke_width() as ConrodScalar),
            )
        };

        // Render circle widget
        conrod::widget::circle::Circle::styled(radius as ConrodScalar, circle_style)
            .top_left_with_margins_on(
                self.parent,
                (center.1 - radius as i32) as ConrodScalar,
                (center.0 - radius as i32) as ConrodScalar,
            )
            .set(self.graph.circle.next(&mut self.ui), &mut self.ui);

        Ok(())
    }

    fn fill_polygon<S: BackendStyle, I: IntoIterator<Item = BackendCoord>>(
        &mut self,
        vert: I,
        style: &S,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Acquire absolute position generator (in parent container)
        if let Some(position) = position::PositionParent::from(&self.ui, self.parent) {
            // Paint a simplified path, where empty areas are removed and un-necessary points are \
            //   cleared. This is required for triangulation to work properly, and it reduces \
            //   the number of triangles on screen to a strict minimum.
            let simplified_path: Vec<_> = path::PathSimplifier::from(
                vert.into_iter()
                    .map(|vertex| position.abs_point_path_simplifier(&vertex)),
            )
            .collect();

            // Find closed shapes (eg. when the plot area goes from positive to negative, we need \
            //   to split the path into two distinct paths, otherwise we will not be able to \
            //   triangulate properly, and thus we will not be able to fill the shape)
            if let Ok(mut shape_splitter) = shape::ShapeSplitter::try_from(&simplified_path) {
                // Generate polygon style
                let polygon_style = conrod::widget::primitive::shape::Style::fill_with(
                    color::Color::from(&style.color()).into(),
                );

                // Triangulate the polygon points, giving back a list of triangles that can be \
                //   filled into a contiguous area.
                // Notice: this method takes into account concave shapes
                for shape_points in shape_splitter.collect() {
                    // Is that enough points to form at least a triangle?
                    if shape_points.len() >= 3 {
                        let triangles = triangulate::triangulate_points(shape_points.iter());

                        for index in 0..triangles.size() {
                            conrod::widget::polygon::Polygon::abs_styled(
                                triangles.get_triangle(index).points.iter().copied(),
                                polygon_style,
                            )
                            .top_left_of(self.parent)
                            .set(self.graph.fill.next(&mut self.ui), &mut self.ui);
                        }
                    }
                }
            }

            Ok(())
        } else {
            Err(DrawingErrorKind::DrawingError(
                ConrodBackendError::NoParentPosition,
            ))
        }
    }

    fn draw_text<S: BackendTextStyle>(
        &mut self,
        text: &str,
        style: &S,
        pos: BackendCoord,
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Adapt font style from rasterizer style to Conrod
        let (text_width_estimated, font_size_final) = convert::font_style(text, style.size());

        // Generate text style
        let mut text_style = conrod::widget::primitive::text::Style::default();

        text_style.color = Some(color::Color::from(&style.color()).into());
        text_style.font_id = Some(Some(self.font));
        text_style.font_size = Some(font_size_final);

        text_style.justify = Some(match style.anchor().h_pos {
            text_anchor::HPos::Left => conrod::text::Justify::Left,
            text_anchor::HPos::Right => conrod::text::Justify::Right,
            text_anchor::HPos::Center => conrod::text::Justify::Center,
        });

        // Render text widget
        conrod::widget::Text::new(text)
            .with_style(text_style)
            .top_left_with_margins_on(
                self.parent,
                pos.1 as ConrodScalar - (style.size() / 2.0 + 1.0),
                pos.0 as ConrodScalar - text_width_estimated,
            )
            .set(self.graph.text.next(&mut self.ui), &mut self.ui);

        Ok(())
    }

    fn estimate_text_size<S: BackendTextStyle>(
        &self,
        text: &str,
        style: &S,
    ) -> Result<(u32, u32), DrawingErrorKind<Self::ErrorType>> {
        let (text_width_estimated, text_height_estimated) = convert::font_style(text, style.size());

        // Return as (size_on_x, size_on_y)
        Ok((text_width_estimated as u32, text_height_estimated))
    }

    fn blit_bitmap(
        &mut self,
        _pos: BackendCoord,
        (_iw, _ih): (u32, u32),
        _src: &[u8],
    ) -> Result<(), DrawingErrorKind<Self::ErrorType>> {
        // Not supported yet (rendering ignored)
        // Notice: doing this efficiently would require building an internal buffer on 'self', and \
        //   rendering it as a Conrod image widget when the final call to 'present()' is done. \
        //   Note that this buffer would be shared with 'draw_pixel()', and thus alpha-channel \
        //   pixels would need to be blended accordingly.

        Ok(())
    }
}