15 Apr 2015

Programming for Physics Simulations – How is it Done ?


A lot of people even those who have experience in programming have very wrong ideas about how programs work. Moreover the common notion among the general public is that software development only requires knowledge and experience in programming, however its actually quite the contrary. Software development can have very high level of specialization unlike many other fields including medical, for instance one experienced cardiologist can do the same another cardiologist can. How two highly experienced web developers may not be able to do what the other can. What people don’t understand is programming on its own is just a tool and nearly worthless on its own. Its like maths, whats the use of maths? No use. But apply math in physics, chem, astronomy …… then suddenly it becomes very useful. That’s how programming is too , People often specialize in different fields like maths, physics and  architecture. Like for example if a developer needs to develop a CAD program , he or she would need to have a good knowledge of architecture to effectively develop a suitable product, therefore they would need to specialize in architecture too.

So here in this post I intend to instill some ideas into the minds of new developers. To do this I will explain how to simulate a basic physics concept used in cut the rope from scratch through C++ code. I will keep it as simple as possible. However one needs basic knowledge of trigonometry to follow. Please note that all the programs embedded on this post is either HTML5 or flash, however I will be discussing from C++ point of view.



This is what we are gonna make using C++, Its pretty basic right ? Yeah it is. But even this is not very easy as people might feel, Many people will be thinking oh whats the big deal, you pull it, it follows , whats so hard? Indeed you pull it, it follows but nothing on a computer ever happens on its own, Someone should take care of the physics through code.

Ok so how do I think the right way ?

The right way to think is not to think in terms of code but in terms of logic, Imagine this as a physics situation, there are 2 balls, separated by a distance and an elastic rope joined between them,  larger the distance, faster the ball moves. However even if the rope becomes slack, due to inertia the ball continues to be in motion. So inertia has to be also considered. Gravity needs to be considered to make the thing realistic. Finally the fact that we are working in a 2D space has to be kept in mind.  
On further analysis, You might feel that there is a need for friction / resistance between the balls, or they would never stop moving

Physics solution :

This is the solution to the problem in physics point of view

Here 'T' is the tension force in the elastic rope. 'x' is the extension (elongation) of  the rope, 'A' is the rope’s cross sectional area, 'L' is the natural length of the rope while 'Y' is the Young's modulus.  This is the formula derived from Hooke's law.

We need to resolve these forces into vectors since we are working in 2D space. Then we need to add the gravitational force on the vertical component so it will be T sinθ + mg.

From here its easy, all one needs to do is calculate acceleration in both components using 'F = ma', then find change in velocity using 'v = u + at', And from velocity you can find new position of the balls. But you might have already realized both acceleration and velocities keep on changing , that means to correctly calculate the final velocity, you will need to use integral calculus which is beyond the scope of this post.

However this analysis is correct and can be implemented in programming

Programming Implementation :

Remember I said we need integration to calculate the velocities and position at a given time? But in programming we have a work around i.e  Running several iterations to approximately calculate the velocity and position . This means we split a time interval, say 1 sec into many smaller time intervals Say 0.1 s, Since 0.1s is a very small interval, we can assume the acceleration and velocity doesn't change in that interval . Accuracy can be increased to any desired extent by decreasing the small time interval.

Ok now we are finally ready to get started
Main variables

float x1=200,y1=200,x2=200,y2=200, s=100;
float vx2=0,vy2=0;

(x1,y1) are the initial position of the first ball , the ball which is controlled by the mouse. (x2,y2) is the position of the ball which is connected to the first ball. 'vx2' and 'vy2' are the components of velocity of the second ball in the X and Y directions respectively. 's' is the natural length of the rope.

The following bits of code has to be put in a loop that runs the iterations

1)  Getting the coordinates of the mouse and setting that as the coordinates of the first ball
 
x1=mousex(); 
y1=mousey();

2) Finding distance and angle between the 2 centres.


float d1=distance(x1,y1,x2,y2);
float ang1=angle(x1,y1,x2,y2);

Here distance() is a function which calculates distance between 2 points at an instant of time and angle() is a function which calculates angle between 2 points i.e. angle made by the line joining the 2 points and the horizontal.

3) Checking if the rope is stretched

We calculate distance between the 2 balls to know if the rope is stretched and angle to resolve force into components

//If the rope is stretched
if(d1-s>0) {   //Resolving tension into vectors
    vy2+=(d1-s)*sin(ang1)*.007;
    vx2+=(d1-s)*cos(ang1)*.007;
}

/*  here all the constants clubbed together as 0.007 , you can change it
We are adding the force directly to velocities by assuming balls to be of unit
mass and time interval to also be unit time
*/

4) Adding gravitational force

 vy2+=.23;
 //Gravitational force added on y coordinate
// 0.23 is an experimentally calculated value ( you can experiment too ! )

5) Moving the body and friction
We move the body as follows as we have assumed time interval to be unit time interval

y2+=vy2;
 x2+=vx2;
//Friction reduces velocity by 1%
vy2*=.99;
vx2*=.99;
      
6) Summing up

//draws 2 circles on the screen
circle(x1,y1,25);
circle(x2,y2,25);
//draws a line between them
line(x1,y1,x2,y2);

And we are done !!
Several improvements can be made like having parameters such as length, area, masses of spheres etc. Further more this concept can be expanded on more than 2 balls


Full code :

#include<graphics.h>

#include<math.h>

//Distance is a function which calculates Distance between 2 points

float distance(int x1,int y1,int x2,int y2)

{

    return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));

}

//Angle is a function which calculates the angle between 2 points

// ( tan inverse of the Slope of the line joining the 2 points )

float angle(int x1 , int y1, int x2 , int y2)

{

    float ang;

    //In case the 2 points are perpendicular

    if(x1-x2==0)

    {

        ang=-1.57;

    }

    else

    {

        ang = atan((float)(y1 - y2) / (x1 - x2));

    }

    //Quadtrants

    if (ang < 0 && y1> y2)

    {

        ang += 3.14;

    }

    else if (ang > 0 && x1 < x2)

    {

        ang += 3.14;

    }

    return ang;

}

int main()

{

    //declaration of variables

    float x1=200,y1=200,x2=200,y2=200, s=100;

    float vx2=0,vy2=0;

    //Creating a new window

    initwindow (550, 400,"Windows BGI",50,50, false,true);

    while(1)

    {

        //Getting the coordinates of the mouse

        x1=mousex();

        y1=mousey();

        //Finding distance and angle between 2 points

        float d1=distance(x1,y1,x2,y2);

        float ang1=angle(x1,y1,x2,y2);

        //If the rope is stretched

        if(d1-s>0)

        {

            //Resolving tension into vectors

            vy2+=(d1-s)*sin(ang1)*.007;

            vx2+=(d1-s)*cos(ang1)*.007;

        }

        //Gravitational force on y coordinate

        vy2+=.23;

        //Now moving the body

        y2+=vy2;

        x2+=vx2;

        //Friction reduces velocity by 1%

        vy2*=.99;

        vx2*=.99;

        //draws 2 circles on the screen

        circle(x1,y1,25);

        circle(x2,y2,25);

        //draws a line between them

        line (x1,y1,x2,y2);

        //waits for 40 milliseconds

        delay(40);

        //something to do with memory

        swapbuffers();

        //clear the screen so that a new frame can be redrawn

        cleardevice();

    }

    return 0;

}

6 comments:

  1. Hello everyone out there, I'm here to give my testimony about a herbalist doctor who helped me. I was infected with HERPES SIMPLEX VIRUS in 2011, I went to many hospitals to heal myself but there was no solution, so I was thinking how I can get a solution so that my body can be well. One day I was in the river thinking about where I can go to get a solution. so a lady walked towards me telling me why I'm so sad and I open everything by telling her my problem, she told me she could help me, she introduced me to a doctor who uses herbal medicines to cure the SIMPLEX HERPES VIRUS and gave me your email, so I sent you an email. He told me everything I had to do and also gave me instructions to take, which I followed correctly. Before I knew what was happening after two weeks, the SIMPLEX HERPES VIRUS that was in my body disappeared. therefore, if you also have a broken heart and need help, you can also send an email to {oliha.miraclemedicine@gmail.com}or whatsapp him number: +2349038382931 or Facebook page https://www.facebook.com/drolihamiraclemedicine/
    Contact him today and he will have a testimony ... Good luck!

    Dr. OLIHA also cures:
    1. HIV / AIDS
    2. HERPES 1/2
    3. CANCER
    4. ALS (Lou Gehrig's disease)
    5. Hepatitis B
    6. chronic pancreatic
    7. emphysema
    8. COPD (chronic obstructive pulmonary disease)....

    ReplyDelete
    Replies
    1. Am Laura Mildred by name, i was diagnosed with Herpes 4 years ago i lived in pain with the knowledge that i wasn't going to ever be well again i contacted so many herbal doctors on this issue and wasted a large sum of money but my condition never got better i was determined to get my life back so one day i saw Mr. Morrison Hansen post on how Dr. Emu saved him from Herpes with herbal medicine i contacted Dr. Emu on his Email: Emutemple@gmail.com we spoke on the issue i told him all that i went through and he told me not to worry that everything will be fine again so he prepared the medicine and send it to me and told me how to use it, after 14 days of usage I went to see the doctor for test,then the result was negative, am the happiest woman on earth now thanks to Dr. Emu God bless you. Email him at: Emutemple@gmail.com Whats-app or Call him +2347012841542 

      Delete
  2. I still don’t know the right words to express my gratitude to this great man Dr Isibor. After been diagnosed of HERPES SIMPLEX VIRUS in 2months ago, i was given so many health prescription and advice with no improvement, I totally lost hope, until i found testimonies of Great Dr Isibor online research and on Facebook, Like anybody would be, I was very skeptical about contacting him, but i later did and he opened up to me and told me what was involved and he started the remedies for my health. Thank God, i was cured from herpes by the herbal medication I received from him. I never thought that herpes can be cured, from the bottom of my heart I'm truly grateful,i pray you have long life so you can help many more people on earth with your herbal medical support, You can Email him via email drisiborspellhome@gmail.com or for easy and fast communication you can also call or add him on whats-app with this mobile number +2348107855231, one thing i love most about DR Isibor is honestly, and he is very polite with his patience, everything he told me what he did, and his herbal medicine are very affordable.

    ReplyDelete
  3. Hello Everyone out there,I am here to give my testimony about a Herbalist doctor who helped me . I was infected with HERPES SIMPLEX VIRUS in 2012, i went to many hospitals for cure but there was no solution, so I was thinking how can I get a solution out so that my body can be okay. One day I was in the river side thinking where I can go to get solution. so a lady walked to me telling me why am I so sad and i open up all to her telling her my problem, she told me that she can help me out, she introduce me to a doctor who uses herbal medication to cure HERPES SIMPLEX VIRUS and gave me his email, so i mail him. He told me all the things I need to do and also give me instructions to take, which I followed properly. Before I knew what is happening after two weeks the HERPES SIMPLEX VIRUS that was in my body got vanished . so if you are also heart broken and also need a help, you can also email him at {oliha.miraclemedicine@gmail.com}
    or whatsapp him number: +2349038382931.

    Contact him today and you will have a testimony...Good luck!

    ReplyDelete

  4. Hello Am From The UK , I want to write a little testimony about the good work of doctor Oyagu who cured me from Hsv 1 and 2 for just 2 weeks with his herbal medicine, I never believe I can be normal again and have a good life like others I always regretted the day I got diagnose with the virus, I was lost of hope when my doctor told me there is no cure for it but I keep thinking and thinking about my future, if I can have kids of my own well I am so grateful for my helper who get me cured with his herbal medicine, I go online in search of anything that can help me because I can’t deal with it forever so I found this doc Oyagu email on a blog of someone who was cured by him I quickly contact him for help and explain all my pain to him, he told me not to worry about it there is cure for real, I never believe until he send me the herbal medicine when I order for it and I have it within 4 days that is how I took the medicine for 2 week and the following week I go for test just to confirm I was 100% cured from this sickness what a miracle in my life I am so happy right now, you can also get in contact with him if you have such sickness through email address oyaguherbalhome@gmail. com or text him on what's app, phone number +2348101755322 Dr Oyagu also has remedy to others disease like COLD SORES,HIV/AIDS,DIABETES.CANCER,HIGH BLOOD PRESSURE AND MANY MORE. I oblige everyone to contact this powerful herbalist Dr Oyagu and be free from suffering.

    ReplyDelete
  5. Hello Everyone out there,I am here to give my testimony about a Herbalist doctor who helped me . I was infected with HERPES SIMPLEX VIRUS in 2011, i went to many hospitals for cure but there was no solution, so I was thinking how can I get a solution out so that my body can be okay. One day I was in the river side thinking where I can go to get solution. so a lady walked to me telling me why am I so sad and i open up all to her telling her my problem, she told me that she can help me out, she introduce me to a doctor who uses herbal medication to cure HERPES SIMPLEX VIRUS and gave me his email, so i mail him. He told me all the things I need to do and also give me instructions to take, which I followed properly. Before I knew what is happening after two weeks the HERPES SIMPLEX VIRUS that was in my body got vanished . so if you are also heart broken and also need a help, you can also email him at {oliha.miraclemedicine@gmail.com}
    or whatsapp him number: +2349038382931

    ReplyDelete