C++ program memory usage keeps increasing when using SDL_TTF - c++

I am doing my code for a simple game using SDL library. I have 2 questions regarding this:
If I don't put a breakpoint and let the program runs by itself, the memory usage going high (like 20-30x compared to the beginning). However, if I stop the loop (main loop of the game) and click by myself, the memory usage stay same after around 100 clicks(?). Why?
So I decided to use instrument to analyze the reason why since I think in the loop I might adding new element without destroying it. And everytime I hit record in Instrument, the app goes on for 5 seconds and shutdowns with a crash report (The app runs perfectly, with the memory stuff, in xcode)
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 org.libsdl.SDL2 0x0000000100f5bea9 0x100ee9000 + 470697
1 Spike 10 0x0000000100ea40cc imageTexture::render() + 50 (imageTexture.cpp:37)
2 Spike 10 0x0000000100ea2b70 GUI::renderImage() + 40 (GUI.cpp:140)
3 Spike 10 0x0000000100ea30b2 GUI::run() + 1258 (GUI.cpp:172)
4 Spike 10 0x0000000100ea439e main + 36 (main.cpp:15)
5 libdyld.dylib 0x00007fff8c60f5ad start + 1
These are some codes that I think might related:
For number 3: //imageVector is just a vector contain all the imageVector pointer
SDL_RenderClear( gRenderer );
for (int i = 0; i < imageVector.size(); i++) {
imageVector[i]->render();
}
For number 2:
//set rendering space and render to screen
SDL_Rect temp = {x, y, width, height};
//render to the screen
SDL_RenderCopy(gRenderer, texture, NULL, &temp);
After a long try disable/enable code around to find what happen, I still have no idea what's wrong.
This is my current loop:
while (true) {
textVector[0]->setInput(system->output());
renderImage();
renderText();
SDL_RenderPresent( gRenderer );
}
Some code for it:
void textTexture::setInput(std::string newText) {
gText = newText;
}
void GUI::renderImage() {
SDL_RenderClear( gRenderer );
for (int i = 0; i < imageVector.size(); i++) {
imageVector[i]->render();
}
}
void GUI::renderText() {
for (int i = 0; i < textVector.size(); i++) {
textVector[i]->render();
}
}
void textTexture::render() {
//set rendering space and render to screen
SDL_Rect temp = {x, y, width, height};
//recreate the texture
createTextureFromRenderedText(gText);
//render to the screen
SDL_RenderCopy(gRenderer, texture, NULL, &temp);
}
void textTexture::createTextureFromRenderedText(std::string text) {
if (text != "") {
SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(gFont, text.c_str(), textColor, 600);
if( textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
else
{
//Create texture from surface pixels
texture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
if( texture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
else
{
//Get image dimensions
width = textSurface->w;
height = textSurface->h;
}
//Get rid of old surface
SDL_FreeSurface( textSurface );
}
}
}

Find the problem. I copy the style of lazyfoo and try to implement in mine so when I render new textTexture, it actually create new texture without destroying it. By using SDL_DestroyTexture, everything works fine
Found the answer here:
https://stackoverflow.com/questions/24938695/memory-leak-sdl-while-using-sdl-createtexturefromsurface

Related

SIGSEGV Segmentation Fault when dereferencing a pointer

I'm aware that there are several similar questions to this one already, but I've read through them and none of them seem to cover my specific problem...
I'm trying to dereference a public pointer from a struct, but it's throwing a SIGSEV Segmentation fault, even though the pointer does point to a value
It prints 1 & 2 but does not get any further. If I change it to reference the pointer rather than the value, the error moves to wherever I reference the value, so I know the issue is with dereferencing, not the rest of the line.
If you need to see any more of my code in order to find the issue, just ask. I just didn't want to make you trawl through hundreds of lines unnecesarily...
#include <vector>
#include "Entities.cpp"
struct Chunk {
public:
std::vector<BaseEntity>* environment; // this is what I'm trying to access
Chunk() {
environment = new std::vector<BaseEntity>(1); // this is where init
environment->push_back(Grass()); // adding something to it works fine
}
~Chunk() {
delete(environment);
}
};
class World {
public:
Chunk* loaded[3][3];
World() {
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++) {
loaded[x][y] = new Chunk();
}
}
~World() {
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++) {
delete(loaded[x][y]);
}
}
};
And here's the code that accesses it (in another class & file)
void render(SDL_Renderer* gRenderer, Atlas* atlas, World* world, int SCREEN_WIDTH, int SCREEN_HEIGHT) {
printf("1");
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++) {
printf("2");
std::vector<BaseEntity> env =
*(world->loaded[x][y]->environment); // here is where the error occurs
printf("3");
printf('0' + env.size() + "");
printf("a");
for (const auto& a : env) {
printf("b");
drawTexture(gRenderer, atlas, a.atlasID,
SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2);
}
printf("4");
}
printf("5");
}
This is the code that calls it:
int main(int argv, char** args) {
SDL_Init( SDL_INIT_VIDEO );
//The window we'll be rendering to
SDL_Window* gWindow = SDL_CreateWindow(
title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if (gWindow == NULL) {
printf("window error");
}
//Create renderer for window
SDL_Renderer* gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
if (gRenderer == NULL) {
printf("renderer error");
}
bool quit = false; // quit flag
//Event handler
SDL_Event e;
//nice little rendering class
Renderer* renderer = new Renderer();
//World
World* world = new World();
//Texture Atlas
Atlas* atlas = new Atlas(SDL_GetWindowSurface( gWindow), gRenderer);
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
switch(e.type) {
case SDL_QUIT: //User requests quit
quit = true;
break;
}
}
//Clear screen
//SDL_SetRenderDrawColor( gRenderer, 0, 0xFF, 0, 0xFF );
SDL_RenderClear( gRenderer );
renderer->render(gRenderer, atlas, world, SCREEN_WIDTH, SCREEN_HEIGHT);
//Update the surface
SDL_RenderPresent(gRenderer);
//SDL_UpdateWindowSurface( gWindow );
}
delete (world, renderer, atlas);
return 0;
}
This allocates a std::vector with one element of BaseEntity
environment = new std::vector<BaseEntity>(1); // this is where init
then another element of Grass is appended
environment->push_back(Grass()); // adding something to it works fine
but maybe this is the first problem, since the vector only holds BaseEntitys, see What is object slicing?
This accesses the first element of the given vector, and this is not the appended Grass but the default constructed BaseEntity object from new std::vector<BaseEntity>(1)
std::vector<BaseEntity> env = *(world->loaded[x][y]->environment); // here is where the error occurs
Accessing the pointer shouldn't be a problem, because it seems to be initialized properly.
But maybe copying the BaseEntity is the real problem here. I would look into the (copy) constructor of BaseEntity (and maybe Grass) and see, if there is some problematic code.
I don't see an immediate problem with your code (except copying the vector is obviously inefficient), but I do see a problem with your printf debugging.
You should use fprintf(stderr, ...) for debug printfs, so as to avoid stdio buffering, or call fflush(NULL).
The fact that 3 is not printed does not necessarily mean that printf("3") is unreached.
You should avoid printf debugging altogether, and learn to use a real debugger (GDB or LLDB) instead.
If you run your program with Address Sanitizer (-fsanitize=address); it will likely point you straight at the bug.
Finally, when writing in C++, avoid C-style arrays, and especially multi-level arrays. Use vectors instead.

SDL2 Transparent surface

I am trying to create a transparent surface, blit it bigger surface (size of my screen), then create a texture of it, copy to the renderer, and finaly render present.
I have seen many other forums saying I have to use SetBlendMode (for surface, texture, and renderer), ColorKey, SetSurfaceBlendMode. I tried them all but I can't seem to get it to work. I read that SDL_BlitScaled is not suitable for combining surfaces that have transparent pixels, but I am completely lost as to what I have to do instead.
What I noticed, when I use SDL_CreateRGBSurface (with an alpha value) to create a surface, the surface's PixelFormat is RGB888 instead of RGBA8888 (what I am expecting since I provide the alpha value). Using SDL_ConvertSurfaceFormat did not help.
Can somebody tell me what I am missing?
Complete code: removed, my appologies
Please note that I have removed the attempts to get transparency working
The renderer:
mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED);
My render loop:
void CApp::Render()
{
SDL_RenderClear(mRenderer);
mBackGround->Render(mRenderer);
mForeGround->Render(mRenderer);
SDL_RenderPresent(mRenderer);
}
The big surface I am blitting to:
mSurface = SDL_CreateRGBSurface(0, CApp::Window_W(), CApp::Window_H(), 32, 0, 0, 0, 0);
The code to get tiles from a spritesheet:
bool Map::GetTilesFromSpriteSheet(SDL_Surface *pSpriteSheet, int pTile_w, int pTile_h)
{
if(pSpriteSheet->w % pTile_w == 0 && pSpriteSheet->h % pTile_h == 0) {
SDL_Rect srcRect;
srcRect.w = pTile_w;
srcRect.h = pTile_h;
for(int y = 0; y < pSpriteSheet->h / pTile_h; y++) {
for(int x = 0; x < pSpriteSheet->w / pTile_w; x++) {
srcRect.x = x*pTile_w;
srcRect.y = y*pTile_h;
SDL_Surface* tempSurface = SDL_CreateRGBSurface(0, pTile_w, pTile_h, 32, 0, 0, 0, 0);
if(SDL_BlitSurface(pSpriteSheet, &srcRect, tempSurface, nullptr)==0) {
mTiles.push_back(tempSurface);
} else {
Log("Error extracting tile (%d,%d)(w,h): %s", x, y, SDL_GetError());
return false;
}
}
}
Log("Number of tiles: %d", static_cast<int>(mTiles.size()));
} else {
Log("Background spritesheet is incompatible with tile dimensions (%d,%d)(w,h).", pTile_w, pTile_h);
return false;
}
return true;
}
This is where I combine the tiles to create the big surface:
bool Map::GenerateMap(std::vector<std::vector<int>> &pMap, std::vector<SDL_Surface*> &pTiles, SDL_Surface* pDestination)
{
SDL_Rect rect;
rect.w = mDstTile_W;
rect.h = mDstTile_H;
SDL_Surface* transparent = SDL_CreateRGBSurface(0, mDstTile_W, mDstTile_H, 32, 0, 0, 0, 0);
for(int y = 0; y < static_cast<int>(pMap.size()); y++) {
for(int x = 0; x < static_cast<int>(pMap.at(static_cast<unsigned long>(y)).size()); x++) {
rect.x = x*mDstTile_W;
rect.y = y*mDstTile_H;
int index = static_cast<int>(pMap.at(static_cast<unsigned long>(y)).at(static_cast<unsigned long>(x)));
if(index < 0) {
if(SDL_BlitScaled(transparent, nullptr, pDestination, &rect) != 0) {
Log("Error blitting transparent surface to destination: %s", SDL_GetError());
}
} else if(SDL_BlitScaled(pTiles[static_cast<unsigned long>(index)],
nullptr, pDestination, &rect) != 0) {
Log("Error blitting surface to destination: %s", SDL_GetError());
return false;
}
}
}
SDL_FreeSurface(transparent);
return true;
}
And finaly, this is the code to render the big surface to the screen, first by creating a texture:
void ForeGround::Render(SDL_Renderer* pRenderer)
{
if(mTexture) SDL_DestroyTexture(mTexture);
mTexture = SDL_CreateTextureFromSurface(pRenderer, mSurface);
if(mTexture == nullptr) {
Log("Unable to create foreground texture: %s", SDL_GetError());
} else if (SDL_RenderCopy(pRenderer, mTexture, nullptr, nullptr)) {
Log("Unable to render foreground: %s", SDL_GetError());
}
}
As #keltar mentioned, I was not creating surfaces with an alpha value.
I had to change the SDL_CreateRGBSurface call. The code snippet below creates an empty, transparent surface where I can blit to if needed (for example, tiles from a spritesheet).
SDL_Surface* tempSurface = SDL_CreateRGBSurface(..., 32, 0xff, 0xff00, 0xff0000, 0xff000000);
The code snippet below creates a black, non-transparent surface.
SDL_Surface* tempSurface = SDL_CreateRGBSurface(..., 32, 0xff, 0xff00, 0xff0000, 0x00000000);
This was enough for me, I did not have to use SDL_SetRenderDrawBlendMode, SDL_SetSurfaceBlendMode, SDL_SetTextureBlendMode, or SDL_ConvertSurface. A quick look at the SDL wiki showed:
By default surfaces with an alpha mask are set up for blending as with
SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND)
Which explained why I did not have to call any of those functions. A big shout-out to keltar for his quick answer!

Showing two or more different animation with SDL2-render in two different threads (no threads in the solution). C++

im trying to show two different animations made with two functions, one render and two threads.
Im getting different kind of error each time i run the code.
Such as: segmentation default in the refresh function (line SDL_RenderPresent(w1.renderer);) and other strange errors too. Everytime is different.
I know its about using the render in both different threads. But i dont know how to solve this problem.
When i run with just one of the threads everything its ok. But not with the two of them.
I just want to show different graphics playing around the window. (always using sdl2).
Here is my code:
window.h:
class Window
{
public:
SDL_Window *window1;
int background,windowWidth,windowHeight,windowXcoord,windowYcoord;
SDL_Renderer * renderer;
SDL_Renderer * renderer2;
Window();
};
void refresh();
extern Window w1;
window.cpp:
Window w1;
Window::Window()
{
window1=nullptr;
background = 0xffffff;
windowWidth=700; windowHeight=500;
windowXcoord = 650; windowYcoord = 0;
this->window1 =
SDL_CreateWindow("Window",windowXcoord,windowYcoord,
windowWidth,windowHeight, SDL_WINDOW_SHOWN);
this->renderer = SDL_CreateRenderer( this->window1, -1 ,
SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor( this->renderer, 255, 255, 255, 255 );
SDL_RenderClear( this->renderer );
SDL_RenderPresent(this->renderer);
}
// this function is called everytime an object or function want to "refresh" the window.
void refresh(){
// clearing the window
SDL_SetRenderDrawColor( w1.renderer, 255, 255, 255,0 );
SDL_RenderClear( w1.renderer );
// r1, the first Rects object to animate.
SDL_SetRenderDrawColor( w1.renderer,255,0,0,255);
SDL_RenderFillRect( w1.renderer, &r1.rect );
// r2, the second Rects.
SDL_SetRenderDrawColor( w1.renderer,255,0,255,255);
SDL_RenderFillRect( w1.renderer, &r2.rect );
SDL_RenderPresent(w1.renderer);
}
rects.h:
class Rects
{
public:
SDL_Rect rect;
Rects();
};
extern Rects r1, r2;
void moveR1();
void moveR2();
rects.cpp:
Rects::Rects()
{ }
Rects r1,r2;
// moveR1 and moveR2, (just some dumm animations-example)
void moveR1(){
r1.rect.x=400; r1.rect.y=100;
r1.rect.w =40; r1.rect.h =10;
SDL_SetRenderDrawColor( w1.renderer,255,0,0,255);
SDL_RenderFillRect( w1.renderer, &r1.rect );
{
for (int u = 1; u<=5;u++){
r1.rect.x=200; r1.rect.y=100;
r1.rect.w =50; r1.rect.h =50;
refresh();
for (int i = 1; i <=200; i++){
r1.rect.x-=1;
usleep (7000);
refresh();
}
}
}
}
void moveR2(){
r2.rect.x=200; r2.rect.y=100;
r2.rect.w =40; r2.rect.h =10;
SDL_SetRenderDrawColor( w1.renderer,255,255,0,255);
SDL_RenderFillRect( w1.renderer, &r2.rect );
{
for (int u = 1; u<=5;u++){
check
r2.rect.x=200; r2.rect.y=100;
r2.rect.w =50; r2.rect.h =50;
refresh();
for (int i = 1; i <=200; i++){
r2.rect.x+=1; r2.rect.y+=1;
usleep (7000);
refresh();
}
}
}
}
and the main:
int main()
{
thread t1(moveR1);
t1.detach();
thread t2(moveR2);
t2.detach();
// sleep instead of showing a loop.
sleep (10);
return 0;
}
any polite help is welcome, im here to learn.
When i run with just one of the threads everything its ok. But not with the two of them.
According to the documentation for 2D accelerated rendering (also known as SDL_render.h, in other terms the place where SDL_RenderPresent lives):
This API is not designed to be used from multiple threads, see SDL bug #1995 for details.
You won't be able to do that any time soon. By looking at the description of the error, it looks like an UB and the link to the bug gives you all the details probably.
I just want to show different graphics playing around the window.
You don't need to use two threads to do that.
You can just update positions, animations and whatever is needed for your graphics and show them from the same thread. Nothing prevents you from calling the same function (as an example SDL_RenderCopy) more than once before to invoke SDL_RenderPresent.
If you needed a thread per graphic, what about a game with thousands of polygons on video?
// thanks to skypjack, i am able to solve the problem
// HOW TO PRESENT TWO (OR MORE) GRAPHICS WITH SDL_RENDERER WITHOUT USING THREADS.
// The two rectangle animation are just and example.
// It could be whatever we want to show.
// In this case, just two rectangles moving around.
#include <unistd.h>
#include <SDL.h>
using namespace std;
SDL_Window *window1;
int background, windowWidth, windowHeight,windowXcoord,
windowYcoord;
SDL_Rect rectangle1;
SDL_Rect rectangle2;
SDL_Renderer *renderer;
int sequence1;
int sequence2;
void moveRectangle1(), moveRectangle2();
int main()
{
window1=nullptr;
background = 0xffffff;
windowWidth=700; windowHeight=500;
windowXcoord = 650; windowYcoord = 0;
window1 = SDL_CreateWindow("Main
Window",windowXcoord,windowYcoord, windowWidth,windowHeight,
SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer( window1, -1 ,
SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor( renderer, 255, 255, 255, 255 );
SDL_RenderClear( renderer );
SDL_RenderPresent(renderer);
rectangle1.x = 100; rectangle1.y = 100; rectangle1.h = 40;
rectangle1.w = 40;
rectangle2.x = 100; rectangle2.y = 100; rectangle2.h = 40;
rectangle2.w = 40;
for (int i = 1;i<500;i++){
SDL_SetRenderDrawColor( renderer, 255, 255, 255,0 );
SDL_RenderClear( renderer );
// chequear return (cerrar programa)
moveRectangle1();
moveRectangle2();
SDL_RenderPresent(renderer);
usleep (12000);
}
return 0;
}
void moveRectangle1(){
sequence1++;
if (sequence1 <= 50){ rectangle1.x++; }
else if (sequence1 <= 100){ rectangle1.x--; }
else { sequence1 = 0; }
SDL_SetRenderDrawColor(renderer,255,0,0,255);
SDL_RenderFillRect(renderer, &rectangle1 );
}
void moveRectangle2(){
sequence2++;
if (sequence2 <= 100){ rectangle2.y++; }
else if (sequence2 <= 200){ rectangle2.y--; }
else { sequence2 = 0; }
SDL_SetRenderDrawColor(renderer,0,200,0,255);
SDL_RenderFillRect( renderer, &rectangle2 );
}

SDL C Program freezes on sdl_blitsurface

I'm having an issue with a program I'm working on. Occasionally, it will just freeze. No errors or anything.
The game is a multiplayer game where you fly a ship around. Pictures of other players and powerups move in and out of view depending on your location. For the most part, it works great, but under certain circumstances, it locks up.
I've tracked it down to when it BLITs one surface onto another. (SDL_BlitSurface).
If I comment out the single line of code where it blits (SDL_BlitSurface), and replace the graphic with a simple circle, it'll never freeze under any circumstances. But, comment out the circle and replace it with blitting the graphic again, and it'll randomly freeze. The frustrating part is, sometimes it will, sometimes it won't. Sometimes the graphic will sit on screen for a few moments and then freeze, sometimes it'll freeze the moment it shows up. Sometimes, it won't freeze at all. I simply cannot track it down to anything in particular.
I have ample amount of code that checks for NULL surfaces and it doesn't seem to stop it.
I also have it set up to output information about all the graphics to a file (such as width, height, location in memory, x, y, etc) and nothing seems out of the ordinary.
My main questions are, what about surfaces can cause SDL_BlitSurface to freeze? And what other checks can I add for surfaces to make sure it doesn't try to blit bad surfaces?
The code is too long to list, but here is how it works:
class Player
{
Player();
int x;
int y;
int xvel;
int yvel;
SDL_Surface *DrawScreen;
SDL_Surface *ShipPic;
void check_player_dist();
void check_powerup_dist();
void update();
};
class PowerUp
{
int x;
int y;
int type;
SDL_Surface *Powerup_Pic;
};
Player::Player()
{
Apply_Surface(0, 0, PlayerShipPics, ShipPic);
}
Player::Update(Player p[], PowerUp pu[])
{
x += xvel;
y += yvel;
for (int i = 0; i < Num_Players; i++)
{
if (check_on_screen(p[i].x, p[i].y) == true)
{
Apply_Surface(x - p[i].x, y - p[i].y, p[i].ShipPic, DrawScreen);
}
}
for (int i = 0; i < Num_PowerUps; i++)
{
if (check_on_screen(pu[i].x, pu[i].y) == true)
{
Apply_Surface(x - pu[i].x, y - pu[i].y, pu[i].Pic, DrawScreen);
}
}
}
int main()
{
SDL_Surface *Screen;
Player players[4];
PowerUp powerups[200];
Num_Players = 4;
Num_PowerUps = 200;
while (quit == false)
{
for (int i = 0; i < Num_Players; i++)
{
players[i].update(players, powerups);
switch (i)
{
case 0: ScreenX = 0; ScreenY = 0; break;
case 1: ScreenX = ScreenWid / 2; ScreenY = 0; break;
case 2: ScreenX = 0; ScreenY = ScreenHigh / 2; break;
case 3: ScreenX = ScreenWid / 2; ScreenY = ScreenHigh / 2; break;
}
Apply_Surface (ScreenX, ScreenY, players[i].DrawScreen, Screen);
}
if (SDL_Flip(Screen) == -1)
{
return -1;
}
}
}
void Apply_Surface (int x, int y, SDL_Surface* Source, SDL_Surface* Destination, SDL_Rect* Clip)
{
SDL_Rect Offset;
Offset.x = x;
Offset.y = y;
if ((Source != NULL) && (Destination != NULL))
{
SDL_BlitSurface (Source, Clip, Destination, &Offset );
}
}
I've noticed it generally freezes when two or more players are near each other and it tries to draw the same power-up on both of their screens. But again...not always!
Well, I figured out what it was.
I was using the SDL_GFX library along with my game. Many of the images were created using rotozoomSurface(), which is a function of SDL_GFX.
Turns out there's a bug in it where, under certain circumstances that I don't know, it'll create a bad surface that will work "most" of the time, but under the right conditions, will crash. Such as, being placed at a particular x & y coordinate on the screen. (Don't know for sure). The rotated/zoomed images would work about 95% of the time, so it was very difficult to pin point what the issue was.
The work around was, when the image was created, just SDL_BlitSurface() it onto another surface under controlled conditions, such as putting it at coordinates (0, 0). Then, delete the rotated and zoomed surface, and just use the new "safe" surface.
Works great after that.
Hopefully this will help anyone who's using SDL_GFX and cannot figure out why their program is crashing.
Example:
Before:
SDL_Surface *original = SDL_CreateRGBSurface(SDL_SWSURFACE, Ship_Width, Ship_Height, Screen_BPP, 0, 0, 0, 0);
Apply_Surface(0, 0, ShipsPic, original, &bounds);
SDL_Surface *finished = rotozoomSurface(original, pic_angle, zoom, SMOOTHING_ON);
SDL_FreeSurface(original);
return finished;
After (fixed):
SDL_Surface *original = SDL_CreateRGBSurface(SDL_SWSURFACE, Ship_Width, Ship_Height, Screen_BPP, 0, 0, 0, 0);
Apply_Surface(0, 0, ShipsPic, original, &bounds);
SDL_Surface *temp = rotozoomSurface(original, pic_angle, zoom, SMOOTHING_ON);
SDL_Surface *finished = SDL_CreateRGBSurface(SDL_SWSURFACE, temp->w, temp->h, Screen_BPP, 0, 0, 0, 0);
Apply_Surface(0, 0, temp, finished);
SDL_FreeSurface(temp);
SDL_FreeSurface(original);
return finished;
And for what it's worth, the Apply_Surface() function:
void Apply_Surface (int x, int y, SDL_Surface* Source, SDL_Surface* Destination, SDL_Rect* Clip)
{
SDL_Rect Offset;
Offset.x = x;
Offset.y = y;
if ((Source != NULL) && (Destination != NULL))
{
SDL_BlitSurface (Source, Clip, Destination, &Offset );
}
}
There's not really enough information to figure out what exactly is going on. Computers don't like to do things "sometimes," they either do them or not, so it leads me to believe that maybe there's some variable that's doing something it shouldn't.
Just in case, what does your Apply_Surface() function look like? I assume that's where you're doing your actual blitting, and if that's where you're having your problems, that would be useful for those of us trying to figure out your dilemma.

Draw on webcam using OpenCV

I want to draw/paint on a webcam screen using OpenCV. Since I'm reading from a cam, the frames are constantly changing, so I'm trying to figure out a way to keep or save the drawing on the current frame and use it for the next frame. The code below allows you to draw on the screen but when it gets the next frame, the drawing is gone and it starts over.
Could someone please help me ... Thanks.
CvCapture *input;
input = cvCaptureFromCAM( 0 );
cvSetMouseCallback("Demo",&on_mouse, 0);
for(;;)
{
frame = cvQueryFrame(input);
if(!image)
{
image = cvCreateImage( cvSize(frame->width, frame->height), IPL_DEPTH_8U, 3);
screenBuffer = cvCreateImage( cvSize(frame->width, frame->height), IPL_DEPTH_8U, 3);
}
cvCopy(frame, image, 0);
if(drawing) //drawing is a global variable
{
cvCircle(image, cvPoint(last_x,last_y), 10,CV_RGB(red,green,blue), -1, CV_AA, 0);
cvCopy(image, screenBuffer, 0);
}
cvShowImage( "Demo", screenBuffer );
}
void on_mouse( int event, int x, int y, int flags, void* param )
{
last_x = x;
last_y = y;
if(event==CV_EVENT_LBUTTONDOWN)
{
drawing = 1;
}
}
Draw into a separate image and then cvAdd() that to the video image immediately before dispalying it
I will not go into all the details why your approach is bad, but keep in mind that creating 2 extra frames for drawing is a little bit too much.
It's important that you realize that all this kinky stuff is being done on the same thread used to capture new frames. This means what exactly? It means that the extra code you are adding inside the loop will slow the process of capturing and displaying new frames. In other words, you are sabotaging yourself by lowering the framerate of your application. If you don't care, it's ok. If you do, my tip for you is that you stack the captured frames into a buffer and have another thread read, process and display them.
Ok, so you REALLY want to draw over the window that's displaying the captured frames. Well, the obvious thing you can't do (and you discovered this yourself) is that the drawing cannot be made on the captured frame because the frame it's replaced with new data on every loop. So what do you do? You create a 2nd frame to do the drawing. Let's call it the drawing_frame.
The only thing that will be on the drawing_frame are the circles that will appear when the mouse moves over the window, when the LBUTTON of the mouse is clicked (a 2nd click switches between ON/OFF).
After the drawing of the circle occurs, the drawing_frame is overlayed on top on the frame captured by the camera. This process is a little expensive on the CPU, and since we are doing it in the main thread of the application, it will also decrease the framerate.
I strongly suggest that everyone interested in adding/merging/overlaying transparent frames with OpenCV take a look at Transparent image overlays in OpenCV.
By the way, I'm using cvCaptureFromCAM(-1) becouse I'm on Linux. You probably should change that to whatever works for you. According to your post it's cvCaptureFromCAM(0).
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
int drawing = 0;
int last_x = 0;
int last_y = 0;
void on_mouse(int event, int x, int y, int flags, void* param)
{
last_x = x;
last_y = y;
if (event == CV_EVENT_LBUTTONDOWN)
{
// switches between On and Off
if (drawing)
drawing = 0;
else
drawing = 1;
}
}
int main()
{
CvCapture* capture = NULL;
if ((capture = cvCaptureFromCAM(-1)) == NULL)
{
fprintf(stderr, "ERROR: capture is NULL \n");
return -1;
}
cvNamedWindow("mywindow", CV_WINDOW_AUTOSIZE);
cvQueryFrame(capture); // Sometimes needed to get correct data
cvSetMouseCallback("mywindow",&on_mouse, 0);
IplImage* frame = NULL;
IplImage* drawing_frame = NULL;
while (1)
{
if ((frame = cvQueryFrame(capture)) == NULL)
{
fprintf( stderr, "ERROR: cvQueryFrame failed\n");
break;
}
if (frame == NULL)
{
fprintf( stderr, "WARNING: cvQueryFrame returned NULL, sleeping..\n");
usleep(100000);
continue;
}
if (!drawing_frame) // This frame is created only once
{
drawing_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, frame->nChannels);
cvZero(drawing_frame);
}
if (drawing)
{
cvCircle(drawing_frame, cvPoint(last_x,last_y), 10,CV_RGB(0, 255, 0), -1, CV_AA, 0);
// For overlaying (copying transparent images) in OpenCV
// http://www.aishack.in/2010/07/transparent-image-overlays-in-opencv/
for (int x = 0; x < frame->width; x++)
{
for (int y = 0; y < frame->height; y++)
{
CvScalar source = cvGet2D(frame, y, x);
CvScalar over = cvGet2D(drawing_frame, y, x);
CvScalar merged;
CvScalar S = { 1,1,1,1 };
CvScalar D = { 1,1,1,1 };
for(int i = 0; i < 4; i++)
merged.val[i] = (S.val[i] * source.val[i] + D.val[i] * over.val[i]);
cvSet2D(frame, y, x, merged);
}
}
}
cvShowImage("mywindow", frame);
int key = cvWaitKey(10);
if (key == 113) // q was pressed on the keyboard
break;
}
cvReleaseImage(&frame);
cvReleaseImage(&drawing_frame);
cvReleaseCapture(&capture);
cvDestroyWindow("mywindow");
return 0;
}
You usually will have problems of adding images (they will eventually saturate), so I guess thats why you start over. I see you have color images... if you use more powerful stuff like OpenGL for your drawing you could use the overlay for your drawings. Otherwise check this out:
http://aishack.in/tutorials/transparent-image-overlays-in-opencv/