Premier commit
Cette révision appartient à :
révision
13bc77fd6c
21 fichiers modifiés
+6169
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,67 @@
|
||||
/target
|
||||
|
||||
# --- double-push : exclusions generiques (secrets, builds, binaires, gros fichiers) ---
|
||||
target/
|
||||
node_modules/
|
||||
build/
|
||||
build-*/
|
||||
dist/
|
||||
out/
|
||||
.gradle/
|
||||
.idea/
|
||||
venv/
|
||||
.venv/
|
||||
env/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.cache/
|
||||
.next/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
accounts.json
|
||||
Clee.API/
|
||||
*.pem
|
||||
*.key
|
||||
*.p12
|
||||
*.pfx
|
||||
*.jks
|
||||
*.keystore
|
||||
keystore.properties
|
||||
id_rsa*
|
||||
id_ed25519*
|
||||
*.kdbx
|
||||
*.odt
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
*.log
|
||||
*.exe
|
||||
*.dll
|
||||
*.msi
|
||||
*.jar
|
||||
*.zip
|
||||
*.7z
|
||||
*.rar
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
*.gguf
|
||||
*.safetensors
|
||||
*.onnx
|
||||
*.pt
|
||||
*.pth
|
||||
*.bin
|
||||
*.iso
|
||||
*.gws
|
||||
*.apk
|
||||
*.aab
|
||||
*.so
|
||||
*.o
|
||||
*.a
|
||||
*.lib
|
||||
*.pdb
|
||||
*.mp4
|
||||
*.mkv
|
||||
*.wav
|
||||
*.flac
|
||||
Générée
+2105
Diff désactivé car ce fichier est trop long.
Voir la Diff
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "MC"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
vulkano = "0.35.2"
|
||||
vulkano-shaders = "0.35.0"
|
||||
winit = "0.30.13"
|
||||
@@ -0,0 +1,110 @@
|
||||
use crate::math::{Mat4, Vec3};
|
||||
|
||||
/// Caméra 3D libre de type "FPS free-fly".
|
||||
pub struct Camera {
|
||||
pub position: Vec3,
|
||||
pub yaw: f32, // Rotation horizontale (lacet en radians)
|
||||
pub pitch: f32, // Rotation verticale (tangage en radians)
|
||||
pub speed: f32, // Vitesse de déplacement (unités/sec)
|
||||
pub sensitivity: f32, // Sensibilité de la souris (radians/pixel)
|
||||
|
||||
// État des touches de déplacement
|
||||
pub move_forward: bool,
|
||||
pub move_backward: bool,
|
||||
pub move_left: bool,
|
||||
pub move_right: bool,
|
||||
pub move_up: bool,
|
||||
pub move_down: bool,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Camera {
|
||||
pub fn new(position: Vec3) -> Self {
|
||||
Self {
|
||||
position,
|
||||
yaw: 0.0,
|
||||
pitch: 0.0,
|
||||
speed: 5.0,
|
||||
sensitivity: 0.0025,
|
||||
move_forward: false,
|
||||
move_backward: false,
|
||||
move_left: false,
|
||||
move_right: false,
|
||||
move_up: false,
|
||||
move_down: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Vecteur directionnel unitaire dans lequel regarde la caméra.
|
||||
/// Pour yaw = 0 et pitch = 0, la caméra regarde vers -Z (convention standard).
|
||||
pub fn forward(&self) -> Vec3 {
|
||||
let cos_pitch = self.pitch.cos();
|
||||
Vec3::new(
|
||||
self.yaw.sin() * cos_pitch,
|
||||
self.pitch.sin(),
|
||||
-self.yaw.cos() * cos_pitch,
|
||||
)
|
||||
.normalize()
|
||||
}
|
||||
|
||||
/// Vecteur pointant vers la droite relative de la caméra.
|
||||
pub fn right(&self) -> Vec3 {
|
||||
self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize()
|
||||
}
|
||||
|
||||
/// Vecteur pointant vers le haut relatif de la caméra.
|
||||
pub fn up(&self) -> Vec3 {
|
||||
self.right().cross(self.forward()).normalize()
|
||||
}
|
||||
|
||||
/// Oriente la caméra en fonction du déplacement relatif de la souris (dx, dy).
|
||||
pub fn rotate(&mut self, dx: f32, dy: f32) {
|
||||
self.yaw += dx * self.sensitivity;
|
||||
// Inversion de dy pour que déplacer la souris vers le haut regarde vers le haut
|
||||
self.pitch -= dy * self.sensitivity;
|
||||
|
||||
// Limite le pitch à ~89 degrés pour éviter le gimbal lock et l'inversion de tête
|
||||
let max_pitch = 89.0f32.to_radians();
|
||||
self.pitch = self.pitch.clamp(-max_pitch, max_pitch);
|
||||
}
|
||||
|
||||
/// Met à jour la position de la caméra selon les touches pressées et le delta-time (dt en secondes).
|
||||
pub fn update(&mut self, dt: f32) {
|
||||
let mut move_dir = Vec3::zero();
|
||||
let forward = self.forward();
|
||||
let right = self.right();
|
||||
let world_up = Vec3::new(0.0, 1.0, 0.0);
|
||||
|
||||
if self.move_forward {
|
||||
move_dir = move_dir + forward;
|
||||
}
|
||||
if self.move_backward {
|
||||
move_dir = move_dir - forward;
|
||||
}
|
||||
if self.move_right {
|
||||
move_dir = move_dir + right;
|
||||
}
|
||||
if self.move_left {
|
||||
move_dir = move_dir - right;
|
||||
}
|
||||
if self.move_up {
|
||||
move_dir = move_dir + world_up;
|
||||
}
|
||||
if self.move_down {
|
||||
move_dir = move_dir - world_up;
|
||||
}
|
||||
|
||||
if move_dir.length_squared() > 0.0001 {
|
||||
self.position = self.position + move_dir.normalize() * (self.speed * dt);
|
||||
}
|
||||
}
|
||||
|
||||
/// Calcule la matrice de vue correspondante.
|
||||
pub fn view_matrix(&self) -> Mat4 {
|
||||
Mat4::look_at(
|
||||
self.position,
|
||||
self.position + self.forward(),
|
||||
Vec3::new(0.0, 1.0, 0.0),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use crate::renderer::mesh::CubeVertex;
|
||||
use crate::world::BlockType;
|
||||
|
||||
pub const HOTBAR_SLOTS: usize = 6;
|
||||
|
||||
/// Représente un emplacement d'inventaire avec un type de bloc et un compteur.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Slot {
|
||||
pub block: BlockType,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
/// Gestion de l'inventaire du joueur (Hotbar de 6 slots façon Minecraft).
|
||||
pub struct Inventory {
|
||||
pub slots: [Slot; HOTBAR_SLOTS],
|
||||
pub selected_slot: usize,
|
||||
}
|
||||
|
||||
impl Inventory {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
slots: [
|
||||
Slot { block: BlockType::Grass, count: 64 },
|
||||
Slot { block: BlockType::Dirt, count: 64 },
|
||||
Slot { block: BlockType::Stone, count: 64 },
|
||||
Slot { block: BlockType::Wood, count: 32 },
|
||||
Slot { block: BlockType::Leaves, count: 32 },
|
||||
Slot { block: BlockType::Sand, count: 32 },
|
||||
],
|
||||
selected_slot: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sélectionne un slot par son index (0..HOTBAR_SLOTS - 1).
|
||||
pub fn select_slot(&mut self, slot: usize) {
|
||||
if slot < HOTBAR_SLOTS {
|
||||
self.selected_slot = slot;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fait défiler le slot actif (ex: molette souris, delta = +1 ou -1).
|
||||
pub fn cycle_slot(&mut self, delta: i32) {
|
||||
let count = HOTBAR_SLOTS as i32;
|
||||
let next = (self.selected_slot as i32 + delta).rem_euclid(count);
|
||||
self.selected_slot = next as usize;
|
||||
}
|
||||
|
||||
/// Retourne le type de bloc sélectionné.
|
||||
pub fn selected_block(&self) -> BlockType {
|
||||
self.slots[self.selected_slot].block
|
||||
}
|
||||
|
||||
/// Retourne la quantité disponible dans le slot actif.
|
||||
pub fn selected_count(&self) -> u32 {
|
||||
self.slots[self.selected_slot].count
|
||||
}
|
||||
|
||||
/// Ajoute un bloc récolté au slot correspondant.
|
||||
pub fn add_block(&mut self, block: BlockType) -> bool {
|
||||
if block == BlockType::Air {
|
||||
return false;
|
||||
}
|
||||
for slot in &mut self.slots {
|
||||
if slot.block == block {
|
||||
slot.count = slot.count.saturating_add(1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Tente de consommer un bloc du slot actif pour le poser.
|
||||
/// Retourne Some(BlockType) si le stock est > 0 (et décrémente),
|
||||
/// ou None si le slot est vide (refus silencieux sans sous-dépassement).
|
||||
pub fn consume_selected(&mut self) -> Option<BlockType> {
|
||||
let slot = &mut self.slots[self.selected_slot];
|
||||
if slot.count > 0 {
|
||||
slot.count -= 1;
|
||||
Some(slot.block)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Couleur représentative du type de bloc pour la vignette UI.
|
||||
fn block_ui_color(block: BlockType) -> [f32; 3] {
|
||||
match block {
|
||||
BlockType::Grass => [0.35, 0.75, 0.30],
|
||||
BlockType::Dirt => [0.55, 0.38, 0.25],
|
||||
BlockType::Stone => [0.58, 0.58, 0.60],
|
||||
BlockType::Wood => [0.45, 0.32, 0.22],
|
||||
BlockType::Leaves => [0.22, 0.58, 0.22],
|
||||
BlockType::Sand => [0.86, 0.80, 0.52],
|
||||
BlockType::Air => [0.0, 0.0, 0.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Génère le maillage 2D en coordonnées écran NDC [-1..1] pour afficher la hotbar.
|
||||
pub fn generate_ui_mesh(&self, aspect_ratio: f32) -> (Vec<CubeVertex>, Vec<u32>) {
|
||||
let mut vertices = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
|
||||
// Dimensions de la hotbar en bas de l'écran (Vulkan Y descend vers +1.0)
|
||||
let slot_w = 0.075f32;
|
||||
let slot_h = slot_w * aspect_ratio;
|
||||
let margin = 0.008f32;
|
||||
let total_w = HOTBAR_SLOTS as f32 * slot_w + (HOTBAR_SLOTS - 1) as f32 * margin;
|
||||
let start_x = -total_w * 0.5;
|
||||
let y_bottom = 0.94f32;
|
||||
let y_top = y_bottom - slot_h;
|
||||
|
||||
// Fonction locale d'ajout de quad 2D
|
||||
let mut add_quad = |x0: f32, y0: f32, x1: f32, y1: f32, color: [f32; 3]| {
|
||||
let base = vertices.len() as u32;
|
||||
let normal = [0.0, 0.0, 1.0];
|
||||
let uv = [0.0, 0.0];
|
||||
|
||||
vertices.push(CubeVertex { position: [x0, y0, 0.0], color, normal, uv });
|
||||
vertices.push(CubeVertex { position: [x1, y0, 0.0], color, normal, uv });
|
||||
vertices.push(CubeVertex { position: [x1, y1, 0.0], color, normal, uv });
|
||||
vertices.push(CubeVertex { position: [x0, y1, 0.0], color, normal, uv });
|
||||
|
||||
indices.push(base);
|
||||
indices.push(base + 1);
|
||||
indices.push(base + 2);
|
||||
indices.push(base + 2);
|
||||
indices.push(base + 3);
|
||||
indices.push(base);
|
||||
};
|
||||
|
||||
for i in 0..HOTBAR_SLOTS {
|
||||
let x_left = start_x + i as f32 * (slot_w + margin);
|
||||
let x_right = x_left + slot_w;
|
||||
|
||||
let is_selected = i == self.selected_slot;
|
||||
|
||||
// 1. Fond du slot (ou surbrillance dorée/blanche si actif)
|
||||
if is_selected {
|
||||
// Cadre extérieur actif éclatant (blanc / doré)
|
||||
let border = 0.005;
|
||||
add_quad(
|
||||
x_left - border,
|
||||
y_top - border * aspect_ratio,
|
||||
x_right + border,
|
||||
y_bottom + border * aspect_ratio,
|
||||
[1.0, 0.95, 0.4],
|
||||
);
|
||||
}
|
||||
|
||||
// Fond sombre du slot
|
||||
let bg_color = if is_selected {
|
||||
[0.28, 0.28, 0.32]
|
||||
} else {
|
||||
[0.15, 0.15, 0.17]
|
||||
};
|
||||
add_quad(x_left, y_top, x_right, y_bottom, bg_color);
|
||||
|
||||
// 2. Carré intérieur représentant le bloc
|
||||
let inner_pad = 0.012;
|
||||
let block_color = Self::block_ui_color(self.slots[i].block);
|
||||
|
||||
// Si le stock est à 0, le bloc est atténué (semi-grisé)
|
||||
let final_color = if self.slots[i].count > 0 {
|
||||
block_color
|
||||
} else {
|
||||
[block_color[0] * 0.3, block_color[1] * 0.3, block_color[2] * 0.3]
|
||||
};
|
||||
|
||||
add_quad(
|
||||
x_left + inner_pad,
|
||||
y_top + inner_pad * aspect_ratio,
|
||||
x_right - inner_pad,
|
||||
y_bottom - inner_pad * aspect_ratio,
|
||||
final_color,
|
||||
);
|
||||
}
|
||||
|
||||
(vertices, indices)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_inventory_add_and_consume() {
|
||||
let mut inv = Inventory::new();
|
||||
inv.select_slot(0); // Grass
|
||||
let initial_grass = inv.selected_count();
|
||||
|
||||
// Pose 1 bloc
|
||||
let consumed = inv.consume_selected();
|
||||
assert_eq!(consumed, Some(BlockType::Grass));
|
||||
assert_eq!(inv.selected_count(), initial_grass - 1);
|
||||
|
||||
// Ajoute 1 bloc récolté
|
||||
let added = inv.add_block(BlockType::Grass);
|
||||
assert!(added);
|
||||
assert_eq!(inv.selected_count(), initial_grass);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_consume_at_zero_refused_silently() {
|
||||
let mut inv = Inventory::new();
|
||||
inv.select_slot(2); // Stone
|
||||
inv.slots[2].count = 0;
|
||||
|
||||
// Tenter de poser avec 0 bloc
|
||||
let consumed = inv.consume_selected();
|
||||
assert_eq!(consumed, None, "Poser un bloc à 0 doit renvoyer None");
|
||||
assert_eq!(inv.selected_count(), 0, "Le stock ne doit pas passer sous 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inventory_cycle_slots() {
|
||||
let mut inv = Inventory::new();
|
||||
inv.select_slot(0);
|
||||
|
||||
inv.cycle_slot(1);
|
||||
assert_eq!(inv.selected_slot, 1);
|
||||
|
||||
inv.cycle_slot(-1);
|
||||
assert_eq!(inv.selected_slot, 0);
|
||||
|
||||
// Débordement négatif -> boucle vers le dernier slot
|
||||
inv.cycle_slot(-1);
|
||||
assert_eq!(inv.selected_slot, HOTBAR_SLOTS - 1);
|
||||
|
||||
// Débordement positif -> boucle vers le premier slot
|
||||
inv.cycle_slot(1);
|
||||
assert_eq!(inv.selected_slot, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_place_block_with_zero_stock_does_not_modify_world() {
|
||||
use crate::world::{Chunk, World};
|
||||
|
||||
let mut inv = Inventory::new();
|
||||
inv.select_slot(3); // Wood
|
||||
inv.slots[3].count = 0; // Stock vide
|
||||
|
||||
let mut world = World::new();
|
||||
let chunk = Chunk::new_empty(0, 0);
|
||||
world.chunks.insert((0, 0), chunk);
|
||||
|
||||
// Simulation de la pose : consume_selected() échoue -> le monde n'est pas modifié
|
||||
let block_opt = inv.consume_selected();
|
||||
assert_eq!(block_opt, None);
|
||||
|
||||
if let Some(block) = block_opt {
|
||||
world.set_block(5, 5, 5, block);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
world.get_block(5, 5, 5),
|
||||
BlockType::Air,
|
||||
"Le monde ne doit pas être modifié si le stock est à 0"
|
||||
);
|
||||
assert_eq!(inv.slots[3].count, 0, "Le compteur doit rester à 0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
mod camera;
|
||||
mod inventory;
|
||||
mod math;
|
||||
mod physics;
|
||||
mod raycast;
|
||||
mod renderer;
|
||||
mod window;
|
||||
mod world;
|
||||
|
||||
use std::error::Error;
|
||||
use window::App;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("=== Moteur Voxel (Moteur Physique, Gravité & Collisions AABB) ===");
|
||||
println!("Contrôles :");
|
||||
println!(" - Z / Q / S / D (ou W / A / S / D) : Déplacement (Marche / Vol)");
|
||||
println!(" - Espace : Sauter (au sol) / Monter (en vol)");
|
||||
println!(" - Maj : Descendre (en vol)");
|
||||
println!(" - F : Basculer Vol libre / Marche avec gravité");
|
||||
println!(" - Souris : Regarder autour (Pitch / Yaw)");
|
||||
println!(" - Clic Gauche : Casser le bloc ciblé (Air)");
|
||||
println!(" - Clic Droit : Poser un bloc sur la face ciblée");
|
||||
println!(" - Touches 1 à 9 : Sélectionner le bloc dans l'inventaire");
|
||||
println!(" - Échap : Basculer la capture du curseur souris");
|
||||
|
||||
let event_loop = EventLoop::new()?;
|
||||
let mut app = App::new();
|
||||
event_loop.run_app(&mut app)?;
|
||||
|
||||
println!("Arrêt du moteur.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
use std::ops::{Add, Div, Mul, Neg, Sub};
|
||||
|
||||
/// Vecteur 3D à virgule flottante 32 bits (f32).
|
||||
/// Utilisé pour les positions, directions, normales et couleurs dans le monde 3D.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[repr(C)]
|
||||
pub struct Vec3 {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub z: f32,
|
||||
}
|
||||
|
||||
impl Vec3 {
|
||||
pub const fn new(x: f32, y: f32, z: f32) -> Self {
|
||||
Self { x, y, z }
|
||||
}
|
||||
|
||||
pub const fn zero() -> Self {
|
||||
Self::new(0.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
pub const fn one() -> Self {
|
||||
Self::new(1.0, 1.0, 1.0)
|
||||
}
|
||||
|
||||
/// Produit scalaire (dot product).
|
||||
/// Permet de mesurer l'alignement entre deux vecteurs ou pour l'éclairage diffus (Lambert).
|
||||
pub fn dot(&self, other: Self) -> f32 {
|
||||
self.x * other.x + self.y * other.y + self.z * other.z
|
||||
}
|
||||
|
||||
/// Produit vectoriel (cross product).
|
||||
/// Donne un vecteur orthogonal aux deux opérandes (essentiel pour calculer normales et repères de caméra).
|
||||
pub fn cross(&self, other: Self) -> Self {
|
||||
Self {
|
||||
x: self.y * other.z - self.z * other.y,
|
||||
y: self.z * other.x - self.x * other.z,
|
||||
z: self.x * other.y - self.y * other.x,
|
||||
}
|
||||
}
|
||||
|
||||
/// Norme au carré (évite un appel coûteux à sqrt si seule une comparaison est nécessaire).
|
||||
pub fn length_squared(&self) -> f32 {
|
||||
self.dot(*self)
|
||||
}
|
||||
|
||||
/// Norme euclidienne du vecteur.
|
||||
pub fn length(&self) -> f32 {
|
||||
self.length_squared().sqrt()
|
||||
}
|
||||
|
||||
/// Normalise le vecteur pour que sa norme devienne 1.0.
|
||||
/// Retourne un vecteur nul si la norme est 0 pour éviter une division par zéro.
|
||||
pub fn normalize(&self) -> Self {
|
||||
let len = self.length();
|
||||
if len > 0.00001 {
|
||||
*self / len
|
||||
} else {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Vec3 {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Vec3 {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<f32> for Vec3 {
|
||||
type Output = Self;
|
||||
fn mul(self, rhs: f32) -> Self::Output {
|
||||
Self::new(self.x * rhs, self.y * rhs, self.z * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul<Vec3> for f32 {
|
||||
type Output = Vec3;
|
||||
fn mul(self, rhs: Vec3) -> Self::Output {
|
||||
rhs * self
|
||||
}
|
||||
}
|
||||
|
||||
impl Div<f32> for Vec3 {
|
||||
type Output = Self;
|
||||
fn div(self, rhs: f32) -> Self::Output {
|
||||
Self::new(self.x / rhs, self.y / rhs, self.z / rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl Neg for Vec3 {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self::Output {
|
||||
Self::new(-self.x, -self.y, -self.z)
|
||||
}
|
||||
}
|
||||
|
||||
/// Matrice 4x4 stockée en ordre 'column-major' (colonnes contiguës en mémoire).
|
||||
///
|
||||
/// Alignement mémoire :
|
||||
/// `cols[colonne][ligne]`
|
||||
/// cols[0] = [m00, m10, m20, m30] (1ère colonne)
|
||||
/// cols[1] = [m01, m11, m21, m31] (2ème colonne)
|
||||
/// cols[2] = [m02, m12, m22, m32] (3ème colonne)
|
||||
/// cols[3] = [m03, m13, m23, m33] (4ème colonne)
|
||||
///
|
||||
/// Cet ordre correspond exactement à l'agencement mémoire attendu par GLSL / SPIR-V
|
||||
/// lorsqu'on transmet la matrice via push constants ou uniform buffer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[repr(C)]
|
||||
pub struct Mat4 {
|
||||
pub cols: [[f32; 4]; 4],
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
impl Mat4 {
|
||||
/// Crée une matrice identité (diagonale = 1, le reste = 0).
|
||||
pub const fn identity() -> Self {
|
||||
Self {
|
||||
cols: [
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée une matrice nulle.
|
||||
pub const fn zero() -> Self {
|
||||
Self {
|
||||
cols: [[0.0; 4]; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée une matrice de translation.
|
||||
pub fn from_translation(t: Vec3) -> Self {
|
||||
let mut m = Self::identity();
|
||||
m.cols[3][0] = t.x;
|
||||
m.cols[3][1] = t.y;
|
||||
m.cols[3][2] = t.z;
|
||||
m
|
||||
}
|
||||
|
||||
/// Crée une matrice de mise à l'échelle (scale).
|
||||
pub fn from_scale(s: Vec3) -> Self {
|
||||
Self {
|
||||
cols: [
|
||||
[s.x, 0.0, 0.0, 0.0],
|
||||
[0.0, s.y, 0.0, 0.0],
|
||||
[0.0, 0.0, s.z, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée une matrice de rotation autour de l'axe Y (angle en radians).
|
||||
pub fn from_rotation_y(rad: f32) -> Self {
|
||||
let cos = rad.cos();
|
||||
let sin = rad.sin();
|
||||
let mut m = Self::identity();
|
||||
m.cols[0][0] = cos;
|
||||
m.cols[0][2] = -sin;
|
||||
m.cols[2][0] = sin;
|
||||
m.cols[2][2] = cos;
|
||||
m
|
||||
}
|
||||
|
||||
/// Crée une matrice de rotation autour de l'axe X (angle en radians).
|
||||
pub fn from_rotation_x(rad: f32) -> Self {
|
||||
let cos = rad.cos();
|
||||
let sin = rad.sin();
|
||||
let mut m = Self::identity();
|
||||
m.cols[1][1] = cos;
|
||||
m.cols[1][2] = sin;
|
||||
m.cols[2][1] = -sin;
|
||||
m.cols[2][2] = cos;
|
||||
m
|
||||
}
|
||||
|
||||
/// Matrice de vue standard (Look At).
|
||||
///
|
||||
/// Convention du repère :
|
||||
/// - Monde : main droite, +Y vers le haut (Up), +X vers la droite, +Z vers l'observateur.
|
||||
/// - Caméra : placée en `eye`, regarde en direction de `target`.
|
||||
/// L'axe de visée de la caméra pointe le long de -Z (repère de vue standard).
|
||||
pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
|
||||
let forward = (target - eye).normalize();
|
||||
let right = forward.cross(up).normalize();
|
||||
let true_up = right.cross(forward);
|
||||
|
||||
// La rotation amène le repère monde dans le repère caméra :
|
||||
// Axe X = right
|
||||
// Axe Y = true_up
|
||||
// Axe Z = -forward
|
||||
let mut m = Self::identity();
|
||||
m.cols[0][0] = right.x;
|
||||
m.cols[1][0] = right.y;
|
||||
m.cols[2][0] = right.z;
|
||||
m.cols[3][0] = -right.dot(eye);
|
||||
|
||||
m.cols[0][1] = true_up.x;
|
||||
m.cols[1][1] = true_up.y;
|
||||
m.cols[2][1] = true_up.z;
|
||||
m.cols[3][1] = -true_up.dot(eye);
|
||||
|
||||
m.cols[0][2] = -forward.x;
|
||||
m.cols[1][2] = -forward.y;
|
||||
m.cols[2][2] = -forward.z;
|
||||
m.cols[3][2] = forward.dot(eye);
|
||||
|
||||
m
|
||||
}
|
||||
|
||||
/// Matrice de projection perspective adaptée à Vulkan.
|
||||
///
|
||||
/// Spécificités Vulkan vs OpenGL :
|
||||
/// 1. Dans Vulkan, l'axe Y en coordonnées NDC (Normalized Device Coordinates)
|
||||
/// va vers le BAS (le haut de l'écran est à -1, le bas à +1). Pour conserver
|
||||
/// notre monde avec +Y vers le haut, nous inversons le signe de P[1][1] (-f).
|
||||
/// 2. Dans Vulkan, la profondeur Z en coordonnées NDC varie de [0.0 (Near), 1.0 (Far)],
|
||||
/// contrairement à OpenGL qui utilise [-1.0, 1.0].
|
||||
/// La projection mappe donc [near, far] sur [0, 1].
|
||||
pub fn perspective(fov_y_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
|
||||
let f = 1.0 / (fov_y_rad * 0.5).tan();
|
||||
let range_inv = 1.0 / (near - far);
|
||||
|
||||
let mut m = Self::zero();
|
||||
m.cols[0][0] = f / aspect;
|
||||
m.cols[1][1] = -f; // Inversion de Y pour le repère d'écran Vulkan
|
||||
m.cols[2][2] = far * range_inv;
|
||||
m.cols[2][3] = -1.0;
|
||||
m.cols[3][2] = near * far * range_inv;
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
impl Mul for Mat4 {
|
||||
type Output = Self;
|
||||
|
||||
/// Multiplication de matrices 4x4 : C = A * B
|
||||
/// En ordre column-major, C[col][row] = sum_k (A[k][row] * B[col][k])
|
||||
fn mul(self, rhs: Self) -> Self::Output {
|
||||
let mut res = Self::zero();
|
||||
for col in 0..4 {
|
||||
for row in 0..4 {
|
||||
res.cols[col][row] = self.cols[0][row] * rhs.cols[col][0]
|
||||
+ self.cols[1][row] * rhs.cols[col][1]
|
||||
+ self.cols[2][row] * rhs.cols[col][2]
|
||||
+ self.cols[3][row] * rhs.cols[col][3];
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_vec3_operations() {
|
||||
let a = Vec3::new(1.0, 2.0, 3.0);
|
||||
let b = Vec3::new(4.0, 5.0, 6.0);
|
||||
assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0));
|
||||
assert_eq!(b - a, Vec3::new(3.0, 3.0, 3.0));
|
||||
assert_eq!(a * 2.0, Vec3::new(2.0, 4.0, 6.0));
|
||||
assert_eq!(a.dot(b), 4.0 + 10.0 + 18.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mat4_identity_mul() {
|
||||
let id = Mat4::identity();
|
||||
let m = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
|
||||
assert_eq!(id * m, m);
|
||||
assert_eq!(m * id, m);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
use crate::camera::Camera;
|
||||
use crate::math::Vec3;
|
||||
use crate::world::World;
|
||||
|
||||
/// Boîte englobante alignée sur les axes (Axis-Aligned Bounding Box).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct AABB {
|
||||
pub min: Vec3,
|
||||
pub max: Vec3,
|
||||
}
|
||||
|
||||
impl AABB {
|
||||
pub fn new(min: Vec3, max: Vec3) -> Self {
|
||||
Self { min, max }
|
||||
}
|
||||
|
||||
/// Crée une AABB depuis la position des pieds du joueur et ses dimensions.
|
||||
pub fn from_feet(feet: Vec3, width: f32, height: f32) -> Self {
|
||||
let half_w = width * 0.5;
|
||||
Self {
|
||||
min: Vec3::new(feet.x - half_w, feet.y, feet.z - half_w),
|
||||
max: Vec3::new(feet.x + half_w, feet.y + height, feet.z + half_w),
|
||||
}
|
||||
}
|
||||
|
||||
/// Teste si deux boîtes AABB s'intersectent de manière stricte (chevauchement en volume).
|
||||
#[inline(always)]
|
||||
pub fn intersects(&self, other: &AABB) -> bool {
|
||||
self.min.x < other.max.x
|
||||
&& self.max.x > other.min.x
|
||||
&& self.min.y < other.max.y
|
||||
&& self.max.y > other.min.y
|
||||
&& self.min.z < other.max.z
|
||||
&& self.max.z > other.min.z
|
||||
}
|
||||
}
|
||||
|
||||
/// Gestion de l'entité Joueur, de sa physique (gravité, saut) et des collisions monde.
|
||||
pub struct Player {
|
||||
pub position: Vec3, // Position des pieds dans le monde
|
||||
pub velocity: Vec3, // Vélocité en m/s
|
||||
pub width: f32, // 0.6 bloc
|
||||
pub height: f32, // 1.8 bloc
|
||||
pub eye_height: f32,// 1.6 bloc (hauteur des yeux par rapport aux pieds)
|
||||
pub is_grounded: bool,
|
||||
pub flying: bool, // Mode vol activable par touche (F)
|
||||
}
|
||||
|
||||
impl Player {
|
||||
pub const WIDTH: f32 = 0.6;
|
||||
pub const HEIGHT: f32 = 1.8;
|
||||
pub const EYE_HEIGHT: f32 = 1.6;
|
||||
pub const GRAVITY: f32 = -26.0; // Accélération verticale en unités/s²
|
||||
pub const JUMP_VELOCITY: f32 = 8.5; // Impulsion de saut permettant de franchir 1.2 bloc
|
||||
pub const WALK_SPEED: f32 = 5.0; // Vitesse de marche normale
|
||||
pub const FLY_SPEED: f32 = 16.0; // Vitesse en mode vol libre
|
||||
|
||||
pub fn new(feet_pos: Vec3) -> Self {
|
||||
Self {
|
||||
position: feet_pos,
|
||||
velocity: Vec3::zero(),
|
||||
width: Self::WIDTH,
|
||||
height: Self::HEIGHT,
|
||||
eye_height: Self::EYE_HEIGHT,
|
||||
is_grounded: false,
|
||||
flying: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Boîte englobante AABB actuelle du joueur.
|
||||
#[inline(always)]
|
||||
pub fn aabb(&self) -> AABB {
|
||||
AABB::from_feet(self.position, self.width, self.height)
|
||||
}
|
||||
|
||||
/// Position des yeux pour la caméra de rendu et le raycasting.
|
||||
#[inline(always)]
|
||||
pub fn eye_position(&self) -> Vec3 {
|
||||
Vec3::new(
|
||||
self.position.x,
|
||||
self.position.y + self.eye_height,
|
||||
self.position.z,
|
||||
)
|
||||
}
|
||||
|
||||
/// Mise à jour physique du joueur pour un pas de temps delta-time (dt en secondes).
|
||||
pub fn update(&mut self, dt: f32, camera: &Camera, world: &World) {
|
||||
if self.flying {
|
||||
// --- Mode vol libre (noclip / debug) ---
|
||||
let fwd = camera.forward();
|
||||
let rgt = camera.right();
|
||||
let up = Vec3::new(0.0, 1.0, 0.0);
|
||||
|
||||
let mut dir = Vec3::zero();
|
||||
if camera.move_forward { dir = dir + fwd; }
|
||||
if camera.move_backward { dir = dir - fwd; }
|
||||
if camera.move_right { dir = dir + rgt; }
|
||||
if camera.move_left { dir = dir - rgt; }
|
||||
if camera.move_up { dir = dir + up; }
|
||||
if camera.move_down { dir = dir - up; }
|
||||
|
||||
if dir.length_squared() > 0.0001 {
|
||||
self.position = self.position + dir.normalize() * (Self::FLY_SPEED * dt);
|
||||
}
|
||||
self.velocity = Vec3::zero();
|
||||
self.is_grounded = false;
|
||||
} else {
|
||||
// --- Mode marche avec gravité et collisions AABB ---
|
||||
// On subdivise les frames longues pour garantir l'intégrité anti-tunneling
|
||||
let max_substep = 0.015;
|
||||
let steps = (dt / max_substep).ceil() as usize;
|
||||
let steps = steps.max(1);
|
||||
let sub_dt = dt / steps as f32;
|
||||
|
||||
for _ in 0..steps {
|
||||
self.physics_step(sub_dt, camera, world);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exécute un sous-pas de physique avec résolution des collisions axe par axe.
|
||||
fn physics_step(&mut self, dt: f32, camera: &Camera, world: &World) {
|
||||
// 1. Calcul de la direction horizontale voulue par le joueur (plan XZ)
|
||||
let yaw = camera.yaw;
|
||||
let fwd = Vec3::new(yaw.sin(), 0.0, -yaw.cos()).normalize();
|
||||
let rgt = Vec3::new(yaw.cos(), 0.0, yaw.sin()).normalize();
|
||||
|
||||
let mut wish_dir = Vec3::zero();
|
||||
if camera.move_forward { wish_dir = wish_dir + fwd; }
|
||||
if camera.move_backward { wish_dir = wish_dir - fwd; }
|
||||
if camera.move_right { wish_dir = wish_dir + rgt; }
|
||||
if camera.move_left { wish_dir = wish_dir - rgt; }
|
||||
|
||||
if wish_dir.length_squared() > 0.0001 {
|
||||
let move_vel = wish_dir.normalize() * Self::WALK_SPEED;
|
||||
self.velocity.x = move_vel.x;
|
||||
self.velocity.z = move_vel.z;
|
||||
} else {
|
||||
self.velocity.x = 0.0;
|
||||
self.velocity.z = 0.0;
|
||||
}
|
||||
|
||||
// 2. Saut (impulsion verticale) uniquement si au sol
|
||||
if camera.move_up && self.is_grounded {
|
||||
self.velocity.y = Self::JUMP_VELOCITY;
|
||||
self.is_grounded = false;
|
||||
}
|
||||
|
||||
// 3. Intégration de la gravité
|
||||
self.velocity.y += Self::GRAVITY * dt;
|
||||
// Vitesse terminale de chute (plafonnée à -35 m/s)
|
||||
if self.velocity.y < -35.0 {
|
||||
self.velocity.y = -35.0;
|
||||
}
|
||||
|
||||
// 4. Résolution des collisions AXE PAR AXE : X, puis Y, puis Z
|
||||
self.resolve_axis_x(dt, world);
|
||||
self.resolve_axis_y(dt, world);
|
||||
self.resolve_axis_z(dt, world);
|
||||
}
|
||||
|
||||
/// Résolution des collisions sur l'axe X
|
||||
fn resolve_axis_x(&mut self, dt: f32, world: &World) {
|
||||
let dx = self.velocity.x * dt;
|
||||
if dx.abs() < 1e-6 {
|
||||
return;
|
||||
}
|
||||
|
||||
self.position.x += dx;
|
||||
let half_w = self.width * 0.5;
|
||||
let aabb = self.aabb();
|
||||
|
||||
let min_x = aabb.min.x.floor() as i32;
|
||||
let max_x = aabb.max.x.floor() as i32;
|
||||
let min_y = aabb.min.y.floor() as i32;
|
||||
let max_y = aabb.max.y.floor() as i32;
|
||||
let min_z = aabb.min.z.floor() as i32;
|
||||
let max_z = aabb.max.z.floor() as i32;
|
||||
|
||||
let mut collided = false;
|
||||
let mut target_x = self.position.x;
|
||||
|
||||
for y in min_y..=max_y {
|
||||
for z in min_z..=max_z {
|
||||
for x in min_x..=max_x {
|
||||
if world.get_block(x, y, z).is_opaque() {
|
||||
let block_aabb = AABB::new(
|
||||
Vec3::new(x as f32, y as f32, z as f32),
|
||||
Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32),
|
||||
);
|
||||
if self.aabb().intersects(&block_aabb) {
|
||||
collided = true;
|
||||
if dx > 0.0 {
|
||||
let limit = (x as f32) - half_w - 0.0001;
|
||||
target_x = target_x.min(limit);
|
||||
} else {
|
||||
let limit = (x + 1) as f32 + half_w + 0.0001;
|
||||
target_x = target_x.max(limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if collided {
|
||||
self.position.x = target_x;
|
||||
self.velocity.x = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Résolution des collisions sur l'axe Y (chute / saut / détection du sol)
|
||||
fn resolve_axis_y(&mut self, dt: f32, world: &World) {
|
||||
let dy = self.velocity.y * dt;
|
||||
self.position.y += dy;
|
||||
|
||||
let aabb = self.aabb();
|
||||
let min_x = aabb.min.x.floor() as i32;
|
||||
let max_x = aabb.max.x.floor() as i32;
|
||||
let min_y = aabb.min.y.floor() as i32;
|
||||
let max_y = aabb.max.y.floor() as i32;
|
||||
let min_z = aabb.min.z.floor() as i32;
|
||||
let max_z = aabb.max.z.floor() as i32;
|
||||
|
||||
let mut collided = false;
|
||||
let mut hit_ground = false;
|
||||
let mut target_y = self.position.y;
|
||||
|
||||
for y in min_y..=max_y {
|
||||
for z in min_z..=max_z {
|
||||
for x in min_x..=max_x {
|
||||
if world.get_block(x, y, z).is_opaque() {
|
||||
let block_aabb = AABB::new(
|
||||
Vec3::new(x as f32, y as f32, z as f32),
|
||||
Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32),
|
||||
);
|
||||
if self.aabb().intersects(&block_aabb) {
|
||||
collided = true;
|
||||
if dy < 0.0 {
|
||||
// Atterrissage sur le dessus d'un bloc plein
|
||||
let limit = (y + 1) as f32;
|
||||
target_y = target_y.max(limit);
|
||||
hit_ground = true;
|
||||
} else if dy > 0.0 {
|
||||
// Choc contre le plafond
|
||||
let limit = (y as f32) - self.height - 0.0001;
|
||||
target_y = target_y.min(limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if collided {
|
||||
self.position.y = target_y;
|
||||
self.velocity.y = 0.0;
|
||||
if hit_ground {
|
||||
self.is_grounded = true;
|
||||
}
|
||||
} else {
|
||||
// Aucun contact au sol -> en chute ou en vol
|
||||
self.is_grounded = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Résolution des collisions sur l'axe Z
|
||||
fn resolve_axis_z(&mut self, dt: f32, world: &World) {
|
||||
let dz = self.velocity.z * dt;
|
||||
if dz.abs() < 1e-6 {
|
||||
return;
|
||||
}
|
||||
|
||||
self.position.z += dz;
|
||||
let half_w = self.width * 0.5;
|
||||
let aabb = self.aabb();
|
||||
|
||||
let min_x = aabb.min.x.floor() as i32;
|
||||
let max_x = aabb.max.x.floor() as i32;
|
||||
let min_y = aabb.min.y.floor() as i32;
|
||||
let max_y = aabb.max.y.floor() as i32;
|
||||
let min_z = aabb.min.z.floor() as i32;
|
||||
let max_z = aabb.max.z.floor() as i32;
|
||||
|
||||
let mut collided = false;
|
||||
let mut target_z = self.position.z;
|
||||
|
||||
for y in min_y..=max_y {
|
||||
for z in min_z..=max_z {
|
||||
for x in min_x..=max_x {
|
||||
if world.get_block(x, y, z).is_opaque() {
|
||||
let block_aabb = AABB::new(
|
||||
Vec3::new(x as f32, y as f32, z as f32),
|
||||
Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32),
|
||||
);
|
||||
if self.aabb().intersects(&block_aabb) {
|
||||
collided = true;
|
||||
if dz > 0.0 {
|
||||
let limit = (z as f32) - half_w - 0.0001;
|
||||
target_z = target_z.min(limit);
|
||||
} else {
|
||||
let limit = (z + 1) as f32 + half_w + 0.0001;
|
||||
target_z = target_z.max(limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if collided {
|
||||
self.position.z = target_z;
|
||||
self.velocity.z = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::world::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Z};
|
||||
|
||||
#[test]
|
||||
fn test_aabb_intersection() {
|
||||
let b1 = AABB::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0));
|
||||
let b2 = AABB::new(Vec3::new(0.5, 0.5, 0.5), Vec3::new(1.5, 1.5, 1.5));
|
||||
let b3 = AABB::new(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 1.0, 1.0));
|
||||
|
||||
assert!(b1.intersects(&b2));
|
||||
assert!(!b1.intersects(&b3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gravity_and_ground_landing() {
|
||||
let mut world = World::new();
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
// Crée un sol de pierre au niveau y = 2
|
||||
for x in 0..CHUNK_SIZE_X {
|
||||
for z in 0..CHUNK_SIZE_Z {
|
||||
chunk.set_block_local(x, 2, z, BlockType::Stone);
|
||||
}
|
||||
}
|
||||
world.chunks.insert((0, 0), chunk);
|
||||
|
||||
let camera = Camera::new(Vec3::new(2.0, 5.0, 2.0));
|
||||
let mut player = Player::new(Vec3::new(2.0, 5.0, 2.0));
|
||||
|
||||
// Intègre la physique sur plusieurs pas de temps
|
||||
for _ in 0..60 {
|
||||
player.update(0.016, &camera, &world);
|
||||
}
|
||||
|
||||
// Le joueur doit être posé sur le sol à y = 3.0 (y=2 est plein, le dessus est à y=3.0)
|
||||
assert!((player.position.y - 3.0).abs() < 0.01, "Position Y: {}", player.position.y);
|
||||
assert!(player.is_grounded, "Le joueur doit être au sol");
|
||||
assert_eq!(player.velocity.y, 0.0, "La vélocité verticale doit être nulle au repos");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_player_jump() {
|
||||
let mut world = World::new();
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
for x in 0..CHUNK_SIZE_X {
|
||||
for z in 0..CHUNK_SIZE_Z {
|
||||
chunk.set_block_local(x, 2, z, BlockType::Stone);
|
||||
}
|
||||
}
|
||||
world.chunks.insert((0, 0), chunk);
|
||||
|
||||
let mut camera = Camera::new(Vec3::new(2.0, 3.0, 2.0));
|
||||
let mut player = Player::new(Vec3::new(2.0, 3.0, 2.0));
|
||||
player.is_grounded = true;
|
||||
camera.move_up = true; // Demande de saut
|
||||
|
||||
// Un pas physique avec saut
|
||||
player.update(0.016, &camera, &world);
|
||||
assert!(player.velocity.y > 0.0, "Le saut doit donner une vitesse vers le haut");
|
||||
assert!(!player.is_grounded, "Le joueur ne doit plus être au sol lors du saut");
|
||||
assert!(player.position.y > 3.0, "Le joueur doit avoir monté");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wall_collision_x() {
|
||||
let mut world = World::new();
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
// Sol à y = 0
|
||||
for x in 0..CHUNK_SIZE_X {
|
||||
for z in 0..CHUNK_SIZE_Z {
|
||||
chunk.set_block_local(x, 0, z, BlockType::Stone);
|
||||
}
|
||||
}
|
||||
// Mur à x = 4, y = 1..=2, z = 0..CHUNK_SIZE_Z
|
||||
for y in 1..=2 {
|
||||
for z in 0..CHUNK_SIZE_Z {
|
||||
chunk.set_block_local(4, y, z, BlockType::Stone);
|
||||
}
|
||||
}
|
||||
world.chunks.insert((0, 0), chunk);
|
||||
|
||||
let mut camera = Camera::new(Vec3::new(3.0, 1.0, 2.0));
|
||||
// Regarde vers +X (yaw = pi/2)
|
||||
camera.yaw = std::f32::consts::FRAC_PI_2;
|
||||
camera.move_forward = true;
|
||||
|
||||
let mut player = Player::new(Vec3::new(3.0, 1.0, 2.0));
|
||||
player.is_grounded = true;
|
||||
|
||||
for _ in 0..30 {
|
||||
player.update(0.016, &camera, &world);
|
||||
}
|
||||
|
||||
// Le bord du joueur à x + 0.3 ne doit jamais pénétrer x = 4.0
|
||||
assert!(player.position.x + player.width * 0.5 <= 4.0001, "Position X: {}", player.position.x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_jump_and_land_on_chunk_boundary() {
|
||||
let mut world = World::new();
|
||||
// Deux chunks côte à côte : (0, 0) et (1, 0)
|
||||
// La frontière en X se situe exactement à x = 16.0
|
||||
let mut chunk0 = Chunk::new_empty(0, 0);
|
||||
let mut chunk1 = Chunk::new_empty(1, 0);
|
||||
|
||||
// Sol continu à y = 4 sur les deux chunks
|
||||
for z in 0..CHUNK_SIZE_Z {
|
||||
for x in 0..CHUNK_SIZE_X {
|
||||
chunk0.set_block_local(x, 4, z, BlockType::Stone);
|
||||
chunk1.set_block_local(x, 4, z, BlockType::Stone);
|
||||
}
|
||||
}
|
||||
world.chunks.insert((0, 0), chunk0);
|
||||
world.chunks.insert((1, 0), chunk1);
|
||||
|
||||
// Joueur positionné exactement à la frontière : x = 16.0, z = 8.0, y = 8.0
|
||||
// Son AABB (largeur 0.6) s'étend de 15.7 (chunk 0) à 16.3 (chunk 1)
|
||||
let mut player = Player::new(Vec3::new(16.0, 8.0, 8.0));
|
||||
let mut camera = Camera::new(player.eye_position());
|
||||
|
||||
// 1. Chute et atterrissage à cheval sur la frontière
|
||||
for _ in 0..60 {
|
||||
player.update(0.016, &camera, &world);
|
||||
}
|
||||
|
||||
assert!((player.position.y - 5.0).abs() < 0.01, "Y après atterrissage: {}", player.position.y);
|
||||
assert!(player.is_grounded, "Le joueur doit être au sol sur la frontière");
|
||||
|
||||
// 2. Saut depuis la frontière
|
||||
camera.move_up = true;
|
||||
player.update(0.016, &camera, &world);
|
||||
assert!(!player.is_grounded);
|
||||
assert!(player.velocity.y > 0.0);
|
||||
|
||||
// 3. Retombée et deuxième atterrissage sur la frontière
|
||||
camera.move_up = false;
|
||||
for _ in 0..60 {
|
||||
player.update(0.016, &camera, &world);
|
||||
}
|
||||
|
||||
assert!((player.position.y - 5.0).abs() < 0.01, "Y après retombée: {}", player.position.y);
|
||||
assert!(player.is_grounded, "Le joueur doit réatterrir de façon stable");
|
||||
assert!((player.position.x - 16.0).abs() < 0.01, "X doit rester aligné");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
use crate::math::Vec3;
|
||||
use crate::world::World;
|
||||
|
||||
/// Résultat d'un raycast voxel traversant la grille du monde.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RaycastHit {
|
||||
/// Coordonnées absolues (x, y, z) du bloc touché (à casser).
|
||||
pub hit_pos: (i32, i32, i32),
|
||||
/// Coordonnées absolues (x, y, z) du bloc adjacent vide sur la face d'impact (où poser un nouveau bloc).
|
||||
pub place_pos: (i32, i32, i32),
|
||||
/// Normale de la face touchée.
|
||||
pub face_normal: (i32, i32, i32),
|
||||
}
|
||||
|
||||
/// Algorithme DDA 3D (Amanatides & Woo - "A Fast Voxel Traversal Algorithm for Ray Tracing").
|
||||
///
|
||||
/// Traverse de manière continue l'espace 3D du monde entier à travers de multiples chunks.
|
||||
pub fn raycast_voxel(
|
||||
origin: Vec3,
|
||||
direction: Vec3,
|
||||
max_distance: f32,
|
||||
world: &World,
|
||||
) -> Option<RaycastHit> {
|
||||
let dir = direction.normalize();
|
||||
if dir.length_squared() < 0.0001 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Coordonnées de la cellule voxel courante en coordonnées monde
|
||||
let mut x = origin.x.floor() as i32;
|
||||
let mut y = origin.y.floor() as i32;
|
||||
let mut z = origin.z.floor() as i32;
|
||||
|
||||
// Direction du pas sur chaque axe (+1 ou -1)
|
||||
let step_x = if dir.x > 0.0 { 1 } else if dir.x < 0.0 { -1 } else { 0 };
|
||||
let step_y = if dir.y > 0.0 { 1 } else if dir.y < 0.0 { -1 } else { 0 };
|
||||
let step_z = if dir.z > 0.0 { 1 } else if dir.z < 0.0 { -1 } else { 0 };
|
||||
|
||||
// Distance le long du rayon pour traverser une cellule complète (1 unité)
|
||||
let t_delta_x = if step_x != 0 { (1.0 / dir.x).abs() } else { f32::INFINITY };
|
||||
let t_delta_y = if step_y != 0 { (1.0 / dir.y).abs() } else { f32::INFINITY };
|
||||
let t_delta_z = if step_z != 0 { (1.0 / dir.z).abs() } else { f32::INFINITY };
|
||||
|
||||
// Distance initiale jusqu'à la première frontière de voxel
|
||||
let mut t_max_x = if step_x > 0 {
|
||||
((x + 1) as f32 - origin.x) * t_delta_x
|
||||
} else if step_x < 0 {
|
||||
(origin.x - x as f32) * t_delta_x
|
||||
} else {
|
||||
f32::INFINITY
|
||||
};
|
||||
|
||||
let mut t_max_y = if step_y > 0 {
|
||||
((y + 1) as f32 - origin.y) * t_delta_y
|
||||
} else if step_y < 0 {
|
||||
(origin.y - y as f32) * t_delta_y
|
||||
} else {
|
||||
f32::INFINITY
|
||||
};
|
||||
|
||||
let mut t_max_z = if step_z > 0 {
|
||||
((z + 1) as f32 - origin.z) * t_delta_z
|
||||
} else if step_z < 0 {
|
||||
(origin.z - z as f32) * t_delta_z
|
||||
} else {
|
||||
f32::INFINITY
|
||||
};
|
||||
|
||||
let mut current_dist = 0.0f32;
|
||||
let mut normal;
|
||||
|
||||
// Si la caméra est déjà dans un bloc solide dès le départ
|
||||
if world.get_block(x, y, z).is_opaque() {
|
||||
return Some(RaycastHit {
|
||||
hit_pos: (x, y, z),
|
||||
place_pos: (x, y, z),
|
||||
face_normal: (0, 1, 0),
|
||||
});
|
||||
}
|
||||
|
||||
while current_dist <= max_distance {
|
||||
// Avance vers la frontière de voxel la plus proche
|
||||
if t_max_x < t_max_y {
|
||||
if t_max_x < t_max_z {
|
||||
current_dist = t_max_x;
|
||||
t_max_x += t_delta_x;
|
||||
x += step_x;
|
||||
normal = (-step_x, 0, 0);
|
||||
} else {
|
||||
current_dist = t_max_z;
|
||||
t_max_z += t_delta_z;
|
||||
z += step_z;
|
||||
normal = (0, 0, -step_z);
|
||||
}
|
||||
} else {
|
||||
if t_max_y < t_max_z {
|
||||
current_dist = t_max_y;
|
||||
t_max_y += t_delta_y;
|
||||
y += step_y;
|
||||
normal = (0, -step_y, 0);
|
||||
} else {
|
||||
current_dist = t_max_z;
|
||||
t_max_z += t_delta_z;
|
||||
z += step_z;
|
||||
normal = (0, 0, -step_z);
|
||||
}
|
||||
}
|
||||
|
||||
if current_dist > max_distance {
|
||||
break;
|
||||
}
|
||||
|
||||
// Test si la nouvelle cellule globale contient un bloc plein
|
||||
if world.get_block(x, y, z).is_opaque() {
|
||||
let place_pos = (x + normal.0, y + normal.1, z + normal.2);
|
||||
return Some(RaycastHit {
|
||||
hit_pos: (x, y, z),
|
||||
place_pos,
|
||||
face_normal: normal,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::world::{BlockType, Chunk};
|
||||
|
||||
#[test]
|
||||
fn test_raycast_hits_block_front() {
|
||||
let mut world = World::new();
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
chunk.set_block_local(10, 10, 10, BlockType::Stone);
|
||||
world.chunks.insert((0, 0), chunk);
|
||||
|
||||
let origin = Vec3::new(10.5, 10.5, 15.0);
|
||||
let dir = Vec3::new(0.0, 0.0, -1.0);
|
||||
|
||||
let hit = raycast_voxel(origin, dir, 8.0, &world);
|
||||
assert!(hit.is_some());
|
||||
let h = hit.unwrap();
|
||||
assert_eq!(h.hit_pos, (10, 10, 10));
|
||||
assert_eq!(h.face_normal, (0, 0, 1));
|
||||
assert_eq!(h.place_pos, (10, 10, 11));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_raycast_across_chunk_boundary() {
|
||||
let mut world = World::new();
|
||||
// Chunk (0, 0) vide
|
||||
world.chunks.insert((0, 0), Chunk::new_empty(0, 0));
|
||||
// Chunk (1, 0) contenant un bloc en local (0, 10, 8), soit en monde (16, 10, 8)
|
||||
let mut chunk1 = Chunk::new_empty(1, 0);
|
||||
chunk1.set_block_local(0, 10, 8, BlockType::Stone);
|
||||
world.chunks.insert((1, 0), chunk1);
|
||||
|
||||
// Rayon tiré depuis chunk 0 en (14.5, 10.5, 8.5) vers +X
|
||||
let origin = Vec3::new(14.5, 10.5, 8.5);
|
||||
let dir = Vec3::new(1.0, 0.0, 0.0);
|
||||
|
||||
let hit = raycast_voxel(origin, dir, 8.0, &world);
|
||||
assert!(hit.is_some());
|
||||
let h = hit.unwrap();
|
||||
assert_eq!(h.hit_pos, (16, 10, 8)); // Bloc dans le chunk voisin !
|
||||
assert_eq!(h.face_normal, (-1, 0, 0)); // Entrée par -X
|
||||
assert_eq!(h.place_pos, (15, 10, 8)); // Poser dans le chunk 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use winit::raw_window_handle::HasDisplayHandle;
|
||||
use std::sync::Arc;
|
||||
use vulkano::device::physical::{PhysicalDevice, PhysicalDeviceType};
|
||||
use vulkano::device::{Device, DeviceCreateInfo, DeviceExtensions, Queue, QueueCreateInfo, QueueFlags};
|
||||
use vulkano::instance::{Instance, InstanceCreateFlags, InstanceCreateInfo};
|
||||
use vulkano::swapchain::Surface;
|
||||
use vulkano::VulkanLibrary;
|
||||
use winit::window::Window;
|
||||
|
||||
/// Structure regroupant le contexte initial du périphérique Vulkan.
|
||||
pub struct DeviceContext {
|
||||
pub instance: Arc<Instance>,
|
||||
pub surface: Arc<Surface>,
|
||||
pub device: Arc<Device>,
|
||||
pub queue: Arc<Queue>,
|
||||
}
|
||||
|
||||
/// Initialise l'instance Vulkan, crée la Surface liée à la fenêtre winit,
|
||||
/// sélectionne le meilleur GPU physique disponible et crée le Logical Device.
|
||||
pub fn init_device(
|
||||
window: Arc<Window>,
|
||||
display_handle: &impl HasDisplayHandle,
|
||||
) -> Result<DeviceContext, Box<dyn std::error::Error>> {
|
||||
// 1. Chargement de la bibliothèque dynamique Vulkan installée sur l'OS (vulkan-1.dll / libvulkan.so)
|
||||
let library = VulkanLibrary::new()?;
|
||||
|
||||
// 2. Extensions d'instance requises pour afficher sur une fenêtre (Winit / OS surface)
|
||||
// Surface::required_extensions interroge le display handle winit pour savoir quelles
|
||||
// extensions WSI (Window System Integration) sont indispensables (ex: VK_KHR_win32_surface, VK_KHR_surface).
|
||||
let required_extensions = Surface::required_extensions(display_handle)?;
|
||||
|
||||
// 3. Création de l'instance Vulkan
|
||||
// L'instance représente la connexion entre notre application et le runtime Vulkan.
|
||||
let instance = Instance::new(
|
||||
library,
|
||||
InstanceCreateInfo {
|
||||
flags: InstanceCreateFlags::ENUMERATE_PORTABILITY,
|
||||
enabled_extensions: required_extensions,
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
// 4. Création de la Surface Vulkan
|
||||
// La Surface fait le pont entre le système de fenêtrage de l'OS (géré par winit)
|
||||
// et l'instance Vulkan. Les images rendues par le GPU y seront présentées.
|
||||
let surface = Surface::from_window(instance.clone(), window)?;
|
||||
|
||||
// 5. Extensions requises au niveau du Device (GPU)
|
||||
// La swapchain (VK_KHR_swapchain) est impérative pour pouvoir présenter des images à l'écran.
|
||||
let device_extensions = DeviceExtensions {
|
||||
khr_swapchain: true,
|
||||
..DeviceExtensions::empty()
|
||||
};
|
||||
|
||||
// 6. Sélection du Physical Device (GPU) et de la Queue Family appropriée
|
||||
//
|
||||
// Pourquoi ce filtrage et ce choix :
|
||||
// - On ne garde que les GPU supportant l'extension `khr_swapchain`.
|
||||
// - On recherche une "Queue Family" qui supporte À LA FOIS :
|
||||
// a) Les opérations graphiques (QueueFlags::GRAPHICS) pour le dessin de nos voxels.
|
||||
// b) La présentation vers notre Surface (`surface_support(...) == true`).
|
||||
// Avoir une queue unique combinant Graphique + Présentation évite d'avoir à gérer
|
||||
// des transferts complexes d'images entre plusieurs files (Queue Family Ownership Transfers).
|
||||
// - On priorise un GPU dédié (DiscreteGpu) par rapport à un GPU intégré (IntegratedGpu),
|
||||
// puis virtuel ou logiciel.
|
||||
let (physical_device, queue_family_index) = select_physical_device(
|
||||
&instance,
|
||||
&surface,
|
||||
&device_extensions,
|
||||
)?;
|
||||
|
||||
println!(
|
||||
"GPU sélectionné : {} (Type: {:?})",
|
||||
physical_device.properties().device_name,
|
||||
physical_device.properties().device_type
|
||||
);
|
||||
|
||||
// 7. Création du Logical Device et de la Queue graphique
|
||||
// Le Logical Device est l'interface principale avec laquelle nous communiquerons avec le GPU.
|
||||
// On alloue 1 queue avec une priorité standard (1.0).
|
||||
let (device, mut queues) = Device::new(
|
||||
physical_device,
|
||||
DeviceCreateInfo {
|
||||
enabled_extensions: device_extensions,
|
||||
queue_create_infos: vec![QueueCreateInfo {
|
||||
queue_family_index,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
let queue = queues.next().expect("Aucune queue trouvée sur le device");
|
||||
|
||||
Ok(DeviceContext {
|
||||
instance,
|
||||
surface,
|
||||
device,
|
||||
queue,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parcourt tous les GPU disponibles et choisit le plus adapté selon nos critères.
|
||||
fn select_physical_device(
|
||||
instance: &Arc<Instance>,
|
||||
surface: &Arc<Surface>,
|
||||
device_extensions: &DeviceExtensions,
|
||||
) -> Result<(Arc<PhysicalDevice>, u32), Box<dyn std::error::Error>> {
|
||||
let mut candidates: Vec<(Arc<PhysicalDevice>, u32, u32)> = Vec::new();
|
||||
|
||||
for p in instance.enumerate_physical_devices()? {
|
||||
// Le GPU doit supporter les extensions demandées (khr_swapchain)
|
||||
if !p.supported_extensions().contains(device_extensions) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// On cherche une queue family supportant Graphique ET Présentation
|
||||
let mut suitable_queue_family = None;
|
||||
for (idx, q) in p.queue_family_properties().iter().enumerate() {
|
||||
let index = idx as u32;
|
||||
let supports_graphics = q.queue_flags.intersects(QueueFlags::GRAPHICS);
|
||||
let supports_presentation = p.surface_support(index, surface).unwrap_or(false);
|
||||
|
||||
if supports_graphics && supports_presentation {
|
||||
suitable_queue_family = Some(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(q_idx) = suitable_queue_family {
|
||||
// Score de priorité selon le type de périphérique
|
||||
let score = match p.properties().device_type {
|
||||
PhysicalDeviceType::DiscreteGpu => 0,
|
||||
PhysicalDeviceType::IntegratedGpu => 1,
|
||||
PhysicalDeviceType::VirtualGpu => 2,
|
||||
PhysicalDeviceType::Cpu => 3,
|
||||
_ => 4,
|
||||
};
|
||||
candidates.push((p, q_idx, score));
|
||||
}
|
||||
}
|
||||
|
||||
// On trie par score croissant (0 = DiscreteGpu en priorité)
|
||||
candidates.sort_by_key(|(_, _, score)| *score);
|
||||
|
||||
if let Some((device, queue_family, _)) = candidates.into_iter().next() {
|
||||
Ok((device, queue_family))
|
||||
} else {
|
||||
Err("Aucun GPU compatible avec le rendu graphique et la présentation Vulkan n'a été trouvé.".into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
use std::sync::Arc;
|
||||
use vulkano::buffer::{Buffer, BufferContents, BufferCreateInfo, BufferUsage, Subbuffer};
|
||||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator};
|
||||
use vulkano::pipeline::graphics::vertex_input::Vertex;
|
||||
|
||||
/// Format d'un sommet pour notre cube (et futurs chunks voxel).
|
||||
///
|
||||
/// Alignement mémoire :
|
||||
/// - `position` : coordonnées 3D (X, Y, Z)
|
||||
/// - `color` : couleur RVB par sommet (permet une couleur unique par face ou teinte)
|
||||
/// - `normal` : normale de la surface (pour un ombrage directionnel basique)
|
||||
/// - `uv` : coordonnées de texture normalisées [0..1] dans l'atlas
|
||||
#[derive(BufferContents, Vertex, Clone, Copy, Debug)]
|
||||
#[repr(C)]
|
||||
pub struct CubeVertex {
|
||||
#[format(R32G32B32_SFLOAT)]
|
||||
pub position: [f32; 3],
|
||||
#[format(R32G32B32_SFLOAT)]
|
||||
pub color: [f32; 3],
|
||||
#[format(R32G32B32_SFLOAT)]
|
||||
pub normal: [f32; 3],
|
||||
#[format(R32G32_SFLOAT)]
|
||||
pub uv: [f32; 2],
|
||||
}
|
||||
|
||||
/// Conteneur des buffers GPU d'un maillage.
|
||||
pub struct MeshBuffers {
|
||||
pub vertex_buffer: Subbuffer<[CubeVertex]>,
|
||||
pub index_buffer: Subbuffer<[u32]>,
|
||||
pub index_count: u32,
|
||||
}
|
||||
|
||||
/// Génère la géométrie d'un cube unitaire de côté 1.0 centré en (0, 0, 0).
|
||||
///
|
||||
/// Pourquoi 24 sommets et non 8 ?
|
||||
/// Un cube partagé avec 8 sommets forcerait les faces adjacentes à partager
|
||||
/// leurs normales et leurs couleurs. En dupliquant les 4 sommets de chaque
|
||||
/// face (6 faces * 4 = 24 sommets), chaque face dispose d'une normale plane
|
||||
/// distincte (flat shading) et d'une couleur propre.
|
||||
#[allow(dead_code)]
|
||||
pub fn create_cube_mesh(
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
) -> Result<MeshBuffers, Box<dyn std::error::Error>> {
|
||||
let mut vertices = Vec::with_capacity(24);
|
||||
let mut indices = Vec::with_capacity(36);
|
||||
|
||||
// Définition des 6 faces : (nom, normale, couleur, [p0, p1, p2, p3])
|
||||
// Ordre des sommets en Counter-Clockwise (sens trigonométrique vu de l'extérieur)
|
||||
let faces = [
|
||||
// Face Dessus (+Y) - Vert Herbe
|
||||
(
|
||||
[0.0, 1.0, 0.0],
|
||||
[0.2, 0.8, 0.25],
|
||||
[
|
||||
[-0.5, 0.5, 0.5],
|
||||
[0.5, 0.5, 0.5],
|
||||
[0.5, 0.5, -0.5],
|
||||
[-0.5, 0.5, -0.5],
|
||||
],
|
||||
),
|
||||
// Face Dessous (-Y) - Marron Terre
|
||||
(
|
||||
[0.0, -1.0, 0.0],
|
||||
[0.55, 0.35, 0.2],
|
||||
[
|
||||
[-0.5, -0.5, -0.5],
|
||||
[0.5, -0.5, -0.5],
|
||||
[0.5, -0.5, 0.5],
|
||||
[-0.5, -0.5, 0.5],
|
||||
],
|
||||
),
|
||||
// Face Avant (+Z) - Bleu
|
||||
(
|
||||
[0.0, 0.0, 1.0],
|
||||
[0.2, 0.45, 0.9],
|
||||
[
|
||||
[-0.5, -0.5, 0.5],
|
||||
[0.5, -0.5, 0.5],
|
||||
[0.5, 0.5, 0.5],
|
||||
[-0.5, 0.5, 0.5],
|
||||
],
|
||||
),
|
||||
// Face Arrière (-Z) - Cyan
|
||||
(
|
||||
[0.0, 0.0, -1.0],
|
||||
[0.2, 0.85, 0.85],
|
||||
[
|
||||
[0.5, -0.5, -0.5],
|
||||
[-0.5, -0.5, -0.5],
|
||||
[-0.5, 0.5, -0.5],
|
||||
[0.5, 0.5, -0.5],
|
||||
],
|
||||
),
|
||||
// Face Droite (+X) - Rouge
|
||||
(
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.9, 0.25, 0.25],
|
||||
[
|
||||
[0.5, -0.5, 0.5],
|
||||
[0.5, -0.5, -0.5],
|
||||
[0.5, 0.5, -0.5],
|
||||
[0.5, 0.5, 0.5],
|
||||
],
|
||||
),
|
||||
// Face Gauche (-X) - Jaune
|
||||
(
|
||||
[-1.0, 0.0, 0.0],
|
||||
[0.9, 0.85, 0.2],
|
||||
[
|
||||
[-0.5, -0.5, -0.5],
|
||||
[-0.5, -0.5, 0.5],
|
||||
[-0.5, 0.5, 0.5],
|
||||
[-0.5, 0.5, -0.5],
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
for (face_idx, (normal, color, quad)) in faces.iter().enumerate() {
|
||||
let base_index = (face_idx * 4) as u32;
|
||||
|
||||
for (i, pos) in quad.iter().enumerate() {
|
||||
let uv = match i {
|
||||
0 => [0.0, 1.0],
|
||||
1 => [1.0, 1.0],
|
||||
2 => [1.0, 0.0],
|
||||
_ => [0.0, 0.0],
|
||||
};
|
||||
vertices.push(CubeVertex {
|
||||
position: *pos,
|
||||
color: *color,
|
||||
normal: *normal,
|
||||
uv,
|
||||
});
|
||||
}
|
||||
|
||||
// Deux triangles par quad : (0, 1, 2) et (2, 3, 0)
|
||||
indices.push(base_index + 0);
|
||||
indices.push(base_index + 1);
|
||||
indices.push(base_index + 2);
|
||||
indices.push(base_index + 2);
|
||||
indices.push(base_index + 3);
|
||||
indices.push(base_index + 0);
|
||||
}
|
||||
|
||||
MeshBuffers::from_data(memory_allocator, vertices, indices)
|
||||
}
|
||||
|
||||
impl MeshBuffers {
|
||||
/// Alloue les Vertex et Index Buffers Vulkan à partir d'une liste de sommets et d'indices.
|
||||
pub fn from_data(
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
vertices: Vec<CubeVertex>,
|
||||
indices: Vec<u32>,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let index_count = indices.len() as u32;
|
||||
|
||||
let vertex_buffer = Buffer::from_iter(
|
||||
memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::VERTEX_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
vertices,
|
||||
)?;
|
||||
|
||||
let index_buffer = Buffer::from_iter(
|
||||
memory_allocator,
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::INDEX_BUFFER,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
indices,
|
||||
)?;
|
||||
|
||||
Ok(Self {
|
||||
vertex_buffer,
|
||||
index_buffer,
|
||||
index_count,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée le maillage filaire (12 arêtes = 24 indices) d'un cube unitaire [0..1]
|
||||
/// légèrement dilaté pour le contour de sélection visuelle.
|
||||
pub fn create_wireframe_cube_mesh(
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
) -> Result<MeshBuffers, Box<dyn std::error::Error>> {
|
||||
let s = 1.002f32;
|
||||
let o = -0.001f32;
|
||||
let color = [0.05f32, 0.05f32, 0.05f32]; // Noir / gris très sombre
|
||||
let normal = [0.0f32, 1.0f32, 0.0f32];
|
||||
|
||||
let p = [
|
||||
[o, o, o],
|
||||
[o + s, o, o],
|
||||
[o + s, o, o + s],
|
||||
[o, o, o + s],
|
||||
[o, o + s, o],
|
||||
[o + s, o + s, o],
|
||||
[o + s, o + s, o + s],
|
||||
[o, o + s, o + s],
|
||||
];
|
||||
|
||||
let vertices: Vec<CubeVertex> = p
|
||||
.iter()
|
||||
.map(|pos| CubeVertex {
|
||||
position: *pos,
|
||||
color,
|
||||
normal,
|
||||
uv: [0.0, 0.0],
|
||||
})
|
||||
.collect();
|
||||
|
||||
let indices: Vec<u32> = vec![
|
||||
// Base inférieure
|
||||
0, 1, 1, 2, 2, 3, 3, 0,
|
||||
// Base supérieure
|
||||
4, 5, 5, 6, 6, 7, 7, 4,
|
||||
// Montants verticaux
|
||||
0, 4, 1, 5, 2, 6, 3, 7,
|
||||
];
|
||||
|
||||
MeshBuffers::from_data(memory_allocator, vertices, indices)
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
pub mod device;
|
||||
pub mod mesh;
|
||||
pub mod pipeline;
|
||||
pub mod render_pass;
|
||||
pub mod swapchain;
|
||||
pub mod texture;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use vulkano::command_buffer::allocator::StandardCommandBufferAllocator;
|
||||
use vulkano::command_buffer::{
|
||||
AutoCommandBufferBuilder, CommandBufferUsage, RenderPassBeginInfo, SubpassBeginInfo,
|
||||
SubpassContents,
|
||||
};
|
||||
use vulkano::device::{Device, Queue};
|
||||
use vulkano::format::Format;
|
||||
use vulkano::memory::allocator::StandardMemoryAllocator;
|
||||
use vulkano::pipeline::graphics::viewport::Viewport;
|
||||
use vulkano::pipeline::{GraphicsPipeline, Pipeline, PipelineBindPoint};
|
||||
use vulkano::render_pass::RenderPass;
|
||||
use vulkano::swapchain::{acquire_next_image, SwapchainPresentInfo};
|
||||
use vulkano::sync::{self, GpuFuture};
|
||||
use vulkano::{Validated, VulkanError};
|
||||
use winit::raw_window_handle::HasDisplayHandle;
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::math::Mat4;
|
||||
use self::device::init_device;
|
||||
use self::mesh::{create_wireframe_cube_mesh, MeshBuffers};
|
||||
use self::pipeline::{create_graphics_pipeline, create_line_pipeline, create_ui_pipeline, vs};
|
||||
use self::render_pass::create_render_pass;
|
||||
use self::swapchain::{create_swapchain_bundle, recreate_swapchain_bundle, SwapchainBundle};
|
||||
use self::texture::{create_texture_atlas_bundle, VulkanTexture};
|
||||
|
||||
/// Le gestionnaire principal du moteur de rendu Vulkan.
|
||||
pub struct VulkanRenderer {
|
||||
_instance: Arc<vulkano::instance::Instance>,
|
||||
device: Arc<Device>,
|
||||
queue: Arc<Queue>,
|
||||
render_pass: Arc<RenderPass>,
|
||||
pipeline: Arc<GraphicsPipeline>,
|
||||
line_pipeline: Arc<GraphicsPipeline>,
|
||||
ui_pipeline: Arc<GraphicsPipeline>,
|
||||
texture: VulkanTexture,
|
||||
chunk_meshes: HashMap<(i32, i32), MeshBuffers>,
|
||||
wireframe_mesh: MeshBuffers,
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
swapchain_bundle: SwapchainBundle,
|
||||
command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
|
||||
previous_frame_end: Option<Box<dyn GpuFuture>>,
|
||||
recreate_swapchain: bool,
|
||||
}
|
||||
|
||||
impl VulkanRenderer {
|
||||
/// Initialise tous les composants Vulkan nécessaires au rendu 3D.
|
||||
pub fn new(
|
||||
window: Arc<Window>,
|
||||
display_handle: &impl HasDisplayHandle,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let dimensions = window.inner_size().into();
|
||||
|
||||
// 1. Initialisation de l'instance, de la surface et du GPU
|
||||
let dev_ctx = init_device(window, display_handle)?;
|
||||
|
||||
// 2. Allocateur de mémoire GPU standard
|
||||
let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(dev_ctx.device.clone()));
|
||||
|
||||
// 3. Détection des formats (couleur sRGB et profondeur D32_SFLOAT)
|
||||
let surface_formats = dev_ctx
|
||||
.device
|
||||
.physical_device()
|
||||
.surface_formats(&dev_ctx.surface, Default::default())?;
|
||||
let (color_format, _) = surface_formats
|
||||
.iter()
|
||||
.cloned()
|
||||
.find(|(format, _)| {
|
||||
*format == Format::B8G8R8A8_SRGB || *format == Format::R8G8B8A8_SRGB
|
||||
})
|
||||
.unwrap_or_else(|| surface_formats[0]);
|
||||
|
||||
// Format de profondeur standard optimal
|
||||
let depth_format = Format::D32_SFLOAT;
|
||||
|
||||
// 4. Création de la RenderPass avec Color + Depth Buffer
|
||||
let render_pass = create_render_pass(dev_ctx.device.clone(), color_format, depth_format)?;
|
||||
|
||||
// 5. Création de la Swapchain et des Framebuffers
|
||||
let swapchain_bundle = create_swapchain_bundle(
|
||||
dev_ctx.device.clone(),
|
||||
memory_allocator.clone(),
|
||||
dev_ctx.surface.clone(),
|
||||
dimensions,
|
||||
render_pass.clone(),
|
||||
depth_format,
|
||||
)?;
|
||||
|
||||
// 6. Création des pipelines graphiques (3D opaque, wireframe de sélection et 2D UI hotbar)
|
||||
let subpass = render_pass.clone().first_subpass();
|
||||
let pipeline = create_graphics_pipeline(dev_ctx.device.clone(), subpass.clone())?;
|
||||
let line_pipeline = create_line_pipeline(dev_ctx.device.clone(), subpass.clone())?;
|
||||
let ui_pipeline = create_ui_pipeline(dev_ctx.device.clone(), subpass)?;
|
||||
|
||||
// 7. Génération du maillage filaire pour la sélection
|
||||
let wireframe_mesh = create_wireframe_cube_mesh(memory_allocator.clone())?;
|
||||
|
||||
// 8. Allocateur de Command Buffers
|
||||
let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new(
|
||||
dev_ctx.device.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
|
||||
// 9. Génération et upload de l'atlas de textures procédurales (Nearest Sampler, Set 0 Binding 0)
|
||||
let texture = create_texture_atlas_bundle(
|
||||
memory_allocator.clone(),
|
||||
command_buffer_allocator.clone(),
|
||||
dev_ctx.device.clone(),
|
||||
dev_ctx.queue.clone(),
|
||||
pipeline.layout().clone(),
|
||||
)?;
|
||||
|
||||
// 10. Initialisation de la synchronisation GPU
|
||||
let previous_frame_end = Some(sync::now(dev_ctx.device.clone()).boxed());
|
||||
|
||||
Ok(Self {
|
||||
_instance: dev_ctx.instance,
|
||||
device: dev_ctx.device,
|
||||
queue: dev_ctx.queue,
|
||||
render_pass,
|
||||
pipeline,
|
||||
line_pipeline,
|
||||
ui_pipeline,
|
||||
texture,
|
||||
chunk_meshes: HashMap::new(),
|
||||
wireframe_mesh,
|
||||
memory_allocator,
|
||||
swapchain_bundle,
|
||||
command_buffer_allocator,
|
||||
previous_frame_end,
|
||||
recreate_swapchain: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Met à jour ou insère les buffers GPU d'un chunk spécifique.
|
||||
pub fn set_chunk_mesh(
|
||||
&mut self,
|
||||
chunk_pos: (i32, i32),
|
||||
data: crate::world::ChunkMeshData,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let buffers = MeshBuffers::from_data(
|
||||
self.memory_allocator.clone(),
|
||||
data.vertices,
|
||||
data.indices,
|
||||
)?;
|
||||
self.chunk_meshes.insert(chunk_pos, buffers);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Supprime le maillage GPU d'un chunk déchargé.
|
||||
#[allow(dead_code)]
|
||||
pub fn remove_chunk_mesh(&mut self, chunk_pos: &(i32, i32)) {
|
||||
self.chunk_meshes.remove(chunk_pos);
|
||||
}
|
||||
|
||||
/// Signale que la fenêtre a été redimensionnée.
|
||||
pub fn notify_resized(&mut self) {
|
||||
self.recreate_swapchain = true;
|
||||
}
|
||||
|
||||
/// Exécute une frame complète de rendu : chunks 3D, contour de sélection et 2D Hotbar d'inventaire.
|
||||
pub fn render(
|
||||
&mut self,
|
||||
window_dimensions: [u32; 2],
|
||||
view_matrix: Mat4,
|
||||
selected_block: Option<(i32, i32, i32)>,
|
||||
ui_mesh: Option<(Vec<crate::renderer::mesh::CubeVertex>, Vec<u32>)>,
|
||||
) {
|
||||
if window_dimensions[0] == 0 || window_dimensions[1] == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
// Nettoyage régulier des ressources désallouées sur le GPU
|
||||
if let Some(future) = &mut self.previous_frame_end {
|
||||
future.cleanup_finished();
|
||||
}
|
||||
|
||||
// Recréation de la swapchain et du depth buffer lors d'un resize
|
||||
if self.recreate_swapchain {
|
||||
if let Err(err) = recreate_swapchain_bundle(
|
||||
&mut self.swapchain_bundle,
|
||||
self.memory_allocator.clone(),
|
||||
window_dimensions,
|
||||
self.render_pass.clone(),
|
||||
) {
|
||||
eprintln!("Erreur lors de la recréation de la swapchain : {err}");
|
||||
return;
|
||||
}
|
||||
self.recreate_swapchain = false;
|
||||
}
|
||||
|
||||
// Calcul de la matrice MVP (Model-View-Projection)
|
||||
let aspect = window_dimensions[0] as f32 / window_dimensions[1] as f32;
|
||||
let fov = 60.0f32.to_radians();
|
||||
let projection = Mat4::perspective(fov, aspect, 0.1, 100.0);
|
||||
let model = Mat4::identity(); // Le cube est positionné à l'origine (0, 0, 0)
|
||||
let mvp = projection * view_matrix * model;
|
||||
|
||||
// 1. Acquisition de la prochaine image de la swapchain
|
||||
let (image_index, suboptimal, acquire_future) = match acquire_next_image(
|
||||
self.swapchain_bundle.swapchain.clone(),
|
||||
None,
|
||||
)
|
||||
.map_err(Validated::unwrap)
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(VulkanError::OutOfDate) => {
|
||||
self.recreate_swapchain = true;
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Échec de l'acquisition de l'image suivante : {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if suboptimal {
|
||||
self.recreate_swapchain = true;
|
||||
}
|
||||
|
||||
// 2. Enregistrement des commandes GPU
|
||||
let mut builder = AutoCommandBufferBuilder::primary(
|
||||
self.command_buffer_allocator.clone(),
|
||||
self.queue.queue_family_index(),
|
||||
CommandBufferUsage::OneTimeSubmit,
|
||||
)
|
||||
.expect("Échec de la création du command buffer builder");
|
||||
|
||||
// Fond bleu ciel et effacement du depth buffer à 1.0
|
||||
let clear_color = [0.25f32, 0.50f32, 0.85f32, 1.0f32];
|
||||
let clear_depth = 1.0f32;
|
||||
|
||||
let viewport = Viewport {
|
||||
offset: [0.0, 0.0],
|
||||
extent: [window_dimensions[0] as f32, window_dimensions[1] as f32],
|
||||
depth_range: 0.0..=1.0,
|
||||
};
|
||||
|
||||
let push_constants = vs::PushConstants { mvp: mvp.cols };
|
||||
|
||||
builder
|
||||
.begin_render_pass(
|
||||
RenderPassBeginInfo {
|
||||
clear_values: vec![Some(clear_color.into()), Some(clear_depth.into())],
|
||||
..RenderPassBeginInfo::framebuffer(
|
||||
self.swapchain_bundle.framebuffers[image_index as usize].clone(),
|
||||
)
|
||||
},
|
||||
SubpassBeginInfo {
|
||||
contents: SubpassContents::Inline,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("Échec du début de la render pass")
|
||||
.bind_pipeline_graphics(self.pipeline.clone())
|
||||
.expect("Échec du bind pipeline")
|
||||
.bind_descriptor_sets(
|
||||
PipelineBindPoint::Graphics,
|
||||
self.pipeline.layout().clone(),
|
||||
0,
|
||||
self.texture.descriptor_set.clone(),
|
||||
)
|
||||
.expect("Échec du bind descriptor set")
|
||||
.set_viewport(0, [viewport].into_iter().collect())
|
||||
.expect("Échec du set viewport")
|
||||
.push_constants(self.pipeline.layout().clone(), 0, push_constants)
|
||||
.expect("Échec de l'envoi des push constants");
|
||||
|
||||
// Rendu de chaque chunk du monde (1 draw call par chunk)
|
||||
for mesh in self.chunk_meshes.values() {
|
||||
if mesh.index_count > 0 {
|
||||
builder
|
||||
.bind_vertex_buffers(0, mesh.vertex_buffer.clone())
|
||||
.expect("Échec du bind vertex buffer")
|
||||
.bind_index_buffer(mesh.index_buffer.clone())
|
||||
.expect("Échec du bind index buffer");
|
||||
|
||||
unsafe {
|
||||
builder
|
||||
.draw_indexed(mesh.index_count, 1, 0, 0, 0)
|
||||
.expect("Échec du draw_indexed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2.bis Rendu du contour filaire (wireframe) autour du bloc visé
|
||||
if let Some((bx, by, bz)) = selected_block {
|
||||
let wireframe_model = Mat4::from_translation(crate::math::Vec3::new(
|
||||
bx as f32, by as f32, bz as f32,
|
||||
));
|
||||
let wireframe_mvp = projection * view_matrix * wireframe_model;
|
||||
|
||||
builder
|
||||
.bind_pipeline_graphics(self.line_pipeline.clone())
|
||||
.expect("Échec du bind line pipeline")
|
||||
.bind_vertex_buffers(0, self.wireframe_mesh.vertex_buffer.clone())
|
||||
.expect("Échec du bind wireframe vertex buffer")
|
||||
.bind_index_buffer(self.wireframe_mesh.index_buffer.clone())
|
||||
.expect("Échec du bind wireframe index buffer")
|
||||
.push_constants(
|
||||
self.line_pipeline.layout().clone(),
|
||||
0,
|
||||
vs::PushConstants {
|
||||
mvp: wireframe_mvp.cols,
|
||||
},
|
||||
)
|
||||
.expect("Échec de l'envoi des push constants wireframe");
|
||||
|
||||
unsafe {
|
||||
builder
|
||||
.draw_indexed(self.wireframe_mesh.index_count, 1, 0, 0, 0)
|
||||
.expect("Échec du draw_indexed wireframe");
|
||||
}
|
||||
}
|
||||
|
||||
// 2.ter Rendu de l'interface 2D (Hotbar d'inventaire)
|
||||
if let Some((ui_vertices, ui_indices)) = ui_mesh {
|
||||
if !ui_indices.is_empty() {
|
||||
if let Ok(ui_buf) = MeshBuffers::from_data(
|
||||
self.memory_allocator.clone(),
|
||||
ui_vertices,
|
||||
ui_indices,
|
||||
) {
|
||||
builder
|
||||
.bind_pipeline_graphics(self.ui_pipeline.clone())
|
||||
.expect("Échec du bind UI pipeline")
|
||||
.bind_vertex_buffers(0, ui_buf.vertex_buffer.clone())
|
||||
.expect("Échec du bind UI vertex buffer")
|
||||
.bind_index_buffer(ui_buf.index_buffer.clone())
|
||||
.expect("Échec du bind UI index buffer");
|
||||
|
||||
unsafe {
|
||||
builder
|
||||
.draw_indexed(ui_buf.index_count, 1, 0, 0, 0)
|
||||
.expect("Échec du draw_indexed UI");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
builder
|
||||
.end_render_pass(Default::default())
|
||||
.expect("Échec de la fin de la render pass");
|
||||
|
||||
let command_buffer = builder
|
||||
.build()
|
||||
.expect("Échec de la construction du command buffer");
|
||||
|
||||
// 3. Soumission et présentation
|
||||
let prev_future = self
|
||||
.previous_frame_end
|
||||
.take()
|
||||
.unwrap_or_else(|| sync::now(self.device.clone()).boxed());
|
||||
|
||||
let execution = prev_future
|
||||
.join(acquire_future)
|
||||
.then_execute(self.queue.clone(), command_buffer)
|
||||
.expect("Échec de la soumission du command buffer")
|
||||
.then_swapchain_present(
|
||||
self.queue.clone(),
|
||||
SwapchainPresentInfo::swapchain_image_index(
|
||||
self.swapchain_bundle.swapchain.clone(),
|
||||
image_index,
|
||||
),
|
||||
)
|
||||
.then_signal_fence_and_flush();
|
||||
|
||||
match execution.map_err(Validated::unwrap) {
|
||||
Ok(future) => {
|
||||
self.previous_frame_end = Some(future.boxed());
|
||||
}
|
||||
Err(VulkanError::OutOfDate) => {
|
||||
self.recreate_swapchain = true;
|
||||
self.previous_frame_end = Some(sync::now(self.device.clone()).boxed());
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Erreur lors de la synchronisation GPU/présentation : {e}");
|
||||
self.previous_frame_end = Some(sync::now(self.device.clone()).boxed());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
use std::sync::Arc;
|
||||
use vulkano::device::Device;
|
||||
use vulkano::pipeline::graphics::color_blend::{ColorBlendAttachmentState, ColorBlendState};
|
||||
use vulkano::pipeline::graphics::depth_stencil::{CompareOp, DepthState, DepthStencilState};
|
||||
use vulkano::pipeline::graphics::input_assembly::{InputAssemblyState, PrimitiveTopology};
|
||||
use vulkano::pipeline::graphics::multisample::MultisampleState;
|
||||
use vulkano::pipeline::graphics::rasterization::{CullMode, FrontFace, RasterizationState};
|
||||
use vulkano::pipeline::graphics::vertex_input::{Vertex, VertexDefinition};
|
||||
use vulkano::pipeline::graphics::viewport::ViewportState;
|
||||
use vulkano::pipeline::graphics::GraphicsPipelineCreateInfo;
|
||||
use vulkano::pipeline::layout::PipelineDescriptorSetLayoutCreateInfo;
|
||||
use vulkano::pipeline::{DynamicState, GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo};
|
||||
use vulkano::render_pass::Subpass;
|
||||
|
||||
use super::mesh::CubeVertex;
|
||||
|
||||
pub mod vs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "vertex",
|
||||
src: r"
|
||||
#version 450
|
||||
layout(location = 0) in vec3 position;
|
||||
layout(location = 1) in vec3 color;
|
||||
layout(location = 2) in vec3 normal;
|
||||
layout(location = 3) in vec2 uv;
|
||||
|
||||
layout(push_constant) uniform PushConstants {
|
||||
mat4 mvp;
|
||||
} pc;
|
||||
|
||||
layout(location = 0) out vec3 v_color;
|
||||
layout(location = 1) out vec3 v_normal;
|
||||
layout(location = 2) out vec2 v_uv;
|
||||
|
||||
void main() {
|
||||
gl_Position = pc.mvp * vec4(position, 1.0);
|
||||
v_color = color;
|
||||
v_normal = normal;
|
||||
v_uv = uv;
|
||||
}
|
||||
",
|
||||
}
|
||||
}
|
||||
|
||||
pub mod fs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "fragment",
|
||||
src: r"
|
||||
#version 450
|
||||
layout(location = 0) in vec3 v_color;
|
||||
layout(location = 1) in vec3 v_normal;
|
||||
layout(location = 2) in vec2 v_uv;
|
||||
|
||||
layout(set = 0, binding = 0) uniform sampler2D tex_sampler;
|
||||
|
||||
layout(location = 0) out vec4 f_color;
|
||||
|
||||
void main() {
|
||||
// Éclairage diffus direct (type soleil de Minecraft)
|
||||
vec3 light_dir = normalize(vec3(0.4, 0.9, 0.3));
|
||||
float diff = max(dot(normalize(v_normal), light_dir), 0.35);
|
||||
vec4 tex_color = texture(tex_sampler, v_uv);
|
||||
f_color = vec4(tex_color.rgb * v_color * diff, tex_color.a);
|
||||
}
|
||||
",
|
||||
}
|
||||
}
|
||||
|
||||
pub mod line_fs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "fragment",
|
||||
src: r"
|
||||
#version 450
|
||||
layout(location = 0) in vec3 v_color;
|
||||
layout(location = 1) in vec3 v_normal;
|
||||
layout(location = 2) in vec2 v_uv;
|
||||
|
||||
layout(location = 0) out vec4 f_color;
|
||||
|
||||
void main() {
|
||||
// Rendu de la couleur directe sans ombrage pour le wireframe
|
||||
f_color = vec4(v_color, 1.0);
|
||||
}
|
||||
",
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée le pipeline graphique 3D avec Depth Testing, Culling et Push Constants.
|
||||
pub fn create_graphics_pipeline(
|
||||
device: Arc<Device>,
|
||||
subpass: Subpass,
|
||||
) -> Result<Arc<GraphicsPipeline>, Box<dyn std::error::Error>> {
|
||||
let vs = vs::load(device.clone())?.entry_point("main").unwrap();
|
||||
let fs = fs::load(device.clone())?.entry_point("main").unwrap();
|
||||
|
||||
let vertex_input_state = [CubeVertex::per_vertex()]
|
||||
.definition(&vs)?;
|
||||
|
||||
let stages = [
|
||||
PipelineShaderStageCreateInfo::new(vs),
|
||||
PipelineShaderStageCreateInfo::new(fs),
|
||||
];
|
||||
|
||||
let layout = PipelineLayout::new(
|
||||
device.clone(),
|
||||
PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
|
||||
.into_pipeline_layout_create_info(device.clone())?,
|
||||
)?;
|
||||
|
||||
let pipeline = GraphicsPipeline::new(
|
||||
device,
|
||||
None,
|
||||
GraphicsPipelineCreateInfo {
|
||||
stages: stages.into_iter().collect(),
|
||||
vertex_input_state: Some(vertex_input_state),
|
||||
input_assembly_state: Some(InputAssemblyState::default()),
|
||||
viewport_state: Some(ViewportState::default()),
|
||||
rasterization_state: Some(RasterizationState {
|
||||
cull_mode: CullMode::Back,
|
||||
front_face: FrontFace::Clockwise,
|
||||
..Default::default()
|
||||
}),
|
||||
depth_stencil_state: Some(DepthStencilState {
|
||||
depth: Some(DepthState::simple()),
|
||||
..Default::default()
|
||||
}),
|
||||
multisample_state: Some(MultisampleState::default()),
|
||||
color_blend_state: Some(ColorBlendState::with_attachment_states(
|
||||
subpass.num_color_attachments(),
|
||||
ColorBlendAttachmentState::default(),
|
||||
)),
|
||||
dynamic_state: [DynamicState::Viewport].into_iter().collect(),
|
||||
subpass: Some(subpass.into()),
|
||||
..GraphicsPipelineCreateInfo::layout(layout)
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
|
||||
/// Crée le pipeline graphique dédié au rendu des lignes du cadre de sélection (Wireframe).
|
||||
pub fn create_line_pipeline(
|
||||
device: Arc<Device>,
|
||||
subpass: Subpass,
|
||||
) -> Result<Arc<GraphicsPipeline>, Box<dyn std::error::Error>> {
|
||||
let vs = vs::load(device.clone())?.entry_point("main").unwrap();
|
||||
let fs = line_fs::load(device.clone())?.entry_point("main").unwrap();
|
||||
|
||||
let vertex_input_state = [CubeVertex::per_vertex()]
|
||||
.definition(&vs)?;
|
||||
|
||||
let stages = [
|
||||
PipelineShaderStageCreateInfo::new(vs),
|
||||
PipelineShaderStageCreateInfo::new(fs),
|
||||
];
|
||||
|
||||
let layout = PipelineLayout::new(
|
||||
device.clone(),
|
||||
PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
|
||||
.into_pipeline_layout_create_info(device.clone())?,
|
||||
)?;
|
||||
|
||||
let pipeline = GraphicsPipeline::new(
|
||||
device,
|
||||
None,
|
||||
GraphicsPipelineCreateInfo {
|
||||
stages: stages.into_iter().collect(),
|
||||
vertex_input_state: Some(vertex_input_state),
|
||||
// Topologie LineList pour dessiner les arêtes du cube
|
||||
input_assembly_state: Some(InputAssemblyState {
|
||||
topology: PrimitiveTopology::LineList,
|
||||
..Default::default()
|
||||
}),
|
||||
viewport_state: Some(ViewportState::default()),
|
||||
rasterization_state: Some(RasterizationState {
|
||||
cull_mode: CullMode::None,
|
||||
..Default::default()
|
||||
}),
|
||||
// CompareOp::LessOrEqual sans écriture dans le depth buffer pour un contour net
|
||||
depth_stencil_state: Some(DepthStencilState {
|
||||
depth: Some(DepthState {
|
||||
compare_op: CompareOp::LessOrEqual,
|
||||
write_enable: false,
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
multisample_state: Some(MultisampleState::default()),
|
||||
color_blend_state: Some(ColorBlendState::with_attachment_states(
|
||||
subpass.num_color_attachments(),
|
||||
ColorBlendAttachmentState::default(),
|
||||
)),
|
||||
dynamic_state: [DynamicState::Viewport].into_iter().collect(),
|
||||
subpass: Some(subpass.into()),
|
||||
..GraphicsPipelineCreateInfo::layout(layout)
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
|
||||
pub mod ui_vs {
|
||||
vulkano_shaders::shader! {
|
||||
ty: "vertex",
|
||||
src: r"
|
||||
#version 450
|
||||
layout(location = 0) in vec3 position;
|
||||
layout(location = 1) in vec3 color;
|
||||
layout(location = 2) in vec3 normal;
|
||||
layout(location = 3) in vec2 uv;
|
||||
|
||||
layout(location = 0) out vec3 v_color;
|
||||
|
||||
void main() {
|
||||
// Coordonnées 2D écran directes en NDC [-1..1]
|
||||
gl_Position = vec4(position.xy, 0.0, 1.0);
|
||||
v_color = color;
|
||||
}
|
||||
",
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée le pipeline graphique dédié à l'interface 2D (Hotbar d'inventaire).
|
||||
pub fn create_ui_pipeline(
|
||||
device: Arc<Device>,
|
||||
subpass: Subpass,
|
||||
) -> Result<Arc<GraphicsPipeline>, Box<dyn std::error::Error>> {
|
||||
let vs = ui_vs::load(device.clone())?.entry_point("main").unwrap();
|
||||
let fs = line_fs::load(device.clone())?.entry_point("main").unwrap();
|
||||
|
||||
let vertex_input_state = [CubeVertex::per_vertex()].definition(&vs)?;
|
||||
|
||||
let stages = [
|
||||
PipelineShaderStageCreateInfo::new(vs),
|
||||
PipelineShaderStageCreateInfo::new(fs),
|
||||
];
|
||||
|
||||
let layout = PipelineLayout::new(
|
||||
device.clone(),
|
||||
PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
|
||||
.into_pipeline_layout_create_info(device.clone())?,
|
||||
)?;
|
||||
|
||||
let pipeline = GraphicsPipeline::new(
|
||||
device,
|
||||
None,
|
||||
GraphicsPipelineCreateInfo {
|
||||
stages: stages.into_iter().collect(),
|
||||
vertex_input_state: Some(vertex_input_state),
|
||||
input_assembly_state: Some(InputAssemblyState::default()),
|
||||
viewport_state: Some(ViewportState::default()),
|
||||
rasterization_state: Some(RasterizationState {
|
||||
cull_mode: CullMode::None,
|
||||
..Default::default()
|
||||
}),
|
||||
// Depth test désactivé : l'UI s'affiche toujours au premier plan
|
||||
depth_stencil_state: Some(DepthStencilState {
|
||||
depth: Some(DepthState {
|
||||
compare_op: CompareOp::Always,
|
||||
write_enable: false,
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
multisample_state: Some(MultisampleState::default()),
|
||||
color_blend_state: Some(ColorBlendState::with_attachment_states(
|
||||
subpass.num_color_attachments(),
|
||||
ColorBlendAttachmentState::default(),
|
||||
)),
|
||||
dynamic_state: [DynamicState::Viewport].into_iter().collect(),
|
||||
subpass: Some(subpass.into()),
|
||||
..GraphicsPipelineCreateInfo::layout(layout)
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::sync::Arc;
|
||||
use vulkano::device::Device;
|
||||
use vulkano::format::Format;
|
||||
use vulkano::render_pass::RenderPass;
|
||||
use vulkano::single_pass_renderpass;
|
||||
|
||||
/// Crée une RenderPass 3D avec attachement couleur et attachement de profondeur (Depth Buffer).
|
||||
///
|
||||
/// Détails des choix Vulkan :
|
||||
/// - Couleur :
|
||||
/// * `load_op: Clear` : Au début de la passe, le GPU efface l'écran avec la couleur de fond choisie.
|
||||
/// * `store_op: Store` : Le résultat rendu est conservé pour être présenté sur la fenêtre.
|
||||
/// - Profondeur :
|
||||
/// * `load_op: Clear` : Réinitialise le depth buffer à 1.0 (distance maximale).
|
||||
/// * `store_op: DontCare` : Une fois la passe terminée, les données de profondeur n'ont plus besoin
|
||||
/// d'être conservées en mémoire vidéo principale (économie de bande passante mémoire).
|
||||
pub fn create_render_pass(
|
||||
device: Arc<Device>,
|
||||
color_format: Format,
|
||||
depth_format: Format,
|
||||
) -> Result<Arc<RenderPass>, Box<dyn std::error::Error>> {
|
||||
let render_pass = single_pass_renderpass!(
|
||||
device,
|
||||
attachments: {
|
||||
color: {
|
||||
format: color_format,
|
||||
samples: 1,
|
||||
load_op: Clear,
|
||||
store_op: Store,
|
||||
},
|
||||
depth: {
|
||||
format: depth_format,
|
||||
samples: 1,
|
||||
load_op: Clear,
|
||||
store_op: DontCare,
|
||||
},
|
||||
},
|
||||
pass: {
|
||||
color: [color],
|
||||
depth_stencil: {depth},
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(render_pass)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
use std::sync::Arc;
|
||||
use vulkano::device::Device;
|
||||
use vulkano::format::Format;
|
||||
use vulkano::image::view::ImageView;
|
||||
use vulkano::image::{Image, ImageCreateInfo, ImageType, ImageUsage};
|
||||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator};
|
||||
use vulkano::render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass};
|
||||
use vulkano::swapchain::{
|
||||
CompositeAlpha, PresentMode, Surface, Swapchain, SwapchainCreateInfo,
|
||||
};
|
||||
|
||||
/// Regroupe la swapchain et les ressources dérivées (images, buffer de profondeur et framebuffers).
|
||||
pub struct SwapchainBundle {
|
||||
pub swapchain: Arc<Swapchain>,
|
||||
pub images: Vec<Arc<Image>>,
|
||||
#[allow(dead_code)]
|
||||
pub image_format: Format,
|
||||
pub depth_format: Format,
|
||||
pub framebuffers: Vec<Arc<Framebuffer>>,
|
||||
}
|
||||
|
||||
/// Crée la Swapchain, l'image de profondeur (Z-Buffer) et les Framebuffers initiaux.
|
||||
pub fn create_swapchain_bundle(
|
||||
device: Arc<Device>,
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
surface: Arc<Surface>,
|
||||
dimensions: [u32; 2],
|
||||
render_pass: Arc<RenderPass>,
|
||||
depth_format: Format,
|
||||
) -> Result<SwapchainBundle, Box<dyn std::error::Error>> {
|
||||
let surface_capabilities = device
|
||||
.physical_device()
|
||||
.surface_capabilities(&surface, Default::default())?;
|
||||
|
||||
// 1. Choix du format de couleur :
|
||||
// On privilégie un format sRGB (B8G8R8A8_SRGB ou R8G8B8A8_SRGB)
|
||||
// car le rendu sRGB permet une correction gamma automatique par le matériel.
|
||||
let surface_formats = device
|
||||
.physical_device()
|
||||
.surface_formats(&surface, Default::default())?;
|
||||
|
||||
let (image_format, _) = surface_formats
|
||||
.iter()
|
||||
.cloned()
|
||||
.find(|(format, _)| {
|
||||
*format == Format::B8G8R8A8_SRGB || *format == Format::R8G8B8A8_SRGB
|
||||
})
|
||||
.unwrap_or_else(|| surface_formats[0]);
|
||||
|
||||
// 2. Nombre d'images dans la swapchain (Triple Buffering si supporté)
|
||||
let max_images = surface_capabilities.max_image_count.unwrap_or(u32::MAX);
|
||||
let min_image_count = (surface_capabilities.min_image_count + 1).min(max_images);
|
||||
|
||||
// 3. Mode de composition alpha : Opaque pour éviter la transparence avec le bureau
|
||||
let composite_alpha = surface_capabilities
|
||||
.supported_composite_alpha
|
||||
.into_iter()
|
||||
.find(|&c| c == CompositeAlpha::Opaque)
|
||||
.unwrap_or_else(|| {
|
||||
surface_capabilities
|
||||
.supported_composite_alpha
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap_or(CompositeAlpha::Opaque)
|
||||
});
|
||||
|
||||
// 4. Mode de présentation : Fifo = V-Sync garanti sans tearing
|
||||
let present_mode = PresentMode::Fifo;
|
||||
|
||||
// 5. Création de la Swapchain
|
||||
let (swapchain, images) = Swapchain::new(
|
||||
device,
|
||||
surface,
|
||||
SwapchainCreateInfo {
|
||||
min_image_count,
|
||||
image_format,
|
||||
image_extent: dimensions,
|
||||
image_usage: ImageUsage::COLOR_ATTACHMENT,
|
||||
composite_alpha,
|
||||
present_mode,
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
// 6. Création de l'image de profondeur (Z-Buffer) et des Framebuffers
|
||||
let framebuffers = create_framebuffers(
|
||||
&images,
|
||||
memory_allocator,
|
||||
dimensions,
|
||||
depth_format,
|
||||
render_pass,
|
||||
)?;
|
||||
|
||||
Ok(SwapchainBundle {
|
||||
swapchain,
|
||||
images,
|
||||
image_format,
|
||||
depth_format,
|
||||
framebuffers,
|
||||
})
|
||||
}
|
||||
|
||||
/// Crée un Framebuffer pour chaque image de la Swapchain en attachant la vue couleur
|
||||
/// et la vue de profondeur (Depth Buffer).
|
||||
pub fn create_framebuffers(
|
||||
images: &[Arc<Image>],
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
dimensions: [u32; 2],
|
||||
depth_format: Format,
|
||||
render_pass: Arc<RenderPass>,
|
||||
) -> Result<Vec<Arc<Framebuffer>>, Box<dyn std::error::Error>> {
|
||||
// Création de l'image de profondeur aux dimensions de la fenêtre
|
||||
let depth_image = Image::new(
|
||||
memory_allocator,
|
||||
ImageCreateInfo {
|
||||
image_type: ImageType::Dim2d,
|
||||
format: depth_format,
|
||||
extent: [dimensions[0], dimensions[1], 1],
|
||||
usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::TRANSIENT_ATTACHMENT,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE,
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
let depth_view = ImageView::new_default(depth_image)?;
|
||||
|
||||
images
|
||||
.iter()
|
||||
.map(|image| {
|
||||
let color_view = ImageView::new_default(image.clone())?;
|
||||
let framebuffer = Framebuffer::new(
|
||||
render_pass.clone(),
|
||||
FramebufferCreateInfo {
|
||||
attachments: vec![color_view, depth_view.clone()],
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
Ok(framebuffer)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Recrée la Swapchain et ses Framebuffers (avec un nouveau depth buffer adapté) lors d'un resize.
|
||||
pub fn recreate_swapchain_bundle(
|
||||
bundle: &mut SwapchainBundle,
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
new_dimensions: [u32; 2],
|
||||
render_pass: Arc<RenderPass>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let (new_swapchain, new_images) = bundle.swapchain.recreate(SwapchainCreateInfo {
|
||||
image_extent: new_dimensions,
|
||||
..bundle.swapchain.create_info()
|
||||
})?;
|
||||
|
||||
let new_framebuffers = create_framebuffers(
|
||||
&new_images,
|
||||
memory_allocator,
|
||||
new_dimensions,
|
||||
bundle.depth_format,
|
||||
render_pass,
|
||||
)?;
|
||||
|
||||
bundle.swapchain = new_swapchain;
|
||||
bundle.images = new_images;
|
||||
bundle.framebuffers = new_framebuffers;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
use std::sync::Arc;
|
||||
use vulkano::buffer::{Buffer, BufferCreateInfo, BufferUsage};
|
||||
use vulkano::command_buffer::allocator::StandardCommandBufferAllocator;
|
||||
use vulkano::command_buffer::{
|
||||
AutoCommandBufferBuilder, CommandBufferUsage, CopyBufferToImageInfo,
|
||||
PrimaryCommandBufferAbstract,
|
||||
};
|
||||
use vulkano::descriptor_set::allocator::StandardDescriptorSetAllocator;
|
||||
use vulkano::descriptor_set::{DescriptorSet, WriteDescriptorSet};
|
||||
use vulkano::device::{Device, Queue};
|
||||
use vulkano::format::Format;
|
||||
use vulkano::image::sampler::{Filter, Sampler, SamplerAddressMode, SamplerCreateInfo};
|
||||
use vulkano::image::view::ImageView;
|
||||
use vulkano::image::{Image, ImageCreateInfo, ImageType, ImageUsage};
|
||||
use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator};
|
||||
use vulkano::pipeline::PipelineLayout;
|
||||
use vulkano::sync::GpuFuture;
|
||||
|
||||
pub const ATLAS_WIDTH: u32 = 128;
|
||||
pub const ATLAS_HEIGHT: u32 = 128;
|
||||
pub const TILE_SIZE: u32 = 16;
|
||||
#[allow(dead_code)]
|
||||
pub const TILES_PER_ROW: u32 = ATLAS_WIDTH / TILE_SIZE; // 8
|
||||
|
||||
/// Conteneur des ressources GPU pour la texture atlas et son DescriptorSet.
|
||||
#[allow(dead_code)]
|
||||
pub struct VulkanTexture {
|
||||
pub image: Arc<Image>,
|
||||
pub view: Arc<ImageView>,
|
||||
pub sampler: Arc<Sampler>,
|
||||
pub descriptor_set: Arc<DescriptorSet>,
|
||||
}
|
||||
|
||||
/// Générateur pseudo-aléatoire déterministe simple (hachage LCG sans crate externe).
|
||||
#[inline(always)]
|
||||
fn hash_pixel(x: u32, y: u32, seed: u32) -> u32 {
|
||||
let mut h = seed
|
||||
.wrapping_add(x.wrapping_mul(374761393))
|
||||
.wrapping_add(y.wrapping_mul(668265263));
|
||||
h = (h ^ (h >> 13)).wrapping_mul(1274126177);
|
||||
h ^ (h >> 16)
|
||||
}
|
||||
|
||||
/// Génère une variation entière signée dans [-range, range].
|
||||
#[inline(always)]
|
||||
fn noise_variation(x: u32, y: u32, seed: u32, range: i32) -> i32 {
|
||||
let span = (range * 2 + 1) as u32;
|
||||
let r = (hash_pixel(x, y, seed) % span) as i32;
|
||||
r - range
|
||||
}
|
||||
|
||||
/// Écrit un pixel RGBA aux coordonnées locales de la tuile.
|
||||
#[inline(always)]
|
||||
fn put_pixel(
|
||||
pixels: &mut [u8],
|
||||
tile_col: u32,
|
||||
tile_row: u32,
|
||||
px: u32,
|
||||
py: u32,
|
||||
r: u8,
|
||||
g: u8,
|
||||
b: u8,
|
||||
a: u8,
|
||||
) {
|
||||
let gx = tile_col * TILE_SIZE + px;
|
||||
let gy = tile_row * TILE_SIZE + py;
|
||||
let idx = ((gy * ATLAS_WIDTH + gx) * 4) as usize;
|
||||
pixels[idx] = r;
|
||||
pixels[idx + 1] = g;
|
||||
pixels[idx + 2] = b;
|
||||
pixels[idx + 3] = a;
|
||||
}
|
||||
|
||||
/// Génère l'atlas procédural de textures 128x128 en mémoire (8x8 tuiles de 16x16 pixels).
|
||||
pub fn generate_texture_atlas() -> Vec<u8> {
|
||||
let mut pixels = vec![255u8; (ATLAS_WIDTH * ATLAS_HEIGHT * 4) as usize];
|
||||
|
||||
for py in 0..TILE_SIZE {
|
||||
for px in 0..TILE_SIZE {
|
||||
// --- Tuile 0 : Dessus d'Herbe (Grass Top) ---
|
||||
let n_grass = noise_variation(px, py, 101, 16);
|
||||
let r_gt = (88 + n_grass).clamp(0, 255) as u8;
|
||||
let g_gt = (168 + n_grass * 2).clamp(0, 255) as u8;
|
||||
let b_gt = (68 + n_grass).clamp(0, 255) as u8;
|
||||
put_pixel(&mut pixels, 0, 0, px, py, r_gt, g_gt, b_gt, 255);
|
||||
|
||||
// --- Tuile 2 : Terre (Dirt) ---
|
||||
let n_dirt = noise_variation(px, py, 202, 14);
|
||||
let is_pebble = hash_pixel(px, py, 999) % 13 == 0;
|
||||
let (r_d, g_d, b_d) = if is_pebble {
|
||||
(90, 65, 52)
|
||||
} else {
|
||||
(
|
||||
(134 + n_dirt).clamp(0, 255) as u8,
|
||||
(96 + n_dirt).clamp(0, 255) as u8,
|
||||
(67 + n_dirt).clamp(0, 255) as u8,
|
||||
)
|
||||
};
|
||||
put_pixel(&mut pixels, 2, 0, px, py, r_d, g_d, b_d, 255);
|
||||
|
||||
// --- Tuile 1 : Côté d'Herbe (Grass Side) ---
|
||||
// Le tiers supérieur est de l'herbe festonnée, le reste est de la terre
|
||||
let grass_cutoff = 3 + (hash_pixel(px, 0, 303) % 3);
|
||||
if py <= grass_cutoff {
|
||||
let r = (88 + n_grass).clamp(0, 255) as u8;
|
||||
let g = (168 + n_grass * 2).clamp(0, 255) as u8;
|
||||
let b = (68 + n_grass).clamp(0, 255) as u8;
|
||||
put_pixel(&mut pixels, 1, 0, px, py, r, g, b, 255);
|
||||
} else {
|
||||
put_pixel(&mut pixels, 1, 0, px, py, r_d, g_d, b_d, 255);
|
||||
}
|
||||
|
||||
// --- Tuile 3 : Pierre (Stone) ---
|
||||
let n_stone = noise_variation(px, py, 404, 18);
|
||||
let is_dark_crack = hash_pixel(px, py, 777) % 9 == 0;
|
||||
let (r_s, g_s, b_s) = if is_dark_crack {
|
||||
(95, 95, 100)
|
||||
} else {
|
||||
let v = (138 + n_stone).clamp(0, 255) as u8;
|
||||
(v, v, (v as i32 + 3).min(255) as u8)
|
||||
};
|
||||
put_pixel(&mut pixels, 3, 0, px, py, r_s, g_s, b_s, 255);
|
||||
|
||||
// --- Tuile 4 : Côté de Tronc d'Arbre / Bois (Wood Log Side) ---
|
||||
let n_bark = noise_variation(px, py, 505, 8);
|
||||
let is_bark_groove = px % 4 == 0 || (px + py) % 7 == 0;
|
||||
let (r_w, g_w, b_w) = if is_bark_groove {
|
||||
(80, 54, 40)
|
||||
} else {
|
||||
(
|
||||
(115 + n_bark).clamp(0, 255) as u8,
|
||||
(82 + n_bark).clamp(0, 255) as u8,
|
||||
(58 + n_bark).clamp(0, 255) as u8,
|
||||
)
|
||||
};
|
||||
put_pixel(&mut pixels, 4, 0, px, py, r_w, g_w, b_w, 255);
|
||||
|
||||
// --- Tuile 5 : Extrémité de Tronc d'Arbre (Wood Log Top/Bottom - Cernes) ---
|
||||
let c_dist = (((px as f32 - 7.5).powi(2) + (py as f32 - 7.5).powi(2)).sqrt()).round() as i32;
|
||||
let (r_wt, g_wt, b_wt) = if c_dist >= 7 {
|
||||
(80, 54, 40) // Écorce extérieure
|
||||
} else if c_dist % 2 == 0 {
|
||||
(160, 120, 80) // Cerne sombre
|
||||
} else {
|
||||
(185, 145, 100) // Cœur de bois clair
|
||||
};
|
||||
put_pixel(&mut pixels, 5, 0, px, py, r_wt, g_wt, b_wt, 255);
|
||||
|
||||
// --- Tuile 6 : Feuilles (Leaves) ---
|
||||
let n_leaf = noise_variation(px, py, 606, 22);
|
||||
let leaf_type = hash_pixel(px, py, 888) % 3;
|
||||
let (r_l, g_l, b_l) = match leaf_type {
|
||||
0 => (42, 105, 38), // Ombre
|
||||
1 => (72, 160, 60), // Normal
|
||||
_ => (
|
||||
(58 + n_leaf).clamp(0, 255) as u8,
|
||||
(135 + n_leaf * 2).clamp(0, 255) as u8,
|
||||
(45 + n_leaf).clamp(0, 255) as u8,
|
||||
),
|
||||
};
|
||||
put_pixel(&mut pixels, 6, 0, px, py, r_l, g_l, b_l, 255);
|
||||
|
||||
// --- Tuile 7 : Sable (Sand) ---
|
||||
let n_sand = noise_variation(px, py, 707, 10);
|
||||
let r_sa = (220 + n_sand).clamp(0, 255) as u8;
|
||||
let g_sa = (205 + n_sand).clamp(0, 255) as u8;
|
||||
let b_sa = (150 + n_sand).clamp(0, 255) as u8;
|
||||
put_pixel(&mut pixels, 7, 0, px, py, r_sa, g_sa, b_sa, 255);
|
||||
}
|
||||
}
|
||||
|
||||
pixels
|
||||
}
|
||||
|
||||
/// Crée la texture atlas sur le GPU, son image view, son sampler Nearest, et alloue son DescriptorSet.
|
||||
pub fn create_texture_atlas_bundle(
|
||||
memory_allocator: Arc<StandardMemoryAllocator>,
|
||||
command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
|
||||
device: Arc<Device>,
|
||||
queue: Arc<Queue>,
|
||||
pipeline_layout: Arc<PipelineLayout>,
|
||||
) -> Result<VulkanTexture, Box<dyn std::error::Error>> {
|
||||
let pixels = generate_texture_atlas();
|
||||
|
||||
// 1. Buffer de transit hôte (Staging Buffer)
|
||||
let staging_buffer = Buffer::from_iter(
|
||||
memory_allocator.clone(),
|
||||
BufferCreateInfo {
|
||||
usage: BufferUsage::TRANSFER_SRC,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_HOST
|
||||
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
|
||||
..Default::default()
|
||||
},
|
||||
pixels,
|
||||
)?;
|
||||
|
||||
// 2. Image GPU (Device Local)
|
||||
let image = Image::new(
|
||||
memory_allocator,
|
||||
ImageCreateInfo {
|
||||
image_type: ImageType::Dim2d,
|
||||
format: Format::R8G8B8A8_SRGB,
|
||||
extent: [ATLAS_WIDTH, ATLAS_HEIGHT, 1],
|
||||
usage: ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED,
|
||||
..Default::default()
|
||||
},
|
||||
AllocationCreateInfo {
|
||||
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE,
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
// 3. Commande de copie du buffer vers l'image GPU
|
||||
let mut builder = AutoCommandBufferBuilder::primary(
|
||||
command_buffer_allocator,
|
||||
queue.queue_family_index(),
|
||||
CommandBufferUsage::OneTimeSubmit,
|
||||
)?;
|
||||
|
||||
let copy_info = CopyBufferToImageInfo::buffer_image(staging_buffer, image.clone());
|
||||
builder.copy_buffer_to_image(copy_info)?;
|
||||
|
||||
let command_buffer = builder.build()?;
|
||||
command_buffer
|
||||
.execute(queue)?
|
||||
.then_signal_fence_and_flush()?
|
||||
.wait(None)?;
|
||||
|
||||
// 4. ImageView et Sampler configuré en Filter::Nearest (Pixel art net sans flou)
|
||||
let view = ImageView::new_default(image.clone())?;
|
||||
let sampler = Sampler::new(
|
||||
device.clone(),
|
||||
SamplerCreateInfo {
|
||||
mag_filter: Filter::Nearest,
|
||||
min_filter: Filter::Nearest,
|
||||
address_mode: [SamplerAddressMode::Repeat; 3],
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
// 5. DescriptorSet (Set 0, Binding 0)
|
||||
let desc_allocator = Arc::new(StandardDescriptorSetAllocator::new(
|
||||
device,
|
||||
Default::default(),
|
||||
));
|
||||
let set_layout = pipeline_layout
|
||||
.set_layouts()
|
||||
.get(0)
|
||||
.ok_or("Le layout de pipeline ne contient pas le descriptor set 0")?
|
||||
.clone();
|
||||
|
||||
let descriptor_set = DescriptorSet::new(
|
||||
desc_allocator,
|
||||
set_layout,
|
||||
[WriteDescriptorSet::image_view_sampler(0, view.clone(), sampler.clone())],
|
||||
[],
|
||||
)?;
|
||||
|
||||
Ok(VulkanTexture {
|
||||
image,
|
||||
view,
|
||||
sampler,
|
||||
descriptor_set,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::LogicalSize;
|
||||
use winit::event::{DeviceEvent, DeviceId, ElementState, MouseButton, WindowEvent};
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
use winit::keyboard::{KeyCode, PhysicalKey};
|
||||
use winit::window::{CursorGrabMode, Window, WindowId};
|
||||
|
||||
use crate::camera::Camera;
|
||||
use crate::inventory::Inventory;
|
||||
use crate::math::Vec3;
|
||||
use crate::physics::Player;
|
||||
use crate::raycast::{raycast_voxel, RaycastHit};
|
||||
use crate::renderer::VulkanRenderer;
|
||||
use crate::world::{build_chunk_mesh_world, BlockType, World, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z};
|
||||
|
||||
/// Structure principale de l'application gérant la fenêtre, la caméra et le monde multi-chunks.
|
||||
pub struct App {
|
||||
window: Option<Arc<Window>>,
|
||||
renderer: Option<VulkanRenderer>,
|
||||
camera: Camera,
|
||||
player: Player,
|
||||
inventory: Inventory,
|
||||
cursor_captured: bool,
|
||||
last_frame_time: Instant,
|
||||
world: World,
|
||||
render_radius: i32,
|
||||
last_player_chunk: (i32, i32),
|
||||
targeted_block: Option<RaycastHit>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new() -> Self {
|
||||
// Le joueur apparaît au-dessus du relief à (0.5, 20.0, 0.5)
|
||||
let player = Player::new(Vec3::new(0.5, 20.0, 0.5));
|
||||
let mut camera = Camera::new(player.eye_position());
|
||||
camera.pitch = -0.2;
|
||||
camera.speed = 18.0;
|
||||
|
||||
Self {
|
||||
window: None,
|
||||
renderer: None,
|
||||
camera,
|
||||
player,
|
||||
inventory: Inventory::new(),
|
||||
cursor_captured: false,
|
||||
last_frame_time: Instant::now(),
|
||||
world: World::new(),
|
||||
render_radius: 3, // Rayon de 3 chunks = grille 7x7 = 49 chunks (112x112 blocs)
|
||||
last_player_chunk: (i32::MAX, i32::MAX),
|
||||
targeted_block: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Active ou désactive la capture du curseur souris dans la fenêtre
|
||||
fn set_cursor_grab(&mut self, grab: bool) {
|
||||
if let Some(window) = &self.window {
|
||||
self.cursor_captured = grab;
|
||||
let _ = window.set_cursor_grab(if grab {
|
||||
CursorGrabMode::Locked
|
||||
} else {
|
||||
CursorGrabMode::None
|
||||
})
|
||||
.or_else(|_| {
|
||||
window.set_cursor_grab(if grab {
|
||||
CursorGrabMode::Confined
|
||||
} else {
|
||||
CursorGrabMode::None
|
||||
})
|
||||
});
|
||||
window.set_cursor_visible(!grab);
|
||||
}
|
||||
}
|
||||
|
||||
/// Régénère et upload vers le GPU uniquement les maillages des chunks marqués `dirty_mesh = true`.
|
||||
fn update_dirty_meshes(&mut self) {
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
let dirty_positions: Vec<(i32, i32)> = self
|
||||
.world
|
||||
.chunks
|
||||
.iter()
|
||||
.filter(|(_, chunk)| chunk.dirty_mesh)
|
||||
.map(|(pos, _)| *pos)
|
||||
.collect();
|
||||
|
||||
for pos in dirty_positions {
|
||||
if let Some(chunk) = self.world.chunks.get(&pos) {
|
||||
// Construction avec culling aux frontières via le World global
|
||||
let mesh_data = build_chunk_mesh_world(chunk, &self.world);
|
||||
let _ = renderer.set_chunk_mesh(pos, mesh_data);
|
||||
}
|
||||
if let Some(chunk) = self.world.chunks.get_mut(&pos) {
|
||||
chunk.dirty_mesh = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sélectionne un slot de la hotbar et affiche l'état.
|
||||
fn select_slot(&mut self, slot: usize) {
|
||||
self.inventory.select_slot(slot);
|
||||
println!(
|
||||
"Hotbar [{}] : {:?} (Disponible : {})",
|
||||
self.inventory.selected_slot + 1,
|
||||
self.inventory.selected_block(),
|
||||
self.inventory.selected_count()
|
||||
);
|
||||
}
|
||||
|
||||
/// Casse le bloc actuellement visé, l'ajoute à l'inventaire et régénère les maillages.
|
||||
fn break_targeted_block(&mut self) {
|
||||
if let Some(hit) = self.targeted_block {
|
||||
let (x, y, z) = hit.hit_pos;
|
||||
let target_block = self.world.get_block(x, y, z);
|
||||
if target_block != BlockType::Air && self.world.set_block(x, y, z, BlockType::Air) {
|
||||
self.inventory.add_block(target_block);
|
||||
self.update_dirty_meshes();
|
||||
println!(
|
||||
"+1 {:?} récolté en ({x}, {y}, {z}) (Total inventaire : {})",
|
||||
target_block,
|
||||
self.inventory.selected_count()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pose un bloc depuis le slot d'inventaire actif sur la face ciblée.
|
||||
fn place_block_on_target(&mut self) {
|
||||
if let Some(hit) = self.targeted_block {
|
||||
let (x, y, z) = hit.place_pos;
|
||||
|
||||
// Protection anti-collision joueur : ne pas poser à l'intérieur du corps du joueur
|
||||
let block_aabb = crate::physics::AABB::new(
|
||||
Vec3::new(x as f32, y as f32, z as f32),
|
||||
Vec3::new((x + 1) as f32, (y + 1) as f32, (z + 1) as f32),
|
||||
);
|
||||
if self.player.aabb().intersects(&block_aabb) {
|
||||
println!("Impossible de poser un bloc à l'intérieur du joueur !");
|
||||
return;
|
||||
}
|
||||
|
||||
// Consomme 1 bloc du stock du slot actif (refus silencieux si 0)
|
||||
if let Some(block_to_place) = self.inventory.consume_selected() {
|
||||
if self.world.set_block(x, y, z, block_to_place) {
|
||||
self.update_dirty_meshes();
|
||||
println!(
|
||||
"-1 {:?} posé en ({x}, {y}, {z}) (Restant : {})",
|
||||
block_to_place,
|
||||
self.inventory.selected_count()
|
||||
);
|
||||
} else {
|
||||
// Remboursement si pose refusée (ex: hors des limites du monde)
|
||||
self.inventory.add_block(block_to_place);
|
||||
}
|
||||
} else {
|
||||
println!("Slot vide ! (0 bloc disponible)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_none() {
|
||||
let window_attributes = Window::default_attributes()
|
||||
.with_title("Moteur Voxel - Monde Multi-Chunks & Chargement Dynamique")
|
||||
.with_inner_size(LogicalSize::new(1280.0, 720.0));
|
||||
|
||||
let window = match event_loop.create_window(window_attributes) {
|
||||
Ok(w) => Arc::new(w),
|
||||
Err(err) => {
|
||||
eprintln!("Impossible de créer la fenêtre : {err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let renderer = match VulkanRenderer::new(window.clone(), event_loop) {
|
||||
Ok(r) => r,
|
||||
Err(err) => {
|
||||
eprintln!("Erreur lors de l'initialisation du moteur Vulkan : {err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
self.window = Some(window);
|
||||
self.renderer = Some(renderer);
|
||||
self.last_frame_time = Instant::now();
|
||||
|
||||
// 1. Initialisation des chunks autour du joueur
|
||||
let player_chunk_x = (self.camera.position.x.floor() as i32).div_euclid(CHUNK_SIZE_X as i32);
|
||||
let player_chunk_z = (self.camera.position.z.floor() as i32).div_euclid(CHUNK_SIZE_Z as i32);
|
||||
self.last_player_chunk = (player_chunk_x, player_chunk_z);
|
||||
|
||||
let (generated_count, gen_time) = self.world.update_chunks_around(
|
||||
self.camera.position.x,
|
||||
self.camera.position.z,
|
||||
self.render_radius,
|
||||
);
|
||||
|
||||
// 2. Maillage initial et upload GPU
|
||||
let mesh_start = Instant::now();
|
||||
self.update_dirty_meshes();
|
||||
let mesh_time = mesh_start.elapsed().as_secs_f32() * 1000.0;
|
||||
|
||||
let total_chunks = self.world.chunks.len();
|
||||
let total_voxels = total_chunks * CHUNK_SIZE_X * CHUNK_SIZE_Y * CHUNK_SIZE_Z;
|
||||
|
||||
println!();
|
||||
println!("============================================================");
|
||||
println!(" INITIALISATION DU MONDE MULTI-CHUNKS ");
|
||||
println!("============================================================");
|
||||
println!(" - Chunks actifs : {total_chunks} (Rayon : {} chunks)", self.render_radius);
|
||||
println!(" - Grille couverte : {} x {} blocs", (self.render_radius * 2 + 1) * CHUNK_SIZE_X as i32, (self.render_radius * 2 + 1) * CHUNK_SIZE_Z as i32);
|
||||
println!(" - Voxels totaux en mémoire : {total_voxels}");
|
||||
println!(" - Nouveaux chunks générés : {generated_count}");
|
||||
println!(" - Temps de génération relief : {gen_time:.2} ms");
|
||||
println!(" - Temps de maillage & upload : {mesh_time:.2} ms");
|
||||
println!("============================================================");
|
||||
println!();
|
||||
|
||||
self.set_cursor_grab(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mouvements relatifs de la souris (orientation caméra)
|
||||
fn device_event(
|
||||
&mut self,
|
||||
_event_loop: &ActiveEventLoop,
|
||||
_device_id: DeviceId,
|
||||
event: DeviceEvent,
|
||||
) {
|
||||
if self.cursor_captured {
|
||||
if let DeviceEvent::MouseMotion { delta } = event {
|
||||
self.camera.rotate(delta.0 as f32, delta.1 as f32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Événements de fenêtre et entrées utilisateur
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
match event {
|
||||
// Fermeture de la fenêtre
|
||||
WindowEvent::CloseRequested => {
|
||||
event_loop.exit();
|
||||
}
|
||||
|
||||
// Redimensionnement de la fenêtre
|
||||
WindowEvent::Resized(physical_size) => {
|
||||
if physical_size.width > 0 && physical_size.height > 0 {
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
renderer.notify_resized();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clics souris pour casser ou poser des blocs
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
if state == ElementState::Pressed {
|
||||
if !self.cursor_captured {
|
||||
self.set_cursor_grab(true);
|
||||
} else {
|
||||
match button {
|
||||
MouseButton::Left => {
|
||||
self.break_targeted_block();
|
||||
}
|
||||
MouseButton::Right => {
|
||||
self.place_block_on_target();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Molette de souris pour faire défiler la hotbar d'inventaire
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
let scroll_y = match delta {
|
||||
winit::event::MouseScrollDelta::LineDelta(_, y) => y,
|
||||
winit::event::MouseScrollDelta::PixelDelta(pos) => pos.y as f32,
|
||||
};
|
||||
if scroll_y > 0.1 {
|
||||
self.inventory.cycle_slot(-1);
|
||||
println!(
|
||||
"Hotbar [{}] : {:?} (Disponible : {})",
|
||||
self.inventory.selected_slot + 1,
|
||||
self.inventory.selected_block(),
|
||||
self.inventory.selected_count()
|
||||
);
|
||||
} else if scroll_y < -0.1 {
|
||||
self.inventory.cycle_slot(1);
|
||||
println!(
|
||||
"Hotbar [{}] : {:?} (Disponible : {})",
|
||||
self.inventory.selected_slot + 1,
|
||||
self.inventory.selected_block(),
|
||||
self.inventory.selected_count()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Touches du clavier
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
let is_pressed = event.state.is_pressed();
|
||||
|
||||
if let PhysicalKey::Code(key_code) = event.physical_key {
|
||||
match key_code {
|
||||
KeyCode::KeyW | KeyCode::KeyZ => self.camera.move_forward = is_pressed,
|
||||
KeyCode::KeyS => self.camera.move_backward = is_pressed,
|
||||
KeyCode::KeyA | KeyCode::KeyQ => self.camera.move_left = is_pressed,
|
||||
KeyCode::KeyD => self.camera.move_right = is_pressed,
|
||||
KeyCode::Space => self.camera.move_up = is_pressed,
|
||||
KeyCode::ShiftLeft | KeyCode::ShiftRight => {
|
||||
self.camera.move_down = is_pressed
|
||||
}
|
||||
KeyCode::Digit1 => { if is_pressed { self.select_slot(0); } }
|
||||
KeyCode::Digit2 => { if is_pressed { self.select_slot(1); } }
|
||||
KeyCode::Digit3 => { if is_pressed { self.select_slot(2); } }
|
||||
KeyCode::Digit4 => { if is_pressed { self.select_slot(3); } }
|
||||
KeyCode::Digit5 => { if is_pressed { self.select_slot(4); } }
|
||||
KeyCode::Digit6 => { if is_pressed { self.select_slot(5); } }
|
||||
KeyCode::KeyF => {
|
||||
if is_pressed {
|
||||
self.player.flying = !self.player.flying;
|
||||
self.player.velocity = Vec3::zero();
|
||||
println!(
|
||||
"Mode de déplacement : {}",
|
||||
if self.player.flying {
|
||||
"VOL LIBRE (noclip/rapide)"
|
||||
} else {
|
||||
"MARCHE & GRAVITÉ"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
KeyCode::Escape => {
|
||||
if is_pressed {
|
||||
let new_grab = !self.cursor_captured;
|
||||
self.set_cursor_grab(new_grab);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rafraîchissement / Rendu de chaque frame
|
||||
WindowEvent::RedrawRequested => {
|
||||
let now = Instant::now();
|
||||
let dt = (now - self.last_frame_time).as_secs_f32().min(0.05);
|
||||
self.last_frame_time = now;
|
||||
|
||||
// Mise à jour de la physique du joueur (marche/gravité ou vol libre)
|
||||
self.player.update(dt, &self.camera, &self.world);
|
||||
self.camera.position = self.player.eye_position();
|
||||
|
||||
// Chargement dynamique des chunks lors du déplacement du joueur
|
||||
let player_chunk_x = (self.camera.position.x.floor() as i32).div_euclid(CHUNK_SIZE_X as i32);
|
||||
let player_chunk_z = (self.camera.position.z.floor() as i32).div_euclid(CHUNK_SIZE_Z as i32);
|
||||
if (player_chunk_x, player_chunk_z) != self.last_player_chunk {
|
||||
self.last_player_chunk = (player_chunk_x, player_chunk_z);
|
||||
let (new_chunks, elapsed) = self.world.update_chunks_around(
|
||||
self.camera.position.x,
|
||||
self.camera.position.z,
|
||||
self.render_radius,
|
||||
);
|
||||
if new_chunks > 0 {
|
||||
println!("Monde : {new_chunks} nouveaux chunks générés en {elapsed:.2} ms");
|
||||
self.update_dirty_meshes();
|
||||
}
|
||||
}
|
||||
|
||||
// Raycasting voxel multi-chunks (portée 7.0 blocs)
|
||||
self.targeted_block = raycast_voxel(
|
||||
self.camera.position,
|
||||
self.camera.forward(),
|
||||
7.0,
|
||||
&self.world,
|
||||
);
|
||||
|
||||
if let (Some(renderer), Some(window)) = (&mut self.renderer, &self.window) {
|
||||
let dimensions: [u32; 2] = window.inner_size().into();
|
||||
let view_matrix = self.camera.view_matrix();
|
||||
let selected_pos = self.targeted_block.map(|h| h.hit_pos);
|
||||
|
||||
// Génération du maillage 2D de la hotbar pour l'aspect ratio de la fenêtre
|
||||
let aspect_ratio = dimensions[0] as f32 / dimensions[1] as f32;
|
||||
let ui_mesh = self.inventory.generate_ui_mesh(aspect_ratio);
|
||||
|
||||
renderer.render(dimensions, view_matrix, selected_pos, Some(ui_mesh));
|
||||
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/// Dimensions d'un chunk voxel (16x32x16 = 8 192 blocs).
|
||||
/// Ce format colonne 16x16 standard permet une génération et régénération incrémentale ultra-rapide.
|
||||
pub const CHUNK_SIZE_X: usize = 16;
|
||||
pub const CHUNK_SIZE_Y: usize = 32;
|
||||
pub const CHUNK_SIZE_Z: usize = 16;
|
||||
|
||||
/// Type de bloc voxel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum BlockType {
|
||||
Air = 0,
|
||||
Grass = 1,
|
||||
Dirt = 2,
|
||||
Stone = 3,
|
||||
Wood = 4,
|
||||
Leaves = 5,
|
||||
Sand = 6,
|
||||
}
|
||||
|
||||
impl BlockType {
|
||||
/// Indique si le bloc est opaque (solide pour le culling des faces et les collisions).
|
||||
#[inline(always)]
|
||||
pub fn is_opaque(&self) -> bool {
|
||||
*self != BlockType::Air
|
||||
}
|
||||
}
|
||||
|
||||
/// Structure représentant un Chunk 3D de voxels dans le monde.
|
||||
pub struct Chunk {
|
||||
pub chunk_x: i32,
|
||||
pub chunk_z: i32,
|
||||
pub voxels: Vec<BlockType>,
|
||||
pub dirty_mesh: bool,
|
||||
}
|
||||
|
||||
impl Chunk {
|
||||
/// Crée un chunk vide aux coordonnées (chunk_x, chunk_z).
|
||||
pub fn new_empty(chunk_x: i32, chunk_z: i32) -> Self {
|
||||
Self {
|
||||
chunk_x,
|
||||
chunk_z,
|
||||
voxels: vec![BlockType::Air; CHUNK_SIZE_X * CHUNK_SIZE_Y * CHUNK_SIZE_Z],
|
||||
dirty_mesh: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Index 1D linéaire correspondant aux coordonnées locales 3D (x, y, z).
|
||||
#[inline(always)]
|
||||
fn index(x: usize, y: usize, z: usize) -> usize {
|
||||
x + z * CHUNK_SIZE_X + y * CHUNK_SIZE_X * CHUNK_SIZE_Z
|
||||
}
|
||||
|
||||
/// Récupère le type de bloc aux coordonnées locales (x, y, z).
|
||||
/// Retourne Air si les coordonnées sont en dehors du chunk local.
|
||||
#[inline(always)]
|
||||
pub fn get_block_local(&self, x: i32, y: i32, z: i32) -> BlockType {
|
||||
if x < 0
|
||||
|| x >= CHUNK_SIZE_X as i32
|
||||
|| y < 0
|
||||
|| y >= CHUNK_SIZE_Y as i32
|
||||
|| z < 0
|
||||
|| z >= CHUNK_SIZE_Z as i32
|
||||
{
|
||||
BlockType::Air
|
||||
} else {
|
||||
self.voxels[Self::index(x as usize, y as usize, z as usize)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifie le bloc aux coordonnées locales (x, y, z).
|
||||
pub fn set_block_local(&mut self, x: usize, y: usize, z: usize, block: BlockType) {
|
||||
if x < CHUNK_SIZE_X && y < CHUNK_SIZE_Y && z < CHUNK_SIZE_Z {
|
||||
let idx = Self::index(x, y, z);
|
||||
self.voxels[idx] = block;
|
||||
self.dirty_mesh = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Génère un terrain procédural ondulé et continu basé sur les coordonnées mondes absolues.
|
||||
/// Cela garantit une transition parfaitement continue et sans jointure entre les chunks adjacents.
|
||||
pub fn generate_terrain(chunk_x: i32, chunk_z: i32) -> Self {
|
||||
let mut chunk = Self::new_empty(chunk_x, chunk_z);
|
||||
let world_base_x = chunk_x * CHUNK_SIZE_X as i32;
|
||||
let world_base_z = chunk_z * CHUNK_SIZE_Z as i32;
|
||||
|
||||
for lx in 0..CHUNK_SIZE_X {
|
||||
let gx = (world_base_x + lx as i32) as f32;
|
||||
|
||||
for lz in 0..CHUNK_SIZE_Z {
|
||||
let gz = (world_base_z + lz as i32) as f32;
|
||||
|
||||
// Fonction de hauteur continue en coordonnées globales
|
||||
let wave1 = (gx * 0.07).sin() * (gz * 0.07).cos() * 5.0;
|
||||
let wave2 = ((gx + gz) * 0.035).sin() * 3.5;
|
||||
let wave3 = (gx * 0.15 - gz * 0.12).cos() * 1.5;
|
||||
|
||||
let height = (14.0 + wave1 + wave2 + wave3).round() as i32;
|
||||
let height = height.clamp(1, (CHUNK_SIZE_Y - 7) as i32);
|
||||
|
||||
for ly in 0..CHUNK_SIZE_Y as i32 {
|
||||
if height <= 10 {
|
||||
// Plages de sable à basse altitude
|
||||
if ly == height {
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Sand);
|
||||
} else if ly >= height - 2 && ly < height {
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Sand);
|
||||
} else if ly < height - 2 {
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Stone);
|
||||
}
|
||||
} else {
|
||||
// Collines herbues
|
||||
if ly == height {
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Grass);
|
||||
} else if ly >= height - 3 && ly < height {
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Dirt);
|
||||
} else if ly < height - 3 {
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Stone);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dispersion déterministe d'arbres (Bois + Feuilles) sur les zones d'herbe
|
||||
let tree_spots = [(4, 4), (11, 11), (4, 11), (11, 4)];
|
||||
for &(tx, tz) in &tree_spots {
|
||||
let mut h = (chunk_x as u32)
|
||||
.wrapping_mul(374761393)
|
||||
^ (chunk_z as u32).wrapping_mul(668265263)
|
||||
^ ((tx as u32) << 4)
|
||||
^ (tz as u32);
|
||||
h = (h ^ (h >> 13)).wrapping_mul(1274126177);
|
||||
|
||||
// Densité modérée : ~25% de chance par spot (en moyenne ~1 arbre par chunk)
|
||||
if h % 4 == 0 {
|
||||
let mut surface_y = -1;
|
||||
for y in (1..CHUNK_SIZE_Y as i32).rev() {
|
||||
if chunk.get_block_local(tx as i32, y, tz as i32) == BlockType::Grass {
|
||||
surface_y = y;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if surface_y > 0 && surface_y + 6 < CHUNK_SIZE_Y as i32 {
|
||||
// Le bloc sous le tronc devient de la terre
|
||||
chunk.set_block_local(tx, surface_y as usize, tz, BlockType::Dirt);
|
||||
|
||||
// Tronc en bois (hauteur 3 blocs)
|
||||
let trunk_h = 3;
|
||||
for ty in 1..=trunk_h {
|
||||
chunk.set_block_local(tx, (surface_y + ty) as usize, tz, BlockType::Wood);
|
||||
}
|
||||
|
||||
// Feuillage (Leaves)
|
||||
let leaf_base = surface_y + trunk_h;
|
||||
// Étage inférieur et médian (3x3)
|
||||
for dy in 0..=1 {
|
||||
for dx in -1..=1 {
|
||||
for dz in -1..=1 {
|
||||
if dy == 0 && dx == 0 && dz == 0 {
|
||||
continue; // Emplacement du sommet du tronc
|
||||
}
|
||||
let lx = (tx as i32 + dx) as usize;
|
||||
let lz = (tz as i32 + dz) as usize;
|
||||
chunk.set_block_local(
|
||||
lx,
|
||||
(leaf_base + dy) as usize,
|
||||
lz,
|
||||
BlockType::Leaves,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Étage sommital en croix (5 blocs)
|
||||
for (dx, dz) in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)] {
|
||||
let lx = (tx as i32 + dx) as usize;
|
||||
let lz = (tz as i32 + dz) as usize;
|
||||
chunk.set_block_local(
|
||||
lx,
|
||||
(leaf_base + 2) as usize,
|
||||
lz,
|
||||
BlockType::Leaves,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chunk.dirty_mesh = true;
|
||||
chunk
|
||||
}
|
||||
|
||||
/// Compte le nombre total de blocs pleins (solides) dans le chunk.
|
||||
#[allow(dead_code)]
|
||||
pub fn count_solid_blocks(&self) -> usize {
|
||||
self.voxels.iter().filter(|b| b.is_opaque()).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_tree_generation_present() {
|
||||
// En scannant plusieurs chunks, au moins certains contiennent des arbres (Bois + Feuilles)
|
||||
let mut total_wood = 0;
|
||||
let mut total_leaves = 0;
|
||||
let mut total_sand = 0;
|
||||
|
||||
for cx in 0..4 {
|
||||
for cz in 0..4 {
|
||||
let chunk = Chunk::generate_terrain(cx, cz);
|
||||
for &b in &chunk.voxels {
|
||||
match b {
|
||||
BlockType::Wood => total_wood += 1,
|
||||
BlockType::Leaves => total_leaves += 1,
|
||||
BlockType::Sand => total_sand += 1,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(total_wood > 0, "Le monde doit générer des troncs de bois");
|
||||
assert!(total_leaves > 0, "Le monde doit générer des feuilles d'arbres");
|
||||
assert!(total_sand > 0, "Le monde doit générer des zones de sable");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
use crate::renderer::mesh::CubeVertex;
|
||||
use super::chunk::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z};
|
||||
|
||||
/// Données géométriques brutes générées pour le maillage du chunk.
|
||||
pub struct ChunkMeshData {
|
||||
pub vertices: Vec<CubeVertex>,
|
||||
pub indices: Vec<u32>,
|
||||
#[allow(dead_code)]
|
||||
pub faces_count: usize,
|
||||
}
|
||||
|
||||
/// Énumération des 6 directions de faces d'un voxel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Direction {
|
||||
PosY, // Haut (Top)
|
||||
NegY, // Bas (Bottom)
|
||||
PosZ, // Avant (Front)
|
||||
NegZ, // Arrière (Back)
|
||||
PosX, // Droite (Right)
|
||||
NegX, // Gauche (Left)
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
const ALL: [Direction; 6] = [
|
||||
Direction::PosY,
|
||||
Direction::NegY,
|
||||
Direction::PosZ,
|
||||
Direction::NegZ,
|
||||
Direction::PosX,
|
||||
Direction::NegX,
|
||||
];
|
||||
|
||||
#[inline(always)]
|
||||
fn offset(&self) -> (i32, i32, i32) {
|
||||
match self {
|
||||
Direction::PosY => (0, 1, 0),
|
||||
Direction::NegY => (0, -1, 0),
|
||||
Direction::PosZ => (0, 0, 1),
|
||||
Direction::NegZ => (0, 0, -1),
|
||||
Direction::PosX => (1, 0, 0),
|
||||
Direction::NegX => (-1, 0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn normal(&self) -> [f32; 3] {
|
||||
match self {
|
||||
Direction::PosY => [0.0, 1.0, 0.0],
|
||||
Direction::NegY => [0.0, -1.0, 0.0],
|
||||
Direction::PosZ => [0.0, 0.0, 1.0],
|
||||
Direction::NegZ => [0.0, 0.0, -1.0],
|
||||
Direction::PosX => [1.0, 0.0, 0.0],
|
||||
Direction::NegX => [-1.0, 0.0, 0.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retourne l'index de tuile dans l'atlas (8x8 tuiles) selon le type de bloc et la face.
|
||||
pub fn get_face_tile_id(block: BlockType, dir: Direction) -> u32 {
|
||||
match block {
|
||||
BlockType::Grass => match dir {
|
||||
Direction::PosY => 0, // Herbe dessus
|
||||
Direction::NegY => 2, // Terre (dessous)
|
||||
_ => 1, // Herbe côté
|
||||
},
|
||||
BlockType::Dirt => 2,
|
||||
BlockType::Stone => 3,
|
||||
BlockType::Wood => match dir {
|
||||
Direction::PosY | Direction::NegY => 5, // Cernes du bois
|
||||
_ => 4, // Écorce
|
||||
},
|
||||
BlockType::Leaves => 6,
|
||||
BlockType::Sand => 7,
|
||||
BlockType::Air => 0,
|
||||
}
|
||||
}
|
||||
|
||||
use super::world::World;
|
||||
|
||||
/// Construit le maillage optimisé d'un chunk avec Culling inter-chunks via le World global.
|
||||
///
|
||||
/// CRITIQUE : Aux frontières du chunk, cette fonction interroge le bloc dans le chunk voisin
|
||||
/// via `world.get_block(gx + dx, gy + dy, gz + dz)`. Cela élimine les faces fantômes et les
|
||||
/// trous aux jonctions entre chunks adjacents.
|
||||
/// Les positions des sommets sont directement générées en coordonnées monde absolues.
|
||||
pub fn build_chunk_mesh_world(chunk: &Chunk, world: &World) -> ChunkMeshData {
|
||||
let mut vertices = Vec::new();
|
||||
let mut indices = Vec::new();
|
||||
let mut faces_count = 0;
|
||||
|
||||
let world_base_x = chunk.chunk_x * CHUNK_SIZE_X as i32;
|
||||
let world_base_z = chunk.chunk_z * CHUNK_SIZE_Z as i32;
|
||||
|
||||
for lx in 0..CHUNK_SIZE_X {
|
||||
let gx = world_base_x + lx as i32;
|
||||
let fx = gx as f32;
|
||||
|
||||
for ly in 0..CHUNK_SIZE_Y {
|
||||
let gy = ly as i32;
|
||||
let fy = gy as f32;
|
||||
|
||||
for lz in 0..CHUNK_SIZE_Z {
|
||||
let gz = world_base_z + lz as i32;
|
||||
let fz = gz as f32;
|
||||
|
||||
let block = chunk.get_block_local(lx as i32, gy, lz as i32);
|
||||
if !block.is_opaque() {
|
||||
continue;
|
||||
}
|
||||
|
||||
for dir in Direction::ALL {
|
||||
let (dx, dy, dz) = dir.offset();
|
||||
// Interrogation globale dans le monde (traverse les chunks voisins)
|
||||
let neighbor = world.get_block(gx + dx, gy + dy, gz + dz);
|
||||
|
||||
// Si le voisin immédiat est opaque, la face est masquée : culling !
|
||||
if neighbor.is_opaque() {
|
||||
continue;
|
||||
}
|
||||
|
||||
faces_count += 1;
|
||||
let base_index = vertices.len() as u32;
|
||||
let normal = dir.normal();
|
||||
|
||||
// Coordonnées de texture dans l'atlas 8x8 tuiles
|
||||
let tile_id = get_face_tile_id(block, dir);
|
||||
let tile_u = (tile_id % 8) as f32;
|
||||
let tile_v = (tile_id / 8) as f32;
|
||||
let tile_size = 1.0 / 8.0;
|
||||
|
||||
let u_min = tile_u * tile_size;
|
||||
let u_max = (tile_u + 1.0) * tile_size;
|
||||
let v_min = tile_v * tile_size;
|
||||
let v_max = (tile_v + 1.0) * tile_size;
|
||||
|
||||
let uvs = [
|
||||
[u_min, v_max],
|
||||
[u_max, v_max],
|
||||
[u_max, v_min],
|
||||
[u_min, v_min],
|
||||
];
|
||||
|
||||
let quad = match dir {
|
||||
Direction::PosY => [
|
||||
[fx, fy + 1.0, fz + 1.0],
|
||||
[fx + 1.0, fy + 1.0, fz + 1.0],
|
||||
[fx + 1.0, fy + 1.0, fz],
|
||||
[fx, fy + 1.0, fz],
|
||||
],
|
||||
Direction::NegY => [
|
||||
[fx, fy, fz],
|
||||
[fx + 1.0, fy, fz],
|
||||
[fx + 1.0, fy, fz + 1.0],
|
||||
[fx, fy, fz + 1.0],
|
||||
],
|
||||
Direction::PosZ => [
|
||||
[fx, fy, fz + 1.0],
|
||||
[fx + 1.0, fy, fz + 1.0],
|
||||
[fx + 1.0, fy + 1.0, fz + 1.0],
|
||||
[fx, fy + 1.0, fz + 1.0],
|
||||
],
|
||||
Direction::NegZ => [
|
||||
[fx + 1.0, fy, fz],
|
||||
[fx, fy, fz],
|
||||
[fx, fy + 1.0, fz],
|
||||
[fx + 1.0, fy + 1.0, fz],
|
||||
],
|
||||
Direction::PosX => [
|
||||
[fx + 1.0, fy, fz + 1.0],
|
||||
[fx + 1.0, fy, fz],
|
||||
[fx + 1.0, fy + 1.0, fz],
|
||||
[fx + 1.0, fy + 1.0, fz + 1.0],
|
||||
],
|
||||
Direction::NegX => [
|
||||
[fx, fy, fz],
|
||||
[fx, fy, fz + 1.0],
|
||||
[fx, fy + 1.0, fz + 1.0],
|
||||
[fx, fy + 1.0, fz],
|
||||
],
|
||||
};
|
||||
|
||||
for (i, pos) in quad.into_iter().enumerate() {
|
||||
vertices.push(CubeVertex {
|
||||
position: pos,
|
||||
color: [1.0, 1.0, 1.0],
|
||||
normal,
|
||||
uv: uvs[i],
|
||||
});
|
||||
}
|
||||
|
||||
// 2 triangles par face : (0, 1, 2) et (2, 3, 0)
|
||||
indices.push(base_index + 0);
|
||||
indices.push(base_index + 1);
|
||||
indices.push(base_index + 2);
|
||||
indices.push(base_index + 2);
|
||||
indices.push(base_index + 3);
|
||||
indices.push(base_index + 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ChunkMeshData {
|
||||
vertices,
|
||||
indices,
|
||||
faces_count,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construit le maillage d'un chunk isolé (utile pour les tests unitaires).
|
||||
#[allow(dead_code)]
|
||||
pub fn build_chunk_mesh(chunk: &Chunk) -> ChunkMeshData {
|
||||
let mut world = World::new();
|
||||
world.chunks.insert((chunk.chunk_x, chunk.chunk_z), Chunk {
|
||||
chunk_x: chunk.chunk_x,
|
||||
chunk_z: chunk.chunk_z,
|
||||
voxels: chunk.voxels.clone(),
|
||||
dirty_mesh: false,
|
||||
});
|
||||
build_chunk_mesh_world(chunk, &world)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_isolated_block_has_6_faces() {
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
chunk.set_block_local(5, 5, 5, BlockType::Stone);
|
||||
let mesh = build_chunk_mesh(&chunk);
|
||||
assert_eq!(mesh.faces_count, 6);
|
||||
assert_eq!(mesh.indices.len(), 36);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_adjacent_blocks_cull_shared_faces() {
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
// Deux blocs adjacents en X : (5, 5, 5) et (6, 5, 5)
|
||||
// Sans culling : 2 * 6 = 12 faces.
|
||||
// Avec culling : la face droite de l'un et la face gauche de l'autre sont masquées -> 10 faces !
|
||||
chunk.set_block_local(5, 5, 5, BlockType::Stone);
|
||||
chunk.set_block_local(6, 5, 5, BlockType::Stone);
|
||||
let mesh = build_chunk_mesh(&chunk);
|
||||
assert_eq!(mesh.faces_count, 10);
|
||||
assert_eq!(mesh.indices.len(), 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_2x2x2_cube_culling() {
|
||||
let mut chunk = Chunk::new_empty(0, 0);
|
||||
// 8 blocs formant un cube 2x2x2
|
||||
// Sans culling : 8 * 6 = 48 faces.
|
||||
// Avec culling : seules les faces extérieures du macro-cube restent -> 6 faces * 4 = 24 faces !
|
||||
for x in 0..2 {
|
||||
for y in 0..2 {
|
||||
for z in 0..2 {
|
||||
chunk.set_block_local(x, y, z, BlockType::Dirt);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mesh = build_chunk_mesh(&chunk);
|
||||
assert_eq!(mesh.faces_count, 24);
|
||||
assert_eq!(mesh.indices.len(), 144);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cross_chunk_boundary_culling() {
|
||||
let mut world = World::new();
|
||||
|
||||
// Chunk (0, 0) avec un bloc sur sa bordure maximale en X (15, 10, 8)
|
||||
let mut chunk0 = Chunk::new_empty(0, 0);
|
||||
chunk0.set_block_local(CHUNK_SIZE_X - 1, 10, 8, BlockType::Stone);
|
||||
world.chunks.insert((0, 0), chunk0);
|
||||
|
||||
// Chunk (1, 0) avec un bloc sur sa bordure minimale en X (0, 10, 8)
|
||||
// Les deux blocs se touchent à la frontière entre les chunks !
|
||||
let mut chunk1 = Chunk::new_empty(1, 0);
|
||||
chunk1.set_block_local(0, 10, 8, BlockType::Stone);
|
||||
world.chunks.insert((1, 0), chunk1);
|
||||
|
||||
// Sans culling inter-chunk : chaque bloc aurait 6 faces (12 au total)
|
||||
// Avec culling inter-chunk : les 2 faces qui se touchent à la frontière sont masquées !
|
||||
let mesh0 = build_chunk_mesh_world(world.chunks.get(&(0, 0)).unwrap(), &world);
|
||||
let mesh1 = build_chunk_mesh_world(world.chunks.get(&(1, 0)).unwrap(), &world);
|
||||
|
||||
assert_eq!(mesh0.faces_count, 5); // 6 - 1 = 5
|
||||
assert_eq!(mesh1.faces_count, 5); // 6 - 1 = 5
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_terrain_culling_stats() {
|
||||
let chunk = Chunk::generate_terrain(0, 0);
|
||||
let solid = chunk.count_solid_blocks();
|
||||
let theoretical = solid * 6;
|
||||
let mesh = build_chunk_mesh(&chunk);
|
||||
let reduction = (1.0 - (mesh.faces_count as f64 / theoretical as f64)) * 100.0;
|
||||
println!("\n[TEST] Terrain chunk : {} blocs solides, {} faces théoriques -> {} faces générées (-{:.2}%)",
|
||||
solid, theoretical, mesh.faces_count, reduction);
|
||||
assert!(mesh.faces_count < theoretical);
|
||||
assert!(reduction > 80.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod chunk;
|
||||
pub mod mesh_builder;
|
||||
pub mod world;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use chunk::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z};
|
||||
#[allow(unused_imports)]
|
||||
pub use mesh_builder::{build_chunk_mesh, build_chunk_mesh_world, ChunkMeshData};
|
||||
pub use world::World;
|
||||
@@ -0,0 +1,183 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Instant;
|
||||
|
||||
use super::chunk::{BlockType, Chunk, CHUNK_SIZE_X, CHUNK_SIZE_Y, CHUNK_SIZE_Z};
|
||||
|
||||
/// Structure gérant l'ensemble des Chunks du monde voxel.
|
||||
pub struct World {
|
||||
pub chunks: HashMap<(i32, i32), Chunk>,
|
||||
}
|
||||
|
||||
impl World {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
chunks: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convertit des coordonnées absolues de bloc (X, Y, Z) en coordonnées de Chunk et coordonnées locales.
|
||||
/// Utilise la division euclidienne pour gérer correctement les coordonnées négatives.
|
||||
#[inline(always)]
|
||||
pub fn world_to_chunk_and_local(x: i32, y: i32, z: i32) -> ((i32, i32), (usize, i32, usize)) {
|
||||
let chunk_x = x.div_euclid(CHUNK_SIZE_X as i32);
|
||||
let chunk_z = z.div_euclid(CHUNK_SIZE_Z as i32);
|
||||
let local_x = x.rem_euclid(CHUNK_SIZE_X as i32) as usize;
|
||||
let local_z = z.rem_euclid(CHUNK_SIZE_Z as i32) as usize;
|
||||
((chunk_x, chunk_z), (local_x, y, local_z))
|
||||
}
|
||||
|
||||
/// Récupère le type de bloc aux coordonnées globales (x, y, z).
|
||||
/// Traverse de manière transparente les frontières de chunks.
|
||||
#[inline(always)]
|
||||
pub fn get_block(&self, x: i32, y: i32, z: i32) -> BlockType {
|
||||
if y < 0 || y >= CHUNK_SIZE_Y as i32 {
|
||||
return BlockType::Air;
|
||||
}
|
||||
|
||||
let ((cx, cz), (lx, ly, lz)) = Self::world_to_chunk_and_local(x, y, z);
|
||||
if let Some(chunk) = self.chunks.get(&(cx, cz)) {
|
||||
chunk.get_block_local(lx as i32, ly, lz as i32)
|
||||
} else {
|
||||
BlockType::Air
|
||||
}
|
||||
}
|
||||
|
||||
/// Modifie un bloc aux coordonnées globales (x, y, z).
|
||||
/// Si le bloc modifié est sur une frontière de chunk, le chunk voisin est également
|
||||
/// marqué comme `dirty_mesh = true` pour mettre à jour le culling des faces à la frontière.
|
||||
pub fn set_block(&mut self, x: i32, y: i32, z: i32, block: BlockType) -> bool {
|
||||
if y < 0 || y >= CHUNK_SIZE_Y as i32 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let ((cx, cz), (lx, ly, lz)) = Self::world_to_chunk_and_local(x, y, z);
|
||||
|
||||
if let Some(chunk) = self.chunks.get_mut(&(cx, cz)) {
|
||||
chunk.set_block_local(lx, ly as usize, lz, block);
|
||||
|
||||
// Détection des bords de chunk pour marquer les voisins affectés
|
||||
let on_min_x = lx == 0;
|
||||
let on_max_x = lx == CHUNK_SIZE_X - 1;
|
||||
let on_min_z = lz == 0;
|
||||
let on_max_z = lz == CHUNK_SIZE_Z - 1;
|
||||
|
||||
if on_min_x {
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx - 1, cz)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
}
|
||||
if on_max_x {
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx + 1, cz)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
}
|
||||
if on_min_z {
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx, cz - 1)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
}
|
||||
if on_max_z {
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx, cz + 1)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge/Génère dynamiquement les chunks dans un rayon donné autour de la position du joueur.
|
||||
/// Retourne le nombre de nouveaux chunks générés et le temps pris en millisecondes.
|
||||
pub fn update_chunks_around(&mut self, player_x: f32, player_z: f32, radius: i32) -> (usize, f32) {
|
||||
let start = Instant::now();
|
||||
let player_chunk_x = (player_x.floor() as i32).div_euclid(CHUNK_SIZE_X as i32);
|
||||
let player_chunk_z = (player_z.floor() as i32).div_euclid(CHUNK_SIZE_Z as i32);
|
||||
|
||||
let mut generated_count = 0;
|
||||
|
||||
for dx in -radius..=radius {
|
||||
for dz in -radius..=radius {
|
||||
let cx = player_chunk_x + dx;
|
||||
let cz = player_chunk_z + dz;
|
||||
|
||||
if !self.chunks.contains_key(&(cx, cz)) {
|
||||
let chunk = Chunk::generate_terrain(cx, cz);
|
||||
self.chunks.insert((cx, cz), chunk);
|
||||
generated_count += 1;
|
||||
|
||||
// Si on génère un nouveau chunk, les voisins déjà existants
|
||||
// doivent recalculer leur frontière commune pour le culling !
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx - 1, cz)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx + 1, cz)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx, cz - 1)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
if let Some(neighbor) = self.chunks.get_mut(&(cx, cz + 1)) {
|
||||
neighbor.dirty_mesh = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed_ms = start.elapsed().as_secs_f32() * 1000.0;
|
||||
(generated_count, elapsed_ms)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_break_block_at_extreme_negative_coordinate() {
|
||||
let mut world = World::new();
|
||||
let x = -1000;
|
||||
let y = 12;
|
||||
let z = -2500;
|
||||
|
||||
let ((cx, cz), (lx, ly, lz)) = World::world_to_chunk_and_local(x, y, z);
|
||||
assert_eq!(cx, (-1000i32).div_euclid(CHUNK_SIZE_X as i32));
|
||||
assert_eq!(cz, (-2500i32).div_euclid(CHUNK_SIZE_Z as i32));
|
||||
assert!(lx < CHUNK_SIZE_X);
|
||||
assert!(lz < CHUNK_SIZE_Z);
|
||||
assert_eq!(ly, 12);
|
||||
|
||||
// Crée le chunk cible à ces coordonnées lointaines
|
||||
let mut chunk = Chunk::new_empty(cx, cz);
|
||||
chunk.set_block_local(lx, ly as usize, lz, BlockType::Stone);
|
||||
world.chunks.insert((cx, cz), chunk);
|
||||
|
||||
// Vérifie la présence du bloc
|
||||
assert_eq!(world.get_block(x, y, z), BlockType::Stone);
|
||||
|
||||
// Casse le bloc à cette coordonnée extrême
|
||||
let broken = world.set_block(x, y, z, BlockType::Air);
|
||||
assert!(broken, "Le bloc doit être cassé avec succès");
|
||||
assert_eq!(world.get_block(x, y, z), BlockType::Air);
|
||||
|
||||
// Tenter de casser un bloc dans un chunk inexistant à x = -999999 ne doit pas crasher
|
||||
let non_existent = world.set_block(-999999, 10, -999999, BlockType::Air);
|
||||
assert!(!non_existent, "Casser dans un chunk non chargé renvoie false sans paniquer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resize_during_chunk_generation() {
|
||||
let mut world = World::new();
|
||||
// Simule une génération dynamique autour d'un joueur qui bouge rapidement
|
||||
let positions = [(0.0, 0.0), (100.0, 100.0), (-50.0, -80.0), (200.0, -150.0)];
|
||||
|
||||
for (px, pz) in positions {
|
||||
let (new_count, elapsed) = world.update_chunks_around(px, pz, 2);
|
||||
assert!(elapsed >= 0.0);
|
||||
assert!(new_count <= 25);
|
||||
}
|
||||
|
||||
assert!(world.chunks.len() >= 25);
|
||||
}
|
||||
}
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur