Vote count:
0
I am trying to write a simple program with the help of SDL. This program loads in an SDL_Texture, and renders it to the window. However, upon starting my program it immediately quits. I am using VS Express 2013 with SDL2 and SDL2_image libraries added to the project. What can be the problem? Thanks in advance!
#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <string>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
bool init();
bool loadMedia();
void close();
// Loads individual image as texture
SDL_Texture* loadTexture(std::string);
SDL_Event event;
SDL_Window* gWindow = NULL;
// The window renderes
SDL_Renderer* gRenderer = NULL;
// Current displayed texture
SDL_Texture* gTexture = NULL;
int main(int argc, char* args[])
{
if (!init())
{
std::cout << "An error has occured while initializing the window: " << SDL_GetError();
return 1;
}
if (loadMedia() == NULL)
{
std::cout << "Could not load media!";
return 1;
}
bool quit = false;
// main game loop
while (!quit)
{
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
quit = true;
break;
}
}
// Clear screen
SDL_RenderClear(gRenderer);
// Render texture to screen
SDL_RenderCopy(gRenderer, gTexture, NULL, NULL);
SDL_RenderPresent(gRenderer);
}
close();
return 0;
}
bool init()
{
//initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) == -1)
{
std::cout << "SDL could not initialize! Error: " << SDL_GetError();
return false;
}
// Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
std::cout << "Warning: Linear texture filtering not enabled!";
//create window
gWindow = SDL_CreateWindow("Hello World", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == NULL)
return false;
// Hardware accelerated renderer
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
if (gRenderer == NULL)
return false;
// Initialize renderer color
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if(!(IMG_Init(imgFlags ) & imgFlags))
{
std::cout << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError();
return false;
}
return true;
}
bool loadMedia()
{
gTexture = loadTexture("texture.png");
if (gTexture == NULL)
{
std::cout << "Failed to load texture image!!";
return false;
}
return true;
}
SDL_Texture* loadTexture(std::string path)
{
SDL_Texture* newTexture = NULL;
// Load an image from a specific path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL)
{
std::cout << "Error while loading surface: " << IMG_GetError();
return newTexture;
}
newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
SDL_FreeSurface(loadedSurface);
loadedSurface = NULL;
return newTexture;
}
void close()
{
SDL_DestroyTexture(gTexture);
SDL_DestroyWindow(gWindow);
IMG_Quit();
SDL_Quit();
}
asked 44 secs ago
Aucun commentaire:
Enregistrer un commentaire