midpoint_ui/renderer/
Grid.rs1use nalgebra::{Matrix4, Point3, Vector3};
2use wgpu::util::DeviceExt;
3
4use crate::renderer::core::Vertex;
5use crate::renderer::Transform::matrix4_to_raw_array;
6
7pub struct Grid {
8 vertex_buffer: wgpu::Buffer,
9 index_buffer: wgpu::Buffer,
10 index_count: u32,
11 bind_group: wgpu::BindGroup,
12}
13
14impl Grid {
15 pub fn new(
16 device: &wgpu::Device,
17 bind_group_layout: &wgpu::BindGroupLayout,
18 color_render_mode_buffer: &wgpu::Buffer,
19 ) -> Self {
20 let (vertices, indices) = Self::generate_grid(100.0, 100.0, 1.0); let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
24 label: Some("Grid Vertex Buffer"),
25 contents: bytemuck::cast_slice(&vertices),
26 usage: wgpu::BufferUsages::VERTEX,
27 });
28
29 let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
30 label: Some("Grid Index Buffer"),
31 contents: bytemuck::cast_slice(&indices),
32 usage: wgpu::BufferUsages::INDEX,
33 });
34
35 let empty_buffer = Matrix4::<f32>::identity();
36 let raw_matrix = matrix4_to_raw_array(&empty_buffer);
37
38 let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
39 label: Some("Grid Uniform Buffer"),
40 contents: bytemuck::cast_slice(&raw_matrix),
41 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
42 });
43
44 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
47 layout: &bind_group_layout,
48 entries: &[
49 wgpu::BindGroupEntry {
50 binding: 0,
51 resource: uniform_buffer.as_entire_binding(),
52 },
53 ],
62 label: None,
63 });
64
65 Self {
66 vertex_buffer,
67 index_buffer,
68 index_count: indices.len() as u32,
69 bind_group,
70 }
71 }
72
73 fn generate_grid(width: f32, depth: f32, spacing: f32) -> (Vec<Vertex>, Vec<u16>) {
74 let mut vertices = Vec::new();
75 let mut indices = Vec::new();
76
77 let half_width = width / 2.0;
78 let half_depth = depth / 2.0;
79
80 for i in 0..=((width / spacing) as u16) {
81 let x = -half_width + i as f32 * spacing;
82 vertices.push(Vertex {
83 position: [x, 0.0, -half_depth],
84 normal: [0.0, 0.0, 0.0],
85 tex_coords: [0.0, 0.0],
86 color: [1.0, 1.0, 1.0],
87 });
88 vertices.push(Vertex {
89 position: [x, 0.0, half_depth],
90 normal: [0.0, 0.0, 0.0],
91 tex_coords: [0.0, 0.0],
92 color: [1.0, 1.0, 1.0],
93 });
94 indices.push(i * 2);
95 indices.push(i * 2 + 1);
96 }
97
98 let base = vertices.len() as u16;
99 for i in 0..=((depth / spacing) as u16) {
100 let z = -half_depth + i as f32 * spacing;
101 vertices.push(Vertex {
102 position: [-half_width, 0.0, z],
103 normal: [0.0, 0.0, 0.0],
104 tex_coords: [0.0, 0.0],
105 color: [1.0, 1.0, 1.0],
106 });
107 vertices.push(Vertex {
108 position: [half_width, 0.0, z],
109 normal: [0.0, 0.0, 0.0],
110 tex_coords: [0.0, 0.0],
111 color: [1.0, 1.0, 1.0],
112 });
113 indices.push(base + i * 2);
114 indices.push(base + i * 2 + 1);
115 }
116
117 (vertices, indices)
121 }
122
123 }