Wednesday, December 31, 2008

Awesome Header

Searching a university for MS was one heck of a journey. Frankly, it was deemag karab. Admist all that headache, i found this really good header from SUNY stony brook university. It's so good that i decided to put it up as my first blog entry...










Pretty good eh? Was refreshing to me!

Saturday, December 20, 2008

Pure Genius...

I accidentally came across a lecture on 'human computing' by Louis Von Ahn, a professor at Carnegie Mellon University. This is one of the best works i have seen. Pure genius and totally awesome...

Dont forget to check this out:
http://video.google.com/videoplay?docid=-8246463980976635143&hl=en

Monday, November 17, 2008

Why use object oriented programming…2

In my previous post, I’ve written how OOP resolves basic issues such as

• Functional Clutter
• Problem with Global Variables
• Unmanageable associations

Apart from these OOP has other powerful features, namely Inheritance and abstract classes. In this blog I’m going to discuss what these terms mean and why are they so useful.

We all know the common book definition of inheritance, but why is it so useful?
Basically inheritance is used when you have to

1) Modify the behavior of the object
2) Add additional features to the existing class

To modify the behavior all you gotta do is inherit the parent class into a new class called the base class and override the necessary methods. Take the example of JLabel in swing. The text in the label is rendered onto the screen by calling the paint method. Suppose you wanted to change the way border is shown, you have to override this method which is in turn called by swing framework to render the label.

To add additional features to the label, you have to inherit it into the base class and write additional methods for enabling new features. The base class now contains all the previous functionality that lets keeps it compatible with the existing framework.

Inheritance is essentially like copying and pasting all the code within the parent class into the base class. So why not copy and paste the code manually? I.e. copy code in class A to Class B instead of inheriting.

Just imagine what would happen if class A is modified later on as a result of bug fix or enhancement. You’ll have to re-copy all the code from class A to class B, thereby hampering the code manageability. Moreover inheritance lets you reuse the well designed and tested classes you’ve already made.

What’s more, inheritance also helps you debug the code. Suppose class A, B, C, D inherits class E. If there is a problem in classes A to D then it’s probable that the code in class A is buggy. If class A is buggy then it’s probable that the new code you’ve added is buggy. It may seem like a small thing but believe it or not, about 70% of development time is wasted in debugging and maintenance.

Abstract classes…Inherit benefits of Inheritance

Suppose there are a lot of things in common between the two classes (A and B), i.e. you notice some sort of code redundancy, but there are also many marked differences between them at the same time. Furthermore the redundant code cannot be grouped within a single class as it doesn’t make any sense. If you come across this kind of a situation, you could put all that redundant code in an abstract class (X) and make then create the other two by inheriting the abstract class. This kind of model is blessed with the benefits of inheritance. In short it Inherit benefits of Inheritance ?

Abstract classes don’t have an instance, i.e. it’s not possible to create an object without implementing the abstract methods. Simply make the class specific methods, the ones used by classes A and B as abstract. Sounds like Greek and Latin? Let’s consider an example.

Yesterday I was trying to make a class that can add the ‘trail period’ feature to any software. To do this I’ll have to –

1) Record the date when the software is first used.
2) Whenever the software is started, check the current date with the start date and evaluate the difference
3) If the difference is greater than say 30 days then prompt the user to enter the serial key.

To record the start date there can be two possibilities.

1) Save the data in an encrypted form within a file.
2) Save the data in an encrypted form within a database in case of a distributed application.

So you make two classes, DBValidator and NonDBValidator. Both of then contain redundant code…i.e. the logic that checks the date difference, a fraud detection system to see if the user tampers with the system date etc etc…The only point of change is the way in which the start date is persisted onto a storage medium.

In this scenario you could create an abstract class called validator with all the redundant code and make the persistDate method abstract.

Classes DBValidator and NonDNValidator inherit the validate class by implementing the abstract method persistDate, each one defining their own persistence logic.

Why go through this entire headache? Read the inheritance part again. This helps in centralizing the changes that may be required. You just have to make a change at a particular common place (the parent) and the necessary updates are forwarded to all the base classes.

Today’s software development standard is not about writing logical code, anyone can do that today. Instead more emphasis is laid on writing code that is better managed, even if you’ll have to compromise on the logic part. This is probably one the reasons as to why they look for people with work experience. Anyone involved in big projects would’ve certainly faced this problem before. This is also the reason why frameworks such as hibernate, JSF, struts are so popular in spite of the high learning curve involved.

Now that the basics of OOP is laid out, in my next post I’ll discuss about UML diagrams. I hope this article was useful.

Monday, November 10, 2008

Why use Object Oriented Programming…

Do you get this feeling, “why use classes and objects un-necessarily when functions can achieve the same in a simpler manner?” If yes, this article is for you. It took me about 3-4 months to fully realize the potential of OOP over structural paradigm. The only way you’ll realize the importance of OOP is when you write big code, I mean BIG, around 50K lines or so.

Here’s the scenario, consider yourself as a topnotch programmer who has written about 50,000 lines of code :) , say you’ve written some utility functions (around 800 of em) and have packaged them in a library.

Why does big code gets messy and un-manageable??

Problem 1…Functional clutter

From the usage point of view, the person using your library will probably be confused will all the functions you’ve provided (they’re about 800!!!) and moreover they have to remember all the parameters to the function, its behavior etc…

Ex- funcA(param1, param2, param3)
Param1, param2 are numbers…
Param3 can take values 1,2,3

1 would mean that the function will add param1 and param2…
2, 3 means it’ll perform multiplication and division

The whole point is that it’ll get real tough to remember the functions and its behavior, parameter’s when there are too many of them. Furthermore not all of the functions are of utility value. What I mean is that there will be some functions that are used by other utility value functions.

Ex - funcA() uses funcB() and funcC() to do its tasks. The end user is only concerned with funcA and not with funcB and funcC.


Problem 2…The headache of global variables

The usage of global variables is the most annoying thing for me. It’s very easy to confuse a global variable with a local one or vice-versa. Also tracking the usages of global variables is considerably difficult. It also increases dependencies between the functions.

Ex-

int x; //(global variable)

void func1()
{
//Uses global var x (reads and modifies)
}

void func2()
{
//Uses global var x (reads and modifies)
}


In this case, there exists a dependency between func1 and func2 indirectly via global variables…

How?
If in the future, you’ve found some bugs in func1 and corrected…it might as well affect func2 as they share the same global variable (dependency).

Problem 3…Unmanageable Associations

Consider a game consisting of 300 circles which are moved randomly (say). Every circle has three status variables associated with it.

x, y coordinate and the radius.
Here’s how your code would work.


loop
{
//Clear screen
//Draw all circles by reading their respective status variables
//Update the positions of all the circles by updating the status variables,
//using some logic
}


The thing is that there are three variables with each circle…So that makes it 300 * 3 variables

You’ll probably end up naming variables as
Int x1, y1, r1, y2, r2….x300, y300, r300

What if there are more objects in the game, like clouds, trees etc (even more status variables). All of this makes the code look messy and also makes the associations harder. You’ll soon start confusing which function operates on what and which variable is associated with an object (circle in this case)

So what are the solutions to these issues? If you think about it’ll almost seem obvious.

Solution to problem 2 & 3

In the world of OOP objects form the building blocks of the code. Suppose you’re coding a game, just think of any sprite (something that’s rendered onto the screen) as an object.

An object is just like any other real world entity.

- It has certain attributes or properties associated with it. In case of the circle consider its status variables as its attributes.

- Has certain operations associated with it. You could have associated an operation (function) ‘move()’ with the circle object that would randomly alter its attributes. Also a function called ‘draw()’ can be added to render the circle onto the screen.

Now there’s no more confusion…All the variables and operations are ‘encapsulated’ within an object


Circle (class or prototype of an object)
--------------------------------------
(Attributes)
--------------------------------------
Int x
Int y
Int radius
--------------------------------------
(Operations)
--------------------------------------
Move()
Draw()
--------------------------------------

Class is just a template; an object on the other hand is an instance of the class having its own attributes.

Moreover there is no longer a menace of global variables as all the attributes (variables) are encapsulated within classes.

Solution to problem 1


To avoid the confusion all the related functions and shared global variables could be encapsulated within a class.
Ex- Suppose you have some functions that perform certificate auth, encryption, decryption etc…You could combine (associate, encapsulate) them all in a class named security. Make all the shared global variables its attributes.

As far as the utility of the function is concerned, OOP introduces access modifiers such as public, private etc…

Make the real utility valued functions as public. The supporting functions can be made private so that they cannot be accessed directly from the object.

This is only the beginning (yea, I know it’s a movie dialog). You haven’t tasted the real power yet. Apart from the issues I discussed, the key strength of OOP is in inheritance and abstraction.
I’ll discuss more about those in my next post. I hope this article was useful.

Friday, October 31, 2008

Better Explained?

Cant help but post this, Check out http://betterexplained.com/. It has amazing new perspectives on simple issues...for starters, take a look at the pythagorean theorem. Im sure it'll amaze you as much as it did to me.

Wednesday, October 29, 2008

Reverse Engineering the Brain

Oh yes, you heard it right. It’s no longer a stuff of science fiction. On July 25, 2008, Intelligence Realm Inc. has completed a simulation of 100 billion neurons, the estimated size of the human brain. The simulation used distributed computing and involved over 3000 volunteers, 10000 processors, 180 TB of data and it lasted for a couple of months. This was the first simulation that bypassed the 100 billion level and used database files to store the data. The simulation is one of the first steps in a long-term project that is aiming to build a large-scale artificial intelligence by reverse engineering the brain.

So how are the neurons simulated? The concept of artificial neural networks (ANN) is used which can perform tasks like predicting stock market, hand writing recognition, face recognition and many more. A typical ANN hardly consists of 100 neurons. Imagine the potential of an ANN with 100 billion neurons. 'Google' on Artificial neural networks for more information...

So what’s the catch? There are many challenges involved to simulate an ANN at this degree.
1) Interconnection of neurons and their weights associated.
2) The processing power and storage capabilities.

The latter can be solved in an economical manner by using a distributed computing scheme similar to SETI (wherein, volunteers can share their processing power). As for the storage, with TB’s of hard disks coming up, that shouldn’t be much of an issue.

To solve the former, scientists have decided to mimic the connections and weights used in the brain. After all it is nothing less than marvelous. Take a look at www.brainmaps.org. They have created a brain map of many species. So far 92% of the human brain is mapped because of the complexity involved.

To get the gravity of this research, imagine the following scenario. A person is permanently blinded because of damage to visual cortex of the brain. Since, human brain mapping is available. A Nano sized chip could be made containing all the ANN’s required to process visual data. The beauty of this is that we don’t even have to understand how the information is processed. All we have to do is device a way for it to interact with the remainder of the brain by interconnecting the neurons of the chip with the real ones with a Nano surgery just as described by the brain map. By this a permanently blind person’s vision can be restored. This is because; the visual cortex neurons, connections and weights are mimicked exactly as it was in the real brain.

Seems far fetched? You’ll be in for a real surprise. Back in 1980’s, it was estimated that the number of computers to be used by the year 2000 would be about 100.

Understanding frameworks by example...2


Step 3: Check your code so far, revise and optimize


All might seem rosy at the moment but when you try out this code…you’ll notice that

1) Frame rates vary widely, some systems show FPS of up to 150 and some about 30
To ensure frame-rate consistency we’ll add ensureMinFPS() and ensureMaxFPS() functions. This can be done by skipping calls too render() function, also known as frame skipping.

That means we update status like 3 times but only draw it once onto the screen. The result is that the sprite may seem to be moving with large steps and may damage smoothness. But that’s the PC's problem nothing to do with us. Also we could add a convenience method getCurrentFPS(), just to check the performance.

2) For animating a moving object like a man, we’ll have to cycle through a set of images…
This requires some handling which is again redundant. So we’ll add AnimatedSprite class. This class may contain methods such as addFrame(Image img, long persistenceTime);

We’ll extend this class with Renderable.class so that its update and render methods can be utilized by the Game.class when registered with it.
@Override
public void update(long time)
{
Image curFrame = frames.get(curFrameIndex);
animTime += elapsedTime;

if(animTime >= curFrameduration)
{
curFrameIndex++;

//provides roll-over for animTime accurately...
animTime = animTime % curFrame.duration;

if(curFrameIndex == frames.size())
curFrameIndex = 0;
}
}
But sprites can move to...So we could use xSpeed, ySpeed and update them using:
xPos += xSpeed * (elapsedTime);
yPos += ySpeed * (elapsedTime);
this xPos and yPos could be utilized in render()
drawImage(getCurFrame() ,xPos,yPos);

Now re-run your code again. This time when you add sufficient renderable objects to your game, you’ll notice Overlapping.

i.e., the object added first is drawn first…
how will it seem if the graphics of a tree is being drawn after drawing man??


Forgive me for my crappy drawing…that’s the best I can come up with!
The problem occurs because in run() method of Game.class, we use:
for(int i=0 to numRenderable)
{
arrRenderable.get(i).update(curTime - prevTime);
arrRenderable.get(i).render();
}
avoid this we could modify addRenderableObject as
//image with smallest index is drawn 1st…
addRenderableObject (Renderable rend, int index)
{
arrRenderable.add(rend, index);
}
Now that the drawing order can be determined, overlapping won’t be a problem.

So far we have managed:
- Screen management, ensure min frame rate, a generic Renderable class that can be used with Game class followed by easier Animation handling.

Now imagine that you’re coding the game using THIS framework, suppose the game works on 500 images…you probably will have to load all the images @ startup and show a progress bar like loading or something…Now we’ll integrate this feature into this framework

Lets design a class called ResourceBox, that holds all the images.
public abstract class ResourceBox
{
Private HashMap hm = new HashMap();

//this is where you’ll load all the images…or ne other stuff
Public abstract void init();

Public void add(String id, Image img)
{
hm.put(id, img);
}

//methods such as remove, replace and so on…
//Include a method getImage(String Id)
}
We first create a ResourceBox object as:
ResourceBox rb = new ResourceBox()
{
@Override
Public void init()
{
//Load whatever resources you want…
//Ex – add(“man”, imgMan);
}
}
Remember the Game class…?
How do we register this object with the game class??
Game(ResourceBox rb)
{
//Copy this ref into a private variable within game class
}
This is how the game would run previously:
run()
{
Init();
Game loop
{

}
}
Here we plug in a bit of code:
run()
{
Init();
If(rb != null)
rb.init();
Game loop
{

}
}
Also we’ll add a utility method to game class as:
public ResourceBox getResourceBox();
This method is needed as we could use:
Image man = gameObj.getResourceBox().get(“man”);
Cool eh?

What about the progress bar??
We can’t provide an implementation as it would restrict the user from customizing/ making his own style of progress bar. More-over the user defined Loading screen or whatever must be shown when rb.init() method is called.

We’re gonna try some sort of an event listener kinda thingy. Here goes:

Include a method in ResourceBox.class
public void registerListener(Listener l);

//This is how Listener’s defined
Public class Listener
{
Public abstract void onInit(Graphics g);
}
First of all user’s gotta create an obj of Listener class for which you HAVE TO override the onInit() method
Listener l = new Listener()
{
@Override
Public void onInit(Graphics g)
{
//Draw your stuff on this graphics context…
//Ex = ((Graphics2D)g).do any thing();
}
}
Now we’ll also include a method getRegisteredListener() in ResourceBox.class
We now modify the game class run method as follows:
run()
{
Init();
if(rb != null)
{
Listener l = rb.getRegisteredListener();
If(l != null)
{
// Assuming we have some hypothetical screen management class
Graphics g = ScreenManager.getGraphics();
l.onInit(g);
}
rb.init();
g.dispose();// or clear…
}

Game loop
{

}
}
Now user can show a progress bar or…loading screen with his/her own graphics style…
So here’s a short summary,

- Abstract methods and stuff is absolutely integral in designing a good framework
(Primarily to give user the control of things, just as swing lets us control the shape of a button)

- You might need event listeners in case where your internal handling code needs to call something…like the onInit() we just discussed (swing provides action listeners etc…to a button which are automatically called on mouse click on that component, hope you can associate this with the onInit())

- Let your imagination run wild…experiment, try, you’ll eventually be able to write the top notch code. Okay, enough philosophy I suppose lets move further.

Go back to step 2:

The best way to add new feature(s) to your framework is like I said can be done by imagining the usage. So let’s start with some analysis...how do we integrate sounds? After all any game would suck without sounds…

In my next blog I’ll put up a nice UML diagram of the concepts so far and also discuss sound integration. As always, do comment and help me improve my posts.

Thursday, September 25, 2008

Understanding Frameworks by example...1

You all must have heard about it, .Net, Swing etc.
So what exactly is this ‘framework’?

Simply put, it is a set of properly organized classes and packages with many features to offer.
In case you want to make one, proper planning and design is a must.

lets take the well known ‘swing ‘ in java
To create a frame all we gotta do is:

new JFrame().setVisible();
If I remember correctly, using windows.h in c++ we need to write a 100+ lines of code just to do that. Creating a simple frame involves registering the handleInstance and some other init steps. Moreover its just a simple frame. It we wanted to add a label to it, it’d take another 20-40 lines to do that. In swing its as simple as:
frame.add(new JLabel());
In a sense most of the code is redundant (no one remembers all that init code, they just copy, paste it and modify it at a few places). That’s where a framework is needed. To avoid redundant stuff and provide several layers of abstraction over the inner mess that’s going on.

Also swing manages repaints very cleverly, suppose we have a frame with blue background and a label with green background. Then the background is to be drawn first onto the screen followed by drawing the label. What’s more, it provides a lot of customization which could be achieved by over-ridding a few key methods.

For example to make the button round all you gotta do is over-ride the necessary shaping method that swing calls internally to display a button.

Now if you’re up to it lets try to design a 2D game framework.

Step 1: Identify the requirements


So what could we do to simplify 2D game designing??
Here’s a few that I figured

1) Screen management (change resolution, manage double buffering etc…)
2) Input management (Keyboard polling and mapping)
3) Animations Management (sprite handling)
4) Sound management (sound effect and stuff)

There are many more to it but I’d like to keep it simple

Step 2: Imagine the usage

For a moment let us assume that the framework is designed.
Then how would it help simplifying game programming??

First we’ll discuss a few basics of game programming
This is typically called ‘The game loop’
loop
{
//Update status of the game objects
//Render graphics onto the screen(typically by using double buffering)

//Provide a certain delay…so that the game doesn’t seem to be
//Running like a cheetah
}
As most of you might have already faced, this poses a severe problem...the delay is the villain here. The game runs at different speeds on different processors because of variable instruction execution speed but a fixed delay. To prevent this, we synchronize the events to a global Timer
prevTime = getTimeInNanos();
loop
{
curTime = getTimeInNanos();
//Update status of the game objects using (curTime – prevTime)
//Render graphics onto the screen
prevTime = curTime;
}
getTimeInNanos() returns an arbitrary timer, it can be the bios timer ticks or OS dependent timer. In JAVA one could use System.nanoTime()

And what about pausing and resuming the game??
The threads sleep and notify needs to be handled within the loop itself

Also we should provide a way to handle screen resolution change…
Also to avoid flickering double buffering must be done
Most of this is almost a necessity to be handled and furthermore this stuff is redundant
So we could add all these features into a class, lets call it Game
public abstract class Game extends Thread
{
Public abstract void init();
public void startGame();
public void stopGame();
public void pauseGame();
public void resumeGame();
public void setScreenRes(int width, int height) throws NotSupportedResException
}
init method is supplied as abstract so that user may customize it to his needs. All the Renderable objects (sprites as a few call it) have the update() and render() associated with it. So why not make a class called Renderable as:
public abstract class Renderable
{
//update status calculations here…parameter time is the num of seconds elapsed since
//last call
Public void abstract update(long time);

//all the graphics are to be drawn onto this graphics object…
public void abstract render(Graphics g);
}
Using abstract methods one of the most commonly used techniques in JAVA.
With this you tell the user to over-ride these methods in order to be used…
(Instead of telling them to create a class which HAS TO contain update(long) and render() functions, which would in turn be used for internal purposes)

Then we could do:
game.addRenderableObject(rendObj);
and in the Game class we could use:
private Arraylist arrRenderable;
addRenderableObject(Renderable rend)
{
arrRenderable.add(rend);
}
the run() in Game can be coded to handle thread start,stop,resume,pause and automatically calls all the registered Renderable objects update and render methods…
this is what how run() would look like:
public void run()
{
init();
prevTime = getTimeMillis();

while(!isStopped)
{
curTime = getTimeMillis() - pausedTime;
pausedTime = 0;

for(int i=0 to numItemsRegistered)
{
arrRenderable.get(i).update(curTime - prevTime);
arrRenderable.get(i).render();
}

if(isPaused)
{
pausedTime = getTimeMillis();
while(isPaused)
{
Graphics g = screen.getGraphics();
screen.drawFrameContents(g);
g.dispose();
scr.updateGraphics();
}
pausedTime = getTimeMillis() - pausedTime;
}
prevTime = curTime;
}
}

public void pauseGame()
{
isPaused = true;
}

public void stopGame()
{
isStopped = true;
}
Hope you got the whole picture here…
I suppose that’s enough stuff for now, I’ll add more in my next post. Do comment…