Skip to content

Commit

Permalink
Added saving(Press K) and loading(Press L)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac8668 committed Jan 2, 2024
1 parent c90c82a commit 965d2ab
Show file tree
Hide file tree
Showing 8 changed files with 160 additions and 54 deletions.
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ async-channel = "2.1.0"
smallvec = "1.11.2"
itertools = "0.12.0"

serde = "1.0"
serde_derive = "1.0"
bincode = "1.3.3"
serde-big-array = "0.5.1"

# Enable a small amount of optimization in debug mode
[profile.dev]
opt-level = 1
Expand Down
9 changes: 7 additions & 2 deletions src/atom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,20 @@ use std::{collections::HashSet, f32::consts::PI};
use crate::prelude::*;

// TODO Make smaller
#[derive(Clone, Copy, Default, PartialEq, Debug)]
#[derive(Clone, Copy, Default, PartialEq, Debug, Serialize, Deserialize)]
pub struct Atom {
pub color: [u8; 4],
pub state: State,

#[serde(skip)]
pub updated_at: u8,
#[serde(skip)]
pub fall_speed: u8,
// Used when thrown up, etc
#[serde(skip)]
pub velocity: (i8, i8),
// Frames idle
#[serde(skip)]
pub f_idle: u8,
}

Expand All @@ -30,7 +35,7 @@ impl Atom {
}

// TODO Change this to a Material type
#[derive(Default, Clone, Copy, PartialEq, Debug)]
#[derive(Default, Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum State {
Solid,
Powder,
Expand Down
11 changes: 5 additions & 6 deletions src/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ use std::collections::HashSet;

use crate::prelude::*;

#[derive(Clone, Serialize, Deserialize)]
pub struct Chunk {
#[serde(with = "BigArray")]
pub atoms: [Atom; CHUNK_LEN],

#[serde(skip)]
pub texture: Handle<Image>,
pub index: IVec2,
}

impl Chunk {
Expand All @@ -30,11 +33,7 @@ impl Chunk {
}
}

Chunk {
atoms,
texture,
index,
}
Chunk { atoms, texture }
}

pub fn new_image() -> Image {
Expand Down
153 changes: 109 additions & 44 deletions src/chunk_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use crate::prelude::*;
pub struct ChunkManager {
pub chunks: HashMap<IVec2, Chunk>,
pub colliders: ChunkColliders,
pub textures_hmap: HashMap<AssetId<Image>, IVec2>,
pub dt: u8,
}

Expand Down Expand Up @@ -134,65 +133,36 @@ impl DirtyRects {
}
}

#[derive(Component)]
pub struct ChunkTextures;

pub fn manager_setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
let side_length = (CHUNK_LENGHT * ATOM_SIZE) as f32;
let (width, height) = (CHUNKS_WIDTH, CHUNKS_HEIGHT);

let mut images_vec = vec![];
let mut chunks = HashMap::new();
let mut textures_hmap = HashMap::new();
let mut chunk_manager = ChunkManager {
chunks: HashMap::new(),
colliders: ChunkColliders::new(),
dt: 0,
};

for (x, y) in (0..width).cartesian_product(0..height) {
let pos = Vec2::new(x as f32 * side_length, -(y as f32) * side_length);
let index = ivec2(x as i32, y as i32);
let chunk = Chunk::new(Handle::default(), index);

//Get and spawn texture/chunk image
let texture = images.add(Chunk::new_image());
images_vec.push(
commands
.spawn(SpriteBundle {
texture: texture.clone(),
sprite: Sprite {
anchor: Anchor::TopLeft,
..Default::default()
},
transform: Transform::from_xyz(pos.x, pos.y, 0.).with_scale(vec3(
ATOM_SIZE as f32,
ATOM_SIZE as f32,
1.,
)),
..Default::default()
})
.id(),
);

//Add texture to chunks manager HashMap
textures_hmap.insert(texture.id(), index);

//Create chunk
let chunk = Chunk::new(texture, index);

//Update chunk image
let image = images.get_mut(&chunk.texture).unwrap();
chunk.update_all(image);

chunks.insert(index, chunk);
let ent = add_chunk(&mut commands, &mut images, &mut chunk_manager, chunk, index);
images_vec.push(ent);
}

commands
.spawn((
Name::new("Chunks textures"),
VisibilityBundle::default(),
TransformBundle::default(),
ChunkTextures,
))
.push_children(&images_vec);

let chunk_manager = ChunkManager {
chunks,
colliders: ChunkColliders::new(),
dt: 0,
textures_hmap,
};

commands.spawn(DirtyRects {
current: HashMap::new(),
new: HashMap::new(),
Expand Down Expand Up @@ -510,11 +480,106 @@ fn prepare_chunk_gpu_textures(
}
}

pub fn save_to_file(chunk_manager: Query<&ChunkManager>, input: Res<Input<KeyCode>>) {
if input.just_pressed(KeyCode::K) {
let chunk_manager = chunk_manager.single();

let mut f = BufWriter::new(File::create("world").unwrap());
serialize_into(&mut f, &chunk_manager.chunks).unwrap();
}
}

pub fn load_from_file(
mut commands: Commands,
mut chunk_manager: Query<&mut ChunkManager>,
chunk_textures: Query<Entity, With<ChunkTextures>>,
input: Res<Input<KeyCode>>,
mut images: ResMut<Assets<Image>>,
) {
if input.just_pressed(KeyCode::L) {
let mut chunk_manager = chunk_manager.single_mut();
for chunk in chunk_manager.chunks.values() {
images.remove(chunk.texture.clone());
}
chunk_manager.chunks = HashMap::new();

chunk_manager.chunks = HashMap::new();
let file = File::open("world").unwrap();
let file_chunks: HashMap<IVec2, Chunk> =
bincode::deserialize_from(BufReader::new(file)).unwrap();

//Add new chunks to world
let mut images_vec = vec![];
for (pos, chunk) in &file_chunks {
let ent = add_chunk(
&mut commands,
&mut images,
&mut chunk_manager,
chunk.clone(),
*pos,
);
images_vec.push(ent);
}

//Clean current chunks

//Delete old and add new textures entities
let mut chunk_textures = commands.get_entity(chunk_textures.single()).unwrap();
chunk_textures
.clear_children()
.insert_children(0, &images_vec);
}
}

//Still needs to add the return entity to a parent
pub fn add_chunk(
commands: &mut Commands,
images: &mut ResMut<Assets<Image>>,
chunk_manager: &mut ChunkManager,
mut chunk: Chunk,
index: IVec2,
) -> Entity {
let pos = Vec2::new(
index.x as f32 * SIDE_LENGHT,
-(index.y as f32) * SIDE_LENGHT,
);

//Add texture
chunk.texture = images.add(Chunk::new_image());
let texture_copy = chunk.texture.clone();

//Update chunk image
let image = images.get_mut(&chunk.texture).unwrap();
chunk.update_all(image);
chunk_manager.chunks.insert(index, chunk);

//Spawn Image
commands
.spawn(SpriteBundle {
texture: texture_copy,
sprite: Sprite {
anchor: Anchor::TopLeft,
..Default::default()
},
transform: Transform::from_xyz(pos.x, pos.y, 0.).with_scale(vec3(
ATOM_SIZE as f32,
ATOM_SIZE as f32,
1.,
)),
..Default::default()
})
.id()
}

pub struct ChunkManagerPlugin;
impl Plugin for ChunkManagerPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, manager_setup)
.add_systems(Update, chunk_manager_update);
.add_systems(Update, chunk_manager_update)
.add_systems(
PreUpdate,
(save_to_file, load_from_file.after(save_to_file)),
);

if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
Expand Down
2 changes: 2 additions & 0 deletions src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ pub const CHUNK_LEN: usize = CHUNK_LENGHT * CHUNK_LENGHT;
pub const HALF_CHUNK_LEN: usize = CHUNK_LEN / 2;
pub const QUARTER_CHUNK_LEN: usize = CHUNK_LEN / 4;

pub const SIDE_LENGHT: f32 = (CHUNK_LENGHT * ATOM_SIZE) as f32;

// Actor consts

pub const UP_WALK_HEIGHT: usize = 3;
Expand Down
12 changes: 10 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,18 @@ mod prelude {
pub use bevy::input::mouse::MouseWheel;
pub use bevy::math::{ivec2, uvec2, vec2, vec3};
pub use bevy::prelude::*;

pub use bincode::serialize_into;
pub use serde::{Deserialize, Serialize};
pub use serde_big_array::BigArray;

pub use std::collections::{HashMap, HashSet};
pub use std::fs;
pub use std::fs::File;
pub use std::io::BufReader;
pub use std::io::BufWriter;
}

use crate::animation::AnimationPlugin;
use prelude::*;

fn main() {
Expand All @@ -36,7 +44,7 @@ fn main() {
//DebugPlugin,
ActorsPlugin,
PlayerPlugin,
AnimationPlugin,
animation::AnimationPlugin,
))
.add_systems(Startup, setup)
.run();
Expand Down
Binary file added world
Binary file not shown.

0 comments on commit 965d2ab

Please sign in to comment.