lots of adds

This commit is contained in:
2026-09-19 21:44:14 +02:00
parent 92f83c1c4e
commit d6e4c06d7e
12 changed files with 630 additions and 39 deletions
+16 -4
View File
@@ -1,8 +1,13 @@
use bevy::prelude::*;
// Fixed game screen
pub const SCREEN_WIDTH: f32 = 720.0;
pub const SCREEN_HEIGHT: f32 = 1080.0;
pub const SCREEN_ASPECT: f32 = SCREEN_WIDTH / SCREEN_HEIGHT; // 2:3
// Grid
pub const CELL_SIZE: f32 = 32.0;
pub const TERRAIN_COLS: i32 = 60;
pub const TERRAIN_COLS: i32 = 21;
pub const CHUNK_ROWS: i32 = 32;
pub const TERRAIN_WIDTH: f32 = CELL_SIZE * TERRAIN_COLS as f32;
@@ -15,7 +20,14 @@ pub const MARGIN_BELLOW: f32 = 400.0;
// Player
pub const PLAYER_HITBOX: Vec2 = Vec2::new(20.0, 40.0);
pub const FALL_SPEED: f32 = 600.0;
pub const DIVE_SPEED: f32 = 1000.0;
pub const HORIZONTAL_SPEED: f32 = 500.0;
pub const FALL_SPEED: f32 = 500.0;
pub const DIVE_SPEED: f32 = 2700.0;
pub const HORIZONTAL_SPEED: f32 = 450.0;
pub const START_POSITION: Vec3 = Vec3::new(0.0, 0.0, 2.0);
pub const CAMERAE_OFFSET: f32 = 280.0;
// Validator
pub const INERTIA_MARGIN: f32 = 4.0;
pub const DESIGN_LATERAL_SPEED_RATIO: f32 = 0.6;
pub const DESIGN_SLOPE_COLS_PER_ROW: f32 =
HORIZONTAL_SPEED * DESIGN_LATERAL_SPEED_RATIO / FALL_SPEED;
+23 -4
View File
@@ -4,6 +4,7 @@ use bevy::{
};
use crate::{
config::{SCREEN_HEIGHT, SCREEN_WIDTH},
gameplay::{camera::MainCamera, player::Player},
states::GameState,
world::RunSeed,
@@ -15,6 +16,9 @@ pub struct Debug;
#[derive(Component)]
pub struct DebugCamera;
#[derive(Component)]
struct ViewDebugText;
fn spawn_debug_camera(mut commands: Commands) {
commands.spawn((
Debug,
@@ -69,8 +73,8 @@ fn spawn_debug_frame(mut commands: Commands) {
FrameSide::Right,
] {
let size = match side {
FrameSide::Top | FrameSide::Bottom => Vec2::new(1936.0, 8.0),
FrameSide::Left | FrameSide::Right => Vec2::new(8.0, 1096.0),
FrameSide::Top | FrameSide::Bottom => Vec2::new(SCREEN_WIDTH + 16.0, 8.0),
FrameSide::Left | FrameSide::Right => Vec2::new(8.0, SCREEN_HEIGHT + 16.0),
};
commands.spawn((
@@ -91,8 +95,8 @@ fn draw_view_frame(
>,
) {
let center = main_camera.translation;
let half_width = 960.0;
let half_height = 540.0;
let half_width = SCREEN_WIDTH / 2.0;
let half_height = SCREEN_HEIGHT / 2.0;
let visible = if debug_camera.is_active {
Visibility::Visible
@@ -154,6 +158,15 @@ fn spawn_debug_texts(mut commands: Commands) {
},
TextColor(Color::srgb(1.0, 1.0, 0.0)),
FpsDebugText,
),
(
Text::new(""),
TextFont {
font_size: FontSize::Px(20.0),
..default()
},
TextColor(Color::srgb(1.0, 1.0, 0.0)),
ViewDebugText,
)
],
));
@@ -184,6 +197,11 @@ fn cleanup_debug(mut commands: Commands, entities: Query<Entity, With<Debug>>) {
}
}
// Show the world rect the game camera renders
fn update_view_debug_text(mut text: Single<&mut Text, With<ViewDebugText>>) {
text.0 = format!("View: {SCREEN_WIDTH:.0}x{SCREEN_HEIGHT:.0}");
}
pub struct DebugPlugin;
impl Plugin for DebugPlugin {
@@ -205,6 +223,7 @@ impl Plugin for DebugPlugin {
toggle_debug_camera,
update_seed_debug_text,
update_fps_debug_text,
update_view_debug_text,
)
.run_if(in_state(GameState::InGame)),
)
+5 -12
View File
@@ -1,24 +1,18 @@
use bevy::prelude::*;
use crate::gameplay::player::Player;
use crate::gameplay::player::move_player;
use crate::config::CAMERAE_OFFSET;
use crate::gameplay::player::{Player, move_player};
use crate::states::GameState;
#[derive(Component)]
pub struct MainCamera;
fn spawn_main_camera(mut commands: Commands) {
commands.spawn((Camera2d, MainCamera, IsDefaultUiCamera));
}
// Follow the player with the camera
fn follow_player(
player: Single<&Transform, (With<Player>, Without<MainCamera>)>,
mut camera: Single<&mut Transform, (With<MainCamera>, Without<Player>)>,
// time: Res<Time>,
) {
camera.translation.y = player.translation.y; // without delay
// camera.translation.y = camera.translation.y
// + (player.translation.y - camera.translation.y) * 3.0 * time.delta_secs(); // with delay
camera.translation.y = player.translation.y - CAMERAE_OFFSET;
}
fn reset_camera(mut main_camera: Single<&mut Camera, With<MainCamera>>) {
@@ -29,8 +23,7 @@ pub struct CameraPlugin;
impl Plugin for CameraPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, spawn_main_camera)
.add_systems(OnEnter(GameState::InGame), reset_camera)
app.add_systems(OnEnter(GameState::InGame), reset_camera)
.add_systems(
Update,
follow_player
+10 -1
View File
@@ -1,11 +1,13 @@
use bevy::{prelude::*, window::PresentMode};
use crate::config::{SCREEN_HEIGHT, SCREEN_WIDTH};
use crate::debug::DebugPlugin;
use crate::gameplay::bounds::BoundsPlugin;
use crate::gameplay::camera::CameraPlugin;
use crate::gameplay::collision::CollisionPlugin;
use crate::gameplay::player::PlayerPlugin;
use crate::gameplay::score::ScorePlugin;
use crate::screen::ScreenPlugin;
use crate::states::GameStatePlugin;
use crate::states::game_over::GameOverPlugin;
use crate::states::main_menu::MainMenuPlugin;
@@ -14,6 +16,7 @@ use crate::world::WorldPlugin;
mod config;
mod debug;
mod gameplay;
mod screen;
mod states;
mod world;
@@ -22,13 +25,19 @@ fn main() {
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Down Into The Void".into(),
resolution: (1920, 1080).into(),
resolution: (SCREEN_WIDTH as u32, SCREEN_HEIGHT as u32).into(),
present_mode: PresentMode::AutoVsync,
resize_constraints: WindowResizeConstraints {
min_width: 360.0,
min_height: 480.0,
..default()
},
..default()
}),
..default()
}))
.add_plugins(PlayerPlugin) // Player
.add_plugins(ScreenPlugin) // Virtual screen
.add_plugins(CameraPlugin) // Camera
.add_plugins(CollisionPlugin) // Collisions
.add_plugins(BoundsPlugin) // Bound player
+81
View File
@@ -0,0 +1,81 @@
use bevy::camera::RenderTarget;
use bevy::camera::visibility::RenderLayers;
use bevy::prelude::*;
use bevy::render::render_resource::TextureFormat;
use crate::config::{SCREEN_ASPECT, SCREEN_HEIGHT, SCREEN_WIDTH};
use crate::gameplay::camera::MainCamera;
#[derive(Component)]
pub struct DisplayScreen;
#[derive(Component)]
pub struct DisplayImage;
fn spawn_virtual_screen(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
let game_image = images.add(Image::new_target_texture(
SCREEN_WIDTH as u32,
SCREEN_HEIGHT as u32,
TextureFormat::Rgba8Unorm,
Some(TextureFormat::Rgba8UnormSrgb),
));
commands.spawn((
Camera2d,
MainCamera,
IsDefaultUiCamera,
Camera {
order: -1,
clear_color: Color::BLACK.into(),
..default()
},
RenderTarget::Image(game_image.clone().into()),
));
commands.spawn((
DisplayScreen,
Camera2d,
Camera {
order: 0,
clear_color: Color::BLACK.into(),
..default()
},
RenderLayers::layer(1),
));
commands.spawn((
DisplayImage,
Sprite::from_image(game_image),
Transform::default(),
RenderLayers::layer(1),
));
}
fn fit_display_screen(
window: Single<&Window>,
mut sprite: Single<&mut Sprite, With<DisplayImage>>,
) {
let scale_factor = window.scale_factor();
let win = Vec2::new(
window.physical_width() as f32 / scale_factor,
window.physical_height() as f32 / scale_factor,
);
let size = if win.x / win.y > SCREEN_ASPECT {
Vec2::new(win.y * SCREEN_ASPECT, win.y)
} else {
Vec2::new(win.x, win.x / SCREEN_ASPECT)
};
sprite.custom_size = Some(size);
}
pub struct ScreenPlugin;
impl Plugin for ScreenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, spawn_virtual_screen)
.add_systems(Update, fit_display_screen);
}
}
-1
View File
@@ -63,7 +63,6 @@ fn game_over_input(
next_state.set(GameState::InGame);
} else if input.just_pressed(KeyCode::KeyT) {
// Return to the Main Menu
run_seed.0 = rand::random::<u64>();
next_state.set(GameState::MainMenu);
}
}
+15 -14
View File
@@ -1,16 +1,20 @@
use bevy::prelude::*;
use crate::{
config::{CHUNK_HEIGHT, MARGIN_ABOVE, MARGIN_BELLOW},
config::{
CAMERAE_OFFSET, CHUNK_HEIGHT, MARGIN_ABOVE, MARGIN_BELLOW, SCREEN_HEIGHT, SCREEN_WIDTH,
},
gameplay::{camera::MainCamera, player::Player},
states::GameState,
};
pub mod background;
pub mod doors;
pub mod generator;
pub mod grid;
pub mod obstacle;
pub mod rng;
pub mod validator;
#[derive(Component)]
pub struct Chunk {
@@ -24,15 +28,9 @@ fn stream_world(
player: Single<&Transform, With<Player>>,
entities: Query<(Entity, &Chunk)>,
mut commands: Commands,
camera: Single<&Camera, With<MainCamera>>,
run_seed: Res<RunSeed>,
) {
let (min_id, max_id) = visible_chunk_range(
player.translation.y,
camera
.logical_viewport_size()
.unwrap_or(Vec2::new(1920.0, 1080.0))
.y,
);
let (min_id, max_id) = visible_chunk_range(player.translation.y);
let existing_ids: Vec<i64> = entities.iter().map(|(_, chunk)| chunk.id).collect();
@@ -45,21 +43,24 @@ fn stream_world(
for id in min_id..=max_id {
if !existing_ids.contains(&id) {
spawn_chunk(&mut commands, id);
spawn_chunk(&mut commands, id, run_seed.0);
}
}
}
// Bounds of chunk's ids to be generated
fn visible_chunk_range(player_y: f32, camera_y: f32) -> (i64, i64) {
fn visible_chunk_range(player_y: f32) -> (i64, i64) {
let bottom = player_y - CAMERAE_OFFSET - SCREEN_HEIGHT / 2.0 - MARGIN_BELLOW;
let top = player_y - CAMERAE_OFFSET + SCREEN_HEIGHT / 2.0 + MARGIN_ABOVE;
(
((player_y - camera_y / 2.0 - MARGIN_BELLOW) / CHUNK_HEIGHT).floor() as i64,
((player_y + camera_y / 2.0 + MARGIN_ABOVE) / CHUNK_HEIGHT).floor() as i64,
(bottom / CHUNK_HEIGHT).floor() as i64,
(top / CHUNK_HEIGHT).floor() as i64,
)
}
fn spawn_chunk(commands: &mut Commands, id: i64) {
fn spawn_chunk(commands: &mut Commands, id: i64, run_seed: u64) {
crate::world::background::spawn_background_chunk(commands, id);
crate::world::obstacle::spawn_obstacle_chunk(commands, id, run_seed);
}
fn cleanup_chunk(mut commands: Commands, entities: Query<Entity, With<Chunk>>) {
+2 -2
View File
@@ -4,7 +4,7 @@ use crate::{config::TERRAIN_COLS, world::rng::SplitMix64, world::rng::derive};
const SALT_DOOR: u64 = 1;
const DOOR_HALF_WIDTH: i32 = 6;
const DOOR_HALF_WIDTH: i32 = 4;
const DOOR_MIN_WIDTH: i32 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -43,7 +43,7 @@ pub fn door(seed: u64, k: i64) -> Option<Door> {
let center =
DOOR_HALF_WIDTH + (rng.next_u64() % (TERRAIN_COLS - 2 * DOOR_HALF_WIDTH) as u64) as i32;
let min_col = center - width / 2;
let min_col = (center - width / 2).clamp(1, TERRAIN_COLS - 1 - width);
Some(Door {
min_col,
max_col: min_col + width - 1,
+335
View File
@@ -0,0 +1,335 @@
use crate::{
config::TERRAIN_COLS,
world::{
doors::{Door, door},
grid::GridRect,
rng::{SplitMix64, derive},
validator::validate,
},
};
const SALT_WALLS: u64 = 2;
const SALT_VARIANT: u64 = 3;
const MIN_WALLS: i32 = 3;
const MAX_WALLS: i32 = 5;
const MAX_ATTEMPTS: i32 = 16;
const FIRST_WALL_ROW: i32 = 26;
const MIN_BOTTOM_ROW: i32 = 4;
const HOLE_MIN_WIDTH: i32 = 2;
const HOLE_MAX_WIDTH: i32 = 10;
const SECOND_HOLE_GAP: i32 = 2;
const THICK_HEIGHT: i32 = 2;
const GAP_VARIANTS: u64 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GapVariant {
Classic,
Double,
Thick,
Staircase,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChunkData {
pub rects: Vec<GridRect>,
}
pub fn generate_chunk(seed: u64, depth: i64) -> ChunkData {
match try_generate(seed, depth) {
Some(chunk) => chunk,
None => fallback_chunk(seed, depth),
}
}
pub fn try_generate(seed: u64, depth: i64) -> Option<ChunkData> {
let bottom_door = door(seed, depth)?;
let top_door = door(seed, depth - 1)?;
let v = gap_variant(seed, depth);
let mut rng = SplitMix64::new(derive(seed, depth, SALT_WALLS));
for _ in 0..MAX_ATTEMPTS {
let n_walls = MIN_WALLS + (rng.next_u64() % ((MAX_WALLS - MIN_WALLS + 1) as u64)) as i32;
let rects = build_gapwalls(v, top_door, bottom_door, n_walls, &mut rng);
if validate(&rects, bottom_door, top_door) {
return Some(ChunkData { rects });
}
}
None
}
fn gap_variant(seed: u64, depth: i64) -> GapVariant {
match derive(seed, depth, SALT_VARIANT) % GAP_VARIANTS {
1 => GapVariant::Double,
2 => GapVariant::Thick,
3 => GapVariant::Staircase,
_ => GapVariant::Classic,
}
}
fn build_gapwalls(
v: GapVariant,
top: Door,
bottom: Door,
n_walls: i32,
rng: &mut SplitMix64,
) -> Vec<GridRect> {
match v {
GapVariant::Classic => classic(top, bottom, n_walls, rng),
GapVariant::Double => double(top, bottom, n_walls, rng),
GapVariant::Thick => thick(top, bottom, n_walls, rng),
GapVariant::Staircase => staircase(top, bottom, n_walls),
}
}
fn classic(top: Door, bottom: Door, n_walls: i32, rng: &mut SplitMix64) -> Vec<GridRect> {
let (t, b) = centers(top, bottom);
let mut rects = Vec::new();
for i in 0..n_walls {
let mut c = lerp(t, b, i, n_walls);
if i < n_walls - 1 {
c += jitter(rng);
}
let h = hole(c, width(bottom, n_walls, i));
emit(&mut rects, wall_row(i, n_walls), 1, &[h]);
}
rects
}
fn double(top: Door, bottom: Door, n_walls: i32, rng: &mut SplitMix64) -> Vec<GridRect> {
let (t, b) = centers(top, bottom);
let mut rects = Vec::new();
for i in 0..n_walls {
let mut c = lerp(t, b, i, n_walls);
if i < n_walls - 1 {
c += jitter(rng);
}
let main = hole(c, width(bottom, n_walls, i));
// Narrow risky hole, SECOND_HOLE_GAP columns of wall away
let side = (rng.next_u64() % 2) as i32 * 2 - 1; // -1 or +1
let (sec_min, sec_max) = if side < 0 {
(main.0 - SECOND_HOLE_GAP - 1, main.0 - SECOND_HOLE_GAP)
} else {
(main.1 + SECOND_HOLE_GAP, main.1 + SECOND_HOLE_GAP + 1)
};
let mut holes = vec![main];
if side < 0 {
if sec_min >= 0 {
holes.insert(0, (sec_min, sec_max));
}
} else if sec_max < TERRAIN_COLS {
holes.push((sec_min, sec_max));
}
emit(&mut rects, wall_row(i, n_walls), 1, &holes);
}
rects
}
fn thick(top: Door, bottom: Door, n_walls: i32, rng: &mut SplitMix64) -> Vec<GridRect> {
let (t, b) = centers(top, bottom);
let mut rects = Vec::new();
for i in 0..n_walls {
let mut c = lerp(t, b, i, n_walls);
if i < n_walls - 1 {
c += jitter(rng);
}
let h = hole(c, width(bottom, n_walls, i));
emit(&mut rects, wall_row(i, n_walls), THICK_HEIGHT, &[h]);
}
rects
}
fn staircase(top: Door, bottom: Door, n_walls: i32) -> Vec<GridRect> {
let (t, b) = centers(top, bottom);
let step = ((b - t) / (n_walls - 1) as f32).round();
let mut rects = Vec::new();
for i in 0..n_walls {
let c = t + step * i as f32;
let h = hole(c, width(bottom, n_walls, i));
emit(&mut rects, wall_row(i, n_walls), 1, &[h]);
}
rects
}
fn centers(top: Door, bottom: Door) -> (f32, f32) {
(
(top.min_col + top.max_col) as f32 * 0.5,
(bottom.min_col + bottom.max_col) as f32 * 0.5,
)
}
fn lerp(t: f32, b: f32, i: i32, n: i32) -> f32 {
t + (b - t) * (i as f32 / (n - 1) as f32)
}
fn jitter(rng: &mut SplitMix64) -> f32 {
(rng.next_u64() % 3) as f32 - 1.0 // -1..=1 column
}
fn width(bottom: Door, n: i32, i: i32) -> i32 {
(bottom.width() + n - 1 - i).clamp(HOLE_MIN_WIDTH, HOLE_MAX_WIDTH)
}
fn hole(center: f32, w: i32) -> (i32, i32) {
let min = ((center - w as f32 * 0.5).round() as i32).clamp(0, TERRAIN_COLS - w);
(min, min + w - 1)
}
fn wall_spacing(n: i32) -> i32 {
(FIRST_WALL_ROW - MIN_BOTTOM_ROW) / (n - 1)
}
fn wall_row(i: i32, n: i32) -> i32 {
FIRST_WALL_ROW - i * wall_spacing(n)
}
fn emit(rects: &mut Vec<GridRect>, row: i32, height: i32, holes: &[(i32, i32)]) {
let mut cursor = 0;
for &(h_min, h_max) in holes {
if h_max < 0 || h_min >= TERRAIN_COLS {
continue;
}
let h_min = h_min.max(0);
let h_max = h_max.min(TERRAIN_COLS - 1);
if h_min > cursor {
rects.push(GridRect {
col: cursor,
row,
width: h_min - cursor,
height,
});
}
cursor = cursor.max(h_max + 1);
}
if cursor < TERRAIN_COLS {
rects.push(GridRect {
col: cursor,
row,
width: TERRAIN_COLS - cursor,
height,
});
}
}
fn fallback_chunk(seed: u64, depth: i64) -> ChunkData {
let Some(bottom_door) = door(seed, depth) else {
return ChunkData { rects: Vec::new() };
};
let mut rects = Vec::new();
emit(
&mut rects,
8,
1,
&[(bottom_door.min_col, bottom_door.max_col)],
);
ChunkData { rects }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::CHUNK_ROWS;
#[test]
fn fallback_rate_is_below_one_percent() {
const SEEDS: u64 = 10_000;
const CHUNKS_PER_SEED: i64 = 200;
let mut fallbacks: u64 = 0;
let mut total: u64 = 0;
for seed in 0..SEEDS {
for depth in 2..=2 + CHUNKS_PER_SEED {
if try_generate(seed, depth).is_none() {
fallbacks += 1;
}
total += 1;
}
}
let rate = fallbacks as f64 / total as f64;
assert!(
rate < 0.01,
"fallback rate {:.2}% too high ({} fallbacks over {} chunks)",
rate * 100.0,
fallbacks,
total
);
}
#[test]
fn every_generated_chunk_is_playable() {
const SEEDS: u64 = 10_000;
const CHUNKS_PER_SEED: i64 = 200;
for seed in 0..SEEDS {
for depth in 2..=2 + CHUNKS_PER_SEED {
let chunk = generate_chunk(seed, depth);
let bottom = door(seed, depth).unwrap();
let top = door(seed, depth - 1).unwrap();
assert!(
validate(&chunk.rects, bottom, top),
"seed {} depth {} is not playable",
seed,
depth
);
}
}
}
#[test]
fn generation_is_deterministic() {
for seed in 0..100 {
for depth in 2..=100 {
let a = generate_chunk(seed, depth);
let b = generate_chunk(seed, depth);
assert_eq!(a, b, "seed {} depth {} is not deterministic", seed, depth);
}
}
}
#[test]
fn every_rect_stays_inside_the_chunk() {
for seed in 0..200 {
for depth in 2..=120 {
for r in &generate_chunk(seed, depth).rects {
assert!(r.width > 0 && r.height > 0, "empty rect {:?}", r);
assert!(r.col >= 0 && r.col + r.width <= TERRAIN_COLS, "col {:?}", r);
assert!(r.row >= 0 && r.row + r.height <= CHUNK_ROWS, "row {:?}", r);
}
}
}
}
#[test]
fn every_variant_appears() {
let (mut classic, mut double, mut thick, mut stair) = (0, 0, 0, 0);
for seed in 0..200u64 {
for depth in 2..=120i64 {
match gap_variant(seed, depth) {
GapVariant::Classic => classic += 1,
GapVariant::Double => double += 1,
GapVariant::Thick => thick += 1,
GapVariant::Staircase => stair += 1,
}
}
}
assert!(classic > 0 && double > 0 && thick > 0 && stair > 0);
}
}
+37
View File
@@ -1,4 +1,41 @@
use bevy::prelude::*;
use crate::{
gameplay::collision::Collider,
world::{
Chunk,
generator::generate_chunk,
grid::{GridRect, grid_to_world},
},
};
// const OBSTACLE_COLOR: Color = Color::srgb(0.1, 0.7, 0.3);
const DEBUG_OBSTACLE_COLOR: Color = Color::srgba(0.0, 1.0, 0.0, 0.7);
#[derive(Component)]
pub struct Obstacle;
pub fn spawn_obstacle_chunk(commands: &mut Commands, id: i64, run_seed: u64) {
if id >= -1 {
return;
}
let depth = -id;
let data = generate_chunk(run_seed, depth);
for rect in data.rects {
spawn_rect(commands, id, rect);
}
}
fn spawn_rect(commands: &mut Commands, id: i64, rect: GridRect) {
let (center, size) = grid_to_world(id, rect);
commands.spawn((
Chunk { id },
Obstacle,
// Collider { size },
Sprite::from_color(DEBUG_OBSTACLE_COLOR, size),
Transform::from_xyz(center.x, center.y, 0.5),
));
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Pseudo random générator SplitMix64
// Pseudo random generator SplitMix64
pub const GENERATOR_VERSION: u32 = 1;
+105
View File
@@ -0,0 +1,105 @@
use crate::config::{
CELL_SIZE, CHUNK_ROWS, DESIGN_SLOPE_COLS_PER_ROW, HALF_TERRAIN_WIDTH, INERTIA_MARGIN,
PLAYER_HITBOX, TERRAIN_COLS,
};
use crate::world::{doors::Door, grid::GridRect};
const INFLATE_X: f32 = PLAYER_HITBOX.x / 2.0 + INERTIA_MARGIN;
const INFLATE_Y: f32 = PLAYER_HITBOX.y / 2.0 + INERTIA_MARGIN;
const EXPAND_PER_ROW: f32 = DESIGN_SLOPE_COLS_PER_ROW * CELL_SIZE;
fn door_px(door: Door) -> (f32, f32) {
let offset = TERRAIN_COLS as f32 / 2.0;
(
(door.min_col as f32 - offset) * CELL_SIZE,
(door.max_col as f32 + 1.0 - offset) * CELL_SIZE,
)
}
fn free_intervals(rects: &[GridRect], row: i32) -> Vec<(f32, f32)> {
let row_y0 = row as f32 * CELL_SIZE;
let row_y1 = row_y0 + CELL_SIZE;
let mut blocked: Vec<(f32, f32)> = Vec::new();
for r in rects {
let y0 = r.row as f32 * CELL_SIZE - INFLATE_Y;
let y1 = (r.row + r.height) as f32 * CELL_SIZE + INFLATE_Y;
if y1 <= row_y0 || y0 >= row_y1 {
continue;
}
let offset = TERRAIN_COLS as f32 / 2.0;
let x0 = (r.col as f32 - offset) * CELL_SIZE - INFLATE_X;
let x1 = ((r.col + r.width) as f32 - offset) * CELL_SIZE + INFLATE_X;
blocked.push((x0, x1));
}
blocked = merge(blocked);
let mut free: Vec<(f32, f32)> = vec![(
-HALF_TERRAIN_WIDTH + INFLATE_X,
HALF_TERRAIN_WIDTH - INFLATE_X,
)];
for (a, b) in &blocked {
free = subtract_all(&free, *a, *b);
}
free
}
pub fn validate(rects: &[GridRect], entry: Door, exit: Door) -> bool {
let mut safe: Vec<(f32, f32)> = vec![door_px(exit)];
for row in (0..CHUNK_ROWS).rev() {
let free = free_intervals(rects, row);
let mut next: Vec<(f32, f32)> = Vec::new();
for f in &free {
for (a, b) in &safe {
if let Some((i0, i1)) = intersect((a - EXPAND_PER_ROW, b + EXPAND_PER_ROW), *f) {
next.push((i0, i1));
}
}
}
safe = merge(next);
if safe.is_empty() {
return false;
}
}
let e = door_px(entry);
safe.iter().any(|(a, b)| *a <= e.0 && e.1 <= *b)
}
fn intersect((a0, a1): (f32, f32), (b0, b1): (f32, f32)) -> Option<(f32, f32)> {
let lo = a0.max(b0);
let hi = a1.min(b1);
(lo < hi).then_some((lo, hi))
}
fn merge(mut list: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
list.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut out: Vec<(f32, f32)> = Vec::new();
for (a, b) in list {
match out.last_mut() {
Some(last) if a <= last.1 => last.1 = last.1.max(b),
_ => out.push((a, b)),
}
}
out
}
fn subtract_all(free: &[(f32, f32)], a: f32, b: f32) -> Vec<(f32, f32)> {
let mut out = Vec::new();
for (x0, x1) in free {
if b <= *x0 || a >= *x1 {
out.push((*x0, *x1));
} else {
if a > *x0 {
out.push((*x0, a));
}
if b < *x1 {
out.push((b, *x1));
}
}
}
out
}