Sign in to follow this  

Devving in Linux

This topic is 3489 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all. I created a simple SDL base project on Windows for my ICT class. My teacher never took the time to find out more about graphical programming, and he asked me to create some sort of project with just a few simple drawing functions for the class to work with. If you wonder why the code I provide is so full of comments, thats why. I made it so that people can read through the code and help themselves with the weird stuff they're readig (seeing all most of them are used to is cout and cin). I've moved away from Windows to Ubuntu Linux this week, and I decided that this little SDL project would be perfect to set up my devving environment in Linux. I used Code::Blocks under Windows, and I've installed it here as well. I'm running into problems compiling anything though. If I try to compile my old project with Code::Blocks, I get the error
-------------- Build: default in Base Project [ESK mod] ---------------

Compiling: font.cpp
S: 1: Syntax error: Unterminated quoted string
Process terminated with status 2 (0 minutes, 0 seconds)
0 errors, 0 warnings
font.cpp is the first file. Also, I have no clue what to tell my compiler options about SDL, as in what libs and linker options to use. I feel it would be better to use command line compiling: I tried compiling from the command line using
rob@fruchtsirup:~/base-esk-mod/code$ g++ -o foo main.cpp font.cpp graphics.cpp timer.cpp -lSDL
This compiles without any problems. When I double click the resulting binary, all I get is a flashing screen though, not a black screen that stays open (what my code should be doing)... [Edit] When I run foo from the command line, it tells me there is a segmentation fault. I never had anything like this in Windows though. What's wrong here? [/Edit] Can someone help me getting my devving environment up in Linux? Thanks. In order to complete my post, I decided to post the full code:
///

/// font.h

///

///





#ifndef FONT_H

#define FONT_H



#include <SDL/SDL.h>

#include <string>





// A bmp font handler

class Font

{

public:



    Font( std::string filename );





    void setSpaceSize( int size );



    SDL_Surface* renderText( std::string text ) const;





    int getHeight() const;

    int getWidth( std::string sz ) const;



private:



    // The surface that stores the font

    SDL_Surface* bitmap;



    // One rect for every char

    SDL_Rect chars[256];



};





/// Description:

// Create a 16x16 grid which holds all characters in their respective cell.

// 0x00FFFF is interpreted as transparent, any other colour as coloured.

// Free space at the LEFT of a character will be ignored.

// ,_________________,_________________,_________________,

// |******           |********         |*********        |

// |******   #       |********#        |*********        |

// |******  # #      |********#        |*********        |

// |****** ## ##     |********#        |*********        |

// |****** #####     |********####     |********* ###    |

// |******##   ##    |********#   #    |*********#       |

// |******##   ##    |********####     |********* ###    |

// |******           |********         |*********        |

// |******           |********         |*********        |

// +-----------------+-----------------+-----------------+

//

// The stars in this diagram represent what will be ignored by the contructor.

//







#endif // FONT_H


///

/// font.cpp

///

///





#include "font.h"



#include "graphics.h"







// Constructor takes a surface that holds the bitmap with the font

Font::Font( std::string filename )

: bitmap(0)

{

    bitmap = loadImage( filename );



    // Only continue if the bitmap was loaded correctly

    if( bitmap != NULL ) {



        // The background color of the bmp is white

        Uint32 background = SDL_MapRGB( bitmap->format, 0x00, 0xFF, 0xFF );



        // The bmp holds 16x16 cells for the 256 chars

        int cell_w = bitmap->w / 16;

        int cell_h = bitmap->h / 16;



        // The char that we are currently setting

        int current_char = 0;



        for( int row = 0; row < 16; row++ ) {

            for( int col = 0; col < 16; col++ ) {



                // Set the rect values for the corresponding char

                chars[current_char].x = cell_w * col;

                chars[current_char].y = cell_h * row;

                chars[current_char].w = cell_w;

                chars[current_char].h = cell_h;





                // Scan current cell to fix the width from the left

                for( int cellcol = 0; cellcol < cell_w; cellcol++ ) {

                    for( int cellrow = 0; cellrow < cell_h; cellrow++ ) {



                        // If a non-background-pixel is found

                        if( getPixel32( cell_w * col + cellcol,

                                        cell_h * row + cellrow,

                                        bitmap )

                                        != background ) {



                            // Fix the rect

                            chars[current_char].x = cell_w * col + cellcol;

                            chars[current_char].w -= cellcol;



                            // Break the loops

                            cellrow = cell_h;

                            cellcol = cell_w;

                        }



                    }

                } // End of scanning from left



                // Edit the next char

                current_char++;



            }

        }



    }



}







SDL_Surface* Font::renderText( std::string text ) const

{

    int width = this->getWidth( text );



    SDL_Surface* surface = SDL_CreateRGBSurface( SDL_SRCCOLORKEY,

                                                 width, chars[0].h,

                                                 bitmap->format->BitsPerPixel,

                                                 bitmap->format->Rmask,

                                                 bitmap->format->Gmask,

                                                 bitmap->format->Bmask,

                                                 0 );



    int current_char = 0;

    SDL_Rect rect;

    rect.x = 0;

    rect.y = 0;

    while( current_char < text.length() ) {

        SDL_BlitSurface( bitmap, const_cast<SDL_Rect*>(&chars[text[current_char]]), surface, &rect );

        rect.x += chars[text[current_char]].w;

        current_char++;

    }





    return surface;

}





void Font::setSpaceSize( int size )

{

    chars[' '].x = bitmap->w / 16 - size; // This works because space is 32nd character

    chars[' '].w = size;

}







int Font::getHeight() const

{

    return bitmap->h / 16;

}



int Font::getWidth( std::string sz ) const

{

    int width = 0;

    for( int i = 0; i < sz.length(); i++ ) {

        width += chars[sz[i]].w;

    }



    return width;

}







/// End of font.cpp

///


///

/// graphics.h

///

///





#ifndef GRAPHICS_H

#define GRAPHICS_H



#include <SDL/SDL.h> // For SDL_Video

#include "font.h"







/// //////// ///

/// Graphics ///

/// //////// ///



class Graphics

{

public:



    //Graphics();

    Graphics( int screen_width = 800, int screen_height = 600 );

    ~Graphics();







    // Draw a single pixel

    void drawPixel( int x, int y, const SDL_Color& color );



    // Fill a square with p as center

    void fillSquare( int x, int y, int size, const SDL_Color& color );



    // Draw a line between p1 and p2

    void drawLine( int x1, int y1, int x2, int y2, const SDL_Color& color );





    // The uberpwnerful printString() function

    SDL_Surface* printString( std::string sz, const Font* fnt, int x, int y, const SDL_Color& color, int flags = 0 );



    // Advanced surface blitting function

    void blitSurface( SDL_Surface* surface, int x, int y, int flags = 0 );







    // Flip screen

    void flip();



    // Change the background color that flip() uses

    void setBGColor( Uint8 r, Uint8 g, Uint8 b );



private:



    // These are deliberately left private and unimplemented

    Graphics( const Graphics & );

    Graphics &operator=( const Graphics & );



    // The surface that we will be drawing on

    SDL_Surface *screen;



    // The background color that gets drawn after each flip()

    SDL_Color bgcolor;



    // The standard Alpha mask

    Uint32 amask;



};







/// Functions

// Get a pixel from a surface

Uint32 getPixel32( int x, int y, SDL_Surface *surface );

// Change a pixel on a surface

void putPixel32( int x, int y, SDL_Surface* surface, Uint32 pixel );

// Load an image into a surface

SDL_Surface* loadImage( std::string filename, int flags = 0 );

// Apply a filter to a surface

void filterSurface( SDL_Surface* surface, int flags );

// Return a SDL_Color (default is opaque)

SDL_Color newColor( Uint8 r, Uint8 g, Uint8 b );

SDL_Color newColor( Uint8 greytone );

// SDL_MapRGBA() with a Color

Uint32 SDL_MapColor( SDL_PixelFormat *fmt, const SDL_Color& c );







/// Flags:

const int GFX_POS_CENTERX = 1;

const int GFX_POS_CENTERY = 2;

const int GFX_POS_RIGHTX = 4;

const int GFX_POS_BOTTOMY = 8;



const int GFX_TXT_ALIGN_CENTER = 1;

const int GFX_TXT_ALIGN_RIGHT = 4;

const int GFX_TXT_RETURN_SURFACE = 16;

const int GFX_TXT_SMOOTH = 32;



const int GFX_IMG_COLORKEY = 1;

const int GFX_IMG_GRAYSCALE = 2;

const int GFX_IMG_DARKEN = 4;







#endif // GRAPHICS_H


///

/// graphics.cpp

///

///





#include "graphics.h"



#include <stdexcept> // For exception handling

#include <cmath> // For sin() and cos()

#include <vector>







/// //////// ///

/// Graphics ///

/// //////// ///



// Constructor for specific screensize

// Default values are 800x600

Graphics::Graphics( int screen_width, int screen_height )

{

    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )

      throw std::runtime_error( SDL_GetError() );





    SDL_WM_SetCaption( "Development", NULL );





    screen = SDL_SetVideoMode( screen_width, screen_height, 32, SDL_SWSURFACE );



    if( !screen ) {

        SDL_Quit();

        throw std::runtime_error( SDL_GetError() );

    }





    if( SDL_BYTEORDER == SDL_BIG_ENDIAN )

      amask = 0x000000ff;

    else

      amask = 0xff000000;





    bgcolor.r = 0x00;

    bgcolor.g = 0x00;

    bgcolor.b = 0x00;

}





// Default destructor

Graphics::~Graphics()

{

    SDL_Quit();

}







// Draw a single pixel

void Graphics::drawPixel( int x, int y, const SDL_Color& color )

{

    SDL_Rect rect;

    rect.x = x;

    rect.y = y;

    rect.w = 1;

    rect.h = 1;



    SDL_FillRect( screen, &rect, SDL_MapColor( screen->format, color ) );

}





// Fill a square with p as center

void Graphics::fillSquare( int x, int y, int size, const SDL_Color& color )

{

    if( size <= 0 )

      size = 1;



    SDL_Rect rect;

    rect.x = x - (size-1)/2;

    rect.y = y - (size-1)/2;

    rect.w = size;

    rect.h = size;



    SDL_FillRect( screen, &rect, SDL_MapColor( screen->format, color ) );

}





// Draw a line

void Graphics::drawLine( int x1, int y1, int x2, int y2, const SDL_Color& color )

{

    int x, y;



    int deltax = abs(x2-x1);

    int deltay = abs(y2-y1);





    drawPixel( x1, y1, color );

    drawPixel( x2, y2, color );





    if( deltax > deltay ) {



        if( x2 > x1 ) {



            for( int i = 0; i < deltax; i++ ) {

                x = x1 + i;

                y = y1 + i * (y2-y1)/(x2-x1);



                drawPixel( x, y, color );

            }

        }

        else { // x1 > x2



            for( int i = 0; i < deltax; i++ ) {

                x = x2 + i;

                y = y2 + i * (y2-y1)/(x2-x1);



                drawPixel( x, y, color );

            }

        }

    }

    else { // deltay > deltax



        if( y2 > y1 ) {



            for( int i = 0; i < deltay; i++ ) {

                x = x1 + i * (x2-x1)/(y2-y1);

                y = y2 - deltay + i;



                drawPixel( x, y, color );

            }

        }

        else { // y1 > y2



            for( int i = 0; i < deltay; i++ ) {

                x = x2 + i * (x2-x1)/(y2-y1);

                y = y1 - deltay + i;



                drawPixel( x, y, color );

            }

        }

    }



}







// The uberpwnerful printString() function

SDL_Surface* Graphics::printString( std::string sz, const Font* fnt, int x, int y, const SDL_Color& color, int flags )

{

    /// Have some material to work with

    SDL_Rect offset;

    offset.x = x;

    offset.y = y;

    offset.w = 0;

    offset.h = 0;



    // Stores all the lines of text

    std::vector<std::string> vlines;

    // The height of one line

    int line_height = fnt->getHeight();

    // Temporary values

    int tmpwidth = 0;

    int tmpheight = 0;

    // Substitution string

    std::string szsub;

    // Colour stuff

    Uint32 background = SDL_MapRGB( screen->format, 0x00, 0xFF, 0xFF );

    Uint32 pixel = SDL_MapRGBA( screen->format, color.r, color.g, color.b, color.unused );





    /// Split up the text in lines

    int n = 0;

    while( n != -1 ) {



        // Find a newline

        n = sz.find( '\n', 0 );

        // Split up at the newline

        szsub = sz.substr( 0, n );

        if( n != -1 ) sz = sz.substr( n+1 );

        // Add the line to the vector

        vlines.push_back( szsub );



        // Measure dimensions

        tmpwidth = fnt->getWidth( szsub );

        if( tmpwidth > offset.w )

          offset.w = tmpwidth;



        offset.h += line_height;

    }





    /// Create text surface

    SDL_Surface *temp = NULL;

    SDL_Surface *text = NULL;



    if( flags & GFX_TXT_SMOOTH ) {

        text = SDL_CreateRGBSurface( SDL_SWSURFACE|SDL_SRCALPHA,

                                     offset.w, offset.h,

                                     screen->format->BitsPerPixel,

                                     screen->format->Rmask,

                                     screen->format->Gmask,

                                     screen->format->Bmask,

                                     amask );

    }



    else {

        text = SDL_CreateRGBSurface( SDL_SWSURFACE|SDL_SRCALPHA,

                                     offset.w, offset.h,

                                     screen->format->BitsPerPixel,

                                     screen->format->Rmask,

                                     screen->format->Gmask,

                                     screen->format->Bmask,

                                     screen->format->Amask );

    }





    SDL_Rect rect;

    rect.x = rect.y = 0;

    rect.w = offset.w;

    rect.h = offset.h;



    SDL_FillRect( text, &rect, background );





    for( int i = 0; i < vlines.size(); i++ ) {



        temp = fnt->renderText( vlines[i] );



        if( flags & GFX_TXT_ALIGN_CENTER )

          rect.x = offset.w/2 - temp->w/2;

        else if( flags & GFX_TXT_ALIGN_RIGHT )

          rect.x = offset.w - temp->w;

        else

          rect.x = 0;



        rect.y = i * line_height;



        SDL_BlitSurface( temp, NULL, text, &rect );

        SDL_FreeSurface( temp );



    }





    /// Modify the text surface

    SDL_SetColorKey( text, SDL_SRCCOLORKEY, background );





    // Lock the surface for pixel manipulation

    if( SDL_MUSTLOCK( text ) )

      SDL_LockSurface( text );





    if( flags & GFX_TXT_SMOOTH ) {

        for( int i = 0; i < text->w; i++ ) {

            for( int j = 0; j < text->h; j++ ) {

                pixel = SDL_MapRGBA( text->format, color.r, color.g, color.b, 255 - (int)getPixel32( i, j, text ) );

                putPixel32( i, j, text, pixel );

            }

        }

    }



    else {

        for( int i = 0; i < text->w; i++ ) {

            for( int j = 0; j < text->h; j++ ) {

                if( getPixel32( i, j, text ) != background ) {

                    if( (int)getPixel32( i, j, text ) < 128 )

                      putPixel32( i, j, text, pixel );

                    else

                      putPixel32( i, j, text, background );

                }

            }

        }

    }





    // Unlock it again

    if( SDL_MUSTLOCK( text ) )

      SDL_UnlockSurface( text );





    /// Finish off



    if( flags & GFX_TXT_RETURN_SURFACE )

      return text;



    else

      blitSurface( text, x, y, flags );



    SDL_FreeSurface( text );



    return 0;

}





// Advanced surface blitting function

void Graphics::blitSurface( SDL_Surface* surface, int x, int y, int flags )

{

    SDL_Rect offset;

    offset.x = x;

    offset.y = y;

    offset.w = surface->w;

    offset.h = surface->h;



    if( flags & GFX_POS_CENTERX )

      offset.x -= offset.w/2;

    else if( flags & GFX_POS_RIGHTX )

      offset.x -= offset.w;



    if( flags & GFX_POS_CENTERY )

      offset.y -= offset.h/2;

    else if( flags & GFX_POS_BOTTOMY )

      offset.y -= offset.h;



    SDL_BlitSurface( surface, NULL, screen, &offset );

}









// Flip screen

void Graphics::flip()

{

    SDL_Flip( screen );



    SDL_Rect rect;



    rect.x = 0;

    rect.y = 0;

    rect.w = screen->w;

    rect.h = screen->h;



    SDL_FillRect( screen, &rect, SDL_MapRGB( screen->format, bgcolor.r, bgcolor.g, bgcolor.b ) );

}



// Change the background color that flip() uses

void Graphics::setBGColor( Uint8 r, Uint8 g, Uint8 b )

{

    bgcolor.r = r;

    bgcolor.g = g;

    bgcolor.b = b;

}









/// Functions



// Get a pixel from a surface

Uint32 getPixel32( int x, int y, SDL_Surface *surface )

{

    Uint32* pixels = (Uint32*)surface->pixels;



    return pixels[ ( y * surface->w ) + x ];

}



// Change a pixel on a surface

void putPixel32( int x, int y, SDL_Surface* surface, Uint32 pixel )

{

    Uint32* pixels = (Uint32*)surface->pixels;



    pixels[ ( y * surface->w ) + x ] = pixel;

}



// Load an image into a surface

SDL_Surface* loadImage( std::string filename, int flags )

{

    SDL_Surface* loaded_img = SDL_LoadBMP( filename.c_str() );

    SDL_Surface* optimized_img = NULL;



    if( loaded_img != NULL ) {

        optimized_img = SDL_DisplayFormat( loaded_img );

        SDL_FreeSurface( loaded_img );



        if( optimized_img != NULL ) {



            if( flags & GFX_IMG_COLORKEY )

              SDL_SetColorKey( optimized_img, SDL_SRCCOLORKEY, SDL_MapRGB( optimized_img->format, 0, 0xFF, 0xFF ) );



            if( flags != 0 )

              filterSurface( optimized_img, flags );



        }

    }



    return optimized_img;

}



// Apply a filter to a surface

void filterSurface( SDL_Surface* surface, int flags )

{

    if( SDL_MUSTLOCK( surface ) )

      SDL_LockSurface( surface );





    if( flags & GFX_IMG_GRAYSCALE ) {



        for( int x = 0; x < surface->w; x++ ) {

            for( int y = 0; y < surface->h; y++ ) {

                // Get pixel values

                Uint8 r, g, b, gray;

                Uint32 pixel = getPixel32( x, y, surface );

                SDL_GetRGB( pixel, surface->format, &r, &g, &b );

                // Magix number grayscaling

                gray = (Uint8)((0.35 * (double)r) + (0.49 * (double)g) + (0.16 * (double)b));

                // Set new pixel

                pixel = SDL_MapRGB( surface->format, gray, gray, gray );

                putPixel32( x, y, surface, pixel );

            }

        }



    }



    else if( flags & GFX_IMG_DARKEN ) {



        for( int x = 0; x < surface->w; x++ ) {

            for( int y = 0; y < surface->h; y++ ) {

                // Get pixel values

                Uint8 r, g, b, gray;

                Uint32 pixel = getPixel32( x, y, surface );

                SDL_GetRGB( pixel, surface->format, &r, &g, &b );

                // Magix number grayscaling

                gray = (Uint8)((0.35 * (double)r) + (0.49 * (double)g) + (0.16 * (double)b));

                r = (Uint8)(((double)r+(double)gray)/3.0);

                g = (Uint8)(((double)g+(double)gray)/3.0);

                b = (Uint8)(((double)b+(double)gray)/3.0);

                // Set new pixel

                pixel = SDL_MapRGB( surface->format, r, g, b );

                putPixel32( x, y, surface, pixel );

            }

        }



    }





    if( SDL_MUSTLOCK( surface ) )

      SDL_UnlockSurface( surface );

}



// Return a SDL_Color

SDL_Color newColor( Uint8 r, Uint8 g, Uint8 b )

{

    SDL_Color color = { r, g, b };

    return color;

}



SDL_Color newColor( Uint8 greytone )

{

    SDL_Color color = { greytone, greytone, greytone };

    return color;

}



// SDL_MapRGB() with a Color

Uint32 SDL_MapColor( SDL_PixelFormat *fmt, const SDL_Color& color )

{

    return SDL_MapRGB( fmt, color.r, color.g, color.b );

}







/// End of graphics.cpp

///


///

/// timer.h

///

///





#ifndef TIMER_H

#define TIMER_H







// The Timer class measures everything in seconds

class Timer

{

public:



    Timer();

    //~Timer();





    /// Functions to move on in time

    // Fills the accumulator with the time passed since previous fill

    void fillAccu();

    // Tries to remove dt from the accumulator,

    // returns false if it didn't succeed

    bool pinchAccu( float dt );





    // Pause/Unpause the timer

    void pause();

    bool paused;



    // Get time since last fill

    float timeSinceFill() const;



private:



    // Time vars

    float current_time;

    float accumulator;

    float new_time;

    float delta_time;



};







#endif // TIMER_H


///

/// timer.cpp

///

///





#include "timer.h"



#include <SDL/SDL.h> // For SDL_GetTicks()







// Default constructor

Timer::Timer()

: paused(false),

  accumulator(0.00),

  new_time(0.00),

  delta_time(0.00)

{

    // SDL_GetTicks() returns time in ms

    current_time = (float)SDL_GetTicks() / 1000.00;

}







/// Functions to move on in time



// Fills the accumulator with the time passed since previous fill

void Timer::fillAccu()

{

    new_time = (float)SDL_GetTicks() / 1000.00;

    delta_time = new_time - current_time;

    current_time = new_time;



    if( !paused )

      accumulator+= delta_time;

}



// Tries to remove dt from the accumulator,

// returns false if it didn't succeed

bool Timer::pinchAccu( float dt )

{

    if( accumulator >= dt ) {

        accumulator -= dt;



        return true;

    }



    return false;

}

/// End of time functions





// Pause/Unpause the timer

void Timer::pause()

{

    paused = !paused;

}





// Get time since last fill

float Timer::timeSinceFill() const

{

    return (float)SDL_GetTicks() / 1000.00 - current_time;

}







/// End of timer.cpp

///


///

/// base-esk-mod

/// main.cpp

///

///





#include <cstdlib>

#include "graphics.h"

#include "font.h"

#include <SDL/SDL.h>

#include "timer.h"

#include <sstream>



const int SCREENW = 1024;

const int SCREENH = 768;







int main( int argc, char* argv[] )

{

    /// Initialize here





    // Seed the randomizer

    //  This gives the computer the start value to calculate

    //  future "random" values. time(0) returns the time in

    //  milliseconds, so it's pretty random.

    srand( time(0) );







    // Create a graphics object

    //  This is an object that does everything related to graphics.

    //  Initialize it with the screen dimensions (int this case

    //  the constants SCREENW and SCREENH). See the documentation for

    //  more info on the Graphics class.

    Graphics gfx( SCREENW, SCREENH );



    // Tips:

    //  gfx.setBGColor( 0x00, 0x00, 0x00 );

    //   This will set the standard background color.







    // Create font objects

    //  A <Font> is a type, pretty much like an <int> or a <char>.

    //  You can load the font as demonstrated with

    //   Font name_of_your_font ( "path_to_your_font.bmp" );

    //  You can set the size of a space with

    //   name_of_your_font.setSpaceSize( <int> );

    Font bitstreamfnt( "fonts\\bitstream24.bmp" );

    bitstreamfnt.setSpaceSize( 8 );

    Font swissfnt( "fonts\\swiss-system.bmp" );

    swissfnt.setSpaceSize( 4 );







    // Event structure

    //  This is something SDL needs to work with user input.

    SDL_Event event;







    // Time vars

    //  The timer object will be the object we use so that everything

    //  runs in the correct speed. Time is measured in seconds.

    //  DELTA is the size of the steps we take in our processing, see the

    //  documentation for more info.

    Timer timer;

    const float DELTA = 0.001;







    // Stringstream for general purposes

    //  This is the general stringstream, we use it to store text

    //  temporarily.

    std::stringstream ss;







    // FPS stuff

    //  Just some vars that we use to count how many Frames Per

    //  Second (FPS) our program has.

    int fps = 0;

    int fps_counter = 0;

    float fps_timer = 0.0;







    // Colors

    //  SDL has a type built-in called SDL_Color. It holds 3 values,

    //  the RGB values of the color. Certain functions in Graphics

    //  need a color, so create the colors you are going to use

    //  here.

    SDL_Color white = { 0xFF, 0xFF, 0xFF };

    SDL_Color black = { 0x00, 0x00, 0x00 };

    SDL_Color orange = { 0xFF, 0xAA, 0x00 };







    // Your own stuff goes here

    //  If you need more things for your program, initialize them here

    //  and _NOT_ in the main loop.









    /// End of initializing





    /// Begin of main loop



    // The main loop will end when quit becomes true

    bool quit = false;

    do {



        /// Timestep here



        // Check documentation for more info.



        timer.fillAccu();



        while( timer.pinchAccu( DELTA ) ) {



            fps_timer += DELTA;



            /// Process here

            //





        } /// End of process



        /// End of timestep







        /// Event polling here



        // Event polling can check for many events, check the

        // documentation for a few examples.



        while( SDL_PollEvent( &event ) ) {



            // When the user quits by pressing the X in the top right corner

            if( event.type == SDL_QUIT )

              quit = true;





            // If a key was pressed

            if( event.type == SDL_KEYDOWN ) {



                // When the user presses escape

                if( event.key.keysym.sym == SDLK_ESCAPE )

                  quit = true;



                // Pause the timer with [P]

                if( event.key.keysym.sym == SDLK_p )

                  timer.pause();



                //







            } // SDL_KEYDOWN



            // If a key is let go

            if( event.type == SDL_KEYUP ) {



                //







            } // SDL_KEYUP



        }



        /// End of event polling







        /// Check the state



        // Check the documentation for more info





        /// End of state checking







        /// Draw here



        //







        // Flip the screen to see the changes

        gfx.flip();



        /// End of drawing





        /// Calculate fps info



        fps_counter++;



        if( fps_timer > 1.0 ) {

            fps = fps_counter;

            fps_timer = 0.0;

            fps_counter = 0;

        }



        /// End of calculations





    } while( !quit );



    /// End of main loop





    // Clean exit

    //  We have to "destroy" our graphics object in order

    //  not to leak any memory.

    gfx.~Graphics();





    return 0;

}





/// End of main.cpp

///


Share this post


Link to post
Share on other sites
Well I've ported some of my Allegro stuff from Windows to Ubuntu before and I'll give you some pointers from what I found out.
#1 your source code may look different and give compilations errors when moved due to the way windows and linux do line endings. A good editor should tell you this though or warn you.
#2 If you are hardcoding your paths to your assets i.e. images,sounds,etc.,which is a bad idea to begin with, you need to change all your windows backslashes \\to forward slashes //. That's probably why you are getting black screen since image not being found/loaded? Allegro will crash instead of giving you black screen though I haven't used SDL in a while so I dunno about SDL.
#3 Default Ubuntu install is not developer friendly! By this I mean that alot of necessary tools i.e. gcc, automake,libtool,etc will be missing and it's a PIA with Ubuntu to track down what is missing or necessary? I tried running the default SDL template "hello world" program that comes with KDevelop for example on Ubuntu and it didn't even compile until I apt-get'ed like 10 different things!
I'd recommend Fedora or Suse if you don't care what distro you using since I know they make it easy to install everything and that way you get all the tools you will need. Only downside is that they are a 4GB download vs Ubuntu 600mb download maybe that's why Ubuntu is missing so much stuff for game development.
In your case it looks like you already have everything for development installed so you can ignore #3. I guess I just wanted to rant about Ubuntu since it was way more work to get my Allegro programs to work in a default install of Ubuntu than I expected.
I can see now why people stick to one platform as much as possible since trying to get your programs to work in Windows and Linux takes time away from development.
Oh and have a look at this if you haven't already:
Frequently Asked Questions: Linux

[Edited by - daviangel on May 24, 2008 6:14:44 AM]

Share this post


Link to post
Share on other sites
Quote:
#3 Default Ubuntu install is not developer friendly! By this I mean that alot of necessary tools i.e. gcc, automake,libtool,etc will be missing and it's a PIA with Ubuntu to track down what is missing or necessary? I tried running the default SDL template "hello world" program that comes with KDevelop for example on Ubuntu and it didn't even compile until I apt-get'ed like 10 different things!
apt-get install build-essential g++ libsdl-dev ide_of_his_choice
There's no good reason to switch distros just because the packages aren't installed. It's not difficult; that's why package managers were invented.

EDIT: Apparently build-essential is already included in Ubuntu these days, too. g++ seems not to, though.

[Edited by - EdR on May 23, 2008 8:42:22 PM]

Share this post


Link to post
Share on other sites
Also some advice on your comments, they would be much more readable if you don't use a newline after each comment line, also you can user multi-line comments like
/*
blá blá
blá blá blá
*/

Share this post


Link to post
Share on other sites
> your source code may look different and give compilations errors when moved due to the way windows and linux do line endings.

C and C++ are both line ending independant. Hence the ';' to signify the end of a statement, not a line ending.

CR or LF are considered whitespace.

Share this post


Link to post
Share on other sites
Yes! Thanks for all your help guys! I was afraid I wouldn't get much support with Linux here, seeing most people probably do game-devving for Windows.

@EdR
g++ must have come with one of the packages I installed, because I can compile using it. I decided not to use an IDE, but just gedit together with the console.

@SplitThumbs
I've never ever used a debugger in my life, I wouldn't know how to.

@gumpy
I didn't try those commands yet. Lazy-foo's tutorial never mentioned anything like that either.

@force_of_will
Hmmm... I will take your advice, but I won't change my comments. It's my style, and I like how they look in an editor (using a monospace font). To each his own eh

@daviangel
Your tip helped my fix my problem, it was the slashes! I can now compile with g++ in commandline and it runs. Even the example Pong program I created to show my class what this base project is capable of wors flawlessly. Thank you!

Share this post


Link to post
Share on other sites
Quote:
Original post by gumpy

g++ -o foo main.cpp font.cpp graphics.cpp timer.cpp `sdl-config --cflags --libs`

See "man sdl-config".


You gotta love the beauty of back-ticks here :)

The sdl-config program provides you with all the necessary libs you need to compile SDL apps and the back-ticks (`) allow you to append the output from that command directly into your current command. Oh where I would be without back-ticks :P

Share this post


Link to post
Share on other sites
Yeah, those are pretty neat. I see what that code does now. I incorporated it into ym simple make file:

cc=g++
cflags=`sdl-config --cflags --libs`

# Linking objects
sdlapp : main.o font.o graphics.o timer.o
${cc} -o sdlapp main.o font.o graphics.o timer.o ${cflags}

# Compiling sources
%.o : %.cpp
${cc} -c $<

Share this post


Link to post
Share on other sites

This topic is 3489 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this