mesh.rs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. use crate::{
  2. error::Result,
  3. gfx2::{Point, Rectangle, RenderApi, Vertex},
  4. };
  5. use miniquad::BufferId;
  6. pub type Color = [f32; 4];
  7. pub const COLOR_RED: Color = [1., 0., 0., 1.];
  8. pub const COLOR_DARKGREY: Color = [0.2, 0.2, 0.2, 1.];
  9. pub const COLOR_GREEN: Color = [0., 1., 0., 1.];
  10. pub const COLOR_BLUE: Color = [0., 0., 1., 1.];
  11. pub const COLOR_WHITE: Color = [1., 1., 1., 1.];
  12. pub struct MeshBuilder {
  13. verts: Vec<Vertex>,
  14. indices: Vec<u16>,
  15. }
  16. impl MeshBuilder {
  17. pub fn new() -> Self {
  18. Self { verts: vec![], indices: vec![] }
  19. }
  20. pub fn append(&mut self, mut verts: Vec<Vertex>, indices: Vec<u16>) {
  21. let mut indices = indices.into_iter().map(|i| i + self.verts.len() as u16).collect();
  22. self.verts.append(&mut verts);
  23. self.indices.append(&mut indices);
  24. }
  25. pub fn draw_box(&mut self, obj: &Rectangle, color: Color, uv: &Rectangle) {
  26. let (x1, y1) = obj.top_left().unpack();
  27. let (x2, y2) = obj.bottom_right().unpack();
  28. let (u1, v1) = uv.top_left().unpack();
  29. let (u2, v2) = uv.bottom_right().unpack();
  30. let verts = vec![
  31. // top left
  32. Vertex { pos: [x1, y1], color, uv: [u1, v1] },
  33. // top right
  34. Vertex { pos: [x2, y1], color, uv: [u2, v1] },
  35. // bottom left
  36. Vertex { pos: [x1, y2], color, uv: [u1, v2] },
  37. // bottom right
  38. Vertex { pos: [x2, y2], color, uv: [u2, v2] },
  39. ];
  40. let indices = vec![0, 2, 1, 1, 2, 3];
  41. self.append(verts, indices);
  42. }
  43. pub fn draw_outline(&mut self, obj: &Rectangle, color: Color, thickness: f32) {
  44. let uv = Rectangle { x: 0., y: 0., w: 0., h: 0. };
  45. let (x1, y1) = obj.top_left().unpack();
  46. let (dist_x, dist_y) = (obj.w, obj.h);
  47. let (x2, y2) = obj.bottom_right().unpack();
  48. // top
  49. self.draw_box(&Rectangle::new(x1, y1, dist_x, thickness), color, &uv);
  50. // left
  51. self.draw_box(&Rectangle::new(x1, y1, thickness, dist_y), color, &uv);
  52. // right
  53. self.draw_box(&Rectangle::new(x2 - thickness, y1, thickness, dist_y), color, &uv);
  54. // bottom
  55. self.draw_box(&Rectangle::new(x1, y2 - thickness, dist_x, thickness), color, &uv);
  56. }
  57. // Needed by OpenGL
  58. pub fn num_elements(&self) -> i32 {
  59. self.indices.len() as i32
  60. }
  61. pub async fn alloc(self, render_api: &RenderApi) -> Result<(BufferId, BufferId)> {
  62. //debug!(target: "mesh", "allocating {} verts:", self.verts.len());
  63. //for vert in &self.verts {
  64. // debug!(target: "mesh", " {:?}", vert);
  65. //}
  66. let vertex_buffer = render_api.new_vertex_buffer(self.verts).await?;
  67. let index_buffer = render_api.new_index_buffer(self.indices).await?;
  68. Ok((vertex_buffer, index_buffer))
  69. }
  70. }