SDL window shows incorrectly. On linux terminal - c++

This is basically my code here, very simple just to load an image to display. But the first thing I open a window surface, the surface has characters like 'X','S' out of nowhere:
int main( int argc, char* args[] )
{
SDL_Init( SDL_INIT_VIDEO );
SDL_Surface* screen = SDL_SetVideoMode( WINDOW_WIDTH, WINDOW_HEIGHT, 0,
SDL_HWSURFACE | SDL_DOUBLEBUF );
SDL_WM_SetCaption( WINDOW_TITLE, 0 );
SDL_Surface* bitmap = SDL_LoadBMP("bat.bmp");
// Part of the bitmap that we want to draw
SDL_Rect source;
source.x = 24;
source.y = 63;
source.w = 65;
source.h = 44;
// Part of the screen we want to draw the sprite to
SDL_Rect destination;
destination.x = 100;
destination.y = 100;
destination.w = 65;
destination.h = 44;
SDL_Event event;
bool gameRunning = true;
int i=1000;
while (i)
{
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
gameRunning = false;
}
}
SDL_BlitSurface(bitmap, &source, screen, &destination);
SDL_Flip(screen);
i--;
}
SDL_FreeSurface(bitmap);
SDL_Quit();
return 0;
}

Related

How to load multiple images in SDL_image and SDL2?

I've been trying to load 2 images in a SDL window, like a player and an enemy, but SDL2_image loads only one image at a time
here's my code :
#include<iostream>
#define SDL_MAIN_HANDLED
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
using namespace std;
SDL_Texture* load(SDL_Renderer* ren, const char* path, SDL_Rect rect)
{
SDL_Texture* img = IMG_LoadTexture(ren, path);
if (img == NULL)
cout << SDL_GetError() << endl;
SDL_RenderClear(ren);
SDL_RenderCopy(ren, img, NULL, &rect);
SDL_RenderPresent(ren);
return img;
}
int main()
{
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
SDL_Window* window = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 460, 380, SDL_WINDOW_RESIZABLE);
SDL_Surface* icon = IMG_Load("sdl.png");
SDL_SetWindowIcon(window, icon);
SDL_Renderer* ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Rect rect,r2;
rect.x = 0; r2.x = 65;
rect.y = 0; r2.y = 80;
rect.w = 64; r2.w = 64;
rect.h = 64; r2.h = 64;
SDL_Texture* img = load(ren, "player.png", rect);
SDL_Delay(2000);
SDL_Texture* tex = load(ren, "enemy.png", r2);
SDL_Event events; bool running = true;
while (running == true)
{
if (SDL_PollEvent(&events))
{
if (events.type == SDL_QUIT)
{
running = false;
break;
}
}
}
IMG_Quit();
SDL_Quit();
return 0;
}
I used SDL_Delay to demonstrate what happens
it loads "player.png" first and then after 2 seconds, it loads "enemy.png"
I wanted to load both at the same time but I couldn't
Please help!
solved, it was due to SDL_RenderClear

How to use SDL_KeyCode to handle a key press each time?

I'm trying to generate a rectangle into a new position whenever I press the Right arrow key, I was able to get the 1st rectangle but now stuck at the 2nd one. As this is not a case of SDL_GetKeyboardState (to move the rectangle when key is pressed continuously), I'm completely clueless on how this should proceed. To create array for rectangles and pass it to poll event?
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
SDL_Window *window = NULL;
SDL_Surface *screen = NULL;
SDL_Renderer *renderer;
SDL_Event e;
SDL_Rect one, two;
bool quit = false;
void init(){
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Testing", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
screen = SDL_GetWindowSurface(window);
}
void draw(){
SDL_SetRenderDrawColor(renderer,255, 255, 255, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor( renderer, 255, 0, 0, 255);
SDL_RenderFillRect( renderer, &one);
SDL_SetRenderDrawColor( renderer, 0, 66, 255, 255);
SDL_RenderFillRect( renderer, &two);
SDL_RenderPresent(renderer);
}
void logic(){
Uint8 *state;
while (SDL_PollEvent(&e) !=0) {
if (e.type == SDL_KEYDOWN)
{
switch (e.key.keysym.sym)
{
case SDLK_RIGHT:
one = {2,2,124,124};
//two = {130,2,124,124};
break;
case SDLK_LEFT:
one = {0,0,0,0};
break;
}
}
else if (e.type == SDL_QUIT)
{
quit = true;
}
}
}
int main(int argc, char* args[]){
init();
while (!quit)
{
logic();
draw();
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
SDL_Quit();
return 0;
}

Preserving alpha when blitting

How can I preserve alpha values when blitting? I want to blit multiple black squares with various alpha values onto a surface and then blit that surface onto the screen. Everything I try just blits a solid opaque black surface.
Edit:
What I want is this:
What I'm getting is this:
The code
#include <SDL.h>
void putPixel(SDL_Surface *surface, int x, int y, Uint32 pixel){
Uint32 *pixels = (Uint32*)surface->pixels;
pixels[(y * surface->w) + x] = pixel;
}
void FillAlpha(SDL_Surface* Surface){
Uint32 Pixel;
Uint8 RGBA[4] = {0, 0, 0, 100};
Pixel = RGBA[3]<<24 | RGBA[2]<<16 | RGBA[1]<<8 | RGBA[0];
for(int x=0; x<32; x++){
for(int y=0; y<32; y++){
putPixel(Surface, x, y, Pixel);
}
}
RGBA[3] = 150;
Pixel = RGBA[3]<<24 | RGBA[2]<<16 | RGBA[1]<<8 | RGBA[0];
for(int x=32; x<64; x++){
for(int y=0; y<32; y++){
putPixel(Surface, x, y, Pixel);
}
}
}
int main(int argc, char* args[])
{
SDL_Window* Window = NULL;
SDL_Surface* Screen = NULL;
SDL_Surface* Alpha = NULL;
SDL_Event Event;
bool Quit = false;
Window = SDL_CreateWindow("Alpha test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 128, 128, SDL_WINDOW_SHOWN);
if(Window == NULL) return 1;
Screen = SDL_GetWindowSurface(Window);
if(Screen == NULL) return 2;
Alpha = SDL_CreateRGBSurface(NULL, 64, 32, 32,
Screen->format->Rmask, Screen->format->Gmask,
Screen->format->Bmask, Screen->format->Amask);
if(Alpha == NULL) return 3;
SDL_SetSurfaceBlendMode(Alpha, SDL_BLENDMODE_BLEND);
FillAlpha(Alpha);
while(!Quit){
while(SDL_PollEvent(&Event)){
if(Event.type == SDL_KEYDOWN){
if(Event.key.keysym.sym == SDLK_ESCAPE){
Quit = true;
}
}else if(Event.type == SDL_QUIT){
Quit = true;
}
}
SDL_FillRect(Screen, NULL, SDL_MapRGB(Screen->format, 255, 255, 255));
SDL_BlitSurface(Alpha, NULL, Screen, NULL);
SDL_UpdateWindowSurface(Window);
}
SDL_Quit();
return 0;
}

SDL2 Access violation multiple windows

I am developing SDL2 application which needs to have multiple windows on multiple monitors. And I am getting access violation when drawing string with SDL_ttf library. I should also mention that Application is opening windows in separate threads and is working ok if there is no SDL_ttf used.
I get this for exception when using SDL_ttf:
Unhandled exception at 0x0F2BC191 (SDL2.dll) in SDLMultipleWindows.exe: 0xC0000005: Access violation writing location 0x0100000C.
And access violation is happening in this function:
bool loadFromRenderedText( std::string textureText, SDL_Color textColor )
{
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
SDL_Texture * mTexture = NULL;
int w, h;
if( textSurface != NULL )
{
mTexture = SDL_CreateTextureFromSurface( renderer, textSurface );
w = textSurface->w;
h = textSurface->h;
SDL_FreeSurface( textSurface );
}
else
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
SDL_Rect renderQuad = { 250, 300, w, h };
int result = SDL_RenderCopyEx( renderer, mTexture, NULL, &renderQuad, 0.0, NULL, SDL_FLIP_NONE );
OutputDebugString(SDL_GetError());
return true;
}
Exception happens on SDL_CreateTextureFromSurface(renderer, textSurface);
This is stack trace from Visual studio:
SDL2.dll!SDL_malloc_REAL(unsigned int bytes) Line 4206 C
SDL2.dll!SDL_calloc_REAL(unsigned int n_elements, unsigned int elem_size) Line 4406 C
SDL2.dll!SDL_CreateRGBSurface_REAL(unsigned int flags, int width, int height, int depth, unsigned int Rmask, unsigned int Gmask, unsigned int Bmask, unsigned int Amask) Line 53 C
SDL2.dll!SDL_ConvertSurface_REAL(SDL_Surface * surface, const SDL_PixelFormat * format, unsigned int flags) Line 840 C
SDL2.dll!SDL_CreateTextureFromSurface_REAL(SDL_Renderer * renderer, SDL_Surface * surface) Line 536 C
SDL2.dll!SDL_CreateTextureFromSurface(SDL_Renderer * a, SDL_Surface * b) Line 342 C
SDLMultipleWindows.exe! loadFromRenderedText(std::basic_string<char,std::char_traits<char>,std::allocator<char> > textureText, SDL_Color textColor) Line 162 C++
Am I doing something wrong or SDL_ttf or SDL2 cannot work on multiple threads?
Is there another way to draw string in SDL2?
Thanks!
Edit:
Adding part of existing code:
ClientWindows::ClientWindows(void)
{
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
TTF_Init();
}
Tread function:
void ClientWindows::WindowThread(int i)
{
AppWindow* rWindow = new AppWindow(i * 1024, 0);
Windows.push_back(rWindow);
rWindow->InitScreen();
}
Start graphics function:
void ClientWindows::StartGraphics(int number)
{
for(int i= 0; i<number; i++)
{
std::thread* wTread = new std::thread(&ClientWindows::WindowThread,this , i);
Threads.push_back(wTread);
}
.
.
.
Client window Constructor:
AppWindow::AppWindow(int x, int y)
{
quit = false;
SCREEN_WIDTH = 1024;
SCREEN_HEIGHT = 768;
imagePositionX = 50;
imagePositionY = 50;
speed_x = 10;
speed_y = 10;
moveX = 10;
moveY = 10;
std::ostringstream convert;
convert << "Graphics";
convert << x;
string name = convert.str();
window = SDL_CreateWindow(name.c_str(), x,
y, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL);
if (window == nullptr){
std::cout << SDL_GetError() << std::endl;
}
opengl3_context = SDL_GL_CreateContext(window);
SDL_assert(opengl3_context);
mt.lock();
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
std::cout << SDL_GetError() << std::endl;
}
mt.unlock();
background = nullptr,image = nullptr;
background = SDLLoadImage("../res/Image1024x768.png");
image = SDLLoadImage("../res/Image1024Classic.png");
animeImage = SDLLoadImage("../res/32_80x80.png");
gFont = TTF_OpenFont("../res/sample.ttf", 28);
}
Client window startGraphics function:
void AppWindow::InitScreen(void)
{
Clear();
Render();
Present();
//Init fps
countedFrames = 0;
fpsTimer.start();
//For tracking if we want to quit
Uint32 frameRate = 0;
while (!quit)
{
if (fpsTimer.getTicks() > frameRate + 15)
{
frameRate = fpsTimer.getTicks();
Clear();
Render();
Present();
}
SDL_Delay(5);
}
}
Function in question:
bool AppWindow::loadFromRenderedText(std::string textureText, SDL_Color textColor)
{
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
SDL_Texture * mTexture = NULL;
int w, h;
if( textSurface != NULL )
{
mTexture = SDL_CreateTextureFromSurface( renderer, textSurface );
w = textSurface->w;
h = textSurface->h;
SDL_FreeSurface( textSurface );
}
else
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
SDL_Rect renderQuad = { 250, 300, w, h };
int result = SDL_RenderCopyEx( renderer, mTexture, NULL, &renderQuad, 0.0, NULL, SDL_FLIP_NONE );
OutputDebugString(SDL_GetError());
return true;
}
You can't use SDL2 functions from other threads than the one in which the rendering context was created, SDL2 guarantees no thread safety for drawing functions.
If I recall correctly, the only thread safe part of SDL2 is pushing custom events to the event queue.
So I'm guessing the AccessViolation occurs because you're trying to use the renderering context from another thread than from on the one which it was created on.

SDL C++ Window Immediately Closes

#include "SDL/SDL.h"
#include "SDL/SDL_Image.h"
#include <string>
using namespace std;
//Const screen variables
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
const char* SCREEN_CAPTION = "Pyro";
const float GRAVITY = 9.8; //Metres per second **NEEDS TO BE ADJUSTED BECAUSE IT'S IN METRES, NOT PIXELS**
const int jumpHeight = 10;
//Non-Const variables
bool running = true;
bool isJumping = true;
int jump = 0;
int frame = 0;
int level = 1;
SDL_Event event;
Uint8 *keystate = NULL;
//SDL Surfaces
SDL_Surface *screen = NULL;
SDL_Surface *background = NULL;
SDL_Surface *sprite = NULL;
SDL_Surface *bEnemy[10];
//Structs
typedef struct entity {
int health;
int damage;
SDL_Rect hitbox;
bool evolved;
} playerType, enemyType;
playerType player;
enemyType basicEnemy[10];
//Functions
SDL_Surface *loadImage( std::string filename )
{
SDL_Surface *loadedImage = NULL;
SDL_Surface *optimizedImage = NULL;
loadedImage = IMG_Load( filename.c_str() );
if( loadedImage != NULL )
{
optimizedImage = SDL_DisplayFormatAlpha( loadedImage );
SDL_FreeSurface( loadedImage );
}
return optimizedImage;
}
void applySurface( int x, int y, SDL_Surface* source, SDL_Surface* location )
{
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface( source, NULL, location, &offset );
}
//Main Function
int main( int argc, char* argv[] )
{
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return 1;
}
screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
if( screen == NULL )
{
return 1;
}
SDL_WM_SetCaption( SCREEN_CAPTION, NULL );
background = loadImage( "images/background.png" );
sprite = loadImage( "images/player.png" );
SDL_FreeSurface( sprite );
SDL_FreeSurface( background );
while( running )
{
//Main game loop
if( SDL_PollEvent( &event ) )
{
switch( event.type )
{
case SDL_QUIT:
running = false;
break;
case SDL_KEYDOWN:
switch( event.key.keysym.sym )
{
case SDLK_q:
running = false;
break;
}
break;
}
}
keystate = SDL_GetKeyState(NULL);
if( keystate[SDLK_q] ) player.evolved = !player.evolved;
if( keystate[SDLK_UP] )
{
if(isJumping != true)
{
isJumping = true;
}
}
if( keystate[SDLK_LEFT] ) player.hitbox.x -= 1;
if( keystate[SDLK_RIGHT] ) player.hitbox.y += 1;
//Window collision
if( player.hitbox.x < 0 ) {player.hitbox.x = 0;}
else if( player.hitbox.x > SCREEN_WIDTH - player.hitbox.w ) {player.hitbox.x = SCREEN_WIDTH - player.hitbox.w;}
if( player.hitbox.y < 0 ) {player.hitbox.y = 0;}
else if( player.hitbox.y > SCREEN_HEIGHT - player.hitbox.h ) {player.hitbox.y = SCREEN_HEIGHT - player.hitbox.h;}
//Jumping
if( isJumping == true )
{
if(jump >= jumpHeight)
{
jump--;
player.hitbox.y++;
}else {
jump++;
player.hitbox.y--;
}
}
//Updating the screen
applySurface( 0, 0, background, screen );
applySurface( player.hitbox.x, player.hitbox.y, sprite, screen );
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
}
SDL_Quit();
return 0;
}
^ That is the exact code I have. When I run the file it immediately closes. It is compiled with: g++ -o myprogram.exe mysource.cpp -lmingw32 -lSDLmain -lSDL -lSDL_image -static-libgcc -static-libstdc++.
The files I have linked to do exist; they are currently placeholders (background is some random png image I found, and the player is an image of 8-bit mario).
How do I stop my program from closing immediately?
SDL_FreeSurface( sprite );
SDL_FreeSurface( background );
This is where your problem lies.
These lines should appear at the end of the program right before you call SDL_Quit().
Currently, you're blitting freed surfaces onto the window.