-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathrenderer.rs
309 lines (277 loc) · 11.9 KB
/
renderer.rs
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
use std::thread;
use std::sync::mpsc::{self, TryRecvError};
use piston_window::{
PistonWindow,
WindowSettings,
AdvancedWindow,
Event as PistonEvent,
Input,
G2d,
context,
clear,
line,
polygon,
};
use app::TurtleApp;
use event::from_piston_event;
use extensions::ConvertScreenCoordinates;
use query::DrawingCommand;
use state::{Path, Polygon, Pen, TurtleState, DrawingState};
use {Point, Event, Color, color};
fn update_window(window: &mut PistonWindow, current: DrawingState, next: DrawingState) -> DrawingState {
if next.title != current.title {
window.set_title(next.title.clone());
}
if next.width != current.width || next.height != current.height {
window.window.window.set_inner_size(next.width, next.height);
}
if next.maximized != current.maximized {
window.window.window.set_maximized(next.maximized);
}
if next.fullscreen != current.fullscreen {
if next.fullscreen {
window.window.window.set_fullscreen(Some(window.window.window.get_current_monitor()));
}
else {
window.window.window.set_fullscreen(None);
}
}
next
}
#[derive(Debug)]
pub enum Drawing {
Path(Path),
Polygon(Polygon),
}
pub struct Renderer {
app: TurtleApp,
drawings: Vec<Drawing>,
/// Polygon that is currently in the process of being filled
/// Removed when EndFill is sent
fill_polygon: Option<(Vec<Path>, Polygon)>,
}
impl Renderer {
pub fn new(app: TurtleApp) -> Renderer {
Self {
app,
drawings: Vec::new(),
fill_polygon: None,
}
}
pub fn run(
&mut self,
drawing_rx: mpsc::Receiver<DrawingCommand>,
events_tx: mpsc::Sender<Event>,
) {
let state = self.app.read_only();
// This check isn't foolproof. Someone can always create a thread named "main".
if thread::current().name().unwrap_or("") != "main" {
// In order to maintain compatibility with MacOS, we need to make sure that windows are
// only created on the main thread. We do this check on all platforms so that no one
// can accidentally make a change that creates the window off of the main thread.
unreachable!("bug: windows can only be created on the main thread");
}
let mut window: PistonWindow = WindowSettings::new(
&*state.drawing().title,
(state.drawing().width, state.drawing().height),
).exit_on_esc(true).build().unwrap();
// We keep a copy of the DrawingState so that we can tell when it is updated and we need
// to change something on the window
let mut current_drawing = DrawingState::default();
let mut center = state.drawing().center;
'renderloop:
while let Some(event) = window.next() {
match event {
PistonEvent::Input(Input::Resize(width, height)) => {
let mut drawing = self.app.drawing_mut();
drawing.width = width;
drawing.height = height;
},
_ => {},
}
if let Some(event) = from_piston_event(&event, |pt| pt.to_local_coords(center)) {
match events_tx.send(event) {
Ok(_) => {},
// Quit - the server thread must have quit
Err(_) => break,
}
}
// Need to handle all of the queries we receive at once so that any lag caused by
// how long rendering takes doesn't cause any problems
loop {
match drawing_rx.try_recv() {
Ok(cmd) => self.handle_drawing_command(cmd),
Err(TryRecvError::Empty) => break, // Do nothing
Err(TryRecvError::Disconnected) => break 'renderloop, // Quit
}
}
// Update the window based on any changes in the DrawingState
current_drawing = update_window(&mut window, current_drawing, state.drawing().clone());
window.draw_2d(&event, |c, g| {
let view = c.get_view_size();
let width = view[0] as f64;
let height = view[1] as f64;
center = state.drawing().center.to_screen_coords([width * 0.5, height * 0.5]);
// We clone the relevant state before rendering so that the rendering thread
// doesn't need to keep locking, waiting or making the main thread wait
let drawing = state.drawing().clone();
let temporary_path = state.temporary_path().clone();
let turtle = state.turtle().clone();
self.render(c, g, center, &drawing, &temporary_path, &turtle);
});
}
}
/// Handles a drawing command sent from the main thread
fn handle_drawing_command(&mut self, command: DrawingCommand) {
//NOTE: Do not pass the ReadOnly state to this function. By the time a DrawingCommand is
// handled, that state may be completely out of date
use self::DrawingCommand::*;
match command {
StorePath(path) => {
if self.fill_polygon.is_some() {
let &mut (ref mut border, ref mut poly) = self.fill_polygon.as_mut().unwrap();
border.push(path.clone());
let Path {start, end, ..} = path;
if poly.vertices.last().map_or(true, |&v| v != start) {
poly.vertices.push(start);
}
poly.vertices.push(end);
}
else if path.pen.enabled {
self.drawings.push(Drawing::Path(path));
}
},
BeginFill(fill_color) => {
// Calling begin_fill multiple times is okay, it just won't do anything until
// end_fill is called
self.fill_polygon = self.fill_polygon.take().or_else(|| Some((Vec::new(), Polygon {
vertices: Vec::new(),
fill_color: fill_color,
})));
},
// Calling end_fill multiple times is not a problem
EndFill => if let Some((border, poly)) = self.fill_polygon.take() {
// Always add the border over the filled polygon so the border is drawn on top
self.drawings.push(Drawing::Polygon(poly));
self.drawings.extend(border.into_iter().filter_map(|p| if p.pen.enabled {
Some(Drawing::Path(p))
} else { None }));
},
Clear => {
self.drawings.clear();
// Because clear doesn't actually shorten the capacity of the vector
// We don't want to leak memory by leaving this Vec at whatever its size was before
self.drawings.shrink_to_fit();
self.fill_polygon.take();
}
}
}
/// The main rendering route. Dispatches to other functions as needed.
fn render(&self, c: context::Context, g: &mut G2d, center: Point,
drawing: &DrawingState, temporary_path: &Option<Path>, turtle: &TurtleState) {
let background = drawing.background;
clear(background.into(), g);
for drawing in &self.drawings {
match *drawing {
Drawing::Path(ref path) => self.render_path(c, g, center, path),
Drawing::Polygon(ref poly) => self.render_polygon(c, g, center,
poly.fill_color, poly.vertices.iter()),
}
}
if let Some(&(ref border, ref poly)) = self.fill_polygon.as_ref() {
// If the temporary_path is not None, we need to add it to the polygon being
// filled or else the polygon will fall one edge behind in the animation
let extra = temporary_path.as_ref().map_or(Vec::new(), |&Path {start, end, ..}| {
if poly.vertices.last().map_or(true, |&v| v != start) {
vec![start, end]
}
else {
vec![end]
}
});
self.render_polygon(c, g, center, poly.fill_color,
poly.vertices.iter().chain(extra.iter()));
for path in border {
if path.pen.enabled {
self.render_path(c, g, center, path);
}
}
}
if let Some(ref path) = *temporary_path {
if path.pen.enabled {
self.render_path(c, g, center, path);
}
}
self.render_shell(c, g, center, turtle);
}
/// Render a path assuming that its pen is enabled
fn render_path(&self, c: context::Context, g: &mut G2d, center: Point, path: &Path) {
let &Path {start, end, ref pen} = path;
let &Pen {thickness, color, enabled} = pen;
debug_assert!(enabled, "bug: attempt to render path when pen was not enabled");
let start = start.to_screen_coords(center);
let end = end.to_screen_coords(center);
line(color.into(), thickness,
[start[0], start[1], end[0], end[1]],
c.transform, g);
}
/// Render a polygon given its vertices
fn render_polygon<'a, T: Iterator<Item=&'a Point>>(
&self,
c: context::Context,
g: &mut G2d,
center: Point,
fill_color: Color,
verts: T,
) {
// Performance note: Why make this function generic instead of just taking Polygon?
// Answer: render_polygon is called multiple times. It's called repeatedly in a loop, and
// it is also called when drawing the current fill_polygon. Rather than moving the
// code to *maybe* add the temporary_path to the rendered polygon into this method, we
// avoid branching unnecessarily by allowing the repeated caller to do what is fast, then
// doing the slow thing (checking if the path is None) only once when it is needed.
//
// We pass in the points as an Iterator so that they do not need to be collected into any
// struct. This avoids an allocation that really isn't needed since these are all temporary
// anyway. Everything is going to get copied anyway on the next line. No need to do it
// twice.
//
// See the commit before this comment was added for the approach that would have required
// branching in every iteration of the loop where render_polygon is called over and over
// again.
let verts = verts.map(|p| p.to_screen_coords(center)).collect::<Vec<_>>();
polygon(fill_color.into(), &verts, c.transform, g);
}
/// Draw the turtle's shell
fn render_shell(&self, c: context::Context, g: &mut G2d, center: Point,
&TurtleState {position, heading, visible, ..}: &TurtleState) {
// Calculate all the points on the shell by rotating the shell shape by the turtle's
// heading and moving it to the turtle's position
if !visible {
return;
}
let cos = heading.cos();
let sin = heading.sin();
let turtle_x = position[0];
let turtle_y = position[1];
let shell: Vec<_> = [
[0., 15.],
[10., 0.],
[0., -15.],
].into_iter().map(|pt| {
// Rotate each point by the heading and add the current turtle position
let x = cos * pt[0] - sin * pt[1] + turtle_x;
let y = sin * pt[0] + cos * pt[1] + turtle_y;
[x, y].to_screen_coords(center)
}).collect();
// Draw the turtle shell with its background first, then its border
polygon(color::WHITE.into(), &shell, c.transform, g);
for i in 0..shell.len() {
let start = shell[i];
let end = shell[(i + 1) % shell.len()];
line(color::BLACK.into(), 1.,
[start[0], start[1], end[0], end[1]],
c.transform, g);
}
}
}