Latest Entries »


SDL is the foundation on which a game could be built without much ado. However, SDL is not complete in itself. It just provides services using, which, interaction between various components of a game/simulation as well as the games interaction with OS becomes seamless. If there are no components to utilize these services, then these services become just proof of concept. In a gaming engine, most of the time, these services are required by the rendering and AI components. From this part onwards I would be concentrating on the rendering component and its interaction with SDL. I will be covering the AI component in the future. Though SDL supports other graphics libraries, its usage with OpenGL is more common. The reason is that SDL and OpenGL fits like parts of a puzzle. So most of the time, the rendering component, or the rendering sub-system (I would be using this term from now onwards) of a gaming engine is built upon OpenGL. Hence understanding OpenGL is a must to build a good rendering sub-system. This part and the articles coming in the near future would be detailing the different aspects of OpenGL along with how SDL helps in creating a good framework for future purposes. In this part I would be providing whys and wherefores of OpenGL. The first section would detail about the whys and wherefores, second section would detail the steps in creating a basic application whereas in the second section I would be creating a framework using SDL that can be used in the future. In the same section, I would also use simple OpenGL routines to test the framework. That is the agenda for this discussion.

OpenGL- What is it:

 

If this question is asked, then the most common answer one would get is that OpenGL is graphics library in C. However, this is a misconception. In fact, OpenGL is low-level graphics library specification. Just like J2EE, OpenGL is nothing but a set of platform neutral, language independent and vendor neutral APIs. These APIs are procedural in nature. In simple terms, this means a programmer does not describes the object and appearances instead he/she details the steps through which an effect or an appearance can be achieved. These steps comprises of many OpenGL commands that includes commands to draw graphic primitives such as point, line, polygon etc in the three dimensions. OpenGL also provides commands and procedures to work with lighting, textures, animations etc. One important aspect to keep in mind is that OpenGL is meant for rendering. Hence it does not provide any APIs for working with I/O management, window management etc. that’s where SDL comes into picture. To understand how OpenGL renders, it is important to understand how it interfaces between graphics application and graphics card. So here we go.

The interfacing works at three levels. They are:

1. Generic Implementation

2. Hardware Implementation

3. OpenGL pipeline

While the Generic deals with providing a rendering layer that sits on top of the OS specific rendering system whereas Hardware implementation provides direct hardware interfacing and pipeline works at taking the command and giving it to hardware after processing. Lets look at the details.

1. Generic Implementation:

The other word for Generic Implementation is Software rendering. If the system can display a generated graphics, then technically speaking Generic Implementation can run anywhere. The place occupied by the Generic implementation is between the program and the software rasterizer. Pictorially it would be:

It is clear from the diagram that the Generic implementation takes the help OS specific APIs to draw the generated graphics. For example on Windows it is GDI whereas on *nix systems it is XLib. The generic implementation on Windows is known as WOGL and that on Linux is MESA 3D.

2. Hardware Implementation:

The problem with Generic implementation is that it depends on the OS for rendering and hence the rendering speed and quality differs from OS to OS. This is where Hardware Implementation comes. In this case, the calls to the OpenGL APIs are passed directly to the device driver (typically the AGP card’s driver). The driver directly interfaces the graphics device instead of routing it through OS specific graphics system. Diagrammatically:

The functioning of Hardware Interfacing is totally different from that of Generic Implementation which is evident from the diagram. Since interfacing with the device driver directly enhances both the quality as well as speed of the rendered graphics.

3. OpenGL Pipeline:

In essence, the term pipeline is a process that is the finer steps of a conversion or transformation. In other words a process such as conversion can be broken down into finer steps. These steps together form the pipeline. In a graphics pipeline, each stage or step refines the scene. In case of OpenGL it is vertex data. Whenever an application makes an API call, it is placed at command buffer alongwith commands, texture, vertex data etc. On flushing of this buffer(either programmatically or by driver), the contained data is passed on to the next step where calculation intensive lighting and transformations are applied. Once this is completed the next step creates colored images from the geometric, color and texture data. The created image is placed in the frame buffer which is the memory of the graphic device that is the screen. Pictorially this would be:

Though this a simplified version of the actual process, yet the above detailed process provides an insight into the working of OpenGL. This brings this section to conclusion. However one question still remains- what are the basic steps in creating an OpenGL application. That is what next section is about.

OpenGL- Basic Steps towards Application:

Till now theory of OpenGL was discussed. Now lets see how to put it into use. To draw any shape onto the screen, there are three main steps. They are:

1. Clearing the screen

2. Resetting the view

3. Drawing the scene

Of these the third step consists of multiple sub-steps. Following are the details:

1. Clearing the Screen:

To set the stage for drawing, clearing the screen is a must. This can be done by using the glClear() command. This command clears the screen by setting the values of the bit plane area of the view port. glClear() takes a single argument that is the bitwise OR of several values indicating which buffer is to be cleared. The values of the parameter can be :

a. GL_COLOR_BUFFER_BIT

It indicates the buffers currently enabled for color writing have to be cleared.

b. GL_DEPTH_BUFFER_BIT

This is used to clear the depth buffer.

c. GL_ACCUM_BUFFER_BIT

If the accumulation buffer has to be cleared use this.

d. GL_STENCIL_BUFFER_BIT

This is passed as parameter when the stencil buffer has to be cleared.

Next the color to be used as the erasing color is specified. This can be done using glClearColor(). This command clears the color buffers specified. That means when the specified color buffers are cleared the screen is recreated accordingly. So to clear the depth buffer and set the clearing color to blue the statements would be:

glClear(GL_DEPTH_BUFFER_BIT);

glClearColor(0.0f,0.0f,1.0f,0.0f);

2. Resetting the View:

The back ground and the required buffers have been cleared. But the actual model of the image is based on the view. View can be considered as the matrix representation of the image. So to draw this matrix has to be set to identity matrix. This is done using glLoadIdentity(). The statement would be:

glLoadIdentity();

3. Drawing the Scene:

To draw the scene we to tell OpenGL two things:

a. Start and Stop the drawing:

These commands are issued through the calls to glBegin() and glEnd(). The glBegin() takes one parameter-the type of shape to be drawn. To draw using three points use GL_TRIANGLES, GL_QUADS to use four points and GL_POLYGON to use multiple points. The glEnd() tells OpenGL to stop the drawing. For example, to draw a triangle the statements would be:

glBegin(GL_TRIANGLES);                                                                                                  :

:

glEnd();                    

The drawing commands come between these commands.

b. Issue the drawing commands:

In the drawing commands, vertex data is specified. These commands are of the type glVertex*f() where * corresponds to the no. of parameters-2 or 3. Each call creates a point and then connects it with the point created with earlier call. So to create a triangle with the coordinates (0.0, 1.0, 0.0), (-1.0,-1.0, 0.0) and (1.0,-1.0, 0.0) the commands would be:

glBegin(GL_TRIANGLES);

glVertex3f( 0.0f, 1.0f, 0.0f);                                            

                        glVertex3f(-1.0f,-1.0f, 0.0f);                                                                                                       glVertex3f( 1.0f,-1.0f, 0.0f);

glEnd();

That’s all there about drawing objects with OpenGL. In the next section, these commands would be used to put the SDL based framework to test.

SDL Based framework- Creation & Testing:

Till now I have discussed various APIs of SDL. Now its time to put them together so that working with OpenGL. So here we go.

First the includes:

#include <stdio.h>//  Include the Standard IO Header

#include <stdlib.h>// and the standard lib header

#include <string.h>// and the string lib header

#include <GL/gl.h>// we’re including the opengl header

#include <GL/glu.h>// and the glu header

#include <SDL.h>//and the SDL header

 

The global variables:

bool isProgramLooping;//we’re using this one to know if the program   

                                       //must go on in the main Loop

SDL_Surface *Screen;

 

Now the common functionalities- initialization, termination, full-screen toggling.

bool Initialize(void)// Any Application & User Initialization Code Goes Here

{

            AppStatus.Visible= true;         // At The Beginning, Our App Is Visible

            AppStatus.MouseFocus= true;// And Have Both Mouse

            AppStatus.KeyboardFocus = true;// And Input Focus

 

            // Start Of User Initialization. These are just examples

            angle    = 0.0f;// Set The Starting Angle To Zero

            cnt1= 0.0f;// Set The Cos(for the X axis) Counter To Zero

            cnt2= 0.0f;// Set The Sin(for the Y axis) Counter To Zero

           

         

            {

                        printf(“Cannot load graphic: %s\n”, SDL_GetError() );

                        return false;

            }

 

           

            return true;                                                                                                                                          // Return TRUE (Initialization Successful)

}

 

 

void Deinitialize(void)                                                                                                                         // Any User Deinitialization Goes Here

{

            return;                                                                                                                                                             // We Have Nothing To Deinit Now

}

 

void TerminateApplication(void)// Terminate The Application

{

            static SDL_Event Q;// We’re Sending A SDL_QUIT Event

 

            Q.type = SDL_QUIT;// To The SDL Event Queue

 

            if(SDL_PushEvent(&Q) == -1)            // Try Send The Event

            {

            printf(“SDL_QUIT event can’t be pushed: %s\n”, SDL_GetError() );             exit(1);                                                                                                                                                                                    // And Exit

            }

 

            return; // We’re Always Making Our Funtions Return

}

 

void ToggleFullscreen(void)                                                                                                                                                    // Toggle Fullscreen/Windowed (Works On Linux/BeOS Only)

{

            SDL_Surface *S;                                                                                                                                                                                  // A Surface To Point The Screen

 

            S = SDL_GetVideoSurface();                                                                                                                                        // Get The Video Surface

 

            if(!S || (SDL_WM_ToggleFullScreen(S)!=1))                                                                                       // If SDL_GetVideoSurface Failed, Or We Can’t Toggle To Fullscreen

            {

                        printf(“Unable to toggle fullscreen: %s\n”, SDL_GetError() );                                  // We’re Reporting The Error, But We’re Not Exiting

            }

           

            return;                                                                                                                                                                                                 // Always Return

}

 

Next comes the OpenGL parts- Creating an OpenGL window. In other words initializing OpenGL. But initializing needs updating as it is created. Hence the reshape function  :

void ReshapeGL(int width, int height) // reshape the window when it’s moved or resized

{

            glViewport(0,0,(GLsizei)(width),(GLsizei)(height));                                                              // Reset The Current Viewport

            glMatrixMode(GL_PROJECTION);                                                                                                                                 // select the projection matrix

            glLoadIdentity();                                                                                                                                                                     // reset the projection matrix

 

            gluPerspective(45.0f,(GLfloat)(width)/(GLfloat)(height),1.0f,100.0f);          // calculate the aspect ratio of the window

            glMatrixMode(GL_MODELVIEW);          // select the modelview matrix

            glLoadIdentity();                                 // reset the modelview matrix

            return;                                                

}

 

bool CreateWindowGL(int W, int H, int B, Uint32 F)                                                                            // This Code Creates Our OpenGL Window

{

            SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );                                                                                               // In order to use SDL_OPENGLBLIT we have to

            SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );                                                                               // set GL attributes first

            SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );

            SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );

            SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );                                                                          // colors and doublebuffering

 

            if(!(Screen = SDL_SetVideoMode(W, H, B, F)))                                                                                    // We’re Using SDL_SetVideoMode To Create The Window

            {

                        return false;                                                                                                                                                                 // If It Fails, We’re Returning False

            }

 

            SDL_FillRect(Screen, NULL, SDL_MapRGBA(Screen->format,0,0,0,0));                                                                                                                                                                                                                                                         

            ReshapeGL(SCREEN_W, SCREEN_H);                                                                                                                           // we’re calling reshape as the window is created

 

            return true;                                                                                                                                                                              // Return TRUE (Initialization Successful)

}

           

I will be discussing the APIs used in resize function in the next issue. Next is the draw function. It also contains the test code:

void Draw3D(SDL_Surface *S)            // OpenGL drawing code here

{

            glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear screen and

                                                                      //depth buffer. Screen color has been cleared at init

            glLoadIdentity();                                                                                                                                 // reset the modelview matrix

            glBegin(GL_TRIANGLES);                                                                   

                        glVertex3f( 0.0f, 1.0f, 0.0f);                                       

                        glVertex3f(-1.0f,-1.0f, 0.0f);                                                                                                  glVertex3f( 1.0f,-1.0f, 0.0f);                                              

              glEnd();

 

 

            glFlush();                                                                                                                                                         // flush the gl rendering pipelines

 

            return;

}

Now the main(). It contains the keyboard handling code

int main(int argc, char **argv)          

{

            SDL_Event E;   // and event used in the polling process

            Uint8 *Keys; // a pointer to an array that will contain the keyboard snapshot

            Uint32  Vflags; // our video flags

           

           

            Screen = NULL;

            Keys = NULL;  

            Vflags = SDL_HWSURFACE|SDL_OPENGLBLIT;//a hardware surface and special  

                                                                                          //openglblit mode

                                                //so we can even blit 2d graphics in our opengl scene

 

            if(SDL_Init(SDL_INIT_VIDEO)<0)// init the sdl library, the video subsystem

            {

              printf(“Unable to open SDL: %s\n”, SDL_GetError() );// if sdl can’t be nitialized

              exit(1);

            }

 

            atexit(SDL_Quit);// sdl’s been init, now we’re making sure thet sdl_quit will be   

                                          //called in case of exit()

 

 

            if(!CreateWindowGL(SCREEN_W, SCREEN_H, SCREEN_BPP, Vflags))                                      //  Video Flags Are Set, Creating The Window

            {

                        printf(“Unable to open screen surface: %s\n”, SDL_GetError() );                

                        exit(1);                                                                                               

            }

 

           

 

            if(!InitGL(Screen))// we’re calling the opengl init function

            {

              printf(“Can’t init GL: %s\n”, SDL_GetError() );

               exit(1);                                                                                                                                 }

 

            if(!Initialize())                                                                                                                         {

                        printf(“App init failed: %s\n”, SDL_GetError() );                                                                              exit(1);                                                                                                                        }

 

            isProgramLooping = true;                                                                                                                                          

           while(isProgramLooping)// and while it’s looping

            {

                        if(SDL_PollEvent(&E))

                        {

                                    switch(E.type)// and processing it

                                    {

                                               

                                    case SDL_QUIT:// it’s a quit event?

                                                {

                                                            isProgramLooping = false;                                                                                         

                                                            break;                                                                                                                          }

 

                                    case SDL_VIDEORESIZE:// It’s a RESIZE Event?

                                                {

                                                            ReshapeGL(E.resize.w, E.resize.h);                                                                

                                                            break;                                                                                                                                                  // And Break

                                                }

 

                                    case SDL_KEYDOWN:// Someone Has Pressed A Key?

                                                {

                                                            Keys = SDL_GetKeyState(NULL);                                                                                             break;                                                                                                                          }

 

                                    }

                        }

                       

                         Draw3D(Screen);                                                                                                                                            // Do The Drawings!

                                                SDL_GL_SwapBuffers();                                                                                                                      // and swap the buffers (we’re double-buffering, remember?)

                                    }

                        }

            }

 

            Deinitialize();  

            exit(0);            // And finally we’re out, exit() will call sdl_quit

 

            return 0;// we’re standard: the main() must return a value

}

 

That brings us to the end of this discussion. This time it was a bit lengthy. But the framework that has been developed just will work as the foundation for developing functionalities like lighting, texture mapping, animation and so on. The next topic would be using timers in animating the triangle just drawn. Till next time.


File Input / Output, also generally known as file I/O, is one of the essential components of any software. Games are no exception. The file I/O can be for loading a background, texture or a simple text indicating level or score. It can also be used for saving player’s current statistics, level details or the custom map of the level. Whatever be the scenario, without a good and optimized file I/O, the game play will not become a rewarding experience for the player. With so many platforms to target, optimization of an API and making it generic to be used on multiple platforms becomes an arduous task. That is where file I/O API of SDL comes into play. The APIs provided by SDL are not platform specific. The platform specific aspects are taken care by SDL under the hood. Hence, developer has to focus only on the logics of the game and not on the ‘logistics’ of file operations. The focus of this discussion will be on the File I/O provided by SDL. The first section will be about the whys and wherefores of the API. In the second section, the steps for using the API will be detailed. The last section will have an example that makes use of the API discussed in the first two sections. That is the outline for this discussion.

SDL File I/O API – the Whys and Wherefores

File I/O API is one of the lesser documented API of SDL. However, the features provided by the API eases many File I/O operations such as loading image from an archived (zip or gzip) files. The main aspect or component of the API that makes such operations to be performed easily is the structure named SDL_RWops. Since SDL_RWops structure forms the basis of file I/O, the file operations as well as the API is also known as RWops. So, in short, the RWops API consists of the following:

1. The SDL_RWops structure

2. The functions that operate upon the structure

The former takes the file handles as well as pointers to memory mapped files. Later provides ways to read from or write to the file handles and memory mapped files. Here are the details.

1. The SDL_RWops structure:

It is akin in functionality to the FILE structure provided by the standard C library. In other words, SDL_RWops is the read write operation structure. All the file I/O functions make use of this structure to keep track of file handlers, current position being accessed etc. To use the API, it is not necessary to know the internals or details of this structure. The main point to keep in mind is all the RWops API needs this structure to work. So, any exceptions encountered during running of an application that makes use of RWops API can be traced back to problems with initialization of this structure. One point to keep in mind is that it is also called as ‘RWops structure’.

2.  The functions that operate upon the structure

Most of the functions provided by the RWops API are similar in functionality to their counterparts found in standard library. The most commonly used functions of RWops are:

a. SDL_RWFromFile

It opens a file, the name of which has been passed as the argument. Apart from the filename, the second argument is the mode in which the file has to be opened. The function returns a pointer to SDL_RWops structure corresponding to the file opened. The following statement opens a file named “tux.bmp” in read mode and returns a pointer to SDL_RWops structure of the “tux.bmp”.

SDL_RWops *file;

file = SDL_RWFromFile(“tux.bmp”, “r”);

b. SDL_RWFromMem

It prepares or allocates memory area for RWops to use. In other words, it sets up the RWops structure based a memory area of a certain size. It takes two arguments – the memory (or pointer to the memory) to be allocated and size of the memory. One of the scenarios where this method comes handy is when one wants to save the current screen as a bitmap. The following example sets up RWops structure based on byte array.

char bitmap[310000];

SDL_RWops *rw;

rw = SDL_RWFromMem(bitmap, sizeof(bitmap));

c. SDL_FreeRW

It frees up the memory allocated to the structure. It takes pointer to the RWops structure as argument.

That brings us to the end of this section. Next section will be about the steps to use the API.

Using RWops API – Step-by-Step:

There are three basic steps to use RWops API. They are

1. Get/initialize the SDL_RWops structure

2. Perform operations on the structure

3. Free the structure

Even though the steps seem similar to that of using standard API, in the case of RWops, the same structure can be used to access memory, stream or a file handle. Here are the details.

1. Get or initialize the SDL_RWops structure

As discussed in the previous section SDL_RWops structure forms the basis of any file I/O operations in SDL. So, the first step is to get RWops structure. There are four ways to get the structure or initialize it. They are

a. Using a filename

In this case, the structure is initialized directly from the file whose name has been provided. To do so, SDL_RWFromFile function needs to be used. The following statement instantiates the structure from “texture.bmp” file

SDL_RWops *file;

file = SDL_RWFromFile(“texture.bmp”, “r”);

 

In the above statements, the structure is initialized from the filename passed as argument. The second argument is the mode in which the structure is initialized. In this case the mode is “r” i.e. read-only. Hence, the structure can be used only to read from “texture.bmp” file. Following are the acceptable values for mode argument

“r” – Open a file for reading. The file must exist.

“w” -Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.

“a” – Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.

“r+” – Open a file for update both reading and writing. The file must exist.

“w+” – Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.

“a+” – Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. One can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

b. From file pointer using SDL_RWFromFP

In this case, a file pointer is used to initialize the RWops structure. The file pointer, in this case, is opened using file I/O of standard library. This function is not present in the latest version of SDL since Windows platform does not support using files opened in an application by the DLLs. And SDL libraries are loaded as DLLs.

c. From a pointer in memory using SDL_RWFromMem

As discussed in first section, SDL_RWFromMem allows one to create RWops structure from memory based on pointer to the memory. On one hand, this comes handy when working with file data placed in memory using other API such as gzip API. On the other hand if one has to write something to a specific memory location, which then can be transferred to file, then also this function can be handy. The following statements depict the second scenario where memory location has to be written to.

char bitmap[310000];

SDL_RWops *rw;

rw = SDL_RWFromMem(bitmap, sizeof(bitmap));

SDL_SaveBMP_RW(screen_bitmap, rw, 0);

 

where screen_bitmap is pointer to the SDL_Surface containing the current screen data.

d. Allocating and filling it in manually using SDL_AllocRW:

Using SDL_AllocRW, one can get an empty RWops structure, the fields of which, needs to be filled manually. Following statement creates an empty RWops structure

SDL_RWops *c=SDL_AllocRW();

Explaining how to fill the structure is beyond the scope of this discussion.

This brings us to the second step.

2. Perform operations on the structure

Once the RWops structure is initialized, it can be used for any kind of file I/O permitted by SDL. It can be to update the texture of a scene, save the current screen as a bitmap, get the contents of a zip file and update the screen with it. It can be used to save the current map or player statistics. Possibilities are many. For example, the following statements reads a bitmap file and displays it on the screen

SDL_RWops *file;

SDL_Surface *image;

 

file = SDL_RWFromFile(“myimage.bmp”, “rb”);

image = SDL_LoadBMP_RW(file, 1); // 1 means the file will be automatically closed

 

3. Free the RWops structure

The last step is to free the structure once its usage is complete. This step is mandatory if the structure is created/initialized using SDL_AllocRW. To free the structure, pass the variable containing RWops structure pointer to SDL_FreeRW method. The following statement frees a RWops structure named rw

SDL_RWops *rw=SDL_AllocRW();

if(rw)

{

            SDL_FreeRW(rw);

}

That completes the section on the steps to use RWops API.

3. RWops API – In the real world

In real world, the API is not used as standalone. Most of the time it is used in conjunction with some other API such as zlib that reads archived files (zip, gzip etc.). The example, I am about to discuss, makes use of zlib API to read a archived file. The example will be developed as a method that will

a. Accept the name/full path of the archive

b. Return the RWops structure corresponding to the archive

Let us start with the header file to be included.

#include “SDL.h”

#include <stdio.h>

#include <zlib.h>

The zlib.h header is required for zlib API. Next is the function. It takes archive name and the size of memory to be allocated for the file content as the arguments and returns the RWops structure

SDL_RWops* GetFromArchive( char *archive, int bufferSize)

{

}

Next step is to declare variables for the RWops structure and the gzFile. gzFile is the zlib equivalent of standard I/O’s FILE structure. It will also initialize an array of size specified by bufferSize argument.

SDL_RWops* GetFromArchive( char *archive, int bufferSize)

{

 /* gzFile is the Zlib equivalent of FILE from stdio */

  gzFile file;

 

 /* This is the RWops structure we’ll be using */

  SDL_RWops *rw;

 

 Uint8 buffer[bufferSize];

 

  /* We’ll need to store the actual size of the file when it comes in

   */

  int filesize;

}

Next, open the archive, fill the buffer with contents of the archive and create RWops structure from the buffer. It will also return the created RWops.

SDL_RWops* GetFromArchive( char *archive, int bufferSize)

{

/* This is the RWops structure we’ll be using */

SDL_RWops *rw;

/* gzFile is the Zlib equivalent of FILE from stdio */

gzFile file;

Uint8 buffer[bufferSize];

/* We’ll need to store the actual size of the file when it comes in

*/

int filesize;

 filesize = gzread(archive, buffer, 13000);

/* Create RWops from memory – SDL_RWFromMem needs to know where

     the data is, and how big it is (that is the file size was saved)

  */

  rw = SDL_RWFromMem(buffer, filesize);

 

return rw;

}

That completes the example. The example assumes knowledge of zlib API. Though RWops provides way to read and write to and from files, neither RWops nor SDL itself provide easy way to manipulate the loaded images. That is where SDL Image library comes into picture. Working with the SDL Image API will be the focus of next discussion. Till then…


PRESS RELEASE
28th September 2012
Packt Publishing reaches 1000 IT titles and celebrates with an open invitation

Birmingham-based IT publisher Packt Publishing is about to publish its 1000th title. Packt books are renowned among developers for being uniquely practical and focused, but you’d be forgiven for not yet being in the know – Packt books cover highly specific tools and technologies which you might not expect to see a high quality book on.

Packt is certain that in its 1000 titles there is at least one book that everyone in IT will find useful right away, and are inviting anyone to choose and download any one of its eBooks for free over its celebration weekend of 28-30th Sep 2012. Packt is also opening its online library for a week for free to give customers an easy to way to research their choice of free eBook.

Packt supports many of the Open Source projects covered by its books through a project royalty donation, which has contributed over $400,000 to Open Source projects up to now. As part of the celebration Packt is allocating $30,000 to share between projects and authors as part of the weekend giveaway, allocated based on the number of copies of each title downloaded.

Dave Maclean, founder of Packt Publishing:

“At Packt we set out 8 years ago to bring practical, up to date and easy to use technical books to the specialist tools and technologies that had been largely overlooked by IT publishers. Today, I am really proud that with our authors and partners we have been able to make useful books available on over 1000 topics and make our contribution to the development community.”

More details can be found at

http://bit.ly/RXnAMc


In the world of gaming, SDL provides the entire necessary infrastructure. This would have become clear from the past parts of the series. But infrastructure is to a game what skeleton is to a human body. But without muscles, no locomotion is possible. So working with the analogy of body, SDL provides the skeletal structure to build up the game whereas the flesh, blood and skin are provided by 2D and 3D graphics libraries. In the current plethora of 3D libraries, OpenGL stands out on various accounts. The most significant of them is its compatibility with almost all the platforms and graphics cards. This even reflects in the architecture of SDL as SDL can create and use OpenGL contexts on several platforms. Such architecture helps the game programmer to use all the sub-systems of SDL seamlessly in conjunction with OpenGL to provide most effective games and gaming environments. In this article I will discuss how to use SDL and OpenGL together where gaming infrastructure is provided by SDL and animation as well as rendering is being handled by OpenGL. The first section would discuss the steps required to integrate OpenGL with SDL. The second section would utilize the pointers provided in the first section to create an application having animation(basic) using OpenGL. That is the agenda for the current discussion.

Initialization- Bringing OpenGL into Picture:

 

In SDL all the sub-systems are initialized via SDL_Init(). OpenGL, being a part of graphics subsystem, is not directly initialized in this manner. For initializing OpenGL following are the steps:

1. Set OpenGL Attributes

2. Specify use of Double Buffering

3. Set the Video Mode

Of these second one is optional as it is used only when double buffering is a requirement. Lets have a detailed look at all of them.

1. Setting the OpenGL Attributes:

Before initializing the video, it is better to set up the OpenGL. These attributes are passed to the OpenGL via SDL calling the SDL_GL_SetAttribute() function. The parameters are the OpenGL attribute and their values. The most common attributes passed to this function are:

i. SDL_GL_RED_SIZE:

It sets the size of the red component of the frame buffer. The value is in bits. The commonly used value is 5. Similar parameters exist for blue and green components which are SDL_GL_BLUE_SIZE and SDL_GL_GREEN_SIZE respectively. To set green component to a bit value of 4 the code would be:

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 4 );

ii. SDL_GL_BUFFER_SIZE:

To set the size of the frame buffer this attribute is passed with the required Buffer size in bits. It is greater than or equal to the combined value i.e. sum of the red, green, blue and alpha components. If the requirement is 24 bit color depth and alpha channel of 32-bits then each color component must be given the size value as 8 and frame buffer must be given size as 32. In code it would be:

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

iii. SDL_GL_DEPTH_SIZE:

This attribute controls the size of depth buffer or Z buffers. Normally the graphics cards provide 16-bit or 24-bit depth. If the value is set more than what is available, the operation will fail. To make it more clear following is the code:

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);

iv. SDL_GL_ACCUM_RED_SIZE:

To set the size of red component of accumulation buffer, this attribute is used.

The value is specified in bits. SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_GREEN_SIZE controls the size of blue and green component of accumulation buffer. In code it would be:

SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,5);

The question that would be arising in your mind would be that whether these attributes could be set after initializing the video mode. The answer is no. The reason is that these settings have to be initialized before invoking and configuring video mode. Next we have to setup the video mode.

2. Setting up double buffering:

This aspect has also to be covered before setting up the video mode as this     attribute goes as a flag parameter to the SDL_GL_SetAttribute. The attribute is     SDL_GL_DOUBLEBUFFER and the value is either 1 or 0. The point to be kept in     mind is that when working in conjunction with OpenGL, the flag specifying double     buffer must be passed as an attribute to the SDL_GL_SetAttribute function and not to the SDL_Set_VideoMode(). In code this would be:

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);

would set the double buffering to one state.

3. Setting the Video Mode:

Once the OpenGL attributes are set, setting the video mode is similar to the     setting of video mode as described in last tutorials. For more details have a look     at Part-II of the tutorial. The only difference comes in flags being sent to the     SDL_Set_VideoMode(). Apart from other required flags the SDL_OPENGL would     also be set i.e.

int flags=0;

flags= SDL_OPENGL | SDL_FULLSCREEN;

setting the SDL_OPENGL flag is a must.

That’s all there about the required steps. Now let the OpenGL play.

OpenGL in Action:

The theory is over. Its now time to see some real action. The example application would render a rotating triangle. The includes will contain one more header file.

#include <SDL/SDL.h>

#include <gl/gl.h>

 

gl.h contains function declarations necessary to work with OpenGL.

Next comes the main() and OpenGL attributes.

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

{

  SDL_Event event;

  float theta = 0.0f;

  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );       

  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

 

:

:

}

Next initialize the video and video mode

 

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

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

  SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE | 

                               SDL_NOFRAME);

:

:

}

 

The video is initialized to 600×300 resolutions. And the hardware rendering mode is being used. This is done by SDL_HWSURFACE flag. Hence OpenGL would write on the graphic card’s memory instead of mapping it to software memory. After this step, the territory of OpenGL starts.

 

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

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

  glClearDepth(1.0);

  glDepthFunc(GL_LESS);

  glEnable(GL_DEPTH_TEST);

  glShadeModel(GL_SMOOTH);

  glMatrixMode(GL_PROJECTION);

  glMatrixMode(GL_MODELVIEW);

:

:

}

to start working with OpenGL, the view port is initialized. Then the screen is cleared or rendered with the specified background color. Since the triangle would be rotating in 3D space hence the depth has to be set and depth testing has to be enabled. If smooth shading is not used, then the edges would seem jagged. Hence smooth shading model is used. This completes the setting up of OpenGL parameters after SDL video initialization. Drawing and rotation is taken care by the following code in bold:

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

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0);

glDepthFunc(GL_LESS);

glEnable(GL_DEPTH_TEST);

glShadeModel(GL_SMOOTH);

glMatrixMode(GL_PROJECTION);

glMatrixMode(GL_MODELVIEW);

int done;

  for(done = 0; !done;)

 {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

 

    glLoadIdentity();

    glTranslatef(0.0f,0.0f,0.0f);

    glRotatef(theta, 0.0f, 0.0f, 1.0f);

   :

:

}

}

The focus is brought to the point of origin by translating it. Then rotation function is provided the theta value through which the triangle has to be rotated.

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

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0);

glDepthFunc(GL_LESS);

glEnable(GL_DEPTH_TEST);

glShadeModel(GL_SMOOTH);

glMatrixMode(GL_PROJECTION);

glMatrixMode(GL_MODELVIEW);

int done;

for(done = 0; !done;)

{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glTranslatef(0.0f,0.0f,0.0f);

glRotatef(theta, 0.0f, 0.0f, 1.0f);

glBegin(GL_TRIANGLES);

    glColor3f(1.0f, 0.0f, 0.0f);

    glVertex2f(0.0f, 1.0f);

    glColor3f(0.0f, 1.0f, 0.0f);

    glVertex2f(0.87f, -0.5f);

    glColor3f(0.0f, 0.0f, 1.0f);

    glVertex2f(-0.87f, -0.5f);

    glEnd();

 

    theta += .5f;

    SDL_GL_SwapBuffers();

   :

:

}

}

The triangle is drawn by specifying the vertices. Then the theta value is increased. Next event handling part cometh.

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

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0);

glDepthFunc(GL_LESS);

glEnable(GL_DEPTH_TEST);

glShadeModel(GL_SMOOTH);

glMatrixMode(GL_PROJECTION);

glMatrixMode(GL_MODELVIEW);

int done;

for(done = 0; !done;)

{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glTranslatef(0.0f,0.0f,0.0f);

glRotatef(theta, 0.0f, 0.0f, 1.0f);

 glBegin(GL_TRIANGLES);

glColor3f(1.0f, 0.0f, 0.0f);

glVertex2f(0.0f, 1.0f);

glColor3f(0.0f, 1.0f, 0.0f);

glVertex2f(0.87f, -0.5f);

glColor3f(0.0f, 0.0f, 1.0f);

glVertex2f(-0.87f, -0.5f);

glEnd();

theta += .5f;

SDL_GL_SwapBuffers();

SDL_PollEvent(&event);

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

      done = 1;

}

}

That’s it. This is how SDL and OpenGL work together. The only piece missing in this puzzle is sound. It will be tackled in the next part which incidentally is the last part of this series. So till next time.


Graphics and handling user inputs- the combination that creates the symphony called game. A world (of game) where these two are out of phase ends in cacophony. In the last article I discussed about the various parameters that goes into creating a screen and loading bitmapped images on to the screen. That was pretty high-level as the work was done on structures that represent the actual screen and maps or sprites. But there are times when one has to get his/her hand dirty by working directly upon pixels. The creators of SDL had already anticipated this requirement and built the capacities to work at raw graphics level into the core itself. Thus developer is redeemed from understanding system, platform and architecture specific nitty-gritty about manipulating the pixels. The other aspect of gaming that gives sleepless nights to developers is handling the user input, as the handling of input devices changes from system to system. To remove this burden from the minds of the developers, SDL provides object-oriented approach in handling the events. In this article, I would be discussing these two aspects of SDL. In the first section, the discussion would focus on using pixel manipulation functions and their usages and the second section would focus on input handling. So now that the agenda for this article have been laid down lets get started.   Raw Graphics-Writing Directly onto the Display:  Though the SDL Graphics APIs provide pretty high level functionality abstracting off all the low-level details, yet, there are times when abstraction is not required. For this purpose also there are ways. These ways doesn’t exist as a library function but as separate functions that has to be embedded into your program. The functions are freely available. But for the completeness I am including them here. These functions are:

  1. getpixel():

This function is useful if pixel value have to be obtained from a given coordinates represented by X and Y values on the display. It works on a single pixel at a time. The first parameter is the surface from which the value has to be obtained. This is represented by a pointer to the SDL_Surface. The next two integer parameters represent the x and y coordinates from where the pixel value has to be obtained. The return value is an Uint32 representing the value of the pixel. Following is the code:   /*  * Return the pixel value at (x, y)  * NOTE: The surface must be locked before calling this!  */ Uint32 getpixel(SDL_Surface *surface, int x, int y) {     int bpp = surface->format->BytesPerPixel;     /* Here p is the address to the pixel we want to retrieve */     Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;       switch(bpp) {     case 1:         return *p;       case 2:         return *(Uint16 *)p;       case 3:         if(SDL_BYTEORDER == SDL_BIG_ENDIAN)             return p[0] << 16 | p[1] << 8 | p[2];         else             return p[0] | p[1] << 8 | p[2] << 16;       case 4:         return *(Uint32 *)p;       default:         return 0;       /* shouldn’t happen, but avoids warnings */     } }   The first thing to be done is to obtain the depth represented by BytesPerPixel. It is done by the first statement: int bpp = surface->format->BytesPerPixel;   Next statement is self explanatory. To get the address of the pixel, the pitch of the of the passed surface is multiplied by the value of Y- coordinate, the depth is multiplied by the X- coordinate and the resulting values are added with pixel data of the surface represented by pixels member of SDL_Surface. This calculation provides the actual address of the pixel. The SDL_Surface could be thought of as multi dimensional array. Hence the value could be accessed as row-major and column-major format. That is done in the second statement: Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;  As the value returned by BytesPerPixels ranges from 1-4 according to the bytes needed to represent the pixel, it can be used for returning the values in the corresponding format i.e. 8, 16, 24 or 32. this is achieved by the switch-case block. That’s all about getpixel function.

  1. putpixel():

This is same as getpixel(). Apart from the parameters accepted by getpixel() function, this accepts one parameter extra- the address where the value has to be put. Following is the code for putpixel():   /*  * Set the pixel at (x, y) to the given value  * NOTE: The surface must be locked before calling this!  */ void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel) {     int bpp = surface->format->BytesPerPixel;     /* Here p is the address to the pixel we want to set */     Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;       switch(bpp) {     case 1:         *p = pixel;         break;       case 2:         *(Uint16 *)p = pixel;         break;       case 3:         if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {             p[0] = (pixel >> 16) & 0xff;             p[1] = (pixel >> 8) & 0xff;             p[2] = pixel & 0xff;         } else {             p[0] = pixel & 0xff;             p[1] = (pixel >> 8) & 0xff;             p[2] = (pixel >> 16) & 0xff;         }         break;       case 4:         *(Uint32 *)p = pixel;         break;     } }   The working of putpixel() is almost opposite to that of getpixel(). In case of later, the returned value is pixel value corresponding to the coordinates whereas the later places the pixel value according the coordinates. For this first the BytesPerPixel of the passed SDL_Suface is extracted just like before. Then pixel’s address (or pixel value) is calculated and according to the value returned by BytesPerPixels the value is placed. Since the calculated value is address of the pixel, hence the passed pixel value can be directly assigned and the display will be getting the new value.   Now that both the functions have been explained, lets see how to put one them to use i.e. putpixel(). For this I am defining a method called putyellowpixel() that places a yellow pixel at the center of the screen. It doesn’t accept any parameter nor does it returns any value.   void putyellowpixel() {     int x, y;     Uint32 yellow;       /* Map the color yellow to this display (R=0xff, G=0xFF, B=0x00)        Note:  If the display is palettized, you must set the palette first.     */     yellow = SDL_MapRGB(screen->format, 0xff, 0xff, 0x00);       x = screen->w / 2;     y = screen->h / 2;       /* Lock the screen for direct access to the pixels */     if ( SDL_MUSTLOCK(screen) ) {         if ( SDL_LockSurface(screen) < 0 ) {             fprintf(stderr, “Can’t lock screen: %s\n”, SDL_GetError());             return;         }     }       putpixel(screen, x, y, yellow);       if ( SDL_MUSTLOCK(screen) ) {         SDL_UnlockSurface(screen);     }     /* Update just the part of the display that we’ve changed */     SDL_UpdateRect(screen, x, y, 1, 1);       return;   }   To get the yellow color, the SDL_MapRGB() has to be used. The SDL_PixelFormat is the first parameter. It stores surface format information. Next three parameters correspond to the red, blue and green components of the color. The return value is the actual color corresponding to the passed color components in hexadecimal format as follows: yellow = SDL_MapRGB(screen->format, 0xff, 0xff, 0x00);   Once the color has been retrieved, the next step is to get the required x and y coordinates which is achieved by the following statement: x = screen->w / 2; y = screen->h / 2; then screen surface is locked. If this is not done, then corruption of the SDL_Surface structure could get corrupted causing instability of the game as putpixel works on the address of pixel directly. This is done by:   SDL_MUSTLOCK(screen);   The next step is to call the putpixel. Once putpixel has returned, then unlock the surface and update the surface. That completes placing a pixel directly on to the surface. Next section would focus on even handling with reference to keyboard.   Handling the Key Board- the SDL way:Whatever has been discussed till now completes only one aspect of providing interactivity. Even now the application doesn’t have the ability to handle user gestures provided through different input devices such as keyboard, joy stick etc. So now the focus would be on the input handling. Two of the most common input devices are mouse and keyboard. SDL has wrappers for each of these. In this section I would be discussing about keyboard handling. Before entering the world of keyboard events, it is better to understand the most recurring structures in keyboard handling jargon. They are:

  1. SDLKey:

It is an enumerated type that represents various keys. For example SDLK_a represents lowercase ‘a’, SDLK_DELETE is for ‘delete’ key and so on.

  1. SDLMod:

SDLKey enumeration represents only keys. To represent key modifiers such as Shift and Ctrl, SDLMod enumeration is provided by the SDL. The KMOD_CAPS is one of the enumeration that can be used to find out whether caps key is down or not. Other modifiers also have representations in SDLMod.

  1. SDL_keysym:

It is a structure that contains the information of a key-press. The members of this structure include scan code in hardware dependent format, SDLKey value of the pressed key in sym field, the value of modifier key in mod field and the Unicode representation of the key in Unicode field.

  1. SDL_KeyboardEvent:

From the name itself it is obvious that this structure describes a keyboard event. The first member, type, tells that the event is key release or key press event. The second member gives the same info as the first but uses different values. The last member is a structure itself- the SDL_keysym structure.   Now that the structures have been brought into the picture, the next step is to use these in handling the keyboard events. For this the logic is simple. The SDL_PollEvent is used to read the events. This is placed within the while loop. Then the value of type member of SDL_Event variable, passed as the parameter to SDL_PollEvent, is checked to find the type of event and then event processing can be done. In code it is thus:   SDL_Event event;   .   .   /* Poll for events. SDL_PollEvent() returns 0 when there are no  */   /* more events on the event queue, our while loop will exit when */   /* that occurs.                                                  */   while( SDL_PollEvent( &event ) ){     /* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */     switch( event.type ){       case SDL_KEYDOWN:         printf( “Key press detected\n” );         break;         case SDL_KEYUP:         printf( “Key release detected\n” );         break;         default:         break;     }   }   .   .   If this is used this in the program developed in last article, the exit condition of the program can be controlled. The new version would exit only at key press.     void display_bmp(char *file_name) { SDL_Surface *image;   /* Load the BMP file into a surface */ image = SDL_LoadBMP(file_name); if (image == NULL) { fprintf(stderr, “Couldn’t load %s: %s\n”, file_name, SDL_GetError()); return; }   /* * Palettized screen modes will have a default palette (a standard * 8*8*4 colour cube), but if the image is palettized as well we can * use that palette for a nicer colour matching */ if (image->format->palette && screen->format->palette) { SDL_SetColors(screen, image->format->palette->colors, 0, image->format->palette->ncolors); }   /* Blit onto the screen surface */ if(SDL_BlitSurface(image, NULL, screen, NULL) < 0) fprintf(stderr, “BlitSurface error: %s\n”, SDL_GetError());   SDL_UpdateRect(screen, 0, 0, image->w, image->h);   /* Free the allocated BMP surface */ SDL_FreeSurface(image); }   int main(int argc,char* argv[]) { /*variable to hold the file name of the image to be loaded *In real world error  handling  code would precede this                                                                          */ char* filename=”Tux.bmp”; /*The following code does the initialization for Audio and Video*/ int i_error=SDL_Init(SDL_INIT_VIDEO); /*If initialization is unsuccessful, then quit */ if(i_error==-1) exit(1); atexit(SDL_Quit); /* * Initialize the display in a 640×480 8-bit palettized mode, * requesting a software surface */ screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE); if ( screen == NULL ) { fprintf(stderr, “Couldn’t set 640x480x8 video mode: %s\n”, SDL_GetError()); exit(1); }   /*Handle the keyboards events here. Catch the SDL_Quit event to exit*/ done = 0;              while (!done)             {                SDL_Event event;                 /* Check for events */         while (SDL_PollEvent (&event))              {             switch (event.type)             {                           case SDL_KEYDOWN:                 break;                           case SDL_QUIT:                             done = 1;                            break;             default:                           break;             }         } /* Now call the function to load the image and copy it to the screen surface*/ load_bmp(filename); }   If you run the above code the window wont be closed until the close button is pressed. Though, this code does nothing much in area of interactivity but it’s a beginning. So as you can see, it is really easy to handle keyboard events using SDL. It totally removes the dependence of developer on Operating System for event handling. Also working at raw graphics level is not that difficult.   This brings us to the end of the third part of SDL programming. The next part would cover using OpenGL with SDL. Also using timers would be covered. Till next time.


“Code less ..Achieve more” is the prime philosophy behind the development of all the Very High Level Languages (or VHLL in short). But less no. of lines should not mean reduced flexibility in terms of choosing an approach in solving a problem. Though many of the VHLL or Scripting Languages as they are popularly known, does not keep in mind the flexibility, yet there area few that have the logic of flexibility and choice as their core. Python is one of them. This fact is evident if one tries to do network programming in Python. The choices are aplenty for the programmer. The choices range from low-level sockets or raw-sockets to a completely extensible and functional web-server. In this tutorial I will be discussing how to use raw sockets to create network oriented applications in Python. The first section will cover the basics of the socket module and by the end of the section a simple echo server will be coded. In the second section the echo server would be enhanced by making it capable of serving multiple clients using the concepts introduced in the first section.

 

Sockets and Ports- Doing it the Python way:

Sockets and ports form the core of any network oriented application. According to the formal definition a socket is “An endpoint of communication to which a name may be bound”. The concept (as well as implementation) comes from the BSD community. The 4.3BSD implementation defines three domains for the sockets:

  1. Unix Domain/ File-system Domain:

The sockets under this domain are used when two or more processes within a system have to communicate with each other. In this domain, the sockets are created within the file system. They are represented as strings that contains local path such as /var/lock/sock or /tmp/sock.

 

  1. Internet Domain:

This domain represents the processes that communicate over the TCP/IP. The sockets created for this domain are represented using a (host, port) tuple. Here host is a fully qualified Internet host name that can be represented using a string or in the dotted decimal format (or IP address).

  1. NS Domain:

This domain is the one used by the processes communicating over Xerox protocol which is now obsolete.

 

Of these only the first two are the most commonly used. Python supports all of these. My discussion would be limited to the Internet Domain. To create an application that uses TCP/IP sockets following are the steps:

 

  1. Creating a socket
  2. Connecting the socket
  3. Binding the socket to an address
  4. Listening and accepting connections
  5. Transferring data/receiving data.

 

But before creating a socket libraries have to be imported. The socket module contains all that is needed to work with sockets. The imports can be done in two ways:

import socket or from socket import *. If the first form is used then to access the methods of socket module, socket.methodname() would have to be used. If the later format is used, then the methods could be called without the fully qualified name. I will be using the second format for clarity of the code and ease. Now lets see the various provisions within socket module for the programmers.

 

  1. Creating a socket:

A socket can be created by making call to the socket() function. The socket() function returns a socket in the domain specified. The parameters to the function are:

 

a. family:

The family parameter specifies in which domain the socket has to be created.  The valid values are AF_UNIX for UNIX domain and AF_INET for internet domain.

b. type:

Type defines the type of the protocol to be used. The type can be                   connection oriented like TCP or connection less like UDP. These are defined by the constants SOCK_STREAM for TCP, SOCK_DGRAM for UDP. Other valid parameters are SOCK RAW, SOCK SEQPACKET and SOCK RDM.

c. protocol:

This generally left for default value. The default is 0.

 

So a socket for Internet domain is created thus:

testsocket=socket(AF_INET,SOCK_STREAM)

 

  1. Connecting the Socket:

Sockets thus created can be used on the server-side or client-side. To use the socket as client-socket it needs to be connected to a host. That can be done using the connect() method of the socket object. The connect() method accepts either the host name as the parameter or a tuple containing host name/address and port number as parameter. For example to connect to a host whose address is 192.168.51.100 and the port number 8080 the statement would be:

 

testsocket.connect((‘192.168.51.100’,8080))

 

  1. Binding the socket to an address:

If the socket has to be used on the server side, then the socket has to be bound to an address and a port, thus naming it. To bind a socket to an address, the bind() method of the socket object has to be used. The valid parameter is a tuple containing the address to which the socket has to be bound and the port at which it has to listen for incoming requests. To use the same socket i.e. testsocket on the server side the statement would be:

 

testsocket.bind((‘192.168.51.100’,8080))

  1. Listening and accepting connections:

Once a socket has been named, then it has to be instructed to listen at the given port for incoming requests. This can be done using the listen() method. The listen accepts a no. representing the maximum queued connection. The argument should be atleast 1. for example the following code sets the max queued connection to 2:

 

testsocket.listen(2)

The next thing to be done is to accept the incoming connection requests. This can be done by the accept() function. This function returns a tuple containing a new socket object representing the client and the address of the client. For example:

clientsock,address= testsocket.accept()

in the above statement clientsock would contains a new socket object and address would contain the address of the client.

 

  1. Transferring data/receiving data:

Data can be transferred using recv() and send() methods of socket object. Socket’s recv() method is used to receive the data send from the server or from the client. The parameters are a buffer size for the data , and flags. The flags parameter is optional. So to receive data the code would be:

buff=1024

testsocket.recv(buff)

 

To send the data, a call to the send method is in order. The parameters are the data to be send and the flags. To elucidate  further:

data=raw_input(‘>>’)

testsocket.send(data)

Now that the steps are clear, lets create a simple echo server. First the imports

from socket import *

Then the constants that defines the host, port, buffer size and the address tuple to be used with bind().

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

 

Then create the server side socket and bind it to the host and the port. Then comes the max queue size to 2:

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

Now to make it listen for incoming requests continuously place the accept() method in a while loop. This is not the most preferable mode. The preferable way will be discussed in next section:

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

:

:

Next  receive the data from the client and echo it back. This has to continue till the client doesn’t send the null data or ctrl+c. to achieve this again use a while loop and then close the connection when done.

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

 

while 1:

data = clientsock.recv(BUFSIZ)

if not data: break

clientsock.send(‘echoed’, data)

 

clientsock.close()

serversock.close()

 

That’s all for the server. Now for the client. The only exception is that there is no bind(), accept() and listen().

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)

tcpCliSock.connect(ADDR)

while 1:

data = raw_input(‘> ‘)

if not data: break

tcpCliSock.send(data)

data = tcpCliSock.recv(1024)

if not data: break

print data

tcpCliSock.close()

Multi-Threaded Echo Server- Other Approach in Creating a Server:

 

In the above example the uses while loop to service different clients. For elucidations it is ok. But in the real world, it won’t work well. The reason is that more than one client cannot be served simultaneously by just while constructs. To overcome the limitations there are several strategies. One of them is making the server multi-threaded. There are two parts in the creation of a multi threaded server:

 

  1. Create threads for each accepted  connections:

This is the core of the multi-threaded server. For each accepted connection request, a different thread is created and the serving that particular client is carried out by an independent thread. Thus quick response time can be achieved.

 

  1. Create a handler:

It is the handler where the whole processing goes on. In our case transferring a file.

 

To make the echo server some changes have to be made. It starts with the accept part as shown below:

 

from socket import *

from threading import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

thread.start_new_thread(handler, (clientsock, addr))

 

 

 

serversock.close()

 

After accepting the request a new thread is created for the client. This is done for each connection request. The logic of handling the client is defined within the handler which goes thus:

 

from socket import *

from threading import *

def handler(clientsock,addr):

while 1:

data = clientsock.recv(BUFSIZ)

if not data: break

clientsock.send(‘echoed:..’, data)

 

clientsock.close()

if __name__==’__main__’:

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

thread.start_new_thread(handler, (clientsock, addr))

#some other cleanup code if necessary

 

The handler has to be defined before calling it. The handler contains the same code that was contained in the inner while loop previously. This example is not optimized. But it serves the purpose of providing a different approach for serving multiple clients. This brings us to the end of this section.

 

Parting Thoughts:

  1. The low level sockets can be mixed and matched with other modules such as threads and forks to create a server capable of serving multiple clients simultaneously.
  2. While using threading approach the locking and synchronization issues must be kept in mind.
  3. The security measures must be taken care of when creating FTP kind of servers.

 

This brings us to the end of this discussion. In the introductory section I mentioned flexibility as one of the core aspects of Python. Ability to work with low-level sockets is one of them. But at the other end of the spectrum are the pre-built yet extensible web-servers. These will be discussed in the near future. Till then…

2010 in review


The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads This blog is on fire!.

Crunchy numbers

Featured image

A helper monkey made this abstract painting, inspired by your stats.

A Boeing 747-400 passenger jet can hold 416 passengers. This blog was viewed about 3,400 times in 2010. That’s about 8 full 747s.

In 2010, there were 7 new posts, growing the total archive of this blog to 65 posts.

The busiest day of the year was August 13th with 39 views. The most popular post that day was Bluetooth Programming in Python: Network Programming using RFCOMM.

Where did they come from?

The top referring sites in 2010 were note19.com, en.wordpress.com, yandex.ru, google.co.in, and packtpub.com.

Some visitors came searching, mostly for server_sock listen python, c# image memory intptr to bitmap, python bluetooth, steps for accessing camera using pys60, and operations on text in pys60.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Bluetooth Programming in Python: Network Programming using RFCOMM May 2010
2 comments

2

Image Manipulation using GDI+ – The C# Way: Thumbnails and Zooming July 2009
2 comments

3

Bluetooth Programming using Python April 2010
1 comment

4

Mobile Programming in Python using PyS60: UI Controls July 2009
3 comments

5

Mobile Programming using PyS60: Advanced UI Controls July 2009
1 comment


The arrangement of data within the memory forms the basis of computing. The arrangement of data is known as data-structure. Every language provides variety of built-in data-structures. Languages such as C provide basic data-structure mechanisms using which complex structures can be built whereas languages such as Java use full-blown object-oriented approach for almost all types of data-structures. Then there are languages like Python which takes a middle approach. In this article I would be discussing the middle path used by Python using two of its built-in data-structures – Lists and Tuples. The first section would focus on functionalities of Lists and Tuples. In the second section I would develop a real world application which makes use of Lists and/or Tuples. That’s the agenda for this discussion.

 

List and Tuple – More About Them:

List and Tuple are two of the basic built-in data-structures. As with all other features of Python, these in-built data-structures provide both flexibility and power. The answer to how flexible and powerful they are is what I am going to discuss now. First lets look at List data-structure.

 

1. List:

By definition a List is “An instance of an abstract data type (ADT), formalizing the concept of an ordered collection of entities”. In other words, a List is a collection of objects. In contrast with Array, List contains different objects. That’s how Python also views Lists. Data types (that’s what Python calls built-in data-structures too) such as List is known as compound data type in Python. The operations that can be performed on a List are:

 

a. Creation

b. Addition of elements

c. Accessing and Searching

d. Deletion

 

Many of the library functions essentially create Lists. These functions may be working on Lists themselves such as during accessing and searching. Here are the details:

 

a. Creation:

A List is defined as list of coma separated values between square brackets thus:

 

a = ['spam', 'eggs', 100, 1234]

 

where the items of the List a are of different data types.  This is the most common method of creating a list. The other technique is to use the range() function. The range() function provides a List of consecutive integers. The range() function takes two arguments. The List returned contains all the integers from the first to the second, including the first but not including the second. For example,

>>range(1, 5)

Gives

[1,2,3,4]

Since List itself is a data type, so a List can contain another List. For example,

 

[1,”a”,[2,3]]

 

is perfectly valid List.

 

b. Addition of elements:

There are three ways to add elements to an existing List using member functions of the List which are:

 

i. append adds a single element to the end of the List. For example, let li be

a List, then

>>> li

['a', 'b', 'mpilgrim', 'z', 'example']

>>> li.append(“new”)

>>> li

['a', 'b', 'mpilgrim', 'z', 'example', 'new']

 

ii. insert method inserts a single element into the List. The numeric argument

is the index of the first element that gets shifted out of position. Also there can be two elements of same value at two different positions.

 

>>> li.insert(2, “new”)

>>> li

['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']

iii. extends concatenates the List passed as argument with the existing List.

For example,

>>> li.extend(["two", "elements"])

>>> li

['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

 

c. Accessing and Searching:

For accessing and searching, one of the following techniques can be used:

 

i. Slicing:

Slice is a sub-list of a List. Slicing is done using the [n : m] which

returns the part of the List from the n-eth character to the m-eth

character, including the first but excluding the last. For example if a_list is

a List of alphabets from a to f, then

 

>>> a_list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> a_list[1:3]

['b', 'c']

>>> a_list[:4]

['a', 'b', 'c', 'd']

>>> a_list[3:]

['d', 'e', 'f']

>>> a_list[:]

['a', 'b', 'c', 'd', 'e', 'f']

 

ii. Indexing:

Index of a given element can be found using the index() function of List. It returns the first occurrence of the element supplied as argument. That means even if the element occurs twice, only the position of the first element would be returned. If  the element is not found an exception is raised. For example

>>>li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

>>> li

['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

>>> li.index(“example”)

5

>>> li.index(“new”)

2

>>> li.index(“c”)

Traceback (innermost last):

File “<interactive input>”, line 1, in ?

ValueError: list.index(x): x not in list

 

Apart from these, a List can be accessed as one access an array by specifying index thus:

>>>li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

>>>li[0]

‘a’

d. Deletion:

To delete an element from a List, one can us del. It removes an element from the specified List. For example:

>>> a = ['one', 'two', 'three']

>>> del a[1]

>>> a

['one', 'three']

 

del also can have slice thus:

>>> a_list = ['a', 'b', 'c', 'd', 'e', 'f']

>>> del a_list[1:5]

>>> print a_list

['a', 'f']

That’s all about the operations on Lists. The way the operations are implemented shows the flexibility of Python’s middle path approach. The flexibility doesn’t just stop here. Though strings are immutable and Lists are mutable yet they are inter-convertible. Two of the most useful functions in the string module involve Lists of strings – split and join. The former returns a List composed of individual elements of string separated by the delimiter passed as argument. While the latter creates a string out of supplied List. Following are the examples:

 

>>> import string

>>> song = “The rain in Spain…”

>>> string.split(song)

['The', 'rain', 'in', 'Spain...']

 

Here the string is split on the basis of space as delimiter which is the default delimiter. Next example shows the reverse of the above functionality – string from a List:

 

>>> lst = ['The', 'rain', 'in', 'Spain...']

>>> string.join(lst)

‘The rain in Spain…’

where the joining is done on the basis of space delimiter which again is default delimiter. That’s all about Lists at present. Next lets look at the other compound data-type – Tuple.

 

2. Tuple:

According to definition, “A tuple is a finite sequence (also known as an “ordered list”) of objects, each of a specified type”. In other words, a Tuple is an ordered collection of  objects of different types. In Python, a Tuple is a list of comma separated values but immutable unlike List. So the operations on a Tuple are restricted to the ones that don’t affect its immutability. Accordingly following are the operations that can be performed on a Tuple are:

 

a. Creation

b. Accessing

 

Due to immutability, deletion and addition of new elements are not possible.

 

a. Creation:

Creating or defining a Tuple is as simple as giving a list of values within parenthesis. For example

 

>>> tup = (2, 4, 6, 8, 10)

 

is a Tuple. If a Tuple is having only one element, then, it would be defined as follows:

>>> tup = (5,)

 

b. Accessing:

Since Lists and Tuples are almost same, so the accessing mechanisms also works in similar fashion. Elements of a Tuple can be accessed in two ways:

 

i. Index based:

The elements of a  Tuple can be accessed using their indices. The

index starts at 0. For example to access an element at index 0 of a Tuple

tup, the statement would be:

 

>>> tup = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)

>>> tup[0]

‘a’

 

ii. Slicing:

As in List, slice operator can be used to access elements of a Tuple. It selects a range of elements. For example the following statement selects elements between 1 and 3 (excluding 3):

>>> tup[1:3]

(‘b’, ‘c’)

That’s about operations on a Tuple. So the question arises, when to use List and when to use Tuple. List can be used almost in all the cases. However, there are certain contexts where Tuple is more useful which are:

 

  • Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list.
  • It makes your code safer if you “write-protect” data that does not need to be changed. Using a Tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.

 

In all other contexts, Lists can be used. That brings us to the next section – a real world example using List.

 

Lists And Tuples – In Real World:

The example application would implement a ring buffer or a bounded buffer using List. In a bounded buffer, once the capacity is full, then the first element i.e. the oldest element is replaced with newest element. The implementation uses class switch pattern. Here is the code:

 

class RingBuffer(object):

“”” class that implements a not-yet-full buffer “””

def __init__(self, size_max):

self.max = size_max

self.data = [  ]

class __Full(object):

“”” class that implements a full buffer “””

def append(self, x):

“”” Append an element overwriting the oldest one. “””

self.data[self.cur] = x

self.cur = (self.cur+1) % self.max

def tolist(self):

“”” return list of elements in correct order. “””

return self.data[self.cur:] + self.data[:self.cur]

def append(self, x):

“”” append an element at the end of the buffer. “””

self.data.append(x)

if len(self.data) == self.max:

self.cur = 0

# Permanently change self’s class from non-full to full

self.__class__ = __Full

def tolist(self):

“”” Return a list of elements from the oldest to the newest. “””

return self.data

The class defines an empty List as a buffer. The nested class __Full implements the logic to overwrite the oldest element if the buffer is full. The tolist method returns the List in correct order. Next the append method of the outer class i.e. RingBuffer appends a new item to the end of the List. It also checks whether the length of the buffer is equal to  the max size. If it is equal, then buffer’s state is changed to full. The tolist method returns the buffer. Following is sample implementation that shows how to use the RingBuffer class:

 

if __name__ == ‘__main__':

x = RingBuffer(5)

x.append(1); x.append(2); x.append(3); x.append(4)

print x.__class__, x.tolist( )

x.append(5)

print x.__class__, x.tolist( )

x.append(6)

print x.data, x.tolist( )

x.append(7); x.append(8); x.append(9); x.append(10)

print x.data, x.tolist( )

That brings us to the end of this discussion. List and Tuple are the basic data-structures found in Python. On the basis of these more complex structures such as trees can be developed. How to implement them would be the topic for discussion in the future. Till then…

Understanding Time – The questions


Everyday we use the term time ‘Everything depends upon time’, ‘There is a time for everything’ and so on But, what is Time exactly? How can one define time? There is a simple definition that has been going around It states Time is that can be measured But this definition arises another question – What is the yardstick for this measurement? From ancient time itself earth’s rotation and revolution has been the basis or yardstick for the measurement of time However, rotation and revolution varies So what are we left with? A whole bundle of misconceptions

Then you will ask what should be the basis? A basis should be a non-varient But is such an ideal, universal and non-variant basis available or can such a basis be found? Let me leave that question for the moment (for your ponderings) Now next problem in understanding the working of time Change in every quantity is measured with respect to chnage in time If time’s measure change from one point in space to another, then how the measured change can be accurate? Thus, in short, all the derivatives of time are set on a foundation of transitory theorems

All the changes measured depend upon time, then on what does time depends? Is the dependency on ever-changing orbits and orbital velocity? Or is it the frequency of atom (believed to be accurate)? But what of changes in them that occurs with changes in environment? These are questions that needs to be answered in order to understand time

In the upcoming posts I will try to put forward my thoughts, ideas and approach in answering these questions So keep visiting

Introducing jQuery


It is JavaScript that brings an HTML page to ‘life’. Whether it is client-side validation, animating the page elements or calling the server in the background to get updated page, one can use JavaScript to achieve all this and much more. However, using JavaScript in its ‘raw’ state compels the developer to write multiple lines to implement each of the afore-mentioned functionality and for each application. The pit-fall in such an approach is that each application will have its own pattern and trying to reuse JavaScript code developed for one application, will ultimately result in re-factoring most of the code so that it meets the requirements of both the applications. This is where JavaScript libraries come into picture. These libraries encapsulate the ordinary yet oft used functionalities (e.g. validation, selection of elements etc.) and provide simplified API to access these functionalities. Among the JavaScript libraries, one of the most used is jQuery. In this discussion, the focus will be on the basics of jQuery. The first section will be about the whys and wherefores of the jQuery. The second section will provide details about using various functionalities of jQuery. That’s the agenda for this discussion.

jQuery – the Whys and Wherefores

To understand how jQuery can ease web client (JavaScript based) development, one has to understand two aspects of jQuery. They are:

1. Functionalities

2. Modules

Understanding the functionalities/services provided by jQuery will tell you what jQuery provides and understanding the modules that constitute jQuery will tell you how to access the services provided by jQuery. Here are the details.

1. Functionalities

The functionalities provided by jQuery can be classified into following

a. Selection

b. Attributes handling

c. Element manipulation

d. Ajax

e. Callbacks

f. Event Handling

Among the above listed functionalities, selection, element manipulation and event handling makes common tasks very easily implementable or trivial.

a. Selection

Using this functionality one can select one or multiple HTML elements. The raw JavaScript equivalent of the selection functionality is

document.getElementByID(‘<element id>’) or

document.getElementByTagName(‘<tag name>’)

b. Attributes handling

One of most required task in JavaScript is to change the value of an attribute of a tag. The conventional way is to use getElementByID to get the element and then use index to get to the required attribute. jQuery eases it by using selection and attributes handling functionality in conjunction.

c. Element handling

There are scenarios where the values of tags need to be modified. One of such scenarios is rewriting text of a <p> tag based on selection from combo box. That is where element handling functionality of jQuery comes handy. Using the element handling or DOM scripting, as it is popularly known, one can not only access a tag but also perform manipulation such as appending child tags to multiple occurrences of a specific tag without using for loop.

d. Ajax

Ajax is of the concept and implementation that brought the usefulness of JavaScript to the fore. However, it also brought the complexities and the boilerplate code required for using Ajax to its full potential. The Ajax related functionalities of jQuery encapsulates away the boilerplate code and lets one concentrate on the result of the Ajax call. The main point to keep in mind is that encapsulation of the setup code does not mean that one cannot access the Ajax related events. jQuery takes care of that too and one can register to the Ajax events and handle them.

e. Callbacks

There are many scenarios in web development, where you want to initiate another task on the basis of completion of one task. An example of such a scenario involves animation. If you want to execute a task after completion of an animation, you will need callback function. The core of jQuery is implemented in such a way that most of the API supports callbacks.

f. Event handling

One of the main aspects of JavaScript and its relationship with HTML is the events triggered by the form elements can be handled using JavaScript. However, when multiple elements and multiple events come into picture, the code complexity becomes very hard to handle. The core of jQuery is geared towards handling the events in such a way that complexity can be maintained at manageable levels.

Now that we have discussed the main functionalities of jQuery, let us move onto the main modules of jQuery and how the functionalities map onto the functionalities.

2. Modules

The modules contain APIs that have one-to-one mapping with the functionalities (most of the time). The main modules of jQuery are

a. Selectors

b. Attributes/CSS

c. Manipulation

d. Ajax

e. Callback

f. Event Handling

The names are indicators as to which functionalities they map to. Here are the details

a. Selectors

As the name indicates, selectors provide the functionality to select elements.  As mentioned earlier, selectors are denoted by dollar ($) sign. Some of the commonly used selectors are

  • all selector – selects all the elements
  • :first and :last selectors – select the first and last occurrence of a recurring element/tag.
  • :eq (index) – selects the element with the index having the  value passed as argument.
  • #id – selects the element whose id is passed.

Following statements show how selectors are commonly used

$(“p”)

The above statement selects all <p> elements.

$(“p.start”)

It selects all <p> elements with class whose name is “start”.

$(“p#demo”)

It selects the first <p> element with “demo” as id.

b. Attributes/CSS:

The attribute handling functionality can be found in the API of this module. It also provides manipulation of CSS classes attached to the elements or attributes. Some of the most commonly used API is

·         .attr( attributeName ) – gets the value of an attribute for the first element having the attribute with name equal to the passed attribute name

  • .addClass (classname) – sets the CSS class of a particular element.
  • .val() – gets the current value of the first element in the set of matched elements. It is primarily used to get the values from form elements.
  • .css(name, value)  – sets the style property that matches the name of the style passed to the value passed for style

Following is an example of css() API

$(“p”).css(“background-color”,”yellow”);

It will set the style of all the <p> elements. In this case the style is background color. Its value is set to yellow.

c. Manipulation

The API related to DOM scripting can be found in this module. In other words, the API in this module is used to manipulate DOM in one way or other. One point to keep in mind is that many of the API in this module overlaps with API in Attributes/CSS module. Some of the most commonly used API is:

  • .after(content) – adds the specified content after each of the elements from a set of matched elements.
  • clone() – duplicates the elements in a set o matched elements.
  • replaceWith(newContent) – replaces each element from a set of matched elements with the specified content.

The term “set of matched elements” means that these APIs need to be used along with selectors. A selector may return more than one element. Hence, the returned values are collectively termed as set. For example, the following statement appends “This is appended” to all the <p> elements

$(“p”).append(“This is appended “);

And the following replaced all the values between <p> and <

d. Ajax

The Ajax related functionality can be found in this module. Following are the most commonly used APIs

  • get() – retrieve data from the server specified by the URL, with the data passed.
  • Post() – same as get but uses POST HTTP method to retrieve the data.

For example, the following statements depict the use of get() API

$.get(

http://mysite.org/test.php&#8221;,

function(data) { alert(data); },

);

In the above example, get takes two parameters – URL of the remote site and the callback that performs some operation on the data passed into the callback by get API. Here the URL is “http://mysite.org/test.php” and the operation performed is alerting the user.

e. Callbacks

One of the aspects of jQuery that is heavily used is callbacks. A callback is a function that is registered with another method and gets called when a specific condition, such as response from the server is fulfilled. Following statements display callback in its simplest form

$(“p#test”).hide(1000,function(){

alert(“The paragraph is now hidden”);

});

The hide() API takes two arguments, speed with which the element has to be hidden and the method that needs to be called when the task of hiding is done. In the above example, when the <p> element with id as test is hidden an alert is displayed. In this case callback function is directly defined within hide().

f. Event handling

As stated before, event handling is part of the core functionalities of jQuery. However, to use it, one point needs to be understood. It is the place (within the HTML document) where event and its handler will be attached. The answer to this question is the correct place is the section which gets called before body section is called and it is the head section.

To attach a handler with an event, the statements need to be place within the ready() function of document DOM element. For example, following statements attach the click event of button to its handler

$(document).ready(function(){

$(“button#test”).click(function(){

$(“p”).hide();

});

});

The click event button with id ‘test’ is attached to the handler using callback functionality which in turn is defined inside the callback for ready(). One point to keep in mind is that any kind event handling code must be defined inside ready() and read() itself must be a part of the head section (<head></head>).

This completes the bird’s eye view of the APIs of jQuery. Next section will deal with the steps in using jQuery and some its APIs. It will also cover how to use some of the APIs discussed in this section.

Developing with jQuery – Step-by-Step:

The steps to use jQuery  include downloading and installing (in some cases), referencing the jQuery library and calling the API. Following are the details

1. Downloading and installing jQuery

This step is not mandatory. The reason for this step being optional is that there are alternative ways to reference jQuery library which will be discussed as a part of next step. To download jQuery, one has to download it from the following URL

http://docs.jquery.com/Downloading_jQuery#Current_Release

Unzip it to the local folder from where it will be referenced. That completes the step for downloading and installing.

2. Referencing the Library

There are two ways to reference jQuery. They are

a. Local reference

c. Remote reference

Both use src attribute of //

a. Local reference

When the library (JS files of jQuery) resides within the application directory structure, then the files are locally referenced. Following statement references files stored in the scripts folder of the application

// <![CDATA[
src="../script/jquery-1.4.2.js">
// ]]>

</script>

b. Remote reference

When the library is hosted on another site ( e.g. code.google.com) and the URL is used to access the functionalities of the library, it is known as remote referencing. The steps to remotely refer jQuery hosted at code.google.com are as follows

i. Refer to the jQuery hosted on code.google.com using the src attribute of the //
statement does the same

// <![CDATA[
javascript"
// ]]>

src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”&gt;

</script>

The main point to remember is that the URL for the jQuery library may change based on the version of jQuery.

ii. Call the initialization function i.e. ready() after the referencing statement. The following example shows both the steps together

<script

src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”&gt;

</script>

<script>

$(document).ready(function() {

// provide the initialization such as event handling here

});

</script>

3. Calling the API

To call the API, one can use one of the following ways

a. Fully qualified name

When calling the API with fully qualified name, the statement starts with jQuery. The following statement calls the selector using fully qualified name

jQuery(‘:first’)

b. Using Dollar sign

The dollar sign ($) can be used to call the APIs, instead of using ‘jQuery’. The following statement uses dollar sign to call the selector instead of jQuery

$(‘:first’)

4. Putting it all Together:

Let’s put all the steps together.  The following example will implement  a simple time server. There are two files –one that sits at the server and the one executed at the client. They are

1. SimpleTimeServer.php – it will reside at the server and respond with the current server time.

2. Client.html – it will send request to the server for current server  time via Ajax and display the response it
receives.

First is the SimpleTimeServer.php.  It will have the following code

<?php

$time_now=mktime(date(‘h’)+5,date(‘i’)+30,date(‘s’));

$time_now_str = date(‘l M dS, Y, h:i:s A’,$time_now)

print $time_now_str;

?>

It uses the mktime function to get the current date time and the date function to convert it to human readable string.

Next is Client.html. Following is the code

xmlns=”http://www.w3.org/1999/xhtml&#8221; xml:lang=”en” lang=”en”>

<head>

<title>Current Date and Time</title>

<script src=”jquery-1.2.6.js”></script>

<script>

function  getTime()

{

$.ajax({

url : “SimpleTimeServer.php”,

success : function (data) {

$(“#contentArea”).html(data);

}

});

setTimeout(“getTime()”, 1000);

}

</script>

</head>

<body onload=”getTime();”>

<table width=”100%”>

<tr>

<td  width=”100%” align=”center”>

14px arial;padding-top:140px;”>

</div>

</td>

</tr>

</table>

</body>

</html>

The core of the client is the getTime function. It make call to the server using the get API and displays the received value using the manipulator html(). Then the function uses setTimeOut() to call itself at specified interval. The getTime() is called when the body section loads, thus once the body is loaded the time is displayed at a specific interval.

That completes the example. What I discussed here is just the tip of the ice-berg. In the next article, the selectors will be covered in details. Till then…

Follow

Get every new post delivered to your Inbox.