Jumat, 04 Desember 2015

When is the right time to use

1. Struct
In C#, a structure is a value type data type. we use Struct when we want to make a single variable hold related data of various data types. The struct keyword is used for creating a structure. Structures are used to represent a record. Suppose you want to keep track of your books in a library


2. Pointer/reference
A pointer is a variable whose value is the address of another variable, we use Pointer when we want to direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address


3. Function
Functions will generally require a prototype. we use Function when we want compiler  function will return, what the function will be called, as well as what arguments the function can be passed. Function can be used in the same manner as a variable would be. For example, a variable can be set equal to a function that returns a value between zero and four.

4. Array
Array will specifies the type of the elements and the number of elements required by an array as follows .You use an array when you need to reference a list of objects or values. You use a while loop when you need to repeat a block of code based on a condition. Example when you have 1000 numbers, if you don't use arrays. you will find it's hard to sort these numbers...

=Write an example that uses combination all of items above.=

1. Pointer to Array of Structure stores the Base address of the Structure array.
void main()
{
struct Cricket *ptr = match;   // By default match[0]
for(i=0;i<4;i++)
    {
    printf("\nMatch : %d",i+1);[
    printf("\n%s Vs %s",ptr->team1,ptr->team2);
    printf("\nPlace : %s",ptr->ground);

    if(match[i].result == 1)
        printf("nWinner : %s",ptr->team1);
    else
        printf("nWinner : %s",ptr->team1);
    printf("\n");

    // Move Pointer to next structure element
    ptr++;
    }
}


2. Example of Pointer And Functions
Program to swap two number using call by reference.

 /* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
  int num1=5,num2=10;
  swap(&num1,&num2);  /* address of num1 and num2 is passed to swap function */
  printf("Number1 = %d\n",num1);
  printf("Number2 = %d",num2);
  return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}


Rabu, 02 Desember 2015

Rotation and Flipping Using SDL

Here adding more functionality to the texture class. The render function now takes in a rotation angle, a point to rotate the texture around, and a SDL flipping enum.

Like with clipping rectangles, give the arguments default values in case you want to render the texture without rotation or flipping.

//Texture wrapper class
class LTexture
{
    public:
        //Initializes variables
        LTexture();

        //Deallocates memory
        ~LTexture();

        //Loads image at specified path
        bool loadFromFile( std::string path );

        //Deallocates texture
        void free();

        //Set color modulation
        void setColor( Uint8 red, Uint8 green, Uint8 blue );

        //Set blending
        void setBlendMode( SDL_BlendMode blending );

        //Set alpha modulation
        void setAlpha( Uint8 alpha );
     
        //Renders texture at given point
        void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );

        //Gets image dimensions
        int getWidth();
        int getHeight();

    private:
        //The actual hardware texture
        SDL_Texture* mTexture;

        //Image dimensions
        int mWidth;
        int mHeight;
};

Before enter the main loop. declare variables to keep track of the rotation angle and flipping type.

       //Main loop flag
            bool quit = false;

            //Event handler
            SDL_Event e;

            //Angle of rotation
            double degrees = 0;

            //Flip type
            SDL_RendererFlip flipType = SDL_FLIP_NONE;

In the event loop, increment/decrement the rotation with the a/d keys and change the type of flipping with the q,w, and e keys.

   //Handle events on queue
                while( SDL_PollEvent( &e ) != 0 )
                {
                    //User requests quit
                    if( e.type == SDL_QUIT )
                    {
                        quit = true;
                    }
                    else if( e.type == SDL_KEYDOWN )
                    {
                        switch( e.key.keysym.sym )
                        {
                            case SDLK_a:
                            degrees -= 60;
                            break;
                         
                            case SDLK_d:
                            degrees += 60;
                            break;

                            case SDLK_q:
                            flipType = SDL_FLIP_HORIZONTAL;
                            break;

                            case SDLK_w:
                            flipType = SDL_FLIP_NONE;
                            break;

                            case SDLK_e:
                            flipType = SDL_FLIP_VERTICAL;
                            break;
                        }
                    }
                }

Sound Effects and Music Using DSL

//Using SDL, SDL_image, SDL_mixer, standard IO, and strings
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <stdio.h>
#include <string>

SDL_mixer is a library use to make audio playing easier (because it can get complicated). to set it up just like set up SDL_image. Like before, it's just a matter of having the headers files, library files, and binary files in the right place with your compiler configured to use them.

     //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                {
                    printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                    success = false;
                }

                 //Initialize SDL_mixer
                if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
                {
                    printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
                    success = false;
                }

To initialize SDL_mixer need to call Mix_OpenAudio. The first argument sets the sound frequency, and 44100 is a standard frequency that works on most systems. The second argument determines the sample format, which again here using the default. The third argument is the number of hardware channels, and here using 2 channels for stereo. The last argument is the sample size, which determines the size of the chunks use when playing sound

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load prompt texture
    if( !gPromptTexture.loadFromFile( "21_sound_effects_and_music/prompt.png" ) )
    {
        printf( "Failed to load prompt texture!\n" );
        success = false;
    }

    //Load music
    gMusic = Mix_LoadMUS( "21_sound_effects_and_music/beat.wav" );
    if( gMusic == NULL )
    {
        printf( "Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

Here load our splash texture and sound.
To load music call Mix_LoadMUS and to load sound effect call Mix_LoadWAV. 

    //Load sound effects
    gScratch = Mix_LoadWAV( "21_sound_effects_and_music/scratch.wav" );
    if( gScratch == NULL )
    {
        printf( "Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }
 
    gHigh = Mix_LoadWAV( "21_sound_effects_and_music/high.wav" );
    if( gHigh == NULL )
    {
        printf( "Failed to load high sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

    gMedium = Mix_LoadWAV( "21_sound_effects_and_music/medium.wav" );
    if( gMedium == NULL )
    {
        printf( "Failed to load medium sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

    gLow = Mix_LoadWAV( "21_sound_effects_and_music/low.wav" );
    if( gLow == NULL )
    {
        printf( "Failed to load low sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
        success = false;
    }

    return success;
}

In the event loop, play a sound effect when the 1, 2, 3, or 4 keys are pressed. The way to play a Mix_Chunk is by calling Mix_PlayChannel. The first argument is the channel you want to use to play it
 //Handle key press
                    else if( e.type == SDL_KEYDOWN )
                    {
                        switch( e.key.keysym.sym )
                        {
                            //Play high sound effect
                            case SDLK_1:
                            Mix_PlayChannel( -1, gHigh, 0 );
                            break;
                         
                            //Play medium sound effect
                            case SDLK_2:
                            Mix_PlayChannel( -1, gMedium, 0 );
                            break;
                         
                            //Play low sound effect
                            case SDLK_3:
                            Mix_PlayChannel( -1, gLow, 0 );
                            break;
                         
                            //Play scratch sound effect
                            case SDLK_4:
                            Mix_PlayChannel( -1, gScratch, 0 );
                            break;

play/pause the music on a 9 keypress and stop the music on a 0 keypress.

When the 9 key pressed first check if the music is not playing with Mix_PlayingMusic. If it isn't,start the music with Mix_PlayMusic. The first argument is the music play and the last argument is the number of times to repeat it. Negative 1 is a special valu to loop it until it is stopped.

 case SDLK_9:
                            //If there is no music playing
                            if( Mix_PlayingMusic() == 0 )
                            {
                                //Play the music
                                Mix_PlayMusic( gMusic, -1 );
                            }
                            //If music is being played
                            else
                            {
                                //If the music is paused
                                if( Mix_PausedMusic() == 1 )
                                {
                                    //Resume the music
                                    Mix_ResumeMusic();
                                }
                                //If the music is playing
                                else
                                {
                                    //Pause the music
                                    Mix_PauseMusic();
                                }
                            }
                            break;
                         
                            case SDLK_0:
                            //Stop the music
                            Mix_HaltMusic();
                            break;
                        }
                    }

Time Capabilites Using SDL

//Using SDL, SDL_image, SDL_ttf, standard IO, strings, and string streams
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>
#include <sstream>

Before enter the main loop to declare some variables.  pay attention to is the startTime variable (which is an Unsigned integer that's 32bits) and the timeText variable which is a string stream.

 //Main loop flag
            bool quit = false;

            //Event handler
            SDL_Event e;

            //Set text color as black
            SDL_Color textColor = { 0, 0, 0, 255 };

            //Current time start time
            Uint32 startTime = 0;

            //In memory text stream
            std::stringstream timeText;

There's a function called SDL_GetTicks which returns the time since the program started in milliseconds. For this demo,  be having a timer that restarts every time  press the return key.

 //While application is running
            while( !quit )
            {
                //Handle events on queue
                while( SDL_PollEvent( &e ) != 0 )
                {
                    //User requests quit
                    if( e.type == SDL_QUIT )
                    {
                        quit = true;
                    }
                    //Reset start time on return keypress
                    else if( e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_RETURN )
                    {
                        startTime = SDL_GetTicks();
                    }
                }
using our string stream. First call str with an empty string to initialize it to be empty. Then treat it like cout and print to it "Milliseconds since start time " and the current time minus the relative start time so it will print the time since last started the timer.

        //Set text to be rendered
                timeText.str( "" );
                timeText << "Milliseconds since start time " << SDL_GetTicks() - startTime;

How to Rendering text from true type Fonts Using SDL

One way to render text with SDL is with the extension library SDL_ttf. SDL_ttf allows you to create images from TrueType fonts which use here to create textures from font text.

//Using SDL, SDL_image, SDL_ttf, standard IO, math, and strings
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>

#include <cmath>

To use SDL_ttf, you have to set up the SDL_ttf extension library just like you would set up SDL_image. Like before, it's just a matter of having the headers files, library files, and binary files in the right place with your compiler configured to use them.

//The window be rendering to
SDL_Window* gWindow = NULL;

//The window renderer
SDL_Renderer* gRenderer = NULL;

//Globally used font
TTF_Font *gFont = NULL;

//Rendered texture

LTexture gTextTexture;

For this and future tutorials, using a global font for our text rendering. In SDL_ttf, the data type for fonts is TTF_Font.


and also have a texture which will be generated from the font.

 //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                {
                    printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                    success = false;
                }

                 //Initialize SDL_ttf
                if( TTF_Init() == -1 )
                {
                    printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
                    success = false;

                }

Just like SDL_image, we have to initialize it or the font loading and rendering functions won't work properly.start up SDL_ttf using TTF_init. We can check for errors using TTF_GetError().

void close()
{
    //Free loaded images
    gTextTexture.free();

    //Free global font
    TTF_CloseFont( gFont );
    gFont = NULL;

    //Destroy window    
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;
    gRenderer = NULL;

    //Quit SDL subsystems
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

}

In our clean up function, we want to free the font using TTF_CloseFont. We also want to quit the SDL_ttf library with TTF_Quit to complete the clean up.

How To Color Keying Using SDL

When rendering multiple images on the screen, having images with transparent backgrounds is usually necessary. Fortunately SDL provides an easy way to do this using color keying.

//Texture wrapper class
class LTexture
{
    public:
        //Initializes variables
        LTexture();

        //Deallocates memory
        ~LTexture();

        //Loads image at specified path
        bool loadFromFile( std::string path );

        //Deallocates texture
        void free();

        //Renders texture at given point
        void render( int x, int y );

        //Gets image dimensions
        int getWidth();
        int getHeight();

    private:
        //The actual hardware texture
        SDL_Texture* mTexture;

        //Image dimensions
        int mWidth;
        int mHeight;
};

Color key the cyan (light blue) colored background and render it on top of this background:

(foo.png)

Next, color key the image with SDL_SetColorKey before creating a texture from it. The first argument is the surface  to color key, the second argument covers whether to enable color keying, and the last argument is the pixel to color key with.

    //The final texture
    SDL_Texture* newTexture = NULL;

    //Load image at specified path
    SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
    if( loadedSurface == NULL )
    {
        printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
    }
    else
    {
        //Color key image
        SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );

=Here are the image loading functions in action.=

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load Foo' texture
    if( !gFooTexture.loadFromFile( "10_color_keying/foo.png" ) )
    {
        printf( "Failed to load Foo' texture image!\n" );
        success = false;
    }
    
    //Load background texture
    if( !gBackgroundTexture.loadFromFile( "10_color_keying/background.png" ) )
    {
        printf( "Failed to load background texture image!\n" );
        success = false;
    }

    return success;
}

=Here are the image loading functions in action.=

void close()
{
    //Free loaded images
    gFooTexture.free();
    gBackgroundTexture.free();

    //Destroy window    
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;
    gRenderer = NULL;

    //Quit SDL subsystems
    IMG_Quit();
    SDL_Quit();
}


How to getting an Image on the Screen using SDL

1. How to getting an Image on the Screen using SDL

Here some global variables.

//The window be rendering to
SDL_Window* gWindow = NULL;
 
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

//The image will load and show on the screen
SDL_Surface* gHelloWorld = NULL;

In the load media function load our image using SDL_LoadBMP. SDL_LoadBMP takes in the path of a bmp file and returns the loaded surface. If the function returns NULL, that means it failed so print to the console an error using SDL_GetError.

bool loadMedia()
{
    //Loading success flag
    bool success = true;

    //Load splash image
    gHelloWorld = SDL_LoadBMP( "02_getting_an_image_on_the_screen/hello_world.bmp" );
    if( gHelloWorld == NULL )
    {
        printf( "Unable to load image %s! SDL Error: %s\n", "02_getting_an_image_on_the_screen/hello_world.bmp", SDL_GetError() );
        success = false;
    }

    return success;
}

void close()
{
    //Deallocate surface
    SDL_FreeSurface( gHelloWorld );
    gHelloWorld = NULL;

    //Destroy window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystems
    SDL_Quit();
}


Make sure to get into the habit of having your pointers point to NULL when they're not pointing to anything.

int main( int argc, char* args[] )
{
    //Start up SDL and create window
    if( !init() )
    {
        printf( "Failed to initialize!\n" );
    }
    else
    {
        //Load media
        if( !loadMedia() )
        {
            printf( "Failed to load media!\n" );
        }
        else
        {
            //Apply the image
            SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL );


Stdarg

A function may be called with a varying number of arguments of  varying types.  The include file <stdarg.h> declares a type va_list and defines three macros for stepping through a list of arguments whose number and types are not known to the called function.

stdarg.h Types
Name           :   va_list
Description       :  type for iterating arguments


Macro functions
va_start            :  Initialize a variable argument list (macro )
va_arg              :  Retrieve next argument (macro )
va_end             :  End using variable argument list (macro )
va_copy           : Copy variable argument list (macro )

 - va_start()
The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.

-  va_arg()
The va_arg() macro expands to an expression that has the type and value of the next argument in the call

- va_end()
Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function.
 
-va_copy()
The va_copy() macro copies the (previously initialized) variable argument list src to dest.

-The function "foo" takes a string of format characters and prints out the argument associated with each format character based on the type.

=Example=

  #include <stdio.h>
  #include <stdarg.h>

       void
       foo(char *fmt, ...)
       {
           va_list ap;
           int d;
           char c, *s;

           va_start(ap, fmt);
           while (*fmt)
               switch (*fmt++) {
               case 's':              /* string */
                   s = va_arg(ap, char *);
                   printf("string %s\n", s);
                   break;
               case 'd':              /* int */
                   d = va_arg(ap, int);
                   printf("int %d\n", d);
                   break;
               case 'c':              /* char */
                   /* need a cast here since va_arg only
                      takes fully promoted types */
                   c = (char) va_arg(ap, int);
                   printf("char %c\n", c);
                   break;
               }
           va_end(ap);
       }