## Sunday, December 18, 2011

### GLUT Tutorial: 2D Animation

This is the second tutorial on GLUT. In this tutorial I am going to show you how to do a 2D animation in GLUT. There are various methods that can be used to animate an object in GLUT. Among them, I will use a simple method that uses a function glutTimerFunc that registers the timer callback function func to be triggered in at least supplied time. For example glutTimerFunc( 25, update, 0) registers a call back function that calls the function update in every 25 milliseconds. We declared a GL variable rAngle with initial value of 0.0f. After each trigger we increase the value of rAngle by some amount that enables the object to  rotate  gradually according to the amount of angle increased. glRotatef is used to rotate the object in GLUT. We supply the angle by which an object to be rotated and the axis of rotation as arguments to the function glRotate. In this way we can do a simple animation ( rotation) in GLUT. The source code for rotation is given below.

#include<windows.h>#include <iostream>#include <stdlib.h>#include <GL/glut.h>float rAngle  = 0.0;using namespace std;void handleKeypress(unsigned char key, int x, int y) {	switch (key) {		case 27:			exit(0);	}}void initRendering() {	glEnable(GL_DEPTH_TEST);}void handleResize(int w, int h) {	glViewport(0, 0, w, h);	glMatrixMode(GL_PROJECTION);	glLoadIdentity();	gluPerspective(45.0,				   (double)w / (double)h,				   1.0,				   200.0);}void update(int value){    rAngle += 1.0f;    if(rAngle > 360){        rAngle -= 360;    }    glutPostRedisplay(); // Inform GLUT that the display has changed    glutTimerFunc(25,update,0);//Call update after each 25 millisecond}void drawScene() {	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	glMatrixMode(GL_MODELVIEW);	glLoadIdentity();	glRotatef(-rAngle, 0.0f, 0.0f, -1.0f);	glBegin(GL_TRIANGLES); //Begin triangle coordinates	//Triangle	glVertex3f(-0.5f, 0.5f, -5.0f);	glVertex3f(-1.0f, 1.5f, -5.0f);	glVertex3f(-1.5f, 0.5f, -5.0f);	glEnd(); //End triangle coordinates	glutSwapBuffers(); //Send the 3D scene to the screen}int main(int argc, char** argv) {	glutInit(&argc, argv);	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);	glutInitWindowSize(400, 400);	glutCreateWindow("Simple Animation - programming-technique.blogspot.com");	initRendering();	glutDisplayFunc(drawScene);	glutKeyboardFunc(handleKeypress);	glutReshapeFunc(handleResize);	glutTimerFunc(25,update,0);	glutMainLoop();	return 0;}

## Saturday, December 17, 2011

### GLUT Tutorial: Drawing Basic Shapes (Triangle and Rectangle)

This is the first tutorial on GLUT. In this tutorial I am going to show you how to draw basic 2D shapes like triangle and rectangles using OpenGL. Although OpenGL is basically made for 3D programming, drawing 2D shapes gives the basic outline and introduction to OpenGL and gives the idea about how to start drawing objects in OpenGL. The following example draws a triangle and a rectangle to a GLUT window. Drawing rectangle and triangle is very easy on OpenGL because it provides a function for it. glBegin(GL_TRIANGLES) and glBegins(GL_QUADS) are functions for drawing triangle and rectangle respectively. We have to give a 3D coordinates of each vertex and OpenGL automatically draws the object as specified by the attribute passed to function glBegin. For example if we call glBegin(GL_QUADS) and provide coordinates of four vertices then OpenGL will draw a rectangle for us.

#include<windows.h>#include <iostream>#include <stdlib.h>#include <GL/glut.h>using namespace std;//Called when a key is pressedvoid handleKeypress(unsigned char key, int x, int y) {	switch (key) {		case 27: //Escape key			exit(0);	}}//Initializes 3D renderingvoid initRendering() {	//Makes 3D drawing work when something is in front of something else	glEnable(GL_DEPTH_TEST);}//Called when the window is resizedvoid handleResize(int w, int h) {	//Tell OpenGL how to convert from coordinates to pixel values	glViewport(0, 0, w, h);	glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective	//Set the camera perspective	glLoadIdentity(); //Reset the camera	gluPerspective(45.0,                  //The camera angle				   (double)w / (double)h, //The width-to-height ratio				   1.0,                   //The near z clipping coordinate				   200.0);                //The far z clipping coordinate}//Draws the 3D scenevoid drawScene() {	//Clear information from last draw	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective	glLoadIdentity(); //Reset the drawing perspective	glBegin(GL_QUADS); //Begin quadrilateral coordinates	//Trapezoid	glVertex3f(-0.7f, -1.5f, -5.0f);	glVertex3f(0.7f, -1.5f, -5.0f);	glVertex3f(0.7f, -0.5f, -5.0f);	glVertex3f(-0.7f, -0.5f, -5.0f);	glEnd(); //End quadrilateral coordinates	glBegin(GL_TRIANGLES); //Begin triangle coordinates	//Triangle	glVertex3f(-0.5f, 0.5f, -5.0f);	glVertex3f(-1.0f, 1.5f, -5.0f);	glVertex3f(-1.5f, 0.5f, -5.0f);	glEnd(); //End triangle coordinates	glutSwapBuffers(); //Send the 3D scene to the screen}int main(int argc, char** argv) {	//Initialize GLUT	glutInit(&argc, argv);	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);	glutInitWindowSize(400, 400); //Set the window size	//Create the window	glutCreateWindow("Basic Shapes - programming-technique.blogspot.com");	initRendering(); //Initialize rendering	//Set handler functions for drawing, keypresses, and window resizes	glutDisplayFunc(drawScene);	glutKeyboardFunc(handleKeypress);	glutReshapeFunc(handleResize);	glutMainLoop(); //Start the main loop	return 0;}

The output for the above program is

## Thursday, December 15, 2011

### Make a Digital Clock in 8085 programming

8085 is a assembly level programming. It uses a lot of mnemonics to write a code. To understand a lot of mnemonics is a negative part of any assembly level programming. The following code designs a digital clock with approximately 1 second delay (it depends upon your kits frequency). The delay is calculated by multiplying total T-states an time required for each T-states. It is a 12 hours clock and resets its time after 12 hours.

Source Code

MVI A,80H
OUT 43
START: MVI D,00H
NEXTHOUR:
MVI C,00H
NEXTMINUTE:
MVI E,00H
NEXTSECOND:
PUSH B
CALL CALLING
POP B
INR E
MOV A,E
OUT 40
CPI 3CH
JNZ NEXTSECOND
INR C
MOV A,C
OUT 41
CPI 3CH
JNZ NEXTMINUTE
INR D
MOV A,D
OUT 42
CPI CH
JNZ NEXTHOUR
JMP START
CALLING:
LXI B,FFFFH
DELAY:
DCX B
MOV A,C
ORA B
NOP
NOP
RZ
JMP DELAY

The two lines of code : MVI A, 80 and OUT 43 is used to initialize output port. It varies on kit to kit. So see your manufacturer's specifications for this.

## Saturday, December 10, 2011

### A 2D Game Helicopter Hurdle with SDL in C/C++ – Free Download (Source code and Exe file)

A Helicopter Hurdle is a interesting game made using C/C++ with SDL graphics library. It is completely return in C++ with a lot of graphics functions of SDL. The source code is very simple to understand and is written with a lot of comments in object oriented style. I thank Mr. Santosh Ghimire (Student of IOE, Pulchowk Campus) for providing me such a great and valuable project.

## Friday, December 9, 2011

### Mini project “3D Bounce” in OpenGL Utility Toolkit (GLUT) using C/C++ – Free Download

3D Bounce is a graphics project which uses a GLUT Library with C++. It is a game with a small ball that bounces over a surface. It consists of different levels of game. If a player completes one level then he can enter into another level. The project is completely written in C++ with OpenGL. The code is written in Object Oriented Fashion with a lots of comment. This project teaches you the following things:
1. To use GLUT Library with C++.
2. To write a code in Object  Oriented Method.
3. To use different functions of glut like callback function.
4. To write Keyboard and mouse events.
5. To draw a different 3D objects and shapes in OpenGL and render them.
7. To use different mathematical formulas and ideas in a game program and so on.
So this project will become a very good learning tool for the beginner of both C++ and OpenGL Library. But there are few limitations of the project
1. This project is not completed.
2. It do not uses any collision detections.
3. A lot of memory leak problems
I can not complete this project due to lack of time. And I believe you will complete it.

## Wednesday, December 7, 2011

### Data Structure - Hashing and Hash Table Generation using C/C++

Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that represents the original string.

Hash Function

A function that transforms a key into a table index is called a hash function. If h is a hash function and key is a key, h(key) is called the hash of key and is the index at which a record with the key key should be placed. If r is a record whose key hashes into hr, hr is called hash key of r.  The has function in the preceding example is h(k) = key % 1000. The values that h produce should cover the entire set of indices in the table. For example, the function x % 1000 can produce any integer between 0 and 999, depending on the value of x. As we shall see shortly, it is good idea for the table size to be somewhat larger than the number of records that are to be inserted.

Hash Collision

Suppose that two keys k1 and k2 are such that h(k1) equals h(k2). Then when a k2 is hashed, because its has key is the same as that of k2, an attempt may be make to insert the record into the same position where the record with key k1 is stored. Clearly, two records cannot occupy the same position, Such a situation is called a hash collision or a hash clash.

Source code for Hashing and Hash table generation in C/C++

#include<iostream>#include<cstdlib>using namespace std;class hash{    private:        int hash_pos;        int array[40];    public:        hash();        void insert();        void search();        int Hash(int );        int reHash(int );        void Delete();};hash::hash(){    for(int i = 0; i < 40; i++){        array[i] = '*';    }}void hash::insert(){    int data;    int count = 0;    cout<<"Enter the data to insert: ";    cin>>data;    hash_pos = Hash(data);    if(hash_pos >= 40){        hash_pos = 0;    }    while(array[hash_pos] != '*'){        hash_pos = reHash(hash_pos);        count++;        if(count>=40){            cout<<"Memory Full!!No space is avaible for storage";            break;        }    }    if(array[hash_pos] == '*'){        array[hash_pos] = data;    }    cout<<"Data is stored at index "<<hash_pos<<endl;}int hash::Hash(int key){    return key%100;}int hash::reHash(int key){    return (key+1)%100;}void hash::search(){    int key,i;    bool isFound = false;    cout<<"Enter the key to search: ";    cin>>key;    for(i = 0; i < 40; i++){        if(array[i] == key){            isFound = true;            break;        }    }    if(isFound){        cout<<"The key is found at index "<< i <<endl;    }else{        cout<<"No record found!!"<<endl;    }}void hash::Delete(){    int key,i;    bool isFound = false;    cout<<"Enter the key to delete: ";    cin>>key;    for(i = 0; i < 40; i++){        if(array[i] == key){            isFound = true;            break;        }    }    if(isFound){        array[i] = '*';        cout<<"The key is deleted"<<endl;    }else{        cout<<"No key is Found!!";    }}int main(){    hash h;    int choice;    while(1){        cout<<"\n1. Insert\n2. Search\n3. Delete\n4. Exit\n";        cout<<"Enter your choice: ";        cin>>choice;        switch(choice){            case 1:                h.insert();                break;            case 2:                h.search();                break;            case 3:                h.Delete();                break;            case 4:                exit(0);            default:                cout<<"\nEnter correct option\n";                break;        }    }    return 0;}

### Tree Search using C/C++.

In the binary tree used to store a file, all the left descendants of a node with key key have keys that are less than key, and all the right descendants have keys that are greater than or equal to key. The inorder traversal of such a binary tree yields the file in ascending key order.

Such a tree may also be used as a binary search tree. Using binary tree notation, the algorithm for searching for the key key in such a tree is as follows ( here we assume that each node contains four fields: k, which holds the record’s key value, r, which holds the record itself, and left and right, which are pointers to the subtrees).

p = tree;while(p != null && key != k(p))    p = (key < k(p))?left(p):right(p);return (p);

The efficiency of the search process can be improved by using a sentinel, as in sequential searching. A sentinel node, with a separate external pointer pointing to it, remains allocated with the tree. All left or right tree pointers that do not point to another tree node now point to this sentinel node instead of equaling null. When a search is performed, the argument key is first inserted into the sentinel node, thus guaranteeing that it will be located in the tree. This enables the header of the search loop to be written while(key != key(p)) without the risk of an infinite loop. After leaving the loop, if p equals the external sentinel pointer, the search is unsuccessful; otherwise p points to the desired node.

Source Code

#include<iostream>#include<cstdlib>#include<string>using namespace std;struct tree{    int info;    tree *Left, *Right;};tree *root;class Binary_tree{    string path;    public:        Binary_tree();        void insert1(int);        tree *insert2(tree *, tree *);        void search(int);        void pretrav(tree *);        void intrav(tree *);        void posttrav(tree *);};Binary_tree::Binary_tree(){    root = NULL;}tree* Binary_tree::insert2(tree *temp,tree *newnode){    if(temp==NULL){        temp=newnode;    }    else if(temp->info < newnode->info){        insert2(temp->Right,newnode);        if(temp->Right==NULL)            temp->Right=newnode;    }    else{        insert2(temp->Left,newnode);        if(temp->Left==NULL) temp->Left=newnode;    }    return temp;}void Binary_tree::insert1(int n){    tree *temp=root,*newnode;    newnode=new tree;    newnode->Left=NULL;    newnode->Right=NULL;    newnode->info=n;    root=insert2(temp,newnode);}void Binary_tree::pretrav(tree *t = root){    if(root == NULL){        cout<<"Nothing to display";    }else    if(t != NULL){        cout<<t->info<<" ";        pretrav(t->Left);        pretrav(t->Right);    }}void Binary_tree::intrav(tree *t = root){    if(root==NULL){        cout<<"Nothing to display";    }else    if(t!=NULL){        intrav(t->Left);        cout<<t->info<<" ";        intrav(t->Right);    }}void Binary_tree::posttrav(tree *t = root){    if(root==NULL){        cout<<"Nothing to display";    }else        if(t!=NULL){        posttrav(t->Left);        posttrav(t->Right);        cout<<t->info<<" ";    }}void Binary_tree::search(int key){    tree *temp=root,*parent=root;    path = "";    if(temp==NULL){        cout<<"The tree is empty"<<endl;    }else{        path = "root";        while(temp!=NULL && temp->info!=key){            parent=temp;            if(temp->info<key){                temp=temp->Right;                path += "->Right";            }else{                temp=temp->Left;                path += "->Left";            }        }    }    if(temp==NULL){        cout<<"Key not found!";    }else{        cout<<"Key is found\n";        cout<<"Paht is: ";        cout<<path;    }}int main(){    Binary_tree bt;    int choice, n, key;    while(1){        cout<<"\n\t1. Insert\n\t2. Search\n\t3. Preorder Traversal\n\t4. Inorder Treversal\n\t5. Postorder Traversal\n\t6. Exit"<<endl;        cout<<"Enter your choice: ";        cin>>choice;        switch(choice){            case 1:                cout<<"Enter item: ";                cin>>n;                bt.insert1(n);                break;            case 2:                cout<<"Enter element to search: ";                cin>>key;                bt.search(key);                break;            case 3:                cout<<endl;                bt.pretrav();                break;            case 4:                cout<<endl;                bt.intrav();                break;            case 5:                cout<<endl;                bt.posttrav();                break;            case 6:                exit(0);        }    }    return 0;}

## Tuesday, December 6, 2011

### Binary Search using C/C++.

The most efficient method of searching a sequential table without the use of auxiliary indices or tables is the binary search. Basically, the argument is compared with the key or the middle element of the table. If they are equal, the search ends successfully; otherwise, either the upper or lower half of the table must be searched in a similar manner.

The binary search can be defined recursively. As a result, a recursive definition, a recursive algorithm, and a recursive program can be presented of the binary search. However, the overhead associated with recursion my make it inappropriate for use in practical situations in which efficiency is a prime consideration. Therefore the following algorithm uses non recursive fashion.

Algorithm

low = 0;hi = n - 1;while(low <= hi){   mid = (low+hi)/2;   if(key==k(mid))     return (mid);   if(key <  k(mid))     hi = mid-1;   else     low = mid+1;}return(-1);

Source Code

#include<iostream>using namespace std;int main(){    int n, search[10],low , high,mid ,temp, key;    bool found = false;    cout<<"Enter the number of element: ";    cin>>n;    for(int i = 0; i < n; i++){        cout<<"search["<<i<<"]: ";        cin>>search[i];    }    for(int i = 0; i < n; i++){        for(int j = 0; j < n-i-1; j++){            if(search[j] > search[j+1]){                temp = search[j];                search[j] = search[j+1];                search[j+1] = temp;            }        }    }    cout<<"the sorted array is: ";    for(int i = 0; i < n; i++){        cout<<search[i]<<" ";    }    cout<<"\nEnter the number to search: ";    cin>>key;    low = 0;    high = n-1;    while(low<=high){        mid  = (low + high)/2;        if(key == search[mid]){            cout<<"The key is found at index "<<mid<<endl;            found = true;            break;        }else if(key < search[mid]){            high = mid - 1;        }else{            low = mid + 1;        }    }    if(!found){        cout<<"Key not found!";    }    return 0;}

Output

Enter the number of element: 7
search[0]: 5
search[1]: 9
search[2]: 21
search[3]: 45
search[4]: 11
search[5]: 3
search[6]: 78
the sorted array is: 3 5 9 11 21 45 78
Enter the number to search: 45
The key is found at index 5

Efficiency of Binary Search

Each comparison in the binary reduces the number of possible candidates by a factor of 2. Thus, the maximum number of key comparisons is approximately logn with base 2.