Friday, March 4, 2016

Traverse tree without recursion and using any data structure

I got this problem statement in one of my technical interviews. I didn't find solution to this problem on google. SO I attempted it myself . It was fun solving this problem and I enjoyed it. Here is solution.


#include
#include
#include
typedef struct node
{
  struct node* left;
  struct node* right;
  struct node* parent;
  int data;
}T;
T* head=NULL;
void add_node(int data)
{
  T* t = (T *)malloc(sizeof(T));
  t->left=NULL;t->right=NULL;t->parent=NULL;t->data=data;
  if (head==NULL) {
   head = t;
  } else {
   T* tmp = head;
   while (1) {
   if (data < tmp->data) {
     // should go on left side
     if (tmp->left==NULL) {
       t->parent=tmp;
       tmp->left = t;
       break;
     }
     tmp=tmp->left;
   } else {
     // should go on right side
     if (tmp->right==NULL) {
      t->parent = tmp;
      tmp->right = t;
      break;
     }
     tmp=tmp->right;
   }
   }
  }
}

void myt(T* root) {
  if (root==NULL) {
    return;
  }
 int left_back=0,right_back=0;

 while(1)
 {
   if (root->left==NULL && root->right==NULL) {
     // I am child node . print my data and move to my parent
     printf(" %d",root->data);
     if (root->parent==NULL) {
       // we are THE ROOT . done traverse
       return;
     }
     if (root==(root->parent)->left) {
       // I was left child of parent
       left_back=1; right_back=0;
     } else {
       // I was right child of parent
       right_back=1; left_back=0;
     }
     root=root->parent;
     continue;
   }

   if (left_back==1) {
     // we have come back from left child   . print data
     printf(" %d",root->data);
     if (root->right!=NULL) {
       root=root->right;  left_back=0;right_back=0;
       continue;
     } else {
       // we dont have right child  . we have to back track
       if (root->parent==NULL) {
  // we are THE ROOT. Done traverse
  return;
       }

       if(root==(root->parent)->left) {
   left_back=1;right_back=0;
       } else {
   left_back=0;right_back=1;
       }
       root=root->parent;
       continue;
     }
   }

   if (right_back==1) {
     // we have come back from right node. we have to back track
     if (root->parent==NULL) {
       // we are THE ROOT. Done traverse
       return;
     }
     if(root==(root->parent)->left) {
       left_back=1;right_back=0;
     } else {
       left_back=0;right_back=1;
     }
     root=root->parent;
     continue;
   }

   if(root->left!=NULL) {
      left_back=0;right_back=0;
      root=root->left;
      continue;
   } else {
    // left child is not present. print data and move to right
    printf(" %d",root->data);
    root=root->right;
    left_back=0;right_back=0;
   }

 }
}

void traverse(T* h) {
  if (h==NULL) {return;}
  traverse(h->left);
  printf(" %d",h->data);
  traverse(h->right);
}
void main()
{
  clrscr();
  printf("\n enter elements \n");
  int n;
  while(1) {
    scanf("%d",&n);
    if(n==0) {
      break;
    }
    add_node(n);
  }
  printf("\n Inorder : ");
  traverse(head);
  printf("\nMinorder : ");
  myt(head);
  getch();
}

Tuesday, April 28, 2015

On getting equal

How many times do you come across phrases such as "I have avenged myself. " "I have taught him a lesson he will remember for his life" "My mind would not rest till I show him for what he is worth. " "wait and see how I deliver my blow" "let my turn come?"

Life has many sides . One of those is to live along with others. It is not possible for you or me to cut ourselves off completely and live by ourselves. The stream of existence is composed of tiny driplets such as you and I. All of us are intrinsically one despite our  separate modes of living and mental reservations. A common bond unites each and every individiual. The human race has evolved out of same parentage and the soul occupying our bodies is one single entity.

In our passage through life and whilst engaged in the struggle for livelihood it is but natural to give our and receive blows. The one who can with stand this knocks best is termed as successful men. Ability to avert getting toppled over by set backs must be acquired. Nature by and large has provided each one of us with equal weapons to fight our battles. Whether you keel the edges of these weapons sharper than your neighbour depends on your own resourcefulness and efforts. Those who are constantly on alert are in the position to take better care of themselves. They in other words minimize the chances of being knocked out. The fight is to be faught with every possible means at your command and every part of your body and mind must be geared to play its part in accordance with demands of the occasion.

The desire to get equal is inborn in human nature. The religious teachers may preach that it is against the wishes of a god to endevour to avenge yourself but from the practical point of view no one can deny that there is pleasure and satisfaction to be derived from returning a blow for a blow. My plea however is that whilst you should leave no stone unturned, no way unexplored and no method untried to bring those who have harmed you to suffer for that do no let the passion envelope you so completely that you forget what is good for you , In striking the enemy do not swing the sword so fast that after slashing through him it injures your own leg. It is important that your peace of mind should not suffer in the process. You should be able to keep your head cool and heart stout. A cool head with stout heart and healthy body can not be matched with any power on earth.

From my personal experience our grievences against others are more often than not a mere figment of imagination. They are mostly based on trivialities. I remember an occasion some ten years ago when i felt an afront at acquaitance of mine not offering me a cigarrete 

Friday, April 24, 2015

ANGER

I was angry with my friend
I told my wrath , my wrath did end.
I was angry with my foe,
I told it not, my wrath did grow.

Anger feeds on our thoughts.  The more we think about it , the more it grows in intensity. Its symptoms are easy to perceive -A bloated face, quivering muscles, shaking body, agitated mind, intense atmosphere. Not altogether a happy combination. A person surcharged with a wrathful feeling can be made out from distance. His feasts will be clenched , teeth closed, eyes red, face set and gait wavering. His emotions hold complete sway over him and , at least for the duration of attack his senses bid him good bye.

I am not saying all this to pull your leg. I know this from personal experience. Anger has had lot to do with setbacks I have come across in life; with ruin friendships and bitterness coupled with irritation at home. A number of frustrations I find on reflections could be avoided if I were able to keep my head cool and temper under control. Imagine what unbridled ire can do to piece at home. Husband comes from his place of work. He is tired, fatigued and somewhat irritated at the way fate has treated him. He is not in happy frame of mind. The need of the hour is for him to pull himself up, shake his head and try to smile or say word of cheer to someone. Such an endevour by itself acts as tonic and serves to clear the mind of the poison infecting it. He does not however take cool of wisdom and falls a pray to the easier but extremely harmful course of giving vent to his irrascible temper by picking up a fault or two with the way his wife has arranged things. It starts a chain reaction. The wife who till his arrival was in joyful mood and in fact looking forward to meeting him is unable to swallow the taunts and replies back with equal venom. Such a flare up if continued may end up in a divorce court. Worst still it will do incalcuable harm to health of both, husband and wife. With the fall in health standard irritation becomes a habitual companion and the irate lips keep on emitting smouldering an embers day in and day out.

What is the out come of all this ? The mind becomes restive , the body feeble and senses corroded. WIth this failings it is difficult to progress on the path of prosperity. Friends leave you one by one. Small and insignificant happenings get magnified in your brain and all sense of proportion is gone

Who would like such as thing happen to him ? Surely no one. Yet knowing fully well the evil effects of anger we fail in taking adequate steps to eradicate it from our being. The consciousness may be there all along that it is bad to get incensed at triflings the will to control is missing.

What is needed in the complete change of process of thinking. Thoughts should never be allowed to dwell on others short comings and effects. Rather a deliberate efforts should be made to remember the good turns done to us, the fine and sympathetic sentiments and feelings expressed by people at times and the realisation that we are not the only ones with unsolved problems. Everyone has his own difficulties. IF each one of us start appreciating this point, the burdens we carry on our shoulders and in our heads would be considerably lightened. Be a cheer to others heart and your soul starts jumping with joy. DO not harbour ill thoughts about others and you would avoid ills approaching you. This is natural law which is supreme and unbreakable.

The feeling of anger usually arises more easily when we are discontented with our lot. The best way to overcome this agony is to try to submerge identity in to others, feel happy in others joys and develop a cheerful disposition. We might at first find it extremely hard to practice but if we persist we would definitely succeed.

Let not the sun go down on your wrath.

Failure to heed this advice might cost you nights sleep. Lack of sleep will make you feel miserable the following day. This will adversely affect your business, your carrier , your prosperity and your relations with those near and dear to you. It is therefore in your interests to carefully weigh the thought conveyed by above statement and decide with a cool head wheather or not it will pay you to follow it.
our
Old testament prescribes a wonderful remedy to keep wrath at an arms distance. It says -
A soft answer turneth a way wrath.
Listen to what john cable says in 'The effect of example '

The deeds we do , the words we say into still air they seem to fleat
We count them ever passed;
but they shall last.
In the dread judgement , they and we shall meet.

Points to remember:
1. ANger is not good for your health and work.
2. Sure cure for it is to speak a word of cheer to those near us
3. Anger begets anger
4. No problems can solved at the anchor sheet of anger 

Sunday, April 19, 2015

Water maintains its level why can't you

Water is one of the natures greatest gifts. In fact 2/3 rd of world of ours consists of water. We must learn something from it. WE must regard its characterisic as guide in many respects. It is the one comodity which perhaps is the dearest to nature as well as human soul. Just recall how shower of rain sends through our system vibrations of romance mirth and cheerfulnes. IS there any living being which does not have water in its assemblage ? BEsides water we actually drink we receive considerable quantity of it from food we eat. ALmost all the different articles of food that we consume contain large quantity of water. If we were to add up all different constitutes of the solid food which we eat every day more than 50 % of it would be water. It is not therefor worth emulating

If you follow a great man you would in due course imbibe some of his greatness . Water is not only great in its own rights but its greatness assumes unsurpassing proportions WHen you consider a good it does to life on this earth. It is senior most partner in running the show of the world. In company vocabulary it is the managing director.

Learn the thing or two from it. The most important quality of water is it maintains its level. Do what you may you cannot make it topsy turvy or hang upside down. If small difficulty and minor irritations upset your mental balance how can you rise to the heights reached by water. Try to be impertureble inexcitable in the face of danger . Maintain your coolness and placidity . The moment it cuts across waters disturbing its even surface it gathers up its folds and resumes its former shape. You cannot make it lose its equanimity

Its endurance and forbearance is unimitable. Put a leg in a pool of water and splash it all around. Remove your leg and you will find it as calm as ever. The tiny drops which you separated from its bulk have rejoined the main body.

Stand along a brook and watch it striving its best to reach its destination and become one with the great ocean. It flows incessantly through hills and plains and overcomes all types of obstacles in its progress. Put a rock in its way and see how it goes over it, under it and round it. Man faced with a difficulty may give up but no , not the stream. No obstruction is too much for it. No hindrance can deflect it from its course and no barrier is too strong to bar its flow. If you put a dam across it to hold it, a day comes when it overflows and rushes again towards its goal.

The problem with which you are surrounded are all capable of solution, given the necessary time and effort. Like the brook you have to go over them, under them and round them. Though soft by itself, water, through sheer perseverance , changes the shape of hard substances such as stone. Big rocks in its way ultimately become small pebbles with which it plays and through which it rustles.

  Small stream and brooklets when they unite become the mighty oceans. There is no distinction in ocean waters about the nationality , colour, creed or religion of its various components. Once they become one, you cannot distinguish between one part and other. In union lies strength is the message conveyed to you by the wateres comprising the oceans. These waters have flowed into it from all the four corners of the world, from all the countries, regardless of whether they are inhabited by whites, blacks, grey or brown people. 

EMULATE WATER AND YOU WILL LEARN TO  MAINTAIN POISE, PEACE, COOLNESS, PLACIDITY,PERSEVERANCE AND UNITY.

    Points to remember.
1. Water maintains its level. you should also strive to do so.
2. Difficulties and irritations should leave you unruffled.
3. Main characteristic of water you must emulate are poise, peace, coolness, placidity, perseverance and unity

Worry part 2

Points to remember
1. Worry does not lead you anywhere . ITs like churning water.
2. Despondency and dispair are utterly hollow and negative aspects of our feelings.
3. A busy executive should always try to keep his head above water.
4. Fear of losses acts as brake on bold and courageous actions
5. Do not allow your expenditure to exceed your income
6. Disappointment in life are common occurrence
7. TO worry about social status is unrealistic
8. DO not become hear broken of unfullfillment of love
9. It is your duty to strive to maintain good health both physical and mental.
10. Do not bother about ingratitude, It is ingrained in human nature.


Worry part-1

Worry is state of mind where currents and cross currents of disturbed thoughts keep on ploughing the mind raising in it many fears and apprehensions of difficulties at hand or expected to take place at a later date. Worst still some minds keep on raking up past mistakes and errors without realising that this tantamounts to digging one's own grave.

It is analogous to churning the water. It carries you nowhere. It may be likened to a farmers effort to raise crops out of a dry and barren piece of land. He may dig it to any depth but it will not yeild any result. What is needed is a tubewell which can make the land fertile enough to help plants and vegetation grow. A worrying mind , if it gets a direction and a purpose could by intensity of its desires achieve some useful ends.

Have you ever ridden a cycle? If its peddle chain is missing no amount of peddling will make it run. THe same position applies to a man given to a worries. He spends days and nights in the company of his torturing thoughts. Peddling them around if only he were turn the gloomy forbiddings to well knit ideas and give some coherence to them. He can hope to make progress in tackling the worries that are worrying them . There is story of father and his 3 sons . THe old man was worrying type. He dreamed that his youngest son was drowned in river. THe middle one was crushed under a train and the eldest died in plane accident. Day and night his mind was worried till he became bedridden. Doctors tried every possible means to restore him to health but to no effect. His mind was terribly upset and hallucinations were taking their tolls. DOctors ultimately gave up the treatment and pronounced the case as hopeless.

Life is what we make it. What we give to it will be returned. If we are particular about resisting the temptations which are harmful to us, we will sow good for ourselves. Material prosperity is much easier to obtain with all your tools intact. If your sword is sharp enough and your hands dextrous at handling it , the enemy will think twice before jumping into fray. If it dares do so, you would be much better fitted to make minced meat out of it.

Despite professions to the contrary , ingratitude is an innate quality of the human mind. A piece of wood in chimney on cold night provides you warmth but in the process burns itself to ashes. Nobody gives it second thought. It is replaced as soon as burnt out. Our mind tends to magnify the good we do but minimize the benefactions we receive, Like rain water sleeping of the umbrella top, it soon forgets the favours bestowed upon us by our well wishers. Why then worry about ingratitude. What others do to us we do to them. It is quits. If someone has been ungrateful for our sacrifices for him , may be we have behaved similarly towards those who have contributed to our well being . Our feelings for others can be compared to a lessons written by a teacher on the blackboard in his class, As soon as it has served his purpose it is wiped out and replaced by a new lesson.

Man is essentially a selfish animal. The instinct of selfishness is the strongest in a child By education and constant sermons his attitude undergoes some modifications as he grows up. Ingratitude is related to this instinct. Where there is a clash between self interest and gratitude the human mind has a tendency to lean to the former.

Old man and women are prone to develop an ache in their heart and feeling of destitution in their minds at their children not returning their love and being grateful for what they did for them, THey should realise that human beings are by nature born with and impulse to look forward and not backward. They would gladly do anything which would make their future secure. But if one expects them to remember and reciprocate what he did to them years ago, he is looking for disappointment. My advice to aged is to keep the purse strings in their hand wherever they possibly can. Those inclined to hand over everything to their children when retired , in the belief that it does not make any difference whether the control is in their or their childrens hand might live to rue their mistake. Not that all children would be inclined to place thier interests above their parents but possibility is always there.


How to Start the working day.

1. Work hard- Tackle the hardest job first
2. Study hard- The more you know the easier and more effective is your work
3. Take the initiative- RUts often deepen into the graves
4. Adore your work- Work well done brings peace to your mind and pleasure to your soul.
5. BE to the point- Haste makes waste and hurry may lead to worry
6. BE courageous and bold- Stoutness of heart with tranquality of mind can make minces meat of all troubles and difficulties.
7. Be cooperative and friendly.
8. Friendlyness is issential for leadership
9. Wear a smile. It will open the door into the sun shine beyond.
10. Develop a transparent and magnetic personality. Personality is to a man what perfume is to a flower.
11. Do your best - IF you give to the world best you have, best will come back to you.
12. BE good to others- that is the key to happiness
13. Never unnecessarrily injure any other mans feelings
14. Keep in mind your responsibilities towards your parents children and wife.
15. Give up obsession with sex.

DAY HAS BEGIN

THE DAY IS BORN

If you have had a good night 's sleep , you are likely to wake up refreshed. Assuming, you have no special worries befogging your mind, sound sleep should engender a feeling of cheerfulness.
Like a flower bud opening with first ray of sun, your face should light up with smile. Today is your luckiest day. You would undoubtefly be able to perform your duties with utmost efficiency and skill. you are the best person in the world for the job confronting you. The problem which will arise in the execution of your responsibilities are no match for you intelligence , wit , energy and mental sharpness. No man is yet born who can deflect you from your purpose. No difficulty has yet been known which you cannot surmount.
The chirping of birds, the sound of the milkmans foot steps and the vibrations of the early morning atmosphere have heralded the day for you,. May it be the day when you will not fail to contribute your mite to your own good, the good of your country and humanity generally. Before nightfall the appointed task will be performed satisfactorily.

Despair and defeat are feelings alien to you. Despondency and hopelessness have no place in your thoughts. Dejection and pessimism are mean adversaries for nobility and bravery of your spirit. Resoluteness is your watchword, gallantry your beacon light and tenacity your guiding principle. Achievement is for those who wish to achieve , success is for those who are detemined to succeed, happiness is for those who resolve to be happy.

All the good traits are found in abundance in you. Why then be afraid of anything. Fear is a feeling reserved for cowards and shirkers , not for those who have the ability to brave the storms , to cross rough seas and scale the highest mountains.
Like a cheerful bird, you are destined to soar high and touch the sky.

Happy the man and Happy he alone, He who can call today his own,
He who secure within can say , Tomorrow do thy worst for I have lived today.

A THOUGHT FOR TODAY,

Thank God every morning when you get up that you have something to do that day which must be done whether you like it or not. Being forced to work and forced to do your best, will breed in you temperance and self control diligence and strength of will, cheerfulness and content and hundred virtues which the idle will never know. 

Friday, April 17, 2015

How to conquer part 1

That man is the happiest who enjoys others happiness for in this way he can partake in the pleasures and merry making of all persons on this earth . Could there be greater reward? Can you conceive of any other wish greater than this All the fun of all the living beings on this world can yours by merely a readjustment of the working of your brain. Alas how few of us realise this basica truth . It may be dined into ears day in and day out yet it does not find a permanent place in the minds of many,.
We try to drown our worries in alcohol or over a game of cards. These may provide temporary palliatives but the need of hour is a permanent solution. If the water in the kettle is boiling and you want to cool it down the first thing you should do is switch off stove. You can not cool it by taking a bagfull of ice and pour it on kettle. It may have temporary effect on kettle but burning fire will assert itself. The difficulties and problems facing us can overcome only by looking them straight in eye and devising methods to go over , under or around them .There is no other solution. you cannot cut a piece of wood with your hands. It requires use of saw. The means you adopt to cut through your mental torture should be proper and effective.
What the eyes see and senses convey to the  mind may be true or untrue, Often what we perceive is not real. It is only by reasoning that we can arrive at the basic truth. What lies hidden behind the rusty piece of metal sheet is anybody's guess. It may be prime tin or a patched up affair. The man who has developed his instincts to distinguish between real and unreal saves himself quite a few headaches,.

Rashness is akin to jumping into deep waters without an adequate knowledge of swimming, We should be careful to avoid being hustled. Undue hurry ay lead to worry. It is no use getting wise after event. Steps should be taken if possible to ensure that an eventuality does not occur which may be harmful to us. Careful deliberation is required to negotiate steep bends and curves in our path. If we just push ourselves along without much thought for security, we may fall into the abyss below.
  Fear and indecision to us are like corrosion to metalks. By giving way to these our vitals are affects . If you put ropes round a person and then ask him to run he would not be able to do so. Unless the mind is freee of inhibitions and artificial restraints it would not act with spees, determintion and agility,. You can not make mind captive to harmful ideas and yet expect best out of it. Captivity has a n adverse effect on the instincts for initiative and boldness.

Perseverance is sine quo none for achievement . THe more strings you put into the rope , the stronger it becomes, A well is never dug by single blow,. Nor can you reach the peak of mountain by a single jump. One has to climb on ladder step by step. To reach the fifth floor of building you have to pass through the first four. He who can continues the effort undaunted by initial hurdles has every possibility of reaching the goal.

Those who are constantly aware of the shortness of this life and the fact that everything has ultimately to come to and end have a much better frame of mind to ensure the troubles that often crop up. Time is great healer. Let it exert its healthy influence.

Like the dew on the mountain,  Like the foam on the river.  Like the bubble on the fountains , Thou art gone and for ever.    Walter scott.

We all strive for happiness . In our mistaken belief, we think it is to be found in wealth and riches, This is an anomaly, It is mirage. Real happiness generally has very little or no connection with material posessions. Shelly said correctly when stated.
You seek for happiness alas the day,
you find it not in luxury , nor in gold,
Nor in the fame nor in the invalid sway,
For which O willing slaves to customs old,
Severe taskmistress! Ye yours hearts are sold.

It all depends on the way you look at things . One person may take the loss of his wife seriously and pass the rest of his life dreaming about her sweet memories. Another may find it riddance. Our mind can draw out any picture you ask to. It is like a mirror which will reflect the object in front of it.

Greatness has its disadvantages too. It brings along with it many burdens and responsibilities.

How dreary to be somebody,
How public like a frog,
To tell your name the livelong day,
To an admiring bog!  Emily dickinson

To be really great, we must emulate nature. It takes pleasure in giving and does not look forward to returns. Yet It has devised a system whereby everything returns to its original position. Clouds lift the water our of mighty oceans and pour it down on mother earth, After helping the earth in sustaining animate and inanimate beings it returns to its origin. The cycle continues indefinitely.

Man's cycle of birth and death is same. One gets born and after acting his part on worlds stage dissolves into the same elements that went into his making,

This little life we all must endure,
The graves most holy peace is ever sure,
WE fail asleep and never wake again,
nothing is of us but the mouldering flesh,
Whose elements dissolve and merge afresh,
In earth air water plants and other men.
James thomas

Sunday, November 23, 2014

samarthchi shikavan

दहा वर्षे बालपण वीस वर्ष तारुण्य !

अंगी चढता मदन मग कैसा नारायण !

सावध सावधान वाचे बोला नारायण !

तीसाशी होय भरती दारा पुत्र लागे प्रिती !

मायेशी पडे भ्रांती मग कैसी ईश्वरप्राप्ती !

चाळीस वर्षे झाली डोळा चालीसी आली !

नेत्रासी भुली पडली कोणी ना दिसे जवळी!

पन्नास वर्षे होती हालती दात पंगती !

काळ्याचे ढवळे होती त्यासी म्हातारा म्हणती !

साठीची बुद्धी नाठी वसवस लागे पाठी !

हाती घेउनिया काठी त्यासी हासतात कार्टी !

सत्तारसी होय रचना हालवेना चालवेना !

उठवेना बसवेना मग तो दिसे दैनवाना !

चाराविसा मिळोनी ऐसी मग तो झाला अपैशी !

जाळा विना जैसी माशी तैसे झाले प्राण्याशी !

वर्षे होता नव्वद बोलवेना एकही शब्द !

दारा पुत्र म्हणती देवा तोडी याचा संबंध !

शत वर्षे पुरुष झाला आला तैसाची गेला !

रामदासी याची बोला वेगा सावध झाला !

Monday, April 7, 2014


खरा तो एकची धर्म जगाला प्रेम अर्पावे
जगी जे हीन अतिपतित, जगी जे दीन पददलित
तया जाऊन उठवावे, जगाला प्रेम अर्पावे
जयांना ना कोणी जगती सदा ते अंतरी रडती
तया जाऊन सुखवावे, जगाला प्रेम अर्पावे
समस्तां धीर तो द्यावा, सुखाचा शब्द बोलावा
अनाथा साह्य ते द्यावे, जगाला प्रेम अर्पावे
सदा जे आर्त अतिविकल, जयांना गांजती सकल
तया जाऊन हसवावे, जगाला प्रेम अर्पावे
कुणा ना व्यर्थ शिणवावे, कुणा ना व्यर्थ हिणवावे
समस्तां बंधु मानावे, जगाला प्रेम अर्पावे
प्रभूची लेकरे सारी तयाला सर्वही प्यारी
कुणा ना तुच्छ लेखावे, जगाला प्रेम अर्पावे
असे जे आपणापाशी असे, जे वित्त वा विद्या
सदा ते देतची जावे, जगाला प्रेम अर्पावे
भरावा मोद विश्वात असावे सौख्य जगतात
सदा हे ध्येय पूजावे, जगाला प्रेम अर्पावे
असे हे सार धर्माचे असे हे सार सत्याचे
परार्थी प्राणही द्यावे, जगाला प्रेम अर्पावे
जयाला धर्म तो प्यारा, जयाला देव तो प्यारा
त्याने प्रेममय व्हावे, जगाला प्रेम अर्पावे

Tuesday, October 8, 2013

Sense of satisfaction

I often conduct lectures for Gate coaching in some institutes . I started this as hobby and now finding myself pursuing it as second carrier/profession .

When I was in school I was always forced to sit in last row(because I was among taller students in class and If I sit anywhere in between it would block the view for boy sitting behind me). Anyway I enjoyed sitting in last row. There is always masti on last bench. People would eat their tiffin while lecture is going on. Would pass some comments or do something which would irritate class teacher.
Since I was sitting in last row all the time in my school days, I was friend with students who were not very good in studies. And I being good in it, they would always take my help in completing assignments, solving question etc. We would often study in groups and I would spend lot of time explaining them concepts. With this I learned to teach and help students. I never knew at that time , that this would be my profession some day. Today I am happy that I am getting to teach / guide students in their studies. It gives sense of satisfaction which our professional job may not give.

SO On one sunday I was conducting Networking class and During break I was just checking out notice boards of Gateforum and found some feedback notes of some previous year students and in one of them I found my name. I felt so good to read that. I even took snap of it to show it to my mother.:-)

Such appreciation notes are worth much more than money. Something money can't buy.

thanks to All students who appreciate the work.
 

Friday, August 23, 2013

Shaders in OpenGL

Hello All, (this is only for techie guys)
I have started delving into So called shaders in openGL. When I learned about it for the first time, I was overwhelmed and at the same time unsure about the use of it . Shaders are small program which takes care of drawing your scene pixel by pixel. Similar to the way we did it back when we were in college. Thought that was very primitive in 16 bit graphics. THis is more advanced but any way you get the point. So shaders are program which remove Fixed pipeline used by opengl to render and Instead gives us control to determine how to shade objects.

Though this seems ardent task , its really not that hard and we can get away with some simple shading pretty easily. Even you can simple download shader programs for fixed pipeline used by opengl and make your ammendments to it.

Anyway Back to topic. Clearly its useful to make use of shaders than relying on opengl fixed pipeline to draw your objects. So what do we do ? Learn it.

There are 2 types of shaders.
1. Vertex shader
2. Fragment shader.

vertex shader is called for every glVertex3f call that we make.
and fragment shader program is called for every pixel that opengl tries to render on the screen . Before we used to set color, texture , lighting properties and let the opengl interpolate and do the calculation of determining color for the individual pixel that its wants to render. But now that control is in our hand.

With this control we can play around with normals and make use of normal map more efficiently. This lets us render more complicated shapes with less complicated geometry. Isn't it cool feature.
Indeed it is. SO have fun. Search for more on this topic. Try some simple programs and make use of best of GPU computation.

Happy coding. Bye for now :-)

Lighting in OpenGL

My new work demanded me to have knowledge of lighting in openGL. I set forth for it. I understood that there are mainly 3 types of lighting sources used while rendering any graphics scene.
They are
1.Ambient lightsource (This is coming from all directions equally)
2.Directional light source (This one is fixed in space and as we move object / view it moves along. It shines fixed portion of the object all the time.)
3.Observer light source  (This one is coming from the direction of viewer. So no matter how y twiddle the object its always going to light the portion facing you).

SO I played around all 3. I used directional light source and changed its position by rotation the source angle in each iteration and rendered the screen. It gives nice effect. Here I am attaching snapshot of it.

Saturday, August 10, 2013

English Vinglish 2

This happened when I was studying in Diploma College. I would take tiffin box(ghar ka khana) with me. One day I was sitting on Katta and for some reason it was only me and Mukram(my friend) was not having any practical and were free during lunch time. I was hungry so I tool out my tiffin box and started eating. Mukram was sitting idle. I thought he didn't bring his tiffin today so i asked him to join me. He said "I have fast". At that time only meaning of "fast" i knew was in context of speed. :-) So I didn't hear him properly and I thought he wanted to say that he eats fast so will join me later. I already finished my tiffin half way. I again asked him please join. he again repeated same thing. this Time I said to him.. " no problem , even I eat fast! " :D :D
He was puzzled with my statement. this time he said in hindi. "mera upvas hai" then it clicked me "oh. ok upvas. Good".

that incident added one more word to my vocabulary.

Friday, August 9, 2013

English-Vinglish 1

Its funny how you remember some incidents in your life. This one is quite old during my Diploma College. I was studying in Pimpri Chinchwad Polytechnic. Coming from bit rural background and marathi medium I was not very good at English. In this regard all my friends were much better than me. They were all from english medium. So they knew english words much better than me.

At that time I didn't know the meaning of word ASS. Though there are multiple meanings to this particular word we all know which one is famous. Still at that time, i was unaware of this famous meaning and hence when our teacher gave us list of assignments to be done in Diwali vacation, with my heroics I did all of them plus the ones which Mam was not expecting before time. The only problem with my work was I named all my assignment programs with naming convention as "Ass1.c" "ass2.c" "ass3.c"  ... and so on "assn.c"

When We came back from vacation, I think I was the one bragging with all assignments done . I went to Mam and told her that I have done all assignments. Firstly, she couldn't believe. Then I asked her to check it on computer. My couple of friends were with me. She said fine, and I copied assignment programs from Floppy. I started showing her one by one.
"this is ass1.c"
"should I open ass2.c?"
"lets see ass3.c"

When I started with that I observed that Mam's face was turning pale and she was embarrassed. I didn't know why. So do my friends. She said fine. She is happy with work. and you can leave.

Its only when one sardarji from my class saw those assignment names and found something odd about it . He said, "I think you should know meaning of word before you start using it. Do you the meaning of this ?" pointing to assignment name. I said "No". He said check it. :-)

When we came to know the real meaning of that word, we couldn't stop laughing. as we knew why mam's face turned blue on seeing those assignments.

Anyway that incident added this nice word to our vocabulary . these days i hear this a lot when I watch english movies. I really think English movies should be bit more sophisticated.Too much F words and A words.



Monday, July 11, 2011

Dijkstra Algorithm

Here is the program of Dijkstra algorithm done in Tubo C++



 // Program to find the shortest path to all the nodes

// From the given SOURCE NODE.

// Using DIJKSTRA ALGORITHM.

#include<stdio.h>

#include<conio.h>

int main()

{

int path[10][10]={0}; // this matrix will store the shortes path to all notes

int edge[10][10]={0}; // this matrix will hold the weights of edges in a graph

int distance[10]={0}; // this matrix will hold the shortest distance to all

// nodes from the given source node

int visited[10]={0}; // this matrix will holds the status of visited nodes in the algorithm

int a=1;

int n,i,j;

clrscr();

printf("Enter number of nodes:");

scanf("%d",&n);

// Initialise Path matrix

for(i=0;i<n;i++) {

path[i][0]=999;

}

printf("Enter the adjacency matrix:\n \n");

// Get the adjacency matrix Input

for(i=1;i<n;i++)

{

for(j=0;j<i;j++)

{

printf(" Distance from %c to %c ",65+i,65+j);

scanf("%d",&edge[i][j]);

edge[j][i]=edge[i][j];

}

}

// Print the adjacency table

printf("\n Adjacency matrix\n");

for(i=0;i<n;i++) {

for(j=0;j<n;j++) {

printf(" %d\t",edge[i][j]);

}

printf("\n");

}

// Get the source and destination node

fflush(stdin);

char source,dest;

printf("Enter the source:");

scanf("%c",&source);

fflush(stdin);

printf("Enter the destination:");

scanf("%c",&dest);

int from=source-65;

int to=dest-65;

printf("\n Source : %d destination:%d\n",from,to);

// Initialise the distance table

// Set the distance to very hight value(in algo infinity)

// except the from node

for(i=0;i<n;i++) {

if(i!=from) {

distance[i]=1000;

}else {

distance[i]=0;

}

}

//////////////////////////////////////////////////////

// DIJKSTRA ALGORITHM

/////////////////////////////////////////////////////

int k;

for(k=0;k<n;k++) {

// Search the node which is closest to the source node

int short_index=0;

int found=0;

int short_value=1000;

for(i=0;i<n;i++)

{

if(visited[i]==0)

{

// Node is not visited

if(distance[i]<short_value) {

short_index=i;

short_value=distance[i];

found=1;

}

}

}

printf("\n visited : %c",65+short_index);

// Mark the node visited

visited[short_index]=1;

// printf("\n\n distance table :");

// print the distance table

// for(i=0;i<n;i++) {

// printf(" %c: %d\t",65+i,distance[i]);

// }

// Update the distance table

// Check if the current distance is larger than the distance

// via shorted node and if YES update the distance table

// and add the node to the shortes path

int p;

for(p=0;p<n;p++)

{

int via_short = distance[short_index]+edge[short_index][p];

if(distance[p]>via_short) {

distance[p]= via_short;

// Add the current node in the path

int h=0;

while(path[p][h]!=999) {

h++;

}

path[p][h]=short_index;

path[p][h+1]=999;

}

}

}

printf("\n\n FINAL TABLE \n");

// print the distance table

for(i=0;i<n;i++) {

printf(" %c: %d\t",65+i,distance[i]);

}

// Print shorted paths to all nodes

printf("\n\n SHORTEST PATHS TO ALL NODES from source node :\n");

for(i=0;i<n;i++) {

int h=0;

printf(" %c :",65+i);

while(path[i][h]!=999) {

printf("%c->",65+path[i][h]);

h++;

}

printf("%c\n",i+65);

}

getch();

return 0;

}

Tuesday, May 24, 2011

CAR Game part-1




Hi,
Here I come with yet another game.
This one came out rather too quickly as I had most of the functions already written and tested. :-) This is the game which i used to play in the video parlour, that was fun back then. well, Now there is fun in developing it.






#include "stdafx.h"

#include <iostream>
#include <stdlib.h>

#include <GL/glut.h>

#include "imageloader.h"
#include "math.h"

using namespace std;

const int MAX_X=1200;
const int MAX_Y=900;
const int MIN_X=0;
const int MIN_Y=0;

int car_x = MAX_X/4;
int car_y = MAX_Y;


int car_width=100;
int car_length=200;
int rx = MAX_X/4;
int ry = MAX_Y;
int road_width = 420;
int path_width = 20;
int lane_distance = car_width+40;
int car_max_x = (car_x+path_width) + lane_distance;
int car_min_x = MAX_X/4;

int car_cnt = 1;
GLuint _textureId; //The id of the texture
GLuint _textureId1; //The id of the texture
GLuint _textureId2; //The id of the texture
GLuint _textureId3; //The id of the texture

GLuint current_textureId; //The id of the texture

int timedelay = 100;
void draw_car(int length,int width,int x, int y);

int move_cnt=0;

typedef struct vehicle {
int x,y;
int length,width;
int texture_id;
struct vehicle* next;
}VEHICLE;

VEHICLE *head=NULL;
int current_y=0;

void create_vehicles() {
int rand_x = 0;

if(current_y>car_length) {
current_y = -200;
} else {
return;
}
// Create a new vehicle;
VEHICLE* temp = new VEHICLE;
temp->length = car_length;
temp->width = car_width;
temp->next = NULL;
temp->x = car_x+path_width;
temp->y = current_y;
if(car_cnt==1) {
temp->texture_id = _textureId1;
} else if(car_cnt==2) {
temp->texture_id = _textureId2;
} else if(car_cnt==3) {
temp->texture_id = _textureId3;
}

car_cnt++;
if(car_cnt==4) car_cnt = 1;

// Add it to the list
if(!head) {
head = temp;
} else {
VEHICLE* t = head;
while(t->next) {
t = t->next;
}
t->next = temp;
}
}

void draw_vehicles() {

VEHICLE* temp = head;
while(temp) {

int car_width = temp->width;
int car_length = temp->length;
int car_x = temp->x;
int car_y = temp->y;
current_textureId = temp->texture_id;
draw_car(car_width,car_length,car_x,car_y);

temp = temp->next;
}
}

void move_vehicles() {
VEHICLE* temp = head;
while(temp) {
temp->y = temp->y+10;
temp = temp->next;
}
current_y+=10;
}
void drawScene();

void *font = GLUT_BITMAP_TIMES_ROMAN_24;
void *fonts[] =
{
GLUT_BITMAP_9_BY_15,
GLUT_BITMAP_TIMES_ROMAN_10,
GLUT_BITMAP_TIMES_ROMAN_24
};


void specialKey(int key, int x, int y) {
switch (key) {
case 101: //UP arrow key
if(timedelay>0){
timedelay-=10;
}

break;
case 103: //DOWN arrow key
if(timedelay<500){
timedelay+=10;
}
break;

case 100: //LEFT arrow key
if(car_x>MAX_X/4){
car_x-=car_width;
}
break;

case 102: //RIGHT arrow key
if(car_x<(MAX_X/4-car_width+400)){
car_x+=car_width;
}
break;

}
}

void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);
}
}

void output(int x, int y, char *string)
{
int len, i;

glRasterPos2f(x, y);
len = (int) strlen(string);
for (i = 0; i < len; i++) {
glutBitmapCharacter(font, string[i]);
}
}

//Makes the image into a texture, and returns the id of the texture
GLuint loadTexture(Image* image) {
GLuint textureId;
glGenTextures(1, &textureId); //Make room for our texture
glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
//Map the image to the texture
glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D
0, //0 for now
GL_RGB, //Format OpenGL uses for image
image->width, image->height, //Width and height
0, //The border of the image
GL_RGB, //GL_RGB, because pixels are stored in RGB format
GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
//as unsigned numbers
image->pixels); //The actual pixel data
return textureId; //Returns the id of the texture
}



void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LINE_STIPPLE);
glLineWidth(4);
Image* image = loadBMP("car3.bmp");
_textureId = loadTexture(image);
delete image;

image = loadBMP("car4.bmp");
_textureId1 = loadTexture(image);
delete image;

image = loadBMP("car5.bmp");
_textureId2 = loadTexture(image);
delete image;

image = loadBMP("car6.bmp");
_textureId3 = loadTexture(image);
delete image;

}

void handleResize(int w, int h) {
/*glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)w / (float)h, 1.0, 200.0);*/

glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, h, 0);
glMatrixMode(GL_MODELVIEW);
}

void draw_lanes() {

glLineStipple(1,0x00ff);
glBegin(GL_LINES);

for(int i=1; i<=3;i++) {
glVertex3f(rx+path_width+car_width*i, MAX_Y, 0);
glVertex3f(rx+path_width+car_width*i, 0, 0);
}

glEnd();

glLineStipple(1,0xffff);
}

void draw_footpath(int x,int y,int path_width) {
int cnt=25;
int bwidth = path_width-2;
int bheight = 40;
int yy=y;
int xx=x+2;

// Blocks on the foot path
for(int i=0; i<cnt; i++) {
glBegin(GL_POLYGON);
glVertex3f(xx,yy,0);
glVertex3f(xx+bwidth,yy,0);
glVertex3f(xx+bwidth,yy+bheight,0);
glVertex3f(xx,yy+bheight,0);
glEnd();
yy+=2*bheight;
}
}

void create_road() {

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

ry = MAX_Y;
// Lines on the side
glBegin(GL_LINES);
glVertex3f(rx, ry, 0);
glVertex3f(rx, 0, 0);
glVertex3f(rx+path_width, ry, 0);
glVertex3f(rx+path_width, 0, 0);

glVertex3f(rx+road_width, ry, 0);
glVertex3f(rx+road_width, 0, 0);
glVertex3f(rx+path_width+road_width, ry, 0);
glVertex3f(rx+path_width+road_width, 0, 0);

glEnd();

ry=-200;
move_cnt ++;
if (move_cnt==8) {
move_cnt = 0;
}
ry = ry + 10*move_cnt;

// Draw footpath on both the sides of the road
draw_footpath(rx,ry,path_width);
draw_footpath(rx+road_width,ry,path_width);

// Draw the lanes in the road
draw_lanes();

}

void draw_car(int length,int width,int x, int y) {

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, current_textureId);

//Bottom
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glColor3f(0.0f, 0.1f, 0.1f);

glBegin(GL_QUADS);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(x, y, 0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(x+length,y,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(x+length,y-width,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(x,y-width,0);

glEnd();

glBindTexture(GL_TEXTURE_2D,0);
}

void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

GLfloat ambientLight[] = {0.2f, 0.2f, 0.2f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);

GLfloat directedLight[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLfloat directedLightPos[] = {-10.0f, 15.0f, 20.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, directedLight);
glLightfv(GL_LIGHT0, GL_POSITION, directedLightPos);

// Show the X and Y coordinate location of the mouse
glClear(GL_COLOR_BUFFER_BIT);

// Draw the main racing
current_textureId = _textureId;
draw_car(car_width,car_length,car_x+path_width,car_y);

// Create a road
create_road();

// Create new vehicle
create_vehicles();

// Move vehicles
move_vehicles();

// Draw the vehicles
draw_vehicles();

glutSwapBuffers();
}

//Called every 25 milliseconds
void update(int value) {

drawScene();

glutPostRedisplay();
glutTimerFunc(timedelay, update, 0);
}

int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(MAX_X, MAX_Y);

glutCreateWindow("Car Game");
initRendering();

glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutSpecialFunc(specialKey);

glutReshapeFunc(handleResize);
glutTimerFunc(timedelay , update, 0);

glutMainLoop();
return 0;
}


Monday, May 23, 2011

Bouncing Ball

Hi, I was having trouble with my half accomplished game. The problem was that I couldnt increase the speed of the moving ball. Even if I put absolutely no timer then also ball was moving with very less speed. I asked my friends on the lunch table and they gave me the solution that I should be increasing the step count OR i should always draw the ball in the origin space and translate it. SO I tried BOTH :-) Increasing step count did help and it doesn't look bad. I was expecting that I will get a little discrete moves but that didnt happen. I still get enough smooth output. Now I went for divide and conquer apporach and decided to get the ball properly rolling first. :-) So here is my program which will show the ball bouncing on the edges of the windows. User can resize the window. He can increase and decrease the speed of moving ball by using the UP and DOWN arrow keys. thanks :-)
#include "stdafx.h"

#include <iostream>
#include <stdlib.h>

#include <GL/glut.h>

#include "math.h"

using namespace std;

int MAX_X=1200;
int MAX_Y=900;
const int MIN_X=0;
const int MIN_Y=0;
int m_x=0;
int m_y=0;

int ball_x=500;
int ball_y=500;
int radius = 30;
int poly_circle[20][2];
int circle_segments = 0;


// BY default ball will go up
int x_dir = 1;
int y_dir = -1;
int base_y;
int base_x;
float move_mag = 5.0;

void init_circle() {
int x1=0;
int y1=0;
int cnt=0;
float angle = 0;
float x2,y2;
for (angle = 0; angle < 360; angle+=25.0,cnt++) {
float rad_angle = angle * 3.14 / 180;
x2 = x1+radius * sin((double)rad_angle);
y2 = y1+radius * cos((double)rad_angle);
poly_circle[cnt][0] = x2;
poly_circle[cnt][1] = y2;
}
poly_circle[cnt][0]=poly_circle[0][0];
poly_circle[cnt][1]=poly_circle[0][1];
circle_segments = cnt;
}



void drawScene();

void move_ball() {
ball_x = ball_x + (move_mag*x_dir);
ball_y = ball_y + (move_mag*y_dir);
}

void change_y_dir() {
y_dir = -y_dir;
}
void change_x_dir() {
x_dir = -x_dir;
}
void change_both_dir() {
change_y_dir();
change_x_dir();
}

int crossed_x_limits() {
if((ball_x-radius)<=MIN_X) {
return 1;
}
if((ball_x+radius)>=MAX_X) {
return 1;
}
return 0;
}


int crossed_y_limits() {
if(ball_y-radius<=MIN_Y) {
return 1;
}
if(ball_y+radius>=MAX_Y) {
return 1;
}
return 0;
}


// the mouse callback function:
void mouse_move(int x, int y)
{
m_x = x;
m_y = y;

drawScene();
}


void handleResize(int w, int h) {

glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
MAX_X = w;
MAX_Y = h;
gluOrtho2D(0, w, h, 0);
glMatrixMode(GL_MODELVIEW);
}


void drawCircle(float radius, float x1, float y1)
{
float angle = 0;
float x2,y2,cx,cy,fx,fy;
int cache = 0;

glPushMatrix();//(NEW) Create a new matrix
glTranslatef(x1,y1,0);//(NEW) Rotate the triangle on z axis based on how much time has passed

glBegin(GL_LINES);
for(int i=0; i<circle_segments;++i) {
glVertex2f(poly_circle[i][0],poly_circle[i][1]);
glVertex2f(poly_circle[i+1][0],poly_circle[i+1][1]);
}
glEnd();

glPopMatrix();//(NEW) stops current transformations to the matrix
}

void play_ball() {
move_ball();

if (crossed_x_limits()) {
change_x_dir();
} else if (crossed_y_limits()) {
change_y_dir();
} else {
// Do nothing
}
}

void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glLineWidth(4);
// Draw the ball
play_ball();
drawCircle(radius,ball_x,ball_y);

glutSwapBuffers();
}

//Called every 25 milliseconds
void update(int value) {

drawScene();

glutPostRedisplay();
glutTimerFunc(25, update, 0);
}

void idle_func(void) {
drawScene();
}

void initRendering() {
glEnable(GL_DEPTH_TEST);

}

void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);

}
}

void specialKey(int key, int x, int y) {
switch (key) {
case 101: //UP arrow key
if (move_mag<radius-1) {
move_mag+=0.5;
}
break;
case 103: //DOWN arrow key
if (move_mag>1) {
move_mag-=0.5;
}
break;
}
}


int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(MAX_X, MAX_Y);

glutCreateWindow("Bouncing Ball");
initRendering();
init_circle();

glutDisplayFunc(drawScene);
glutSpecialFunc(specialKey);
glutReshapeFunc(handleResize);
glutMotionFunc(mouse_move);
glutPassiveMotionFunc(mouse_move);
glutTimerFunc(25 , update, 0);
//glutIdleFunc(idle_func);

glutMainLoop();
return 0;
}

Sunday, May 22, 2011

Brick Game part1

Hi, Here I am uploading game which i developed in openGL (motive was to kill the time on boring friday) This is very novice and still in the early in its life. This is work of just 4-5 hours. I wasted some of time just to figure out that the Image which I used for texture mapping needs to be of size 256X256 or some multiple of it. It's only after Kapil(one of my colleague) came for my rescue and we figured out the flaw. thanks Kapil! :) Once I could draw the wall of bricks i developed the logic on weekend and implemented it as first thing on monday morning. All I can say is it works! :) it can be made more efficient and more cool but I will leave that for some other day. You can download the code and make your own amendments to it. Its all free. thanks. :)


#include <iostream>
#include <stdlib.h>

#include <GL/glut.h>

#include "imageloader.h"
#include "math.h"

using namespace std;

const int MAX_X=1200;
const int MAX_Y=900;
const int MIN_X=0;
const int MIN_Y=0;
int m_x=0;
int m_y=0;
int brick_length=100,brick_width=30;

int ball_x=500;
int ball_y=500;
int radius = 20;

// BY default ball will go up
int x_dir = 1;
int y_dir = -1;
int base_y;
int base_x;
float move_mag = 5.0;

typedef struct brick {
int x;
int y;
int visible;
}BRICK;

BRICK BR[10][10];

void drawScene();

void *font = GLUT_BITMAP_TIMES_ROMAN_24;
void *fonts[] =
{
GLUT_BITMAP_9_BY_15,
GLUT_BITMAP_TIMES_ROMAN_10,
GLUT_BITMAP_TIMES_ROMAN_24
};

void init_bricks() {

// Initialise the bricks
int x=100,y=50;

for(int row=0;row<10;row++) {
for(int column=0;column<10;column++) {
BRICK temp;
temp.visible = 1;
temp.x = (brick_length*column)+x;
temp.y = (brick_width*row)+y;
BR[row][column] = temp;
}
}

}

void move_ball() {
ball_x = ball_x + (move_mag*x_dir);
ball_y = ball_y + (move_mag*y_dir);
}

void change_y_dir() {
y_dir = -y_dir;
}
void change_x_dir() {
x_dir = -x_dir;
}
void change_both_dir() {
change_y_dir();
change_x_dir();
}

int crossed_x_limits() {
if((ball_x-radius)<=MIN_X) {
ball_x = MIN_X+radius;
return 1;
}
if((ball_x+radius)>=MAX_X) {
ball_x = MAX_X-radius;
return 1;
}
return 0;
}


int crossed_y_limits() {
if(ball_y-radius<=MIN_Y) {
ball_y = MIN_Y+radius;
return 1;
}
if(ball_y+radius>=MAX_Y) {
ball_y = MAX_Y-radius;
return 1;
}
return 0;
}
int hit_base() {

if (ball_x>=m_x-brick_length && ball_x<=m_x+brick_length) {
if((ball_y+radius)<=MAX_Y && (ball_y+radius)>=(MAX_Y-brick_width)) {
return 1;
}
}

return 0;
}


// the mouse callback function:
void mouse_move(int x, int y)
{
m_x = x;
m_y = y;

drawScene();
}

void specialKey(int key, int x, int y) {
switch (key) {
case 101: //UP arrow key
if (move_mag<radius-1) {
move_mag+=0.5;
}
break;
case 103: //DOWN arrow key
if (move_mag>1) {
move_mag-=0.5;
}
break;
}
}

void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);
}
}

void output(int x, int y, char *string)
{
int len, i;

glRasterPos2f(x, y);
len = (int) strlen(string);
for (i = 0; i < len; i++) {
glutBitmapCharacter(font, string[i]);
}
}

//Makes the image into a texture, and returns the id of the texture
GLuint loadTexture(Image* image) {
GLuint textureId;
glGenTextures(1, &textureId); //Make room for our texture
glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
//Map the image to the texture
glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D
0, //0 for now
GL_RGB, //Format OpenGL uses for image
image->width, image->height, //Width and height
0, //The border of the image
GL_RGB, //GL_RGB, because pixels are stored in RGB format
GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
//as unsigned numbers
image->pixels); //The actual pixel data
return textureId; //Returns the id of the texture
}

GLuint _textureId; //The id of the texture

void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);

Image* image = loadBMP("br.bmp");
_textureId = loadTexture(image);
delete image;
}

void handleResize(int w, int h) {
/*glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)w / (float)h, 1.0, 200.0);*/

glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, h, 0);
glMatrixMode(GL_MODELVIEW);
}

void create_brick(int length,int width,int x, int y) {
glBegin(GL_QUADS);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(x, y, 0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(x+length,y,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(x+length,y-width,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(x,y-width,0);

glEnd();
}



void drawCircle(float radius, float x1, float y1)
{
float angle = 0;
float x2,y2,cx,cy,fx,fy;
int cache = 0;
glBegin(GL_LINES);
for (angle = 0; angle < 360; angle+=25.0) {
float rad_angle = angle * 3.14 / 180;
x2 = x1+radius * sin((double)rad_angle);
y2 = y1+radius * cos((double)rad_angle);
if (cache) {
glVertex2f(cx,cy);
glVertex2f(x2,y2);
} else {
fx = x2;
fy = y2;
}
cache = 1;
cx = x2;
cy = y2;
}
glVertex2f(x2,y2);
glVertex2f(fx,fy);

glEnd();
}

void play_ball() {
move_ball();

if (crossed_x_limits()) {
change_x_dir();
} else if (crossed_y_limits()) {
change_y_dir();
} else {
// Do nothing
}
}

void detect_collision() {

if(hit_base()) {
change_y_dir();
return;
}

for(int row=0;row<10;row++) {
for(int column=0;column<10;column++) {
BRICK temp = BR[row][column];
if (temp.visible) {
int min_y = temp.y - brick_width;
int min_x = temp.x;
int max_x = temp.x + brick_length;
int max_y = temp.y ;

if ((ball_x+radius)>=min_x &&
(ball_x-radius)<=max_x &&
(ball_y+radius)>=min_y &&
(ball_y-radius)<=max_y) {
BR[row][column].visible = 0;
change_both_dir();
return;
}

}
}
}
}


void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();


/*GLfloat ambientLight[] = {0.2f, 0.2f, 0.2f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);

GLfloat directedLight[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLfloat directedLightPos[] = {-10.0f, 15.0f, 20.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, directedLight);
glLightfv(GL_LIGHT0, GL_POSITION, directedLightPos);*/

// Show the X and Y coordinate location of the mouse
glClear(GL_COLOR_BUFFER_BIT);

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, _textureId);

//Bottom
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glColor3f(1.0f, 0.2f, 0.2f);

// Draw the wall of bricks
int x=100,y=50;

for(int row=0;row<10;row++) {
for(int column=0;column<10;column++) {
if (BR[row][column].visible ==1) {
create_brick(
brick_length,
brick_width,
(brick_length*column)+x,
(brick_width*row)+y);
}
}
}

// Draw the moving support base
{
int x=m_x-brick_length,y=MAX_Y;
for(int row=0;row<1;row++) {
for(int column=0;column<2;column++) {
create_brick(
brick_length,
brick_width,
(brick_length*column)+x,
y-(brick_width*row));
}
}
}

// Draw the ball
play_ball();
drawCircle(radius,ball_x,ball_y);
detect_collision();

glutSwapBuffers();
}

//Called every 25 milliseconds
void update(int value) {

drawScene();

glutPostRedisplay();
glutTimerFunc(5, update, 0);
}

int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(MAX_X, MAX_Y);

glutCreateWindow("Texture demo");
initRendering();

init_bricks();
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutSpecialFunc(specialKey);

glutReshapeFunc(handleResize);
glutMotionFunc(mouse_move);
glutPassiveMotionFunc(mouse_move);
glutTimerFunc(5 , update, 0);

glutMainLoop();
return 0;
}