Plague-fx/src/save.c

84 lines
2.3 KiB
C

#include <gint/bfile.h>
#include <gint/defs/types.h>
#include <gint/std/stdlib.h>
#include "save.h"
// Name of the savefile
static const uint16_t *filename = u"\\\\fls0\\Plague.sav";
void read_save(struct game *current_game)
{
struct BFile_FileInfo fileInfo;
int fd, handle;
uint16_t foundpath[30];
// Sizes of data
const int planes_size = sizeof(*current_game->planes) * (NB_PLANES + 1);
struct plane *new_planes[NB_PLANES + 1];
for (int i = 0; i < NB_PLANES; i ++)
{
new_planes[i] = current_game->planes[i];
}
const int data_size = current_game->grid.width * current_game->grid.height;
uint8_t *data = current_game->grid.data;
// Check if the savefile exists
char checkfile = BFile_FindFirst(filename, &handle, foundpath, &fileInfo);
BFile_FindClose(handle);
// If file doesn't exists
if (checkfile == -1)
{
int size = sizeof(*current_game) + planes_size + data_size;
BFile_Create(filename, BFile_File, &size);
}
// Loading of the game data
else
{
fd = BFile_Open(filename, BFile_ReadOnly);
BFile_Read(fd, current_game, sizeof(*current_game), 0);
for (int i = 0; i < NB_PLANES; i ++)
{
current_game->planes[i] = new_planes[i];
}
for (int i = 0; i < NB_PLANES; i ++)
{
BFile_Read(fd, current_game->planes[i], sizeof(struct plane), -1);
}
BFile_Read(fd, data, data_size, -1);
BFile_Close(fd);
current_game->grid.data = data;
}
}
void write_save(const struct game *current_game)
{
// Open file
int fd = BFile_Open(filename, BFile_WriteOnly);
// Create a new savefile
const int data_size = current_game->grid.width * current_game->grid.height;
const int planes_size = NB_PLANES * sizeof(struct plane);
int size = sizeof(*current_game) + planes_size + data_size;
BFile_Remove(filename);
BFile_Create(filename, BFile_File, &size);
// Write data
BFile_Write(fd, current_game, sizeof(*current_game));
for (int i = 0; current_game->planes[i] ; i ++)
{
BFile_Write(fd, current_game->planes[i], sizeof(struct plane));
}
BFile_Write(fd, current_game->grid.data, data_size);
// Close file
BFile_Close(fd);
}