Tuesday, April 30, 2013

Programming A Simple Kernel Program / Module

What is kernel?

A kernel is an important part of operating system, which acts as a bridge between user level applications and computer hardware. Kernel allows user level applications, to use system resources such as CPU, Memory, I/O Devices etc.

Why / When to write kernel Programs / Modules?

We know that there are two levels of programming. 1). User space level 2). Kernel level. We already writing so many user space level programs using C, C++, Java, D ...etc. Then why to write a kernel level programs/modules? The reasons are as follows

1). If your program / module excessively using low-level resources.
2). If you are defining a new interface / driver for hardware, which can not build on user level.
3). If you are developing something that is used by kernel subsystems.

Writing a Kernel Program / Module

Create a folder some where in your home directory and name that folder to USB_Module. Now create a C source file called usb_driver.c in that folder with the following source code.

// File Name: usb_driver.c
 #include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/init.h>

static int usb_driver_module_load(void)
{
     printk(KERN_INFO "USB-Driver Module Loaded...!!!\n");
     return 0;
}
static void usb_driver_module_unload(void)
{
     printk(KERN_INFO "USB-Driver Module UnLoaded...!!!\n");
}

module_init(usb_driver_module_load);
module_exit(usb_driver_module_unload);

MODULE_AUTHOR("Reniguntla Sambaiah http://umencs.blogspot.in");
MODULE_DESCRIPTION("Kernel module to load USB Driver");
MODULE_LICENSE("GPL");
// code end


Now create a Makefile in the same folder with the following code.

ifeq ($(KERNELRELEASE),)

KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

.PHONY: build clean

build:
         $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

clean:
         rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c
else

$(info Building with KERNELRELEASE = ${KERNELRELEASE})
obj-m :=    usb_driver.o

endif


Note: Becareful that Makefiles require indentation. So, use Tab character, not a multiple spaces below build and clean options.

Compiling Kernel Program / Module

If you created above two files, then compile the kernel module using following Command.
>make
Once you execute the above command it will create a bunch of files in USB_Module folder. In that bunch of files you can find usb_driver.ko which is a kernel module.

Loading Kernel Module / Program

To load usb_driver.ko kernel module use following command
>sudo insmod usb_driver.ko

 Now you must be thinking why printk in usb_driver.c didn't print "USB-Driver Module Loaded...!!!" on console. Because you are looking at wrong location. It is a Kernel level programming, you can find "USB-Driver Module Loaded...!!!" in syslog. To see this message run following command.
>dmesg | tail

 UnLoading Kernel Module / Program

To unload usb_driver.ko kernel module use following command
>sudo rmmod usb_driver.ko

To see "USB-Driver Module UnLoaded...!!!" message use following command
>dmesg | tail

Getting Kernel Module / Program details

use following command to know the details of any kernel module
>/sbin/modinfo usb_driver.ko




Saturday, April 27, 2013

Programming a Virtual / Online Key Board

Virtual / online key board is software program, which allows users to enter characters. This virtual / online key board can be operated by various input devices like Mouse, touch pad, external touch tablet etc. Virtual / Online key boards provides different input mechanisms to disability persons also.

Here I am going to share a java code, which was developed and used to create a Hindi virtual / online key board for application level.

You can download an application level Hindi Virtual / Online Key Board DOWNLOAD HERE.

The GUI of this Hindi online / virtual keyboard looks like as follows


Here you can Analyze the java code to create  Hindi Online / Virtual Key board.

// File Name:  HindiKeyBoard.java

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.*;
import javax.swing.*;

public class HindiKeyBoard {
    public static void main(String args[])
    {
        Hindi_KeyBoard_Main J = new Hindi_KeyBoard_Main();
        J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        J.set_TextArea_prop();
        J.set_menu();
        J.Hindi_KeyBoard_Main_();
        J.setSize(500, 600);
        J.setVisible(true);   
    }
}
class Hindi_App_Level_Key_Board extends JDialog{
       private static final long serialVersionUID = 1L;
       protected JTextArea textArea;
        HindiStateBuffer stateBuffer=new HindiStateBuffer();
        String hindi[]={"अ","आ","इ","ई‌","उ","ऊ","ऋ","ए","ऐ","ओ","औ","अं","अः","क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्"};
        String hindiMatraSet[]={"","ा","ि","ी","ु","ू","ृ","े","ै","ो","ौ","ं","ः"};
        public Hindi_App_Level_Key_Board(Hindi_KeyBoard_Main aui){
            super(aui,"हिन्दी",false);
            JButton button[]=new JButton[63];
            textArea=aui.textArea;
            for(int i=0; i<63 br="" i="">                button[i]= new JButton("");
            }
            Container contPane = getContentPane();
            JPanel panel =new JPanel();
            JPanel flowPanel= new JPanel();
            flowPanel.setLayout(new GridLayout(9,7));
           
            for(int j=0; j<7 br="" j="">                button[j].setText(hindi[j]);
                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();;
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            for(int lo=0; lo<7 br="" lo="">                                if(btn.getText().equals(hindi[lo])){
                                    stateBuffer.precomposedString=stateBuffer.precomposedString+hindiMatraSet[lo];
                                }
                            }
                           
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                        }
                        textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                        textArea.replaceSelection(stateBuffer.precomposedString);
                        stateBuffer.reset();
                    }
                });
            }       
            int k=7;
            for(int j=7; j<14 br="" j="">                button[j].setText(hindi[k++]);
                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();;
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            for(int lo=7; lo<14 br="" lo="">                                if(btn.getText().equals(hindi[lo])){
                                    stateBuffer.precomposedString=stateBuffer.precomposedString+hindiMatraSet[lo];
                                }
                            }   
                            if(btn.getText().equals("‌्")){
                                stateBuffer.precomposedString=stateBuffer.precomposedString+"\u094d";
                            }
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                        }
                        textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                        textArea.replaceSelection(stateBuffer.precomposedString);
                        stateBuffer.reset();
                    }
                });
            }
            button[12].setText("‌्");
            button[13].setText(hindiMatraSet[11]);
            k=13;
            for(int set=15; set<=19; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=14; j<21 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                       }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            k=18;
            for(int set=22; set<=26; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=21; j<28 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                               }
                        stateBuffer.commit=false;                               
                    }
                });
            }   
            k=23;
            for(int set=29; set<=33; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=28; j<35 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            k=28;
            for(int set=36; set<=40; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=35; j<42 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            k=33;
            for(int set=43; set<=47; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=42; j<49 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }   
             k=38;
            for(int j=49; j<56 br="" j="">                button[j].setText(hindi[k++]);
                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            button[56].setText(hindi[45]);
            for(int j=56; j<57 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                        }
                        stateBuffer.commit=false;                               
                    }
                });
            }
           
            for(int j=57; j<63 br="" j="">                flowPanel.add(button[j]);
            }
            button[57].setText("space");
            button[57].addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e) {
                    int caretposition= textArea.getCaretPosition();
                    String space="\u0020";
                        if(stateBuffer.commit==false){
                        stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                        textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                        textArea.replaceSelection(stateBuffer.precomposedString);
                    }
                    stateBuffer.precomposedString=space;
                    textArea.replaceSelection(stateBuffer.precomposedString);
                    stateBuffer.reset();
                }
            });
           
            button[58].setText("clear");
            button[58].addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e) {
                    if(stateBuffer.precomposedString.equals("\u0020")){
                        stateBuffer.commit=false;
                    }else{
                    stateBuffer.reset();
                    }
                }
            });
           
            flowPanel.setVisible(true);
            panel.add(flowPanel);
            panel.setVisible(true);
            contPane.setLayout(new BoxLayout(contPane,BoxLayout.Y_AXIS));
            contPane.add(panel);
            contPane.setVisible(true);
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            pack();
            this.setVisible(true);   
        }
    }
    class HindiStateBuffer{
        public boolean commit =true;
        public String precomposedString;
        HindiStateBuffer(){
            commit=true;
            precomposedString="";
        }
        public void reset(){
            commit=true;
            precomposedString="";
        }
}

class Hindi_KeyBoard_Main extends JFrame{
   
    private static final long serialVersionUID = 1L;
    protected JTextArea textArea = new JTextArea();   
    protected JScrollPane textAreaScrollPane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    protected int textAreaRows = 10;
    protected JFileChooser fileChooser=new JFileChooser();
    Hindi_KeyBoard_Main thisreference =this;
    Hindi_App_Level_Key_Board halkb;
   
    public void Hindi_KeyBoard_Main_()
    {
        halkb = new Hindi_App_Level_Key_Board(thisreference);
    }
    public void set_TextArea_prop()
    {
    Container contPane = getContentPane();
    contPane.setLayout(new BorderLayout());
    textArea.setRows(textAreaRows);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setBorder(BorderFactory.createLineBorder(Color.black));
    textArea.setSize(500, 600);
    Font font = new Font("TimesRoman",Font.BOLD,15);
    textArea.setFont(font);
    contPane.add(textAreaScrollPane, BorderLayout.WEST);
    }
   
    public void set_menu()
    {
        JMenuBar menu = new JMenuBar();
        JMenu menuTool = new JMenu("File");
        menuTool.setMnemonic('F');
        JMenuItem menuToolOpenText = new JMenuItem("Open File...");
        menuToolOpenText.setMnemonic('O');
        JMenuItem menuToolSaveToText = new JMenuItem("Save as Text...");
        menuToolSaveToText.setMnemonic('S');
        JMenuItem menuToolExit = new JMenuItem("Exit...");
        menuToolSaveToText.setMnemonic('E');
        menuTool.add(menuToolOpenText);
        menuTool.add(menuToolSaveToText);
        menuTool.add(menuToolExit);
        menu.add(menuTool);
        setJMenuBar(menu);
       
        menuToolSaveToText.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae){
                int returnVal = fileChooser.showSaveDialog(thisreference);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                   
                    try {
                        String taString=textArea.getText();
                        FileOutputStream fosr=new FileOutputStream(file);
                        fosr.write(taString.getBytes());

                        fosr.close();

                        System.out.println(taString+"");
                    } catch (IOException ioe) {
                        System.out.println("Some error occurred while creating " + file + " : " + ioe);
                    }               
                    System.out.println("Saving: " + file.getName());
                } else {
                    System.out.println("Save command cancelled by user.");
                }
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }           
        });
       
        menuToolOpenText.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae){
                int returnVal = fileChooser.showOpenDialog(thisreference);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                        try {
                            Reader r = new BufferedReader(new FileReader(file));
                            int ch;
                            String nav="";
                            while ((ch = r.read()) != -1){
                                char chr=(char)ch;
                                nav=nav+chr;
                            }
                           
                            textArea.setText(nav);
                            r.close();
                        } catch (IOException ioe) {
                            System.out.println("Some error occurred while creating " + file + " : " + ioe);
                        }               
                                    }           
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }
        });
        menuToolExit.addActionListener(new ActionListener()
        {
                public void actionPerformed(ActionEvent ae){
                    dispose();
                    System.exit(0);   
                }
        });
    }

}

Wednesday, April 24, 2013

KillingSoftly- A Simple Game Development Using SDL / C++

Hi.. Today i am going to post some thing related to game development using SDL and C++. Simple DirectMedia Layer (SDL) is a cross-platform, free and open source multimedia library written in C that presents a simple interface to various platforms' graphics, sound, and input devices.

In this post I am going to develop, a basic game called killingSoftly using SDL. Let us assume that killingSoftly game has following rules.

1. There are four Dayaans(witch) and they enter into gaming area randomly.
2. There is one Warrior at centre of gaming area, who can be controlled by arrow keys.
3. If Warrior is overlapped with Dayaan then Dayaan will die and your score will increase.
4. To start new game you have to press 'n' key.
5. Whenever you start new game you can see your previous game score.
6. Before quitting game, press 'n' to see the score then quit.

Watch Video Here: http://www.youtube.com/watch?v=TYRft9dRcqs

You can Download KillingSoftly-0.1, A game which is developed by me DOWNLOAD HERE.



 The GUI of this game looks like as follows

Note: The aim this post is not to create a game (you may not like this game!) but to help other developers who are interested in learning game development programming using SDL and C++.

If you observe/ read the comments of the code which i wrote for the development of  KillingSoftly you will come to know the following things.

1. How to initialize SDL components for game development.
2. How to load different objects of game.
3. How to control game objects based on events.
4. How to load TTF's and How to display text in gaming environment.
5. How to play audio files in the background etc.

 // Filename: KillingSoftly.cpp

#include <string>
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_mixer.h"

using namespace std;

// Display Properties
const int DISPLAY_HEIGHT = 480;
const int DISPLAY_WIDTH = 480;
const int DISPLAY_BPP = 32;

// The dimensions of the Dayaan/Warrior objects
const int OBJECT_HEIGHT = 30;
const int OBJECT_WIDTH = 30;

// frame rate
const int FRAMES_PER_SEC = 25;

// surfaces for various objects
SDL_Surface *Warrior = NULL;
SDL_Surface *Dayaan1 = NULL,*Dayaan2 = NULL,*Dayaan3 = NULL,*Dayaan4 = NULL;
SDL_Surface *display = NULL;
SDL_Surface *scoreDisplay = NULL;

// font
TTF_Font *font = NULL;

// event variable
SDL_Event event;

//color of the font
SDL_Color text_Color = { 0, 0, 255};

// Varibales to caluculate score
int targets =4;
int score=0;

//sound effects used
Mix_Chunk *KillSound = NULL;

// Objects that will move on the display
class Object
{
    public:
    // x, y offsets of the objects
    int x, y, x1, y1, x2, y2, x3, y3, x4, y4;

    // Speed of the warrior object
    int x_speed, y_speed;

    public:
    // Initializes the variables
    Object();

    // Takes key presses and adjusts warrior speed
    void handle_warrior();

    // Moves the warrior
    void move_warrior();

    // Moves Dayaans and updates scoring
    void move_Dayaans();

    // Shows All the objects on the display
    void show_All_objects();
};

// Clock class
class Clock
{
    private:
    // The clock time when clock started
     int ticking_start;

    // The ticks stored when the clock paused
    int pausedTicks;
    int ticks_paused;

    // Clock status
    bool ispaused;
    bool isstarted;

    public:
    // Initializes variables
    Clock();

    // The various clock actions
    void start();
    void stop();
    void pause();
    void unpause();

   // Checking status of clock
    bool is_started();
    bool is_paused();

    // Gets the Clock's time
    int get_No_of_ticks();
 
};


// fucntion to load bliting surface
void loading_surface( int x, int y, SDL_Surface* source, SDL_Surface* dest, SDL_Rect* area = NULL )
{
    // Holding offsets
    SDL_Rect offset;

    // Geting offsets
    offset.x = x;
    offset.y = y;

    // Bliting using SDL_BlitSurface
    SDL_BlitSurface( source, area, dest, &offset );
}


// Function to load optimised images/objects
SDL_Surface *load_optimized_image( std::string filename )
{
    // optimised surface
    SDL_Surface* optiImage = NULL;

    // loaded image
    SDL_Surface* loadImage = NULL;

    // loading image
    loadImage = IMG_Load( filename.c_str() );

    if( loadImage != NULL )
    {
        // creating optimised surface
        optiImage = SDL_DisplayFormat( loadImage );

        // Free old surface
        SDL_FreeSurface( loadImage );

        // Checking optimised surface
        if( optiImage != NULL )
        {
            //Colouring key surface area
            SDL_SetColorKey( optiImage, SDL_SRCCOLORKEY, SDL_MapRGB( optiImage->format, 0, 0xFF, 0xFF ) );
        }
    }

    // Returning optimized surface
    return optiImage;
}

// Function to load required files
bool loading()
{
    // Loading the Warrior/Dayaans images
    Warrior = load_optimized_image( "Warrior.bmp" );
    Dayaan1 = load_optimized_image( "Dayaan.bmp" );
    Dayaan2 = load_optimized_image( "Dayaan.bmp" );
    Dayaan3 = load_optimized_image( "Dayaan.bmp" );
    Dayaan4 = load_optimized_image( "Dayaan.bmp" );

    // Checking for problems in loading Warrior/Dayaans images
    if( Warrior == NULL ||  Dayaan1 == NULL || Dayaan2 == NULL || Dayaan3 == NULL || Dayaan4 == NULL)
        return false;
   
    // Loading killing sound effect
    KillSound = Mix_LoadWAV( "Kill.wav" );
   
    // Checking for problem in loading the sound effect
    if( KillSound == NULL )
        return false;

    // Opening font called akshar
    font = TTF_OpenFont( "akshar.ttf", 20 );

    // Checking for error in loading the font
    if( font == NULL)
        return false;

    // If everything is fine returing true
    return true;
}

// Function to initialize SDL sub functions
bool initialize()
{
    // Initialising SDL
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
        return false;

    // Setting up display
    display = SDL_SetVideoMode( DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_BPP, SDL_SWSURFACE );

    // Checking for problems in setting up display
    if( display == NULL )
        return false;

    // Initializing SDL_mixer
    if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
        return false;
   
    // Intializing TTF and checking for problems
    if( TTF_Init() == -1 )
        return false;

    // Setting up window Name
    SDL_WM_SetCaption( "Killing Softly", NULL );

    // If everything is fine returning true
    return true;
}

// Function to clean everything
void Do_cleaning()
{
   
    // Removing all surfaces
    SDL_FreeSurface( Warrior );
    SDL_FreeSurface( Dayaan1 );
    SDL_FreeSurface( Dayaan2 );
    SDL_FreeSurface( Dayaan3 );
    SDL_FreeSurface( Dayaan4 );
   
    // Removing font
    TTF_CloseFont( font );

    // Removing sound effect
    Mix_FreeChunk( KillSound );

    // Exiting from SDL_mixer
    Mix_CloseAudio();

    //Exiting from SDL
    SDL_Quit();
}

// Initialising object variables
Object::Object()
{
    // Setting up object positions
    x = DISPLAY_WIDTH/2;
    y = DISPLAY_HEIGHT/2;
    x1 = 0;
    y1 = 0;
    x2 = 0;
    y2 = DISPLAY_HEIGHT-OBJECT_HEIGHT;
    x3 = DISPLAY_WIDTH-OBJECT_WIDTH;
    y3 = 0;
    x4 = DISPLAY_WIDTH-OBJECT_WIDTH;
    y4 = DISPLAY_HEIGHT-OBJECT_HEIGHT;

    // Setting speed of warrior
    x_speed = 0;
    y_speed = 0;
}

// Speeding up warrior with Keys
void Object::handle_warrior()
{
    // If Key pressed
    if( event.type == SDL_KEYDOWN )
    {
        // Changing speed
        switch( event.key.keysym.sym )
        {
            case SDLK_UP: y_speed -= OBJECT_HEIGHT / 5;
                          break;
            case SDLK_DOWN: y_speed += OBJECT_HEIGHT / 5;
                            break;
            case SDLK_LEFT: x_speed -= OBJECT_WIDTH / 5;
                            break;
            case SDLK_RIGHT: x_speed += OBJECT_WIDTH / 5;
                             break;
        }
    }
    // If Key released
    else if( event.type == SDL_KEYUP )
    {
        // Changing speed
        switch( event.key.keysym.sym )
        {
            case SDLK_UP: y_speed += OBJECT_HEIGHT / 5;
                          break;
            case SDLK_DOWN: y_speed -= OBJECT_HEIGHT / 5;
                            break;
            case SDLK_LEFT: x_speed += OBJECT_WIDTH / 5;
                            break;
            case SDLK_RIGHT: x_speed -= OBJECT_WIDTH / 5;
                             break;
        }
    }
}

// Moving warrior
void Object::move_warrior()
{
    // Moving warrior left or right
    x += x_speed;

    // checking Boundaries
    if( ( x < 0 ) || ( x + OBJECT_WIDTH > DISPLAY_WIDTH ) )
    {
        //  Moving warrior back
        x -= x_speed;
    }

    // Moving warrior up or down
    y += y_speed;

    // Checking Boundaries
    if( ( y < 0 ) || ( y + OBJECT_HEIGHT > DISPLAY_HEIGHT ) )
    {
        // Moving warrior back
        y -= y_speed;
    }
}

// Moving Dayaans and updating scoring
void Object::move_Dayaans()
{
    // Moving Dayaan1
    x1 = x1+3;
    if((x1 + OBJECT_WIDTH) > DISPLAY_WIDTH)
       {
        x1 = 0;
        targets++;
       }
    // Dayaan1 killed Score updated
    if(x1==x && y1==y)
      {
        // Playing killing Music
        Mix_PlayChannel( -1, KillSound, 0 );
        x1=0;
        score++;
      }
    // Moving Dayaan2
    y2 = y2-3;
    if((y2 + OBJECT_WIDTH) < 0)
       {
        y2 = DISPLAY_HEIGHT-OBJECT_HEIGHT;
         targets++;
       }
    // Dayaan2 killed Score updated
    if(x2==x && y2==y)
    {
        // Playing killing Music
        Mix_PlayChannel( -1, KillSound, 0 );
        y2 = DISPLAY_HEIGHT-OBJECT_HEIGHT;
        score++;
      }
    // Moving Dayaan3
    y3 = y3+3;
    if((y3 + OBJECT_HEIGHT) > DISPLAY_HEIGHT)
      {
        y3 = 0;
        targets++;
      }
    // Dayaan3 killed Score updated
    if(x3==x && y3==y)
     {
        // Playing killing Music
        Mix_PlayChannel( -1, KillSound, 0 );
        y3=0;
        score++;
     }
    // Moving Dayaan4
    x4 = x4-3;
    if((x4 + OBJECT_WIDTH) < 0)
        {
         x4 = DISPLAY_WIDTH - OBJECT_WIDTH;
         targets++;
         }
    // Dayaan4 killed Score updated
    if(x4==x && y4==y)
      {
         // Playing killing Music
         Mix_PlayChannel( -1, KillSound, 0 );
         x4 = DISPLAY_WIDTH - OBJECT_WIDTH;
         score++;
      }
}

// Showing Dayaans/warrior on display
void Object::show_All_objects()
{
    // Show warrior/dayaans
    loading_surface( x, y, Warrior, display );
    loading_surface( x1, y1, Dayaan1, display );
    loading_surface( x2, y2, Dayaan2, display );
    loading_surface( x3, y3, Dayaan3, display );
    loading_surface( x4, y4, Dayaan4, display );
}

// Intializing clock
Clock::Clock()
{
    // Initialize the variables
    ticking_start = 0;
    ticks_paused = 0;
    ispaused = false;
    isstarted = false;
}

// Starting Clock
void Clock::start()
{
    // Start clock
    isstarted = true;

    // Unpause clock
    ispaused = false;

    // Get the current clock time
    ticking_start = SDL_GetTicks();
}

// Stopping Clock
void Clock::stop()
{
    // Stop clock
    isstarted = false;

    // Unpause clock
    ispaused = false;
}

// Pausing Clock
void Clock::pause()
{
    // If the clock running and not already paused
    if( ( isstarted == true ) && ( ispaused == false ) )
    {
        // Pause clock
        ispaused = true;

        // counting paused ticks
        ticks_paused = SDL_GetTicks() - ticking_start;
    }
}

// unPausing Clock
void Clock::unpause()
{
    // If clock is paused
    if( ispaused == true )
    {
        // Unpause clock
        ispaused = false;

        //Reset clock
        ticking_start = SDL_GetTicks() - ticks_paused;

        // Reset clock
        ticks_paused = 0;
    }
}

// Getting Number of ticks
int Clock::get_No_of_ticks()
{
    // If clock is running
    if( isstarted == true )
    {
        // If clock is paused
        if( ispaused == true )
            return ticks_paused;
        else
            return SDL_GetTicks() - ticking_start;
    }
    // If clock not running
    return 0;
}

// Checking clock started or not
bool Clock::is_started()
{
    return isstarted;
}

// Checking clock paused or not
bool Clock::is_paused()
{
    return ispaused;
}

// Main Function
int main( int argc, char* args[] )
{
    // quit flag to check quitting
    bool quit = false;

    // Object to be used
    Object obj;

    // The frame rate checker
    Clock clk;

    // checking for Initialisation
    if( initialize() == false )
        return 1;

    //Loading necessary files
    if( loading() == false )
        return 1;

    // When user Not quit
    while( quit == false )
    {
        //Start frame clock
        clk.start();

        // Events to handle
        while( SDL_PollEvent( &event ) )
        {
            // Handle events for Display
            obj.handle_warrior();
            if( event.key.keysym.sym == SDLK_n )
                {
                        // Diplaying score and starting new game on pressing 'n' key
                         char line[50];
                         sprintf(line,"You Killed: %d/%d Dayaans::Starting New game ;-)",score, targets);
                         scoreDisplay = TTF_RenderText_Solid( font, line, text_Color );
                         // Sendign score to Display
                         SDL_BlitSurface(scoreDisplay, NULL, display, NULL);
                         // Setting deplay to see score
                         SDL_Delay(5000);
                         // Free the score
                         SDL_FreeSurface( scoreDisplay );
                         SDL_Flip( display );
                         // Setting object positions to orizinal
                         obj.x = DISPLAY_WIDTH/2;
                         obj.y = DISPLAY_HEIGHT/2;
                         obj.x1 = 0;
                         obj.y1 = 0;
                         obj.x2 = 0;
                         obj.y2 = DISPLAY_HEIGHT-OBJECT_HEIGHT;
                         obj.x3 = DISPLAY_WIDTH-OBJECT_WIDTH;
                         obj.y3 = 0;
                         obj.x4 = DISPLAY_WIDTH-OBJECT_WIDTH;
                         obj.y4 = DISPLAY_HEIGHT-OBJECT_HEIGHT;
                         targets =0;
                         score =0;
                }

            // If the user close window
            if( event.type == SDL_QUIT )
                quit = true;
        }

        // Moving warrior
        obj.move_warrior();
        // Moving Dayaans
        obj.move_Dayaans();
        // Filling display with white
        SDL_FillRect( display, &display->clip_rect, SDL_MapRGB( display->format, 0x00, 0x00, 0x00 ) );

        // Showing all objects on display
        obj.show_All_objects();

        // Updating the Display
        if( SDL_Flip( display ) == -1 )
            return 1;

        // Checking frame rate
        if( clk.get_No_of_ticks() < 1000 / FRAMES_PER_SEC )
        {
            SDL_Delay( ( 1000 / FRAMES_PER_SEC ) - clk.get_No_of_ticks() );
        }
    }

    // Doing cleaning
    Do_cleaning();

    return 0;
}

To Run KillingSoftly Game:

step-1.  Install required libraries using following command
    >sudo apt-get install libsdl1.2-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev g++
step-2. Download KillingSoftly-0.1.
step-3. Extract using following command
    >tar -xzvf KillingSoftly-0.1.tar.gz
step-4. Move to extracted killingSoftly folder
    >cd KillingSoftly
step-5. To compile execute following command
    >g++ -lSDL -lSDL_image -lSDL_mixer -lSDL_ttf KillingSoftly.cpp
step-6. To run execute following command
   >./a.out


Saturday, April 20, 2013

A Sample D Programming Language Program

The D programming Language is an Object oriented programming language. It is designed by Walter Bright, Andrei Alexandrescu and developed by Digital Mars, Andrei Alexandrescu. Though it originated as a re-engineering of C++, D is a distinct language, having redesigned some core C++ features while also taking inspiration from other languages, notably Java, Python, Ruby, C#, and Eiffel. In D programming language usual filename extension is ".d".

Now lets write a sample D programming language program to add two numbers.

NOTE: before running this program make sure that GDC compiler installed on your system. (sudo apt-get install gdc)

// File Name: Addition.d

import std.stdio;
import std.cstream;
import std.conv;

int main()
{
   int num1, num2, sum;
   char[] line;
   // Readign first number
   writef("Enter 1st Number: ");
   line = din.readLine();
   num1 = std.conv.toInt(line);
   // Reading second number
   writef("Enter 2nd Number: ");
   line = din.readLine();
   num2 = std.conv.toInt(line);
   // Adding
   sum = num1 + num2;
   // Displaying sum
   writefln("The Sum is %d", sum);
   return 0;
}

To Run: gdc Addition.d
               ./a.out

Thursday, April 18, 2013

Creating PDF in C/C++ using Cairo graphics

Hi....Most of the times in C/C++ programming, we deal with binary or text files only. Binary file stores any kind of data in binary format, where text file stores a sequence of lines of electronic text.

In this post, i am going to show you how to create PDF files, through C/C++ programming. PDF files are more suitable, to present content to the user than binary/text files. More over PDF files provides, more accessibility features for disabled people.

Now lets write a C/C++ program, to create PDF file and write some text in that file. For this purpose i am using Cairo graphics library.

NOTE: Before running the following program, plz make sure that you have already installed cairo library and xdg-utils. (sudo apt-get install libcairo2-dev xdg-utils)

// Fine Name: CreatePDF.c

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <cairo/cairo.h>
#include <cairo/cairo-pdf.h>

void main()
{
        // Creating a cairo PDF Surface
        cairo_surface_t *csurface = cairo_pdf_surface_create("/home/reniguntla/Reni.pdf", 500, 400);
        // Creating a cairo context
        cairo_t *ctx = cairo_create(csurface);
        // Creating rectangle in PDF
        cairo_rectangle(ctx, 0.0, 0.0, 400, 300);
        // Changing rectangle bacground color to Blue
        cairo_set_source_rgb(ctx, 0.0, 0.0, 0.5);
        cairo_fill(ctx);
        // Moving to (10, 10) position in PDF
        cairo_move_to(ctx, 10.0, 10.0);
        // Changing text color to Yellow
        cairo_set_source_rgb(ctx, 1.0, 1.0, 0.0);
        // Writing some text to PDF
        cairo_show_text(ctx, "I am Reniguntla Sambaiah :-)");
        cairo_show_page(ctx);
        // Destroying cairo context
        cairo_destroy(ctx);
        cairo_surface_flush(csurface);
        // Destroying PDF surface
        cairo_surface_destroy(csurface);
        // Opening PDF File
        if (!fork()) {
        execlp("xdg-open", "xdg-open", "/home/reniguntla/Reni.pdf", NULL);
        exit(0);
    }
}

To Run: gcc -lcairo CreatePDF.c
              ./a.out

Out Put: In the output you can see a PDF as follows..


Sunday, April 14, 2013

MySQL Database In C Programming

Hi guys..In this post i am going to show you, how to use MySQL databases in C programs.

Installing MySQL on Debian based Linux:

To install MySQL, run the following command in terminal:
#sudo apt-get install mysql-server

During the installation, you will be prompted to enter a password for the MySQL root user. After that, install MySQL  client using following command.
#sudo apt-get install libmysqlclient-dev

To log into MySQL use following command. It will ask you to enter root password
#mysql -u root -p


To see existing databases use the following command
#mysql> show databases;

To exit from MySQL use following command
#mysql> exit


Using MySQL in C:

Now lets write a C program in which we create a MySQL employee database, and insert few records.

//FileName: MySQLinC.c

 #include <my_global.h>
#include <mysql.h>
#include <stdio.h>

int main(int argc, char **argv)
{

  MYSQL *conn;
  // initializing mysql connection
  conn = mysql_init(NULL);

  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
  // connecting to mysql server
  if (mysql_real_connect(conn, "localhost", "root",
          "rootpassword", NULL, 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
 // creating employeedb
  if (mysql_query(conn, "create database employeedb")) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

 // closing MySQL Coneection
    mysql_close(conn);

 // again initializing mysql connection
  conn = mysql_init(NULL);

  if (conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
  // connecting to employeedb in mysql server
  if (mysql_real_connect(conn, "localhost", "root",
          "rootpassword", "employeedb", 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }
 // creating employee table
 mysql_query(conn, "CREATE TABLE employee(name VARCHAR(25))");

 // inserting records in employee table
  mysql_query(conn, "INSERT INTO employee VALUES('Sagun Baijal')");
  mysql_query(conn, "INSERT INTO employee VALUES('Leena Chouray')");
  mysql_query(conn, "INSERT INTO employee VALUES('D.V Bhat')");
  mysql_query(conn, "INSERT INTO employee VALUES('Reniguntla Sambaiah')");
  mysql_query(conn, "INSERT INTO employee VALUES('Shivnath Kumar')");

 // closing MySQL Coneection
  mysql_close(conn);
}

To Run: gcc MySQLinC.c -o MySQLinC  `mysql_config --cflags --libs`
             ./MySQLinC

To check the emploeedb is created or not use following commands at command line

# mysql -u root -p
#mysql> show databases;
#mysql> use employeedb;
#mysql> show tables;
#mysql> select * from employee;