Adding visibility system

This commit is contained in:
Benjamyn Love 2022-10-30 21:59:10 +11:00
parent fa2d7b8e9e
commit b56eaac0a2
5 changed files with 225 additions and 134 deletions

View File

@ -18,3 +18,9 @@ pub struct Renderable {
#[derive(Component, Debug)] #[derive(Component, Debug)]
pub struct Player {} pub struct Player {}
#[derive(Component)]
pub struct Viewshed {
pub visible_tiles : Vec<rltk::Point>,
pub range : i32
}

View File

@ -13,12 +13,17 @@ pub use player::*;
mod rect; mod rect;
pub use rect::Rect; pub use rect::Rect;
mod visibility_system;
pub use visibility_system::*;
pub struct State { pub struct State {
pub ecs: World, pub ecs: World,
} }
impl State { impl State {
fn run_systems(&mut self) { fn run_systems(&mut self) {
let mut vis = VisibilitySystem{};
vis.run_now(&self.ecs);
self.ecs.maintain(); self.ecs.maintain();
} }
} }
@ -27,11 +32,11 @@ impl GameState for State {
fn tick(&mut self, ctx: &mut Rltk) { fn tick(&mut self, ctx: &mut Rltk) {
ctx.cls(); ctx.cls();
self.run_systems();
player_input(self, ctx); player_input(self, ctx);
self.run_systems();
let map = self.ecs.fetch::<Vec<TileType>>(); // let map = self.ecs.fetch::<Map>();
draw_map(&map, ctx); draw_map(&self.ecs, ctx);
let positions = self.ecs.read_storage::<Position>(); let positions = self.ecs.read_storage::<Position>();
let renderables = self.ecs.read_storage::<Renderable>(); let renderables = self.ecs.read_storage::<Renderable>();
@ -51,10 +56,12 @@ fn main() -> rltk::BError {
gs.ecs.register::<Position>(); gs.ecs.register::<Position>();
gs.ecs.register::<Renderable>(); gs.ecs.register::<Renderable>();
gs.ecs.register::<Player>(); gs.ecs.register::<Player>();
gs.ecs.register::<Viewshed>();
let (rooms, map) = new_map_rooms_and_corridors(); let map = Map::new_map_rooms_and_corridors();
let (player_x, player_y) = map.rooms[0].center();
gs.ecs.insert(map); gs.ecs.insert(map);
let (player_x, player_y) = rooms[0].center();
gs.ecs gs.ecs
.create_entity() .create_entity()
@ -68,8 +75,10 @@ fn main() -> rltk::BError {
bg: RGB::named(rltk::BLACK), bg: RGB::named(rltk::BLACK),
}) })
.with(Player {}) .with(Player {})
.with(Viewshed{ visible_tiles : Vec::new(), range : 8})
.build(); .build();
// Main loop runner // Main loop runner
rltk::main_loop(context, gs) rltk::main_loop(context, gs)
} }

View File

@ -1,6 +1,9 @@
use super::Rect; use crate::Viewshed;
use rltk::{RandomNumberGenerator, Rltk, RGB};
use std::cmp::{max, min}; use super::{Rect, Player};
use rltk::{RandomNumberGenerator, Rltk, RGB, Algorithm2D, Point, BaseMap};
use std::{cmp::{max, min}};
use specs::prelude::*;
#[derive(PartialEq, Copy, Clone)] #[derive(PartialEq, Copy, Clone)]
pub enum TileType { pub enum TileType {
@ -8,40 +11,53 @@ pub enum TileType {
Floor, Floor,
} }
pub fn xy_idx(x: i32, y: i32) -> usize { pub struct Map {
pub tiles : Vec::<TileType>,
pub rooms : Vec::<Rect>,
pub width : i32,
pub height : i32
}
impl Map {
pub fn xy_idx(&self, x: i32, y: i32) -> usize {
(y as usize * 80) + x as usize (y as usize * 80) + x as usize
} }
/// Makes a map with solid boundaries and 400 randomly placed walls, this is bad
pub fn new_map_test() -> Vec<TileType> {
let mut map = vec![TileType::Floor; 80 * 50];
for x in 0..80 { pub fn apply_room_to_map(&mut self, room: &Rect) {
map[xy_idx(x, 0)] = TileType::Wall; for y in room.y1 + 1..=room.y2 {
map[xy_idx(x, 49)] = TileType::Wall; for x in room.x1 + 1..=room.x2 {
let idx = self.xy_idx(x, y);
self.tiles[idx] = TileType::Floor;
} }
for y in 0..50 {
map[xy_idx(0, y)] = TileType::Wall;
map[xy_idx(79, y)] = TileType::Wall;
}
let mut rng = rltk::RandomNumberGenerator::new();
for _i in 0..400 {
let x = rng.roll_dice(1, 79);
let y = rng.roll_dice(1, 49);
let idx = xy_idx(x, y);
if idx != xy_idx(40, 25) {
map[idx] = TileType::Wall;
} }
} }
map fn apply_horizontal_tunnel(&mut self, x1: i32, x2: i32, y: i32) {
for x in min(x1, x2)..=max(x1, x2) {
let idx = self.xy_idx(x, y);
if idx > 0 && idx < self.width as usize * self.height as usize {
self.tiles[idx as usize] = TileType::Floor;
}
}
} }
pub fn new_map_rooms_and_corridors() -> (Vec<Rect>, Vec<TileType>) { fn apply_vertical_tunnel(&mut self, y1: i32, y2: i32, x: i32) {
let mut map = vec![TileType::Wall; 80 * 50]; for y in min(y1, y2)..=max(y1, y2) {
let idx = self.xy_idx(x, y);
if idx > 0 && idx < self.width as usize * self.height as usize {
self.tiles[idx as usize] = TileType::Floor;
}
}
}
pub fn new_map_rooms_and_corridors() -> Map {
let mut map = Map{
tiles : vec![TileType::Wall; 80*50],
rooms : Vec::new(),
width : 80,
height : 50
};
let mut rooms: Vec<Rect> = Vec::new();
const MAX_ROOMS: i32 = 30; const MAX_ROOMS: i32 = 30;
const MIN_SIZE: i32 = 6; const MIN_SIZE: i32 = 6;
const MAX_SIZE: i32 = 10; const MAX_SIZE: i32 = 10;
@ -51,65 +67,91 @@ pub fn new_map_rooms_and_corridors() -> (Vec<Rect>, Vec<TileType>) {
for _ in 0..MAX_ROOMS { for _ in 0..MAX_ROOMS {
let w = rng.range(MIN_SIZE, MAX_SIZE); let w = rng.range(MIN_SIZE, MAX_SIZE);
let h = rng.range(MIN_SIZE, MAX_SIZE); let h = rng.range(MIN_SIZE, MAX_SIZE);
let x = rng.roll_dice(1, 80 - w - 1) - 1; let x = rng.roll_dice(1, map.width - w - 1) - 1;
let y = rng.roll_dice(1, 50 - h - 1) - 1; let y = rng.roll_dice(1, map.height - h - 1) - 1;
let new_room = Rect::new(x, y, w, h); let new_room = Rect::new(x, y, w, h);
let mut ok = true; let mut ok = true;
for other_room in rooms.iter() { for other_room in map.rooms.iter() {
if new_room.intersect(other_room) { if new_room.intersect(other_room) {
ok = false ok = false
} }
} }
if ok { if ok {
apply_room_to_map(&new_room, &mut map); map.apply_room_to_map(&new_room);
if !rooms.is_empty() { if !map.rooms.is_empty() {
let (new_x, new_y) = new_room.center(); let (new_x, new_y) = new_room.center();
let (prev_x, prev_y) = rooms[rooms.len() - 1].center(); let (prev_x, prev_y) = map.rooms[map.rooms.len() - 1].center();
if rng.range(0, 2) == 1 { if rng.range(0, 2) == 1 {
apply_horizontal_tunnel(&mut map, prev_x, new_x, prev_y); map.apply_horizontal_tunnel(prev_x, new_x, prev_y);
apply_vertical_tunnel(&mut map, prev_y, new_y, new_x); map.apply_vertical_tunnel(prev_y, new_y, new_x);
} else { } else {
apply_vertical_tunnel(&mut map, prev_y, new_y, prev_x); map.apply_vertical_tunnel(prev_y, new_y, prev_x);
apply_horizontal_tunnel(&mut map, prev_x, new_x, new_y); map.apply_horizontal_tunnel(prev_x, new_x, new_y);
} }
} }
rooms.push(new_room); map.rooms.push(new_room);
} }
} }
(rooms, map) map
} }
pub fn apply_room_to_map(room: &Rect, map: &mut [TileType]) {
for y in room.y1 + 1..=room.y2 {
for x in room.x1 + 1..=room.x2 {
map[xy_idx(x, y)] = TileType::Floor;
} }
impl Algorithm2D for Map {
fn dimensions(&self) -> rltk::Point {
Point::new(self.width, self.height)
} }
} }
fn apply_horizontal_tunnel(map: &mut [TileType], x1: i32, x2: i32, y: i32) { impl BaseMap for Map {
for x in min(x1, x2)..=max(x1, x2) { fn is_opaque(&self, idx: usize) -> bool {
let idx = xy_idx(x, y); self.tiles[idx as usize] == TileType::Wall
if idx > 0 && idx < 80 * 50 {
map[idx as usize] = TileType::Floor;
}
} }
} }
fn apply_vertical_tunnel(map: &mut [TileType], y1: i32, y2: i32, x: i32) { // /// Makes a map with solid boundaries and 400 randomly placed walls, this is bad
for y in min(y1, y2)..=max(y1, y2) { // pub fn new_map_test() -> Vec<TileType> {
let idx = xy_idx(x, y); // let mut map = vec![TileType::Floor; 80 * 50];
if idx > 0 && idx < 80 * 50 {
map[idx as usize] = TileType::Floor;
}
}
}
pub fn draw_map(map: &[TileType], ctx: &mut Rltk) { // for x in 0..80 {
// map[xy_idx(x, 0)] = TileType::Wall;
// map[xy_idx(x, 49)] = TileType::Wall;
// }
// for y in 0..50 {
// map[xy_idx(0, y)] = TileType::Wall;
// map[xy_idx(79, y)] = TileType::Wall;
// }
// let mut rng = rltk::RandomNumberGenerator::new();
// for _i in 0..400 {
// let x = rng.roll_dice(1, 79);
// let y = rng.roll_dice(1, 49);
// let idx = xy_idx(x, y);
// if idx != xy_idx(40, 25) {
// map[idx] = TileType::Wall;
// }
// }
// map
// }
pub fn draw_map(ecs: &World, ctx: &mut Rltk) {
let mut viewsheds = ecs.write_storage::<Viewshed>();
let mut players = ecs.write_storage::<Player>();
let map = ecs.fetch::<Map>();
for (_player, viewshed) in (&mut players, &mut viewsheds).join() {
let mut y = 0; let mut y = 0;
let mut x = 0; let mut x = 0;
for tile in map.iter() { for tile in map.tiles.iter() {
let pt = Point::new(x,y);
if viewshed.visible_tiles.contains(&pt) {
match tile { match tile {
TileType::Floor => { TileType::Floor => {
ctx.set( ctx.set(
@ -130,7 +172,7 @@ pub fn draw_map(map: &[TileType], ctx: &mut Rltk) {
); );
} }
} }
}
x += 1; x += 1;
if x > 79 { if x > 79 {
x = 0; x = 0;
@ -138,3 +180,6 @@ pub fn draw_map(map: &[TileType], ctx: &mut Rltk) {
} }
} }
} }
}

View File

@ -1,16 +1,16 @@
use rltk::{VirtualKeyCode, Rltk}; use rltk::{VirtualKeyCode, Rltk};
use specs::prelude::*; use specs::prelude::*;
use super::{Position, Player, TileType, xy_idx, State}; use super::{Position, Player, TileType, Map, State};
use std::cmp::{min, max}; use std::cmp::{min, max};
pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) { pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
let mut positions = ecs.write_storage::<Position>(); let mut positions = ecs.write_storage::<Position>();
let mut players = ecs.write_storage::<Player>(); let mut players = ecs.write_storage::<Player>();
let map = ecs.fetch::<Vec<TileType>>(); let map = ecs.fetch::<Map>();
for (_player, pos) in (&mut players, &mut positions).join() { for (_player, pos) in (&mut players, &mut positions).join() {
let destination_idx = xy_idx(pos.x + delta_x, pos.y + delta_y); let destination_idx = map.xy_idx(pos.x + delta_x, pos.y + delta_y);
if map[destination_idx] != TileType::Wall { if map.tiles[destination_idx] != TileType::Wall {
pos.x = min(79, max(0, pos.x + delta_x)); pos.x = min(79, max(0, pos.x + delta_x));
pos.y = min(49, max(0, pos.y + delta_y)); pos.y = min(49, max(0, pos.y + delta_y));
} }
@ -21,10 +21,21 @@ pub fn player_input(gs: &mut State, ctx: &mut Rltk) {
match ctx.key { match ctx.key {
None => {} None => {}
Some(key) => match key { Some(key) => match key {
VirtualKeyCode::Left => try_move_player(-1, 0, &mut gs.ecs), VirtualKeyCode::Left |
VirtualKeyCode::Right => try_move_player(1, 0, &mut gs.ecs), VirtualKeyCode::Numpad4 |
VirtualKeyCode::Up => try_move_player(0, -1, &mut gs.ecs), VirtualKeyCode::H => try_move_player(-1, 0, &mut gs.ecs),
VirtualKeyCode::Down => try_move_player(0, 1, &mut gs.ecs),
VirtualKeyCode::Right |
VirtualKeyCode::Numpad6 |
VirtualKeyCode::L => try_move_player(1, 0, &mut gs.ecs),
VirtualKeyCode::Up |
VirtualKeyCode::Numpad8 |
VirtualKeyCode::K => try_move_player(0, -1, &mut gs.ecs),
VirtualKeyCode::Down |
VirtualKeyCode::Numpad2 |
VirtualKeyCode::J => try_move_player(0, 1, &mut gs.ecs),
_ => {} _ => {}
}, },
} }

20
src/visibility_system.rs Normal file
View File

@ -0,0 +1,20 @@
use specs::prelude::*;
use super::{Viewshed, Position, Map};
use rltk::{field_of_view, Point};
pub struct VisibilitySystem {}
impl<'a> System<'a> for VisibilitySystem {
type SystemData = ( ReadExpect<'a, Map>,
WriteStorage<'a, Viewshed>,
WriteStorage<'a, Position>);
fn run(&mut self, data : Self::SystemData) {
let (map, mut viewshed, pos) = data;
for (viewshed, pos) in (&mut viewshed, &pos).join() {
viewshed.visible_tiles.clear();
viewshed.visible_tiles = field_of_view(Point::new(pos.x, pos.y), viewshed.range, &*map);
viewshed.visible_tiles.retain(|p| p.x >= 0 && p.x < map.width && p.y >= 0 && p.y < map.height);
}
}
}