wde_renderer/assets/meshes/
plane.rs1use bevy::math::Vec3;
2use wde_wgpu::vertex::Vertex;
3
4use crate::assets::{Mesh, MeshBbox};
5
6pub struct PlaneMesh;
7impl PlaneMesh {
8 pub fn from(label: &str, subdivisions: u32, normal: Vec3) -> Mesh {
22 let subdivisions = subdivisions.max(1);
23 let half_size = [0.5, 0.5];
24
25 let normal = normal.normalize();
27
28 let (tangent, bitangent) = compute_tangent_bitangent(normal);
30
31 let mut vertices = Vec::new();
33 let mut min_bounds = Vec3::new(f32::MAX, f32::MAX, f32::MAX);
34 let mut max_bounds = Vec3::new(f32::MIN, f32::MIN, f32::MIN);
35
36 for i in 0..=subdivisions {
37 for j in 0..=subdivisions {
38 let u = (i as f32) / (subdivisions as f32);
39 let v = (j as f32) / (subdivisions as f32);
40
41 let local_x = -half_size[0] + u;
43 let local_y = -half_size[1] + v;
44
45 let position = tangent * local_x + bitangent * local_y;
47
48 min_bounds = min_bounds.min(position);
50 max_bounds = max_bounds.max(position);
51
52 vertices.push(Vertex {
53 position: [position.x, position.y, position.z],
54 normal: [normal.x, normal.y, normal.z],
55 uv: [u, v],
56 tangent: [tangent.x, tangent.y, tangent.z, 1.0]
57 });
58 }
59 }
60
61 let mut indices = Vec::new();
63 for i in 0..subdivisions {
64 for j in 0..subdivisions {
65 let row = subdivisions + 1;
66 let v0 = i * row + j;
67 let v1 = v0 + 1;
68 let v2 = v0 + row;
69 let v3 = v2 + 1;
70
71 indices.push(v0);
73 indices.push(v2);
74 indices.push(v1);
75
76 indices.push(v1);
78 indices.push(v2);
79 indices.push(v3);
80 }
81 }
82
83 let bounding_box = MeshBbox {
85 min: min_bounds,
86 max: max_bounds
87 };
88
89 Mesh {
90 label: label.to_string(),
91 vertices,
92 indices,
93 bbox: bounding_box,
94 use_ssbo: false
95 }
96 }
97}
98
99fn compute_tangent_bitangent(normal: Vec3) -> (Vec3, Vec3) {
102 let up = if normal.y.abs() > 0.9 {
104 Vec3::new(1.0, 0.0, 0.0)
105 } else {
106 Vec3::new(0.0, 1.0, 0.0)
107 };
108
109 let tangent = normal.cross(up).normalize();
110 let bitangent = normal.cross(tangent).normalize();
111
112 (tangent, bitangent)
113}