problemas con SDL

Consulte acerca de programas, técnicas, algoritmos etc.

problemas con SDL

Notapor sofoke » Jue Abr 10, 2008 8:26 pm

Tengo un problema con SDL.
Cuando ejecuto alguna aplicación creada con SDL y la dejo corriendo sin hacer ni presionar nada... al parecer consume todos los recursos del sistema aun cuando la aplicacion es muy sencilla...
Intente poniendo un SDL_Delay(1) en el gameloop pero aun así consume demasiados recursos y cuesta algo de trabajo matar o cerrar la aplicación.
Alguien tiene idea de por que pasa esto¿?
...cuando lo popular no es suficiente...
Gnu-Linux-y-Más
Avatar de Usuario
sofoke
 
Mensajes: 102
Registrado: Jue May 24, 2007 8:10 pm
Ubicación: México

Notapor lucesita » Vie Abr 11, 2008 12:34 am

ajam yo tengo exactamente el mismo problema, no solo me consume el CPU

que con SDL_Delay(x); (siendo x el complemento para lograr un FPS rate fijo)

logro reducir de 99% a unos 40% aun que me parezca exagerado para la aplicacion que tengo, es mejor que 99%

el problema que mas me inquieta, que supongo debo yo tener un error en el codigo y vos tambien, es que progresivamente AUMENTA EL CONSUMO DE MEMORI RAM!!!!!! y esto si que es escalofriante... me aument de 25 MB

yo creo que es por que estoy redefiniendo superficies o algo por el estilo, que tenga que ver con memoria dinamica.

aqui el codigo del main.cpp e mi prog

Código: Seleccionar todo
#include <cstdlib>
#include <SDL.h>
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include "video.h"
#include "contador.h"
#define BLUE_COL 0,0,255
#define WHITE_COL 255,255,255

#define FP_TIME 14
#define MOVE_UPLEFT 1
#define MOVE_UPRIGTH 2
#define MOVE_DOWNLEFT 3
#define MOVE_DOWNRIGHT 4

#define GAME_INIT 1
#define GAME_OVER 2
#define GAME_TANTO 3
#define GAME_INGAME 4
#define GAME_OVER_WP1 5
#define GAME_OVER_WP2 6
#define GAME_MENU 7
#define GAME_CREDITOS 8
#define GAME_AYUDA 9


#define MENU_CONTROLES 1
#define MENU_NEWGAME 2
#define MENU_CREDITS 3
#define MENU_AYUDA 4
int cmenu = 0;

SDL_Surface *screen;
SDL_Surface *fondopantalla;
SDL_Surface *play1paleta;
SDL_Surface *play2paleta;
SDL_Surface *ball;
SDL_Surface *sfcredits;

SDL_Rect rectscreen;
SDL_Rect rectplayer1pos;
SDL_Rect rectplayer2pos;
SDL_Rect rectballpos;
SDL_Rect rectcolp1;
SDL_Rect rectcolp2;

Uint8 direccionball;
Uint8 stepx = 5;
Uint8 stepy = 5;

int timer_secs = 0;
int timer_tanto = 3;
int tsec_ini;
int tfrac_fin;
int tsec_fin;
int ttemp;

int tcount_200;

int gamestat = GAME_INGAME;

bool done = false;

Uint32 tinit;
Uint32 tfin;

Uint8 *keys;

CTanteador tant1;
CTanteador tant2;
CTanteador gametime;
CTanteador gametantos;
CTanteador twinp1;
CTanteador twinp2;

CTanteador tmenunueva;
CTanteador tmenucreditos;
CTanteador tmenuayuda;
bool drawt = false;


void ResetTime();
int GetTime();
void InitSprites();
void DrawEscene();
void P1MoveUP();
void P1MoveDOWN();
void P2MoveUP();
void P2MoveDOWN();
void MoveBall();
void InitSecTimer();
void RefreshTime();
void InitPos();


int main ( int argc, char** argv )
{
SDL_Event event;




// Inicializa SDL Video, Seteamos 800*600 32bpp, HWACCEL, DBLBuff
    TTF_Init();
    SDL_Init(SDL_INIT_VIDEO);

    screen = SDL_SetVideoMode(RES_X, RES_Y, RES_DEPT, SDL_HWACCEL | SDL_DOUBLEBUF);
    InitSprites();

    gamestat = GAME_MENU;

    direccionball = MOVE_UPLEFT;
    gametantos.SetTantos(timer_tanto);
    SDL_ShowCursor(SDL_DISABLE);
    while(done == false)
    {
        ResetTime();

        switch (gamestat)
        {
            case GAME_INGAME:

                if(SDL_PollEvent(&event))
                {
                    if (event.type == SDL_KEYDOWN)
                        if (event.key.keysym.sym == SDLK_ESCAPE)
                            done = true;

                    if (event.type == SDL_QUIT)
                        done = true;

                }
                timer_tanto = 3;
                DrawEscene();
                keys = SDL_GetKeyState(NULL);
                if(keys[SDLK_UP] == 1)
                    P2MoveUP();
                if(keys[SDLK_DOWN] == 1)
                    P2MoveDOWN();
                if(keys[SDLK_a] == 1)
                    P1MoveUP();
                if(keys[SDLK_z] == 1)
                    P1MoveDOWN();

                while (GetTime() < FP_TIME){}
                MoveBall();
                tant1.DrawFont(screen);
                tant2.DrawFont(screen);
                RefreshTime();
                gametime.SetTantos(timer_secs);
                gametime.DrawFont(screen);
                SDL_Flip(screen);
                break;

            case GAME_TANTO:
                InitPos();
                DrawEscene();
                ttemp = timer_secs;
                RefreshTime();

                tant1.DrawFont(screen);
                tant2.DrawFont(screen);
                //gametime.SetTantos(timer_secs);
                gametime.DrawFont(screen);

                if(ttemp != timer_secs)
                {
                    gametantos.SetTantos(timer_tanto);
                    //done =1;


                    if (timer_tanto == 1)
                    {
                        //done = 1;
                        gamestat = GAME_INGAME;
                        gametime.SetTantos(0);
                        timer_secs = 0;
                        timer_tanto = 3;
                        gametantos.SetTantos(timer_tanto);
                    }
                    timer_tanto--;



                }
                gametantos.SetTantos(timer_tanto);
                gametantos.DrawFont(screen);

                if (tant1.GetTantos() >= 3)
                    gamestat = GAME_OVER_WP1;

                if (tant2.GetTantos() >= 3)
                    gamestat = GAME_OVER_WP2;

                SDL_Flip(screen);
                break;
            case GAME_OVER_WP1:
                DrawEscene();
                twinp1.puttext("vos so de la B");
                twinp1.DrawFont(screen);


            case GAME_OVER_WP2:
                if(SDL_PollEvent(&event))
                {
                    if (event.type == SDL_KEYDOWN)
                        if (event.key.keysym.sym == SDLK_ESCAPE)
                            done = true;

                    if (event.type == SDL_QUIT)
                        done = true;

                }
                RefreshTime();
                if (drawt)
                    twinp2.SetFontColor(255,255,255);
                else
                    twinp2.SetFontColor(0,0,0);

                DrawEscene();
                twinp2.puttext("vos so de la C");
                twinp2.DrawFont(screen);
                SDL_Flip(screen);
                gamestat = GAME_MENU;
                break;
            case GAME_MENU:
                if(SDL_PollEvent(&event))
                {
                    if (event.type == SDL_KEYDOWN)
                        if (event.key.keysym.sym == SDLK_ESCAPE)
                            done = true;

                        if (event.type == SDL_QUIT)
                            done = true;
                    if (event.type == SDL_KEYDOWN)
                    {
                        if(event.key.keysym.sym == SDLK_UP)
                        {
                            if (cmenu > 0)
                                cmenu--;
                            else
                                cmenu = 2;

                        }

                        if(event.key.keysym.sym == SDLK_DOWN)
                        {
                            if (cmenu < 2)
                                cmenu++;
                            else
                                cmenu = 0;
                        }

                        if(event.key.keysym.sym == SDLK_RETURN)
                        {
                            switch(cmenu)
                            {
                                case 0:
                                    gamestat = GAME_INGAME;
                                    tant1.SetTantos(0);
                                    tant2.SetTantos(0);
                                    break;
                                case 1:
                                    gamestat = GAME_CREDITOS;
                                    break;
                                case 2:
                                    gamestat = GAME_MENU;
                                    break;
                            }
                        }

                    }
                }



                switch (cmenu)
                {
                    case 0:
                        tmenunueva.SetFontColor(WHITE_COL);
                        tmenucreditos.SetFontColor(BLUE_COL);
                        tmenuayuda.SetFontColor(BLUE_COL);
                        break;
                    case 1:
                        tmenunueva.SetFontColor(BLUE_COL);
                        tmenucreditos.SetFontColor(WHITE_COL);
                        tmenuayuda.SetFontColor(BLUE_COL);
                        break;
                    case 2:
                        tmenunueva.SetFontColor(BLUE_COL);
                        tmenucreditos.SetFontColor(BLUE_COL);
                        tmenuayuda.SetFontColor(WHITE_COL);
                        break;
                }


                tmenunueva.DrawFont(screen);
                tmenucreditos.DrawFont(screen);
                tmenuayuda.DrawFont(screen);

                SDL_Flip(screen);
                SDL_Delay(GetTime());
                break;
            case GAME_CREDITOS:
                if(SDL_PollEvent(&event))
                {
                    if (event.type == SDL_KEYDOWN)
                        if (event.key.keysym.sym == SDLK_ESCAPE)
                            done = true;
                        if (event.key.keysym.sym == SDLK_RETURN)
                            gamestat = GAME_MENU;

                    if (event.type == SDL_QUIT)
                        done = true;

                }
                SDL_BlitSurface(sfcredits, NULL, screen, NULL);
                SDL_Flip(screen);
                break;
            case GAME_AYUDA:
                break;

        }
    }
    tant1.liberar();
    tant2.liberar();
    gametime.liberar();
    gametantos.liberar();
    twinp1.liberar();
    twinp2.liberar();

    tmenunueva.liberar();
    tmenucreditos.liberar();
    tmenuayuda.liberar();
    atexit(SDL_Quit);
    return 0;
}
//cancha 44,221
//747,546

void ResetTime ()
{
    tinit = SDL_GetTicks();
}

int GetTime()
{
    tfin = SDL_GetTicks();
    return tfin - tinit;
}

void InitSprites()
{
    twinp1.SetFontColor(255,255,255);
    twinp2.SetFontColor(255,255,255);
    fondopantalla = IMG_Load("recursos/fondo.bmp");
    play1paleta = IMG_Load("recursos/paleta.bmp");
    play2paleta = IMG_Load("recursos/paleta.bmp");
    ball = IMG_Load("recursos/pelota.bmp");
    sfcredits = IMG_Load("recursos/Creditos.bmp");


    SDL_SetColorKey(play1paleta, SDL_SRCCOLORKEY, SDL_MapRGB(play1paleta->format,255,0,255));
    SDL_SetColorKey(play2paleta, SDL_SRCCOLORKEY, SDL_MapRGB(play1paleta->format,255,0,255));
    SDL_SetColorKey(ball, SDL_SRCCOLORKEY, SDL_MapRGB(play1paleta->format,255,0,255));

    InitPos();
}

void InitPos()
{
    rectplayer1pos.x = 50;
    rectplayer1pos.y = 400;

    rectplayer2pos.x = 720;
    rectplayer2pos.y = 400;

    rectballpos.x = 400 - (ball->w /2) ;
    rectballpos.y = 350 - (ball->h / 2) ;

    tant1.SetX(300);
    tant1.SetY(12);
    tant2.SetX(460);
    tant2.SetY(12);
    gametime.SetX(390);
    gametime.SetY(12);
    gametime.SetFontSize(32);

    tmenunueva.puttext("Nueva Partida");
    tmenunueva.SetX(300);
    tmenunueva.SetY(300);
    tmenunueva.SetFontSize(18);

    tmenucreditos.puttext("Creditos");
    tmenucreditos.SetX (300);
    tmenucreditos.SetY (340);
    tmenucreditos.SetFontSize(18);

    tmenuayuda.puttext ("ayuda");
    tmenuayuda.SetX(300);
    tmenuayuda.SetY(380);
    tmenuayuda.SetFontSize(18);
}

void DrawEscene()
{
    SDL_BlitSurface(fondopantalla, NULL, screen, NULL);
    SDL_BlitSurface(play1paleta, NULL, screen, &rectplayer1pos);
    SDL_BlitSurface(play2paleta, NULL, screen, &rectplayer2pos);
    SDL_BlitSurface(ball, NULL, screen, &rectballpos);

}


void P1MoveUP()
{
    if (rectplayer1pos.y > 200 - 14)
        rectplayer1pos.y -= 2;
}
void P1MoveDOWN()
{
    if (rectplayer1pos.y < 500 - rectplayer1pos.h + 14)
        rectplayer1pos.y += 2;
}

void P2MoveUP()
{
    if (rectplayer2pos.y > 200 - 14)
    rectplayer2pos.y -= 2;
}

void P2MoveDOWN()
{
    if (rectplayer2pos.y < 500 - rectplayer1pos.h + 14)
    rectplayer2pos.y += 2;
}

void MoveBall()
{
    switch (direccionball)
    {
        case MOVE_UPLEFT:
        {
            if( rectballpos.x > 15 )
                rectballpos.x -=stepx;
            else
            {
                direccionball = MOVE_UPRIGTH;
                rectballpos.x +=stepx;
            }
            if (rectballpos.y > 200)
            {
                rectballpos.y -= stepy;
            }

            else
            {
                if (direccionball == MOVE_UPRIGTH)
                {
                    direccionball = MOVE_DOWNRIGHT;
                    rectballpos.y += stepy;
                }
                else
                {
                    direccionball = MOVE_DOWNLEFT;
                    rectballpos.y += stepy;
                }
            }
            break;
        }

        case MOVE_UPRIGTH:
            if (rectballpos.x < 780)
            {
                rectballpos.x += stepx;
            }
            else
            {
                direccionball = MOVE_UPLEFT;
                rectballpos.x -= stepx;
            }

            if (rectballpos.y > 200)
            {
                rectballpos.y -= stepy;
            }
            else
            {
                if (direccionball == MOVE_UPLEFT)
                {
                    direccionball = MOVE_DOWNLEFT;
                    rectballpos.y +=stepy;
                }
                else
                {
                    direccionball = MOVE_DOWNRIGHT;
                    rectballpos.y +=stepy;
                }
            }
            break;

        case MOVE_DOWNLEFT:
            if (rectballpos.x > 20)
                rectballpos.x -= stepx;
            else
            {
                direccionball = MOVE_DOWNRIGHT;
                rectballpos.x +=stepx;
            }
            if (rectballpos.y < 500 - rectballpos.h )
                rectballpos.y += stepy;
            else
            {
                if (direccionball == MOVE_DOWNRIGHT)
                {
                    direccionball = MOVE_UPRIGTH;
                    rectballpos.y -=stepy;
                }
                else
                {
                    direccionball = MOVE_UPLEFT;
                    rectballpos.y -=stepy;
                }
            }
            break;

        case MOVE_DOWNRIGHT:
            if (rectballpos.x < 780)
                rectballpos.x +=stepx;
            else
            {
                direccionball = MOVE_DOWNLEFT;
                rectballpos.x -=stepx;
            }

            if (rectballpos.y < 500 - rectballpos.h )
                rectballpos.y += stepy;
            else
            {
                if (direccionball = MOVE_DOWNLEFT)
                {
                    direccionball = MOVE_UPLEFT;
                    direccionball -=stepy;
                }
                else
                {
                    direccionball = MOVE_UPRIGTH;
                    direccionball -=stepy;
                }
            }
            break;
        default:
            //done = true;
            direccionball = MOVE_UPRIGTH;
    }
    rectcolp1.x = rectplayer1pos.x + 5;
    rectcolp1.y = rectplayer1pos.y + 10;
    rectcolp1.w = rectplayer1pos.w + rectplayer1pos.x - 5;
    rectcolp1.h = rectplayer1pos.y + rectplayer1pos.h - 10;

    rectcolp2.x = rectplayer2pos.x + 5;
    rectcolp2.y = rectplayer2pos.y + 10;
    rectcolp2.w = rectplayer2pos.w + rectplayer2pos.x - 5;
    rectcolp2.h = rectplayer2pos.h + rectplayer2pos.y - 10;

    if (rectballpos.x < (rectcolp1.x - stepx))
    {
        if ((rectballpos.y > rectcolp1.y) && (rectballpos.y < rectcolp1.h))
        {
            //done = 1;
            switch (direccionball)
            {
                case MOVE_DOWNLEFT:
                    direccionball = MOVE_DOWNRIGHT;
                    rectballpos.x += stepx;
                    break;
                case MOVE_UPLEFT:
                    direccionball = MOVE_UPRIGTH;
                    rectballpos.x += stepx;
                    break;
            }
        }
        else
        {
        //Tanto anotado para P2
            gamestat = GAME_TANTO;
            tant2.SetTantos(tant2.GetTantos() + 1);
        }
    }
    if( rectballpos.x > (rectcolp2.x - stepx))
    {
        if ((rectballpos.y > rectcolp2.y) && (rectballpos.y < rectcolp2.h))
        {
            switch (direccionball)
            {
                case MOVE_DOWNRIGHT:
                    direccionball = MOVE_DOWNLEFT;
                    rectballpos.x -= stepx;
                    break;
                case MOVE_UPRIGTH:
                    direccionball = MOVE_UPLEFT;
                    rectballpos.x -= stepx;
                    break;
            }
        }
        else
        {
            tant1.SetTantos(tant1.GetTantos() + 1);
            gamestat = GAME_TANTO;
            //Tanto para P1
        }
    }
}


void InitSecTimer()
{
    tsec_ini = SDL_GetTicks();
}
void RefreshTime()
{
int ttime;
    tfrac_fin = SDL_GetTicks();
    ttime = tfrac_fin - tsec_ini;
    if (ttime >= 200)
    {
        tcount_200++;
        drawt = !drawt;
        if (tcount_200 >=5)
        {
            timer_secs++;
            tcount_200 = 0;
        }

        tsec_ini = SDL_GetTicks();
    }

}


Espero sepan disculpar mi aberracion al lenguaje ya que esta TODO SUMAMENTE DESORDENADO, no libero algunas cosas al finalizar el programa, comentarios... 0 comentarios.

si algun alma caritativa me indica el buen camino, se los agradezco, yo se que el codigo es muy confuso, asi que si se aburren le dejan xD

es el codigo de un poing, si a alguien le interesa mas detalles, me avisan y yo publico un rar en el foro (si puedo) con el codigo completo.
lucesita
 
Mensajes: 57
Registrado: Mié Mar 12, 2008 2:49 pm

Notapor sofoke » Mié Abr 30, 2008 3:48 am

Yo enrealidad lo probe con algo sencillo solo un gameloop simple con y sin frames fijos... (unos 90fps) y mesigue consumiendo demaciados recursos...
Tambien intente con SDL_Delay tal como lo hace lucesita y tambien con algunos ciclos de C/C++ y spersiste el problema...
imagino que tal vez es de SDL el problema pues en linux y window$ me pasa lo mismo...
No se si alguien haya podido correguir el error...
NOTA:cuando se mantiene pulsasiones de teclas constantes la aplicacion sigue normal tal cual y sin consumir demasiados recursos....
...cuando lo popular no es suficiente...
Gnu-Linux-y-Más
Avatar de Usuario
sofoke
 
Mensajes: 102
Registrado: Jue May 24, 2007 8:10 pm
Ubicación: México

Notapor hugoruscitti » Mié Abr 30, 2008 2:51 pm

Hace ya unos años publiqué un artículo sobre el tema:

http://www.losersjuegos.com.ar/referenc ... /bucle.php

¿pudieron ver si esos ejemplos presentan el mismo problema
de rendimiento que ustedes tienen?.
Avatar de Usuario
hugoruscitti
Site Admin
 
Mensajes: 1242
Registrado: Dom Jul 30, 2006 3:57 am
Ubicación: Buenos Aires, Argentina

Notapor lucesita » Mié Abr 30, 2008 4:08 pm

Gracias por la respuesta hugo, los problemas que yo tenia con el rendimiento se solucionaron, con el SDL_Delay, y el problema que tenia que me consuimia cada vez mas RAM era por que recargaba imagenes.
lucesita
 
Mensajes: 57
Registrado: Mié Mar 12, 2008 2:49 pm

Notapor sofoke » Sab Jul 12, 2008 1:46 am

Despues de varios intentos (i algo de perdida de cabello) he podido correguir el problema..
vamos, que era un problema mio :oops: Con el Delay y corriguiendo el gameloop se ha corregio...
Gracias por el Aporte
...cuando lo popular no es suficiente...
Gnu-Linux-y-Más
Avatar de Usuario
sofoke
 
Mensajes: 102
Registrado: Jue May 24, 2007 8:10 pm
Ubicación: México


Volver a General

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 0 invitados

cron