Display Modes

Handling Unsupported Display Modes

What happens if a player has a monitor that doesn't support the display mode our game wants to use?

Abstract art representing computer programming

SDL provides several layers of protection against this scenario. Let's look at how to handle unsupported display modes safely:

Using SDL_GetClosestDisplayMode()

The safest approach is to always use SDL_GetClosestDisplayMode() before setting a display mode. This function will find the closest supported mode:

#include <SDL.h>
#include <iostream>

int main(int argc, char* argv[]) {
  SDL_Init(SDL_INIT_VIDEO);

  // The mode we want to use
  SDL_DisplayMode Desired{
    0, 1920, 1080, 144, nullptr
  };
  SDL_DisplayMode Closest;

  // Find the closest supported mode
  if (SDL_GetClosestDisplayMode(
    0, &Desired, &Closest)) {
    std::cout << "Found mode: "
      << Closest.w << "x" << Closest.h << " @ "
      << Closest.refresh_rate << "Hz\n";
  } else {
    std::cout << "No compatible mode found\n";
  }

  SDL_Quit();
  return 0;
}
Found mode: 1920x1080 @ 144Hz

Error Handling

If we try to set an unsupported mode directly, SDL will return an error:

#include <SDL.h>
#include <iostream>

int main(int argc, char* argv[]) {
  SDL_Init(SDL_INIT_VIDEO);

  SDL_Window* Window{SDL_CreateWindow(
    "Window",
    SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED,
    800, 600, 0
  )};

  // Try to set an unsupported mode
  SDL_DisplayMode Unsupported{
    0, 99999, 99999, 0, nullptr
  }; 
  
  if (SDL_SetWindowDisplayMode(
    Window, &Unsupported
  ) < 0) {
    std::cout << "Error: " << SDL_GetError();
  }

  SDL_DestroyWindow(Window);
  SDL_Quit();
  return 0;
}

The best practice is to always validate display modes before attempting to use them, and have a fallback mode ready in case the preferred mode isn't available.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 71 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved