1
1
Fork 0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

115 lines
2.6 KiB

#include "controlscheme.h"
#include <SDL2/SDL_scancode.h>
#include <sys/stat.h>
struct InputMap input_map;
#define INPUT_MAP_ID 83921864
#define INPUT_MAP_VERSION 0
#define CONTROLS_FNAME "controls.bin"
/*
* Serialise controlscheme using simple (char *) cast. It is obviously not cross
* platform but it doesnt need to be. Takes a very tentative approach to error
* handling, if something is wrong it resets.
*
* There is no UI for setting controls yet.
*
*/
struct InputMap_Ser {
unsigned int id;
unsigned int ver;
size_t size;
struct InputMap input_map;
};
int load_controls(void);
void get_input_map(void) {
if (load_controls()) {
return;
}
input_map.player_down = SDL_SCANCODE_S;
input_map.player_up = SDL_SCANCODE_W;
input_map.player_right = SDL_SCANCODE_D;
input_map.player_left = SDL_SCANCODE_A;
input_map.player_rope = SDL_SCANCODE_E;
input_map.player_pull_rope = SDL_SCANCODE_Q;
input_map.mute = SDL_SCANCODE_M;
input_map.pause = SDL_SCANCODE_ESCAPE;
input_map.quit = SDL_SCANCODE_Q;
input_map.goto_level = SDL_SCANCODE_G;
input_map.high_contrast_mode = SDL_SCANCODE_H;
input_map.mouse_attach_rope_pull = SDL_BUTTON_LEFT;
input_map.mouse_attach_rope = SDL_BUTTON_RIGHT;
}
struct Buffer {
size_t len;
char *data;
};
struct Buffer read_whole_file(char const *file_name) {
struct stat sb;
struct Buffer b = {};
if (stat (file_name, & sb) != 0) {
return b;
}
char *buffer = malloc(sb.st_size + 1);
FILE *f = fopen(file_name, "r");
size_t bytes_read = fread(buffer, sizeof (unsigned char), sb.st_size, f);
if (bytes_read != sb.st_size) {
fclose(f);
free(buffer);
return b;
}
fclose(f);
b.data = buffer;
b.len = bytes_read;
return b;
}
int load_controls(void) {
struct Buffer b = read_whole_file(CONTROLS_FNAME);
if (b.len != sizeof (struct InputMap_Ser)) {
return 0;
}
struct InputMap_Ser *im = (struct InputMap_Ser *)b.data;
if (im->size != sizeof(struct InputMap_Ser))
return 0;
if (im->id != INPUT_MAP_ID)
return 0;
if (im->ver != INPUT_MAP_VERSION)
return 0;
memcpy(&input_map, &im->input_map, sizeof(struct InputMap));
return 1;
}
void save_controls(void) {
FILE *f = fopen(CONTROLS_FNAME, "w");
struct InputMap_Ser im;
im.id = INPUT_MAP_ID;
im.ver = INPUT_MAP_VERSION;
im.size = sizeof(struct InputMap_Ser);
im.input_map = input_map;
fwrite(&im, sizeof(unsigned char), sizeof(struct InputMap_Ser), f);
fclose(f);
}