Who should be blamed for the failure of democracy?

Today many states of India including Delhi are conducting General Election 2014. For the last one month the whole society was submerged in election talks. Election Commision of India is doing huge effort by making citizens of India aware of the value of their votes. Media is playing a crucial role in the same. Facebook, FM radio channel, Twitter, news channels, newspapers etc every aspect of social media has been used for these inititives. Moreover this is brining a positive attitude in the society towards the voting. Definity this is a good sign for a democary that citizens are showing interest in the election to choose most appropriate candidate of their choice.

But the questions still remain the same “How the social problem like curruption would be handled?” or “Would the pepole we are going to elect run this democracy honestly?”. If we ask these questions from any citizen of India no one has answer to these questions. Every year if we see union budget of the India we are under many thousands dollers deficit. That means we still do not have knowledge of why our democracy is failing?

Let’s look back into the history of India. For many centuries there was monarchy and was quite sucessfully. But it’s been only 66 years since Indian independence and we are facing lot of system problems in running a democarcy. Let’s try to figure out why. I think in monarchy king used to be the owner of his empire and that was his birth right. The prince used to be prince from birth. No one was there to remove him from his postion. On the other side any political leader has the thought “I am not a king of this courntry. I am here for defintely interval of time.”. I know the above comparison will bring many questions to your mind like everyone would not get equal rights in monarchy. Well that’s right. But that is another topic for debate. What I want to highlight would be clear form another example, suppose someone is a head of a family he will put his best to make his family prosperous and happy irrespective of his personal profit or loss. But if he is working in a company he will definity think personally first then for the company. The reason behind this is he is not owing the company.

According to the definition of democracy (A political system in which the supreme power lies in a body of citizens who can elect people to represent them.) who is owning the democarcy is its citizens and political leaders are eleted to get work done for the citizens. That means we the citizens(owner) are assigning some work to our political leader (employee). Now if suppose I am the owner of company I have hired an employee and I have given full power to him to run my company. And I am not asking from him what he was supposed to be done whether he is doing that or not or how he is spending my money. Do you think my employee would work in my favor when he is not accountable for anything and have rights to access all my resources? Most of you will answer “No, definitly not”. So in this case problem is with me not with my employee.

Actually our political leaders are not problem. We should not question their loyality. That is human nature. Where the change is required is in citizens. Being citizens(owner) we should account our political leaders(employees) for their work. I think we should work towards the accountibility of political leader’s work instead of blaming. But the question is how. I don’t have much understanding of politics but I know there are some tools in our constitution with which we can achieve this, for example RTI (Right to information). Similar kind of tools are need to be created to make political leaders accountable. Instead of punishing the corrupted we should focus on making them accountable. I think this is the only positive way to achive a healthy democracy.

We have started taking first step by voting. Let’s move forward.

I vs We

Few days are left for Indian general elections 2014. The whole country is submerged in political turbulence. Everyday we get to know about a new turn in political arena. Well, I am not here to discuss the politics as I am not a fan of politics. But still there are few interesting things happening in politics which are directly or indirectly related to every individual from us.

It’s very natural phenomenon that new people join any corporation, social group, a team or even a family and be that part of that or get rejected. Some of them have a different vision to look towards the things. But out of those few get accepted by the group forever and other get accepted initially and then rejected even when they have same target as that of the group they join.

Well I am talking about Mr. Kejriwal who started a movement to eradicate corruption and got a huge support from the people. Then suddenly what wrong happened after he became the chief minister of New Delhi. The equations are getting changed day by day for him. He is losing his value, his people are leaving him. Well, you might be thinking I am a supporter of Kejriwal or any other political party but I am not. I am just trying to figure out what really went wrong because this is not Kejriwal’s story. This is mine or yours story as well. Similar to when we debut in our career or we get married. We starts a new inning very optimistically and soon things get complicated day by day. In all the cases one thing is common which is “I turns into we”.

“We” seems simple but it is very complicated word. Lets first talk about “I”. “I” denotes me. If it is me I have a single vision with limited power which might not we enough to accomplish big goal. And there “we” comes in. Let me explain you this with an example. Edison invented electric bulb but was he enough to make world illuminated? Definitely the answer would we “No”. “I” can start a new vision or can bring a new idea but this is “we” which can make it effective for a mass(society, group, team, corporation etc.).

Sometimes we feel I can achieve anything I have the skills and I have the right vision. This works perfect for small tasks where you are the only who is working. Keeping such though while working in a group this doesn’t works, either you will be overworked and will be doing others tasks or you will not be accepted by group and ultimately people in group will start leaving group. The same happened with Kejriwal. He had a very good vision but his “I” was dominating “we”.

Lets take another example from Indian general elections. We all are voters who decides who will be our leader. Today’s morning I was watching last episode of “Satyamev Jayate season 2” a TV show by Amir Khan. In that it was shown how voters get affected by “I-We” factor. Voters vote for a candidate for just a few hundred rupees, some gifts like phone, sarees etc or a bottle of wine or on the basis of cast, religion. When we see the same from bird eye view voters are more concerned about their personal interests so are the leaders. In that “We” is failing because of “I”, whether it is voters “I” or leaders “I”.

That means “we” is all about thinking together and drawing solution of the problem and achieving big goal which will benefit the whole group. Remember those days when our elders, parents, or teachers used to say “stay together” or “unity is power”. Even we have heard many stories on this in our childhood. We are all aware about this fact but the question is “HOW?”. You might be thinking I will conclude this article with some solution. But unfortunately it is not a black and white this is a grey area. There is not clear defined way to achieve positive togetherness. I leave this on you to think over this. Still I have some thoughts, a constructive group can be created with honest contribution for the group goals by each member. It doesn’t matter whether you are valued or not just honestly contribute if you deserve you will be valued.

BulletPhysics(Physics Engine) Android Port – Demo App using OpenGL

Tags

, , , , ,

In my last post I discussed about the BulletPhysics port on android. Now in this post I am going to elaborate how to use it with OpenGL graphics to visualize the the BulletPhysics. In my last post I ported BulletPhysics the using NDK build system for Android. This time I have extended that port to bind the graphics with that. I wrote the drawing logic of the object in OpenGL. I have created a very simple scene in which four balls fall and moves according to the physics laws. The transformation in the balls positions and orientations is handled by the bullet.

Hope you would find this interesting. For more detailed documentation you can refer http://bulletphysics.org/ for Bullet and http://opengl.org/for OpenGL.

Checkout code: https://github.com/manoj-chauhan/AndroBullet

BulletPhysics(Physics Engine) Android Port – Hello World

Tags

, ,

Technological advancements in mobile computing have affected our life and business as well. Now we expect from our mobile devices(phones, tablets) high quality communication, entertainment, education, gaming and much more.
These days technological advancements have made our mobile device much powerful that the desktop computer we were using 10 years back. Now we have more processing power, graphics processing power, much higher capacity RAM’s in our devices which has opened avenues for the high end computing on our small handheld devices. In this gaming comes very first. Every gamer needs the best in terms of quality and technology. Simulation for the real world is always more catchy and interesting in gaming. I am talking about 3D world simulation. If it is added by the physics simulation in 3D it adds value and interest in the game for gamer. In this article I am going to talk about 3D physics simulation only.

It is always been a hard part to implement the physics laws in the game logic. And to overcome this problem and to get it done easily we have BulletPhysics physics engine. There are so many physics engines available in market most of them are not for mobile platform or propitiatory. The best part of the BulletPhysics is, it is free and open source community project. Enthusiasts and professional developer can use it to add physics to their games.

When someone decides to use this on any mobile platform, the biggest hurdle comes in the way is porting the engine to that platform. As we all know Android is gaining huge acceptance in the market and has a big slice of market pie. I decided to port BulletPhysics to Android. You can download the HelloWord of BulletPhyics ported on android. Right now it doesn’t have the GUI but soon in my next post I would post demos on this. You can download and run this by just importing it to you eclipse IDE. The source you can download from the link mentioned below. The output would come on logcat.

Hope you would find this interesting and for more detailed documentation you can refer the http://bulletphysics.org/.

Checkout code: https://github.com/manoj-chauhan/AndroBullet

Using FreeImage library for loading image in memory

In this article I am going to discuss how to use FreeImage on Ubuntu. FreeImage provides the convenient way to load various graphics image formats like PNG, BMP, JPEG, TIFF and others as needed by multimedia applications. Free Image can be used on various platforms like Linux, NetBSD, Windows, Mac OS X, Symbian etc. FreeImage is easy to use, fast, multithreading safe. FreeImage can be used in an image editor, visual tool, games or anywhere you need a bitmap.
You can install this utility libary on you Ubuntu by just giving a simple command while you are connected to the Internet. This command would install the Freeimage and its all dependencies. You need to just type following on terminal window.

sudo apt-get install libfreeimage3

If you are not on the Ubuntu. You can get the FreeImage install by compiling the source. You can the source from FreeImage offical website http://freeimage.sourceforge.net/. You can compile the source by following the following steps:

1. Extract the archive file on your desired location.
2. Open the terminal and change the present working directory to the the extracted source directory.
3. Now type following commands:

make
make install

After getting FreeImage installed let’s created HelloWorld program. Create a new HelloWorld.c as follows:

#include 
#include 

int main(void){

	printf("FreeImage Version : %sn",FreeImage_GetVersion());
	printf("Copyright Message : %sn",FreeImage_GetCopyrightMessage());

	FIBITMAP *bitmap = FreeImage_Load(FIF_JPEG,"img.jpg",JPEG_DEFAULT);

	if(bitmap){
		printf("Bitmap loaded successfully.n");
                FreeImage_Unload(bitmap);
	}else{
		printf("Bitmap could't be loaded.n");
	}

return 0;
}

You can compile the above source using gcc compiler by giving the following command on terminal:

gcc -o HelloWorld HelloWorld.c -lfreeimage

Getting started with OpenGL on Linux

Tags

, ,

When a newbie wants to get hands in opengl, he feels lost. He doesn’t get the place where and how to start. In this article I gonna discuss how to get started with opengl on a Linux host.
I gonna use Ubuntu Linux distro as my host environmeet. Following are the prerequisites to compile my Hello World program. Let’s have a glimpse of these.

1. GCC : Ubuntu is shipped with the GCC compiler, which we would use for compiling our source code.
2. Make Uitility : Make utility is basically used to manage the source code of the project. It is a command line tool. Ubuntu is shipped with this as well.
3. Freeglut : Freeglut is basically an API to perform basic opengl drawing and rendering those on the screen. It is the open source version of the GLUT(OpenGL Utility Toolkit). Ubuntu is not shipped with the Freeglut. So you need to intall this package on you host machine. You can do this easily by executing following command if you are connected the the Internet.

sudo apt-get install freeglut3-dev

4. GLU : It is a open source library consists of a number of functions that use the base OpenGL library to provide higher-level drawing routines from the more primitive routines that OpenGL provides. You can install this libaray by executing the following command.

sudo apt-get install libGLU

Now we are ready to write some code. First of all create a folder with the name of your choice in which we gonna put our source file main.c.
The following is the content of the file main.c.

#include 
#include 


GLfloat xrot, yrot, zrot;

void resize(int width, int height)
{
    glViewport(0, 0, width, height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0f, (GLfloat)width/(GLfloat)height, 1.0f, 1000.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);

    glEnable(GL_CULL_FACE);
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	glTranslatef(0.0f,0.0f,-5.0f);
	glRotatef(xrot,1.0f,0.0f,0.0f);
	glRotatef(yrot, 0.0f, 1.0f, 0.0f);
	glRotatef(zrot, 0.0f, 0.0f, 1.0f);
	glBegin(GL_QUADS);

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

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

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

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

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

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

	glEnd();

	xrot += 0.2f;
	yrot += 0.1f;
	zrot += 0.3f;

    glutSwapBuffers();
}

void key(unsigned char key, int x, int y)
{
    switch (key)
    {
        case 27 :
            exit(0);
            break;
        default:
            break;
    }

    glutPostRedisplay();
}

void idle()
{
    glutPostRedisplay();
}

int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(640,480);
    glutInitWindowPosition(10,10);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

    glutCreateWindow("HELLO WORLD");
    glutReshapeFunc(resize);
    glutDisplayFunc(display);
    glutKeyboardFunc(key);
    glutIdleFunc(idle);

    glutMainLoop();
}

If you are working on opengl first this you might not get much out of this. But don’t worry our intention is to just run our first opengl code. In my next articles I gonna explain you this in detail.

Now we gonna write a simple makefile which would be used by the make utility to compile main.c. We can also compile the main.c without makefile by executing the following command.

gcc -g -o hello main.c -lglut -lGLU

But use of the makefile makes it easy to compile and manage a large source by writing all details of the code in the makefile. Without makefile it is hard to manage a large number of source file directly on command line. Following is the makefile named Makefile to compile the main.c.

all:
	gcc -g -o hello main.c -lglut -lGLU

Now we are ready to compile the code we have written. Now just open terminal window. Change the present working directory to the directory you have created by following command.

cd path-of-your-directory

Now execute command.

make 

If the compilation would get done successfully ‘hello’ an executable file would get generated. Now run the ‘hello’ executable by typing following commmand on the terminal.

./hello

and here is the HelloWorld program running on your screen.
HelloOpenGL

3D Page Curl Animation on Android

Tags

, , , ,

Advancements in computer graphics technologies have taken computers more towards the real world. We can now simulate the real world scenarios in computer like special effects in movies, animations, CAD/CAM etc. My this article is more devoted to the same. In this article I am gonna discuss how to simulate the page curl effect in 3D world using OpenGL on Android platform. In this article I am not going to discuss about the technical details of the OpenGL rendering. I would discuss only about the mathematics and logic behind this animation. The picture below depicts what we gonna discuss.


This demo is very simple page curl in which page is curled form one edge uniformly as shown in figure:(a). To withdraw the mathematical equation of the curl we assume that the page is made of infinite parallel curves as shown in figure:(b). We would calculate the equation for one curve as shown in the figure:(c). We also assume that curve is formed of line segments drawn by joining the points shown in figure:(d). We imagine a circle moving linearly along the line and as it moves points get wrap around the circle and the circle moves quantized i.e. on points and not in between them. The same thing is applied to each curve to achieve page curl animation.

The class ‘Page’ holds all those calculations which we discussed above.

package com.page.curl;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

public class Page {
	public final int GRID = 25;
	private final float RADIUS = 0.2f;
	public float curlCirclePosition = 25;

	private FloatBuffer vertexBuffer;
	private FloatBuffer textureBuffer;
	private ShortBuffer indexBuffer;
	private int[] textures = new int[1];
	private float vertices[] = new float[(GRID+1)*(GRID+1)*3];
	private float texture[] = new float[(GRID+1)*(GRID+1)*2];
	private short indices[] = new short[GRID*GRID*6];

	public Page() {
		calculateVerticesCoords();
		calculateFacesCoords();
		calculateTextureCoords();
		ByteBuffer byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		textureBuffer = byteBuf.asFloatBuffer();
		textureBuffer.put(texture);
		textureBuffer.position(0);

	        byteBuf = ByteBuffer.allocateDirect(indices.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		indexBuffer = byteBuf.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
	}

	public void calculateVerticesCoords(){
		float angle = 1.0f/((float)GRID*RADIUS);
		for(int row=0;row<=GRID;row++)
			for(int col=0;colcurlCirclePosition){
					vertices[pos]=(float) ((curlCirclePosition/GRID)+RADIUS*Math.sin(angle*(col-curlCirclePosition)));
					vertices[pos+2]=(float) (RADIUS*(1-Math.cos(angle*(col-curlCirclePosition))));
				}else{
				        vertices[pos]=(float)col/(float)GRID;
					vertices[pos+2]=0;
				}
				vertices[pos+1]=(float)row/(float)GRID;
			}
		ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
		byteBuf.order(ByteOrder.nativeOrder());
		vertexBuffer = byteBuf.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
	}

	private void calculateFacesCoords(){
		for(int row=0;row<GRID;row++)
			for(int col=0;col<GRID;col++){
			        int pos = 6*(row*GRID+col);
				indices[pos] = (short) (row*(GRID+1)+col);
				indices[pos+1]=(short) (row*(GRID+1)+col+1);
				indices[pos+2]=(short) ((row+1)*(GRID+1)+col);
				indices[pos+3]=(short) (row*(GRID+1)+col+1);
				indices[pos+4]=(short) ((row+1)*(GRID+1)+col+1);
				indices[pos+5]=(short) ((row+1)*(GRID+1)+col);
			}
	}

	private void calculateTextureCoords(){
		for(int row=0;row<=GRID;row++)
	        	for(int col=0;col<=GRID;col++){
				int pos = 2*(row*(GRID+1)+col);
				texture[pos]=col/(float)GRID;
				texture[pos+1]=1-row/(float)GRID;
			}
	}

	public void draw(GL10 gl) {
		calculateVerticesCoords();	
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glFrontFace(GL10.GL_CCW);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
		gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
	}

	public void loadGLTexture(GL10 gl, Context context) {
		InputStream is = context.getResources().openRawResource(R.drawable.page);
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(is);
		} finally {
			try {
				is.close();
				is = null;
			} catch (IOException e) {
			}
		}
        	gl.glGenTextures(1, textures, 0);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
		bitmap.recycle();
	}
}

Checkout code: https://github.com/manoj-chauhan/3dPageCurl

Sparkle (Simple Particle System) on Android Canvas

Tags

, , , ,

Computer graphics is really an interesting domain to work in. There are numerous topics to study in computer graphics but in this article I am gonna discuss about a simple particle system. Which I am gonna demonstrate on the Android canvas. Particle systems are used to simulate the fire, smoke, fog, explosions etc. This demonstration would simulate the sparkle effect on touching the screen of the Android device. As you can see in the video below:

Let’s first discuss about few basics of the simple particle systems. In a simple particle system every particle has a life span. Particles take birth, lives their life and dies. In a particle system there is an emitter of the particles which generates the particles. In our case the emitter is the point where the user touches the screen and the particles have the life span till they are visible on the screen of the device. As the particles go off the screen the particles get removed from the drawing list of the particles.

In the demo the class Particle represents a single particle. The init() method initializes the particle generation point (initX, initY) and its distance form that point. When the Particle object is created the particle is initialized with init() method, set the random color out of (0,1,2), direction out of NO_OF_DIRECTION directions, directionCosine and directionSine. The directionCosine and directionSine are just to improve the performance of the animation so that these values would not get calculated again and again on each drawing on the canvas. And move() is just to increase the distFromOrigin for the movement of the particle in animation.

package com.sparkle;

import java.util.Random;

public class Particle {
	public int distFromOrigin = 0;
	private double direction;
	private double directionCosine;
	private double directionSine;
	public int color;
	public int x;
	public int y;
	private int initX;
	private int initY;

	public Particle(int x, int y) {
		init(x, y);
		this.direction = 2*Math.PI * new Random().nextInt(NO_OF_DIRECTION)/NO_OF_DIRECTION;
		this.directionCosine = Math.cos(direction);
		this.directionSine = Math.sin(direction);
		this.color = new Random().nextInt(3);
	}

	public void init(int x, int y) {
		distFromOrigin = 0;
		this.initX = this.x = x;
		this.initY = this.y = y;
	}

	public synchronized void move(){
		distFromOrigin +=2;
		x = (int) (initX+distFromOrigin*directionCosine);
		y = (int) (initY+distFromOrigin*directionSine);
	}
	private final static int NO_OF_DIRECTION = 400; 

}

ParticleDrawingThread is a thread, which is responsible for drawing on the canvas of the view. Basically there are two lists of particle one is ‘mParticleList’ which has to be drawn on the canvas and another ‘mRecycleList’ which is used for holding all the particle which get off the screen and ready for the recycling. The ParticleDrawingThread removes the particles from the ‘mParticleList’ if the particles get off the screen add them to the ‘mRecycleList’. With this recycling we can reduce allocation and deallocation of the particle object which improves the performance.

package com.sparkle;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.view.SurfaceHolder;

class ParticleDrawingThread extends Thread {

	private boolean mRun = true;

	private SurfaceHolder mSurfaceHolder;

	private ArrayList mParticleList =new ArrayList();
	private ArrayList mRecycleList =new ArrayList();

	private int mCanvasWidth;
	private int mCanvasHeight;
	private Paint mPaint;
	private Bitmap mImage[] =new Bitmap[3];

	public ParticleDrawingThread(SurfaceHolder mSurfaceHolder, Context mContext) {
		this.mSurfaceHolder = mSurfaceHolder;
		this.mPaint = new Paint();
		mPaint.setColor(Color.WHITE);
		mImage[0] =((BitmapDrawable)mContext.getResources().getDrawable(R.drawable.yellow_spark)).getBitmap();
		mImage[1] =((BitmapDrawable)mContext.getResources().getDrawable(R.drawable.blue_spark)).getBitmap();
		mImage[2] =((BitmapDrawable)mContext.getResources().getDrawable(R.drawable.red_spark)).getBitmap();

	}

	@Override
	public void run() {
		while (mRun) {
			Canvas c = null;
			try {
				c = mSurfaceHolder.lockCanvas(null);
				synchronized (mSurfaceHolder) {
					doDraw(c);
				}
			} finally {
				if (c != null) {
					mSurfaceHolder.unlockCanvasAndPost(c);
				}
			}
		}
	}

	private void doDraw(Canvas c) {
		c.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint);
		synchronized (mParticleList) {
			for (int i = 0; i < mParticleList.size(); i++) {
				Particle p = mParticleList.get(i);
				p.move();
				c.drawBitmap(mImage[p.color], p.x-10, p.y-10, mPaint);
				if (p.x < 0 || p.x > mCanvasWidth || p.y < 0 || p.y > mCanvasHeight) {
					mRecycleList.add(mParticleList.remove(i));
					i--;
				}
			}
		}
	}

	public void stopDrawing() {
		this.mRun = false;
	}

	public ArrayList getParticleList() {
		return mParticleList;
	}

	public ArrayList getRecycleList() {
		return mRecycleList;
	}

	public void setSurfaceSize(int width, int height) {
		mCanvasWidth = width;
		mCanvasHeight = height;
	}

}

In ParticalView main thing to concentrate about is particle generation. onTouchEvent() method is responsible for adding particle to the ‘mParticleList’. If the particle is available in the ‘mRecycleList’ it would get added from there otherwise create new particle object and add to the ‘mParticleList’.

package com.sparkle;

import java.util.ArrayList;

import android.content.Context;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class ParticalView extends SurfaceView implements SurfaceHolder.Callback {

	private ParticleDrawingThread mDrawingThread;

	private ArrayList mParticleList;
	private ArrayList mRecycleList;

	private Context mContext;

	public ParticalView(Context context) {
		super(context);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		this.mContext = context;

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		mDrawingThread.setSurfaceSize(width, height);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mDrawingThread = new ParticleDrawingThread(holder, mContext);
		mParticleList = mDrawingThread.getParticleList();
		mRecycleList = mDrawingThread.getRecycleList();
		mDrawingThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		mDrawingThread.stopDrawing();
		while (retry) {
			try {
				mDrawingThread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Particle p;
		int recycleCount = 0;

		if(mRecycleList.size()>1)
			recycleCount = 2;
		else
			recycleCount =mRecycleList.size();

		for (int i = 0; i < recycleCount; i++) {
			p = mRecycleList.remove(0);
			p.init((int) event.getX(), (int) event.getY());
			mParticleList.add(p);
		}

		for (int i = 0; i < 2-recycleCount; i++)
			mParticleList.add(new Particle((int)event.getX(), (int)event.getY()));

		return super.onTouchEvent(event);
	}

}

Checkout code: https://github.com/manoj-chauhan/Sparkles

Hi!

It’s been a long time since I was thinking to write a blog of me. I tried it earlier with www.blogspot.com as www.techie-manoj.blogspot.com but I felt that’s not sufficient for my needs. So, now I have come up with this www.techie-manoj.com as my blog. Here I would be happy to share my thoughts and experiences with you people and your comments and suggestions are always welcome. Soon I would come with some interesting posts to share with you people.