Compare commits

..

14 Commits

11 changed files with 292 additions and 52 deletions

View File

@ -10,6 +10,9 @@ keywords = ["game-engine", "smallgames", "pixel-art", "tracker-music"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
eframe = "^0.12.0"
egui = "^0.12.0"
epi = "^0.12.0"
env_logger = "0.8.3" env_logger = "0.8.3"
hex = "^0.4.3" hex = "^0.4.3"
image = "0.23.14" image = "0.23.14"

14
TODO.md
View File

@ -2,6 +2,11 @@
## game data structure ## game data structure
more colours? max 10? (0-9)
colours not in palette can use modulo
--
add "move" functions for entities add "move" functions for entities
e.g. move(direction), teleport e.g. move(direction), teleport
@ -30,6 +35,7 @@ idea:
* re-use player avatar drawing function as generic image drawing function * re-use player avatar drawing function as generic image drawing function
* text (how?) * text (how?)
* support older graphics adaptors * support older graphics adaptors
* player has some graphical tearing on non-integer window sizes
### windows ### windows
@ -54,3 +60,11 @@ will need:
* build something in egui * build something in egui
* can we do a web version that works with zip files? * can we do a web version that works with zip files?
* investigate zip compression/decompression in rust * investigate zip compression/decompression in rust
## documentation
where to find XMs?
https://modarchive.org/index.php?request=view_by_license&query=publicdomain etc.
keygenmusic.org?
pouet.net or something?

102
src/bin/editor.rs Normal file
View File

@ -0,0 +1,102 @@
use eframe::epi::Frame;
use eframe::egui::CtxRef;
use peachy::{Colour, Config, Game, Palette};
struct EditorState {
game: Option<peachy::Game>,
// selected_palette: Option<&Palette>,
}
impl epi::App for EditorState {
fn update(&mut self, ctx: &CtxRef, frame: &mut Frame<'_>) {
egui::TopPanel::top("top_panel").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
egui::menu::menu(ui, "File", |ui| {
if ui.button("Quit").clicked() {
frame.quit();
}
});
});
});
egui::SidePanel::left("side_panel", 200.0).show(ctx, |ui| {
ui.heading("Side Panel");
ui.horizontal(|ui| {
ui.label("Blah blah…");
});
// if let Some(game) = &mut self.game {
// // todo colour picker
// // todo tool picker
// // todo collapsing panels for different things? buttons to launch browse windows?
// }
});
egui::CentralPanel::default().show(ctx, |ui| {
// todo if game is none, add a "load project" window?
if let Some(game) = &mut self.game {
// for palette in &mut game.palettes {
// }
// todo store selected palette in application state
// todo show palette window if selected
let palette = game.find_palette("example palette".into());
if let Some(palette) = palette {
egui::Window::new(&palette.name)
.default_width(200.0)
.collapsible(false)
.show(ctx, |ui| {
ui.label("palette name");
ui.text_edit_singleline(&mut palette.name);
});
}
}
});
}
fn name(&self) -> &str {
"peachy"
}
}
fn main() {
// testing…
let state = EditorState {
game: Some(Game {
config: Config {
name: Some("example".into()),
width: 16,
height: 9,
tick: 400,
starting_room: None,
version: (0, 1)
},
entities: vec![],
images: vec![],
palettes: vec![
Palette { name: "example palette".into(), colours: vec![
Colour { red: 79, green: 30, blue: 69 },
Colour { red: 150, green: 48, blue: 87 },
Colour { red: 215, green: 68, blue: 89 },
Colour { red: 235, green: 112, blue: 96 },
Colour { red: 255, green: 179, blue: 131 },
Colour { red: 255, green: 255, blue: 255 },
Colour { red: 127, green: 227, blue: 187 },
Colour { red: 92, green: 187, blue: 196 },
Colour { red: 69, green: 126, blue: 163 },
Colour { red: 56, green: 66, blue: 118 },
Colour { red: 50, green: 36, blue: 81 }
]},
],
scenes: vec![],
tiles: vec![],
music: vec![]
})
};
let native_options = eframe::NativeOptions::default();
eframe::run_native(Box::new(state), native_options);
}

View File

@ -20,8 +20,6 @@ struct Image {
struct State { struct State {
game: Game, game: Game,
width: usize,
height: usize,
player_position: (u8, u8), player_position: (u8, u8),
player_avatar: Image, player_avatar: Image,
palette: [[u8; 4]; 4], palette: [[u8; 4]; 4],
@ -47,13 +45,13 @@ impl State {
screen[ screen[
( (
// player vertical offset (number of lines above) // player vertical offset (number of lines above)
(player_y as usize * 8 * (8 * self.width as usize)) (player_y as usize * 8 * (8 * self.game.config.width as usize))
+ +
// player horizontal offset; number of pixels to the left // player horizontal offset; number of pixels to the left
(player_x as usize * 8) (player_x as usize * 8)
+ +
// tile vertical offset; number of lines within tile // tile vertical offset; number of lines within tile
(tile_y as usize * (8 * self.width as usize)) (tile_y as usize * (8 * self.game.config.width as usize))
+ +
(tile_x as usize) // tile horizontal offset (tile_x as usize) // tile horizontal offset
) )
@ -78,8 +76,6 @@ fn main() -> Result<(), Error> {
let mut state = State { let mut state = State {
game, game,
width: 16,
height: 9,
player_position: (8, 4), player_position: (8, 4),
player_avatar: Image { pixels: [ player_avatar: Image { pixels: [
0,0,0,2,2,0,0,0, 0,0,0,2,2,0,0,0,
@ -240,6 +236,7 @@ fn main() -> Result<(), Error> {
fn window_builder(title: &str, event_loop: &EventLoop<()>) -> winit::window::Window { fn window_builder(title: &str, event_loop: &EventLoop<()>) -> winit::window::Window {
winit::window::WindowBuilder::new() winit::window::WindowBuilder::new()
.with_visible(false) .with_visible(false)
.with_resizable(false)
.with_title(title).build(&event_loop).unwrap() .with_title(title).build(&event_loop).unwrap()
} }
@ -250,6 +247,7 @@ fn window_builder(title: &str, event_loop: &EventLoop<()>) -> winit::window::Win
winit::window::WindowBuilder::new() winit::window::WindowBuilder::new()
.with_drag_and_drop(false) .with_drag_and_drop(false)
.with_visible(false) .with_visible(false)
.with_resizable(false)
.with_title(title).build(&event_loop).unwrap() .with_title(title).build(&event_loop).unwrap()
} }
@ -292,12 +290,12 @@ fn create_window(
LogicalSize::new(width * scale, height * scale); LogicalSize::new(width * scale, height * scale);
let center = LogicalPosition::new( let center = LogicalPosition::new(
(monitor_width - width * scale) / 2.0, (monitor_width - width * scale) / 2.0,
(monitor_height - height * scale) / 2.0, (monitor_height - height * scale) / 2.0,
); );
window.set_inner_size(default_size); window.set_inner_size(default_size);
window.set_min_inner_size(Some(min_size)); // window.set_min_inner_size(Some(min_size));
window.set_outer_position(center); window.set_outer_position(center);
window.set_visible(true); window.set_visible(true);

View File

@ -1,5 +1,7 @@
use std::fmt; use std::fmt;
use image;
use image::Rgba;
use serde_derive::{Serialize, Deserialize}; use serde_derive::{Serialize, Deserialize};
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
@ -37,6 +39,18 @@ impl Into<Vec<u8>> for Colour {
} }
} }
impl Into<image::Rgba<u8>> for Colour {
fn into(self) -> Rgba<u8> {
Rgba::from([self.red, self.green, self.blue, 255])
}
}
impl Into<[u8; 4]> for Colour {
fn into(self) -> [u8; 4] {
[self.red, self.green, self.blue, 255]
}
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::Colour; use crate::Colour;

View File

@ -1,6 +1,8 @@
use std::path::PathBuf; use std::path::PathBuf;
use serde_derive::{Serialize, Deserialize}; use serde_derive::{Serialize, Deserialize};
use std::fs::read_to_string; use std::fs::read_to_string;
use image::{DynamicImage, ImageBuffer};
use crate::Palette;
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Image { pub struct Image {
@ -21,6 +23,16 @@ impl Image {
Self { name, pixels } Self { name, pixels }
} }
fn into_image(self, palette: &Palette) -> DynamicImage {
let mut buffer: Vec<u8> = Vec::new();
for pixel in self.pixels {
buffer.append(&mut palette.get_colour_rgba8(&pixel));
}
DynamicImage::ImageRgba8(ImageBuffer::from_raw(8, 8, buffer).unwrap())
}
} }
#[cfg(test)] #[cfg(test)]
@ -35,4 +47,16 @@ mod test {
let expected = crate::mock::image::avatar(); let expected = crate::mock::image::avatar();
assert_eq!(output, expected); assert_eq!(output, expected);
} }
#[test]
fn image_to_dynamic_image() {
let palette = &crate::mock::palette::default();
let output = crate::mock::image::avatar().into_image(palette);
let expected = image::io::Reader::open(
"src/test-resources/images/avatar.png"
).unwrap().decode().unwrap();
assert_eq!(output, expected);
}
} }

View File

@ -26,6 +26,12 @@ pub struct Position {
y: u8, y: u8,
} }
impl Position {
pub fn to_index(&self, width: u8) -> u16 {
(self.y * width + self.x) as u16
}
}
// #[derive(Serialize, Deserialize)] // #[derive(Serialize, Deserialize)]
// pub enum DataType { // pub enum DataType {
// Image, // Image,
@ -100,10 +106,11 @@ pub struct Position {
pub struct Game { pub struct Game {
pub config: Config, pub config: Config,
pub palettes: Vec<Palette>,
pub images: Vec<Image>,
pub tiles: Vec<Tile>,
pub entities: Vec<Entity>, pub entities: Vec<Entity>,
pub images: Vec<Image>,
pub palettes: Vec<Palette>,
pub scenes: Vec<Scene>,
pub tiles: Vec<Tile>,
// pub variables: Vec<Variable>, // pub variables: Vec<Variable>,
// pub triggers: HashMap<String, ScriptCollection>, // pub triggers: HashMap<String, ScriptCollection>,
pub music: Vec<Music>, pub music: Vec<Music>,
@ -113,12 +120,32 @@ pub struct Game {
pub struct GameParseError; pub struct GameParseError;
impl Game { impl Game {
pub fn new() -> Self {
Self {
config: Config {
name: None,
width: 16,
height: 9,
tick: 400,
starting_room: None,
version: (0, 1)
},
entities: vec![],
images: vec![],
palettes: vec![],
scenes: vec![],
tiles: vec![],
music: vec![]
}
}
pub fn from_dir(path: PathBuf) -> Result<Game, GameParseError> { pub fn from_dir(path: PathBuf) -> Result<Game, GameParseError> {
let mut images = Vec::new(); let mut images = Vec::new();
let mut tiles = Vec::new(); let mut tiles = Vec::new();
let mut entities = Vec::new(); let mut entities = Vec::new();
let mut music = Vec::new(); let mut music = Vec::new();
let mut palettes = Vec::new(); let mut palettes = Vec::new();
let mut scenes = Vec::new();
let mut music_dir = path.clone(); let mut music_dir = path.clone();
music_dir.push("music"); music_dir.push("music");
@ -176,6 +203,17 @@ impl Game {
entities.push(Entity::from_file(file.path())); entities.push(Entity::from_file(file.path()));
} }
let mut scenes_dir = path.clone();
scenes_dir.push("scenes");
let scenes_files = scenes_dir.read_dir()
.expect("couldn't read scene dir");
for file in scenes_files {
let file = file.unwrap();
scenes.push(Scene::from_file(file.path()));
}
let mut game_config = path.clone(); let mut game_config = path.clone();
game_config.push("game.toml"); game_config.push("game.toml");
let config = fs::read_to_string(game_config) let config = fs::read_to_string(game_config)
@ -183,7 +221,7 @@ impl Game {
let config: Config = toml::from_str(&config) let config: Config = toml::from_str(&config)
.expect("Couldn't parse game config"); .expect("Couldn't parse game config");
Ok(Game { config, images, tiles, palettes, music, entities }) Ok(Game { config, images, tiles, palettes, music, entities, scenes })
} }
// todo Result<&Image>? // todo Result<&Image>?
@ -213,7 +251,7 @@ impl Game {
pub fn get_entity_by_name(&self, name: String) -> Option<&Entity> { pub fn get_entity_by_name(&self, name: String) -> Option<&Entity> {
for entity in self.entities.iter() { for entity in self.entities.iter() {
if entity.name == name { if entity.name == name {
return Some(&entity); return Some(entity);
} }
} }
@ -224,7 +262,7 @@ impl Game {
pub fn get_music_by_name(&self, name: String) -> Option<&Music> { pub fn get_music_by_name(&self, name: String) -> Option<&Music> {
for music in self.music.iter() { for music in self.music.iter() {
if music.name == name { if music.name == name {
return Some(&music); return Some(music);
} }
} }
@ -232,10 +270,10 @@ impl Game {
} }
// todo Result<&Palette>? // todo Result<&Palette>?
pub fn get_palette_by_name(&self, name: String) -> Option<&Palette> { pub fn find_palette(&mut self, name: &str) -> Option<&mut Palette> {
for palette in self.palettes.iter() { for palette in self.palettes.iter_mut() {
if palette.name == name { if palette.name == name {
return Some(&palette); return Some(palette);
} }
} }
@ -246,10 +284,48 @@ impl Game {
pub fn get_tile_by_name(&self, name: String) -> Option<&Tile> { pub fn get_tile_by_name(&self, name: String) -> Option<&Tile> {
for tile in self.tiles.iter() { for tile in self.tiles.iter() {
if tile.name == name { if tile.name == name {
return Some(&tile); return Some(tile);
} }
} }
None None
} }
pub fn get_scene_by_name(&mut self, name: String) -> Option<&mut Scene> {
for scene in self.scenes.iter_mut() {
if scene.name == name {
return Some(scene);
}
}
None
}
pub fn remove_entity(&mut self, scene_name: String, position: Position) {
let width = self.config.width.clone();
self.get_scene_by_name(scene_name).unwrap()
.foreground[position.to_index(width) as usize] = None;
}
}
#[cfg(test)]
mod test {
use crate::{Position, Game};
#[test]
fn position_to_index() {
assert_eq!(Position { x: 1, y: 5 }.to_index(8), 41);
assert_eq!(Position { x: 0, y: 0 }.to_index(8), 0);
}
#[test]
fn remove_entity() {
let mut game = Game::new();
game.scenes.push(crate::mock::scenes::zero());
game.remove_entity("zero".into(), Position { x: 1, y: 1 });
assert_eq!(game.scenes[0].foreground[9], None);
}
} }

View File

@ -1,7 +1,7 @@
pub(crate) mod image { pub(crate) mod image {
use crate::image::Image; use crate::image::Image;
pub fn bg() -> Image { pub fn _bg() -> Image {
Image { Image {
name: "bg".to_string(), name: "bg".to_string(),
pixels: vec![ pixels: vec![
@ -17,7 +17,7 @@ pub(crate) mod image {
} }
} }
pub fn block() -> Image { pub fn _block() -> Image {
Image { Image {
name: "block".to_string(), name: "block".to_string(),
pixels: vec![ pixels: vec![
@ -49,7 +49,7 @@ pub(crate) mod image {
} }
} }
pub fn cat() -> Image { pub fn _cat() -> Image {
Image { Image {
name: "cat".to_string(), name: "cat".to_string(),
pixels: vec![ pixels: vec![
@ -73,10 +73,9 @@ pub(crate) mod palette {
Palette { Palette {
name: "blueprint".to_string(), name: "blueprint".to_string(),
colours: vec![ colours: vec![
Colour { red: 0, green: 0, blue: 0 }, Colour { red: 0, green: 82, blue: 204 },
Colour { red: 0, green: 81, blue: 104 }, Colour { red: 128, green: 159, blue: 255 },
Colour { red: 118, green: 159, blue: 155 }, Colour { red: 255, green: 255, blue: 255 },
Colour { red: 155, green: 155, blue: 155 },
], ],
} }
} }

View File

@ -13,7 +13,24 @@ pub struct Palette {
} }
impl Palette { impl Palette {
/// todo result /// if trying to get an out-of-bounds index, colours will wrap around
/// so if palette has 8 colours (0-7) and index is 8, will return 0
pub fn get_colour(&self, index: &u8) -> Option<&Colour> {
self.colours.get((index % self.colours.len() as u8) as usize)
}
/// colour 0 is transparent
pub fn get_colour_rgba8(&self, index: &u8) -> Vec<u8> {
match index {
0 => vec![0,0,0,0],
_ => {
let colour = self.get_colour(index).unwrap();
vec![colour.red, colour.green, colour.blue, 255]
}
}
}
/// todo Result<Palette>
pub fn from_file(path: PathBuf) -> Self { pub fn from_file(path: PathBuf) -> Self {
match path.extension().unwrap().to_str().unwrap() { match path.extension().unwrap().to_str().unwrap() {
"gpl" => Self::from_gpl(path), "gpl" => Self::from_gpl(path),
@ -84,8 +101,11 @@ impl Palette {
) )
}).collect(); }).collect();
// todo re-insert original comments // todo fix palette description? does it matter?
format!("GIMP Palette\r\n{}\r\n", colours.join("\r\n")) format!(
"GIMP Palette\r\n#Palette Name: {}\r\n#Colors: {}\r\n{}\r\n",
self.name, colours.len(), colours.join("\r\n")
)
} }
/// Paint.net .txt format /// Paint.net .txt format
@ -157,6 +177,7 @@ impl Palette {
Self { name, colours } Self { name, colours }
} }
/// todo maybe this should be Into<DynamicImage>
pub fn to_png(&self) -> DynamicImage { pub fn to_png(&self) -> DynamicImage {
let mut image = DynamicImage::new_rgb8( let mut image = DynamicImage::new_rgb8(
self.colours.len() as u32, 1 as u32 self.colours.len() as u32, 1 as u32
@ -174,29 +195,13 @@ impl Palette {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::path::PathBuf; use std::path::PathBuf;
use crate::{Colour, Palette}; use crate::Palette;
#[test] #[test]
fn palette_from_jasc() { fn palette_from_jasc() {
let path = PathBuf::from("src/test-resources/basic/palettes/soup11.pal"); let path = PathBuf::from("src/test-resources/palettes/soup11.pal");
let output = Palette::from_jasc(path); let output = Palette::from_jasc(path);
let expected = crate::mock::palette::soup11();
let expected = Palette {
name: "soup11".into(),
colours: vec![
Colour { red: 79, green: 30, blue: 69 },
Colour { red: 150, green: 48, blue: 87 },
Colour { red: 215, green: 68, blue: 89 },
Colour { red: 235, green: 112, blue: 96 },
Colour { red: 255, green: 179, blue: 131 },
Colour { red: 255, green: 255, blue: 255 },
Colour { red: 127, green: 227, blue: 187 },
Colour { red: 92, green: 187, blue: 196 },
Colour { red: 69, green: 126, blue: 163 },
Colour { red: 56, green: 66, blue: 118 },
Colour { red: 50, green: 36, blue: 81 }
]
};
assert_eq!(output, expected); assert_eq!(output, expected);
} }
@ -210,7 +215,7 @@ mod test {
#[test] #[test]
fn palette_from_gpl() { fn palette_from_gpl() {
let path = PathBuf::from("src/test-resources/basic/palettes/soup11.gpl"); let path = PathBuf::from("src/test-resources/palettes/soup11.gpl");
let output = Palette::from_gpl(path); let output = Palette::from_gpl(path);
let expected = crate::mock::palette::soup11(); let expected = crate::mock::palette::soup11();
@ -227,7 +232,7 @@ mod test {
#[test] #[test]
fn palette_from_txt() { fn palette_from_txt() {
let path = PathBuf::from("src/test-resources/basic/palettes/soup11.txt"); let path = PathBuf::from("src/test-resources/palettes/soup11.txt");
let output = Palette::from_txt(path); let output = Palette::from_txt(path);
let expected = crate::mock::palette::soup11(); let expected = crate::mock::palette::soup11();
assert_eq!(output, expected); assert_eq!(output, expected);
@ -243,7 +248,7 @@ mod test {
#[test] #[test]
fn palette_from_hex() { fn palette_from_hex() {
let path = PathBuf::from("src/test-resources/basic/palettes/soup11.hex"); let path = PathBuf::from("src/test-resources/palettes/soup11.hex");
let output = Palette::from_hex(path); let output = Palette::from_hex(path);
let expected = crate::mock::palette::soup11(); let expected = crate::mock::palette::soup11();
assert_eq!(output, expected); assert_eq!(output, expected);
@ -258,7 +263,7 @@ mod test {
#[test] #[test]
fn palette_from_png() { fn palette_from_png() {
let path = PathBuf::from("src/test-resources/basic/palettes/soup11.png"); let path = PathBuf::from("src/test-resources/palettes/soup11.png");
let output = Palette::from_png(path); let output = Palette::from_png(path);
let expected = crate::mock::palette::soup11(); let expected = crate::mock::palette::soup11();
assert_eq!(output, expected); assert_eq!(output, expected);
@ -269,7 +274,7 @@ mod test {
use image::io::Reader as ImageReader; use image::io::Reader as ImageReader;
let output = crate::mock::palette::soup11().to_png(); let output = crate::mock::palette::soup11().to_png();
let path = PathBuf::from("src/test-resources/basic/palettes/soup11.png"); let path = PathBuf::from("src/test-resources/palettes/soup11.png");
let expected = ImageReader::open(path).unwrap().decode().unwrap(); let expected = ImageReader::open(path).unwrap().decode().unwrap();
assert_eq!(output, expected); assert_eq!(output, expected);
} }

View File

@ -1,6 +1,7 @@
use std::fs::read_to_string; use std::fs::read_to_string;
use std::path::PathBuf; use std::path::PathBuf;
use serde_derive::{Serialize, Deserialize}; use serde_derive::{Serialize, Deserialize};
use crate::Position;
#[derive(Debug, Eq, PartialEq)] #[derive(Debug, Eq, PartialEq)]
pub struct Scene { pub struct Scene {
@ -36,6 +37,10 @@ impl Scene {
Self { name, background, foreground } Self { name, background, foreground }
} }
pub fn set_tile(_position: Position, _new: String) {
todo!();
}
} }
/// scene name is derived from the filename, /// scene name is derived from the filename,

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 B