vertex_arrays/
vertex-arrays.rs1use sfml::{
2 graphics::{
3 vertex_array_bounds, Color, PrimitiveType, RectangleShape, RenderStates, RenderTarget,
4 RenderWindow, Shape, Vertex,
5 },
6 window::{Event, Style},
7 SfResult,
8};
9
10fn main() -> SfResult<()> {
11 let mut window = RenderWindow::new(
12 (800, 600),
13 "Vertex array example",
14 Style::CLOSE,
15 &Default::default(),
16 )?;
17 window.set_vertical_sync_enabled(true);
18
19 let mut vertex_array = [
20 Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
21 Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
22 Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
23 Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
24 Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
25 Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
26 ];
27
28 println!("\nIterate over the vertices of a vertex array");
29 for v in &vertex_array {
30 println!("Vertex Color: {:?} | Position: {:?}", v.color, v.position)
31 }
32
33 println!("\nMutable access to a vertex");
34 println!(
35 "Before Vertex Color: {:?} | Position: {:?}",
36 vertex_array[1].color, vertex_array[1].position
37 );
38 vertex_array[1].position.x = 100.0;
39 println!(
40 "After Vertex Color: {:?} | Position: {:?}",
41 vertex_array[1].color, vertex_array[1].position
42 );
43
44 println!("\nImmutable access to a vertex");
45 println!(
46 "Vertex Color: {:?} | Position: {:?}",
47 vertex_array[1].color, vertex_array[1].position
48 );
49
50 let vertex = &mut vertex_array[1];
51 println!(
52 "Before Vertex Color: {:?} | Position: {:?}",
53 vertex.color, vertex.position
54 );
55 vertex.position.x = 100.0;
56 println!(
57 "After Vertex Color: {:?} | Position: {:?}",
58 vertex.color, vertex.position
59 );
60
61 vertex_array[1] = Vertex::with_pos((20., 40.).into());
63 println!("[2] After Vertex Position: {:?}", vertex_array[1].position);
64 println!(
65 "Vertex Color: {:?} | Position: {:?}",
66 vertex_array[1].color, vertex_array[1].position
67 );
68 let bounds = vertex_array_bounds(&vertex_array);
69 let mut bound_rect = RectangleShape::from_rect(bounds);
70 bound_rect.set_fill_color(Color::TRANSPARENT);
71 bound_rect.set_outline_thickness(1.0);
72 bound_rect.set_outline_color(Color::YELLOW);
73
74 'mainloop: loop {
75 while let Some(e) = window.poll_event() {
76 if e == Event::Closed {
77 break 'mainloop;
78 }
79 }
80 let rs = RenderStates::default();
81 window.clear(Color::BLACK);
83 window.draw_primitives(&vertex_array, PrimitiveType::LINE_STRIP, &rs);
84 window.draw(&bound_rect);
85 window.display()
87 }
88 Ok(())
89}