Let's create a system to manage persistent brightness settings. We'll use a simple file-based approach, but you could adapt this to use your game's existing save system:
#include <SDL.h>
#include <filesystem>
#include <fstream>
#include <iostream>
class BrightnessSettings {
SDL_Window* Window;
std::string SettingsPath;
float DefaultBrightness{1.0f};
struct Settings {
float Brightness{1.0f};
float GammaRed{1.0f};
float GammaGreen{1.0f};
float GammaBlue{1.0f};
} Current;
public:
BrightnessSettings(
SDL_Window* W,const std::string& SavePath
) : Window{W},
SettingsPath{SavePath + "/display.cfg"} {
LoadSettings();
ApplySettings();
}
void SaveSettings() {
try {
// Ensure directory exists
std::filesystem::create_directories(
std::filesystem::path{SettingsPath}.
parent_path());
std::ofstream File{
SettingsPath, std::ios::binary};
if (!File) {
std::cout <<
"Failed to save settings\n";
return;
}
File.write(
reinterpret_cast<char*>(&Current),
sizeof(Settings));
std::cout << "Settings saved\n";
}
catch (const std::exception& E) {
std::cout << "Error saving settings: "
<< E.what() << '\n';
}
}
void SetBrightness(float NewBrightness) {
Current.Brightness = NewBrightness;
SDL_SetWindowBrightness(
Window, NewBrightness);
}
void SetGamma(float Red, float Green,
float Blue) {
Current.GammaRed = Red;
Current.GammaGreen = Green;
Current.GammaBlue = Blue;
Uint16 RedRamp[256];
Uint16 GreenRamp[256];
Uint16 BlueRamp[256];
SDL_CalculateGammaRamp(Red, RedRamp);
SDL_CalculateGammaRamp(Green, GreenRamp);
SDL_CalculateGammaRamp(Blue, BlueRamp);
SDL_SetWindowGammaRamp(
Window, RedRamp, GreenRamp, BlueRamp);
}
private:
void LoadSettings() {
try {
std::ifstream File{
SettingsPath, std::ios::binary};
if (!File) {
std::cout << "Using default settings\n";
return;
}
File.read(
reinterpret_cast<char*>(&Current),
sizeof(Settings));
std::cout << "Settings loaded\n";
}
catch (const std::exception& E) {
std::cout << "Error loading settings: "
<< E.what() << '\n';
Current = Settings{}; // Use defaults
}
}
void ApplySettings() {
SetBrightness(Current.Brightness);
SetGamma(Current.GammaRed,
Current.GammaGreen,
Current.GammaBlue);
}
};
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* Window{
SDL_CreateWindow("Settings Demo",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
800, 600,
SDL_WINDOW_SHOWN)};
BrightnessSettings Settings{
Window, "./saves"};
// Simulate user changing settings
Settings.SetBrightness(1.5f);
Settings.SetGamma(1.1f, 1.0f, 0.9f);
// Save changes
Settings.SaveSettings();
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
This system:
Consider adding:
Answers to questions are automatically generated and may not have been reviewed.
Learn how to control display brightness and gamma correction using SDL's window management functions