wde_terrain/render/dependencies/
terrain_mesh.rs

1use bevy::prelude::*;
2use wde_renderer::prelude::*;
3
4use crate::manager::{CHUNK_RENDER_SUBDIVISIONS, CHUNK_SIZE};
5
6#[derive(Resource, Default)]
7pub struct TerrainRenderPassMesh {
8    pub deferred_mesh: Option<Handle<Mesh>>
9}
10impl TerrainRenderPassMesh {
11    // Creates the rendering mesh.
12    pub fn init(assets_server: Res<AssetServer>, mut render_pass: ResMut<TerrainRenderPassMesh>) {
13        let mut mesh = PlaneMesh::from("terrain_tile", CHUNK_RENDER_SUBDIVISIONS, Vec3::Y);
14
15        // Scale the plane to cover the entire terrain tile size
16        for vertex in &mut mesh.vertices {
17            vertex.position[0] *= CHUNK_SIZE;
18            vertex.position[2] *= CHUNK_SIZE;
19        }
20
21        // Fix the UVs to cover the entire texture
22        for vertex in &mut mesh.vertices {
23            vertex.uv[0] = vertex.position[0] / CHUNK_SIZE + 0.5; // Map from [-TILE_SIZE/2, TILE_SIZE/2] to [0, 1]
24            vertex.uv[1] = vertex.position[2] / CHUNK_SIZE + 0.5; // Map from [-TILE_SIZE/2, TILE_SIZE/2] to [0, 1]
25        }
26
27        render_pass.deferred_mesh = Some(assets_server.add(mesh));
28    }
29
30    // Extracts the mesh handle to the render world.
31    pub fn extract_terrain_mesh(
32        mesh_cpu: ExtractWorld<Res<TerrainRenderPassMesh>>,
33        mut mesh: ResMut<TerrainRenderPassMesh>
34    ) {
35        // Check if the mesh is already extracted
36        if mesh.deferred_mesh.is_some() {
37            return;
38        }
39
40        // Extract the mesh handle to the render world
41        if let Some(ref mesh_cpu) = mesh_cpu.deferred_mesh {
42            mesh.deferred_mesh = Some(mesh_cpu.clone());
43        }
44    }
45}