Navigate to a given point using the OGM and virtual forces

Dependencies:   ISR_Mini-explorer mbed

Fork of VirtualForces by Georgios Tsamis

main.cpp

Committer:
geotsam
Date:
3 months ago
Revision:
46:e57ebcf747dc
Parent:
45:fb07065a64a9

File content as of revision 46:e57ebcf747dc:

#include "mbed.h"
#include "robot.h" // Initializes the robot. This include should be used in all main.cpp!
#include "math.h"

using namespace std;

//makes the angle inAngle between pi and minus pi
float rad_angle_check_pi_and_minus_pi(float inAngle);
void initialise_parameters();
//fill initialLogValues with the values we already know (here the bordurs)
void fill_initial_log_values();
//generate a position randomly and makes the robot go there while updating the map
void randomize_and_map();
//make the robot do a pi/2 flip
void do_half_flip();
//go the the given position while updating the map
void go_to_point_with_angle(float target_x, float target_y, float target_angle);
//Updates sonar values 
void update_sonar_values(float leftMm, float frontMm, float rightMm);
//function that check if a cell A(x,y) is in the range of the front sonar S(xs,ys) (with an angle depending on the sonar used, front 0, left pi/3, right -pi/3) returns the probability it's occupied/empty [0;1]
float compute_probability_t(float x, float y,float xs,float ys, float angleFromSonarPosition, float distanceObstacleDetected);
//print the map
void print_final_map();
//print the map with the robot marked on it
void print_final_map_with_robot_position();
//print the map with the robot and the target marked on it
void print_final_map_with_robot_position_and_target();
//go to a given line by updating angularLeft and angularRight
void go_to_line(float* angularLeft,float* angularRight,float line_a, float line_b, float line_c);
//calculate virtual force field and move
void vff(bool* reached);
void test_got_to_line(bool* reached);

//MATHS heavy functions
float dist(float robot_x, float robot_y, float target_x, float target_y);
//returns the probability [0,1] that the cell is occupied from the log value lt
float log_to_proba(float lt);
//returns the log value that the cell is occupied from the probability value [0,1]
float proba_to_log(float p);
//returns the new log value
float compute_log_estimation_lt(float previousLogValue,float currentProbability,float originalLogvalue );
//makes the angle inAngle between 0 and 2pi
float rad_angle_check(float inAngle);
//returns the angle between the vectors (x,y) and (xs,ys)
float compute_angle_between_vectors(float x, float y,float xs,float ys);
float x_robot_in_orthonormal_x(float x, float y);
float y_robot_in_orthonormal_y(float x, float y);
float robot_center_x_in_orthonormal_x();
float robot_center_y_in_orthonormal_y();
float robot_sonar_front_x_in_orthonormal_x();
float robot_sonar_front_y_in_orthonormal_y();
float robot_sonar_right_x_in_orthonormal_x();
float robot_sonar_right_y_in_orthonormal_y();
float robot_sonar_left_x_in_orthonormal_x();
float robot_sonar_left_y_in_orthonormal_y();
float estimated_width_indice_in_orthonormal_x(int i);
float estimated_height_indice_in_orthonormal_y(int j);
//update angleError,distanceFromTarget,d2, beta
void compute_angles_and_distance(float target_x, float target_y, float target_angle,float dt,float* angleError,float* distanceFromTarget,float* d2,float* beta);
//update angularLeft and angularRight
void compute_linear_angular_velocities(float angleError,float distanceFromTarget,float beta, float* angularLeft, float* angularRight);
//update foceX and forceY if necessary
void update_force(int widthIndice, int heightIndice, float range, float* forceX, float* forceY, float xRobotOrtho, float yRobotOrtho );
//compute the X and Y force
void compute_forceX_and_forceY(float* forceX, float* forceY);
//robotX and robotY are from Odometria, calculate line_a, line_b and line_c
void calculate_line(float forceX, float forceY, float robotX, float robotY,float *line_a, float *line_b, float *line_c);
//return 1 if positiv, -1 if negativ
float sign1(float value);
//return 1 if positiv, 0 if negativ
int sign2(float value);
//set target in ortho space, in reference to the robot (so if the robot is in the middle, you want to him to go 10cm down and 15 right, set_target_to(15,-10)
void set_target_to(float x, float y);
void try_to_reach_target();

const float pi=3.14159;

//spec of the sonar
//TODO MEASURE THE DISTANCE on X and Y of the robot space, between each sonar and the center of the robot and add it to calculus in updateSonarValues
const float RANGE_SONAR=50;//cm
const float RANGE_SONAR_MIN=10;//Rmin cm
const float INCERTITUDE_SONAR=10;//cm
const float ANGLE_SONAR=pi/3;//Omega rad

//those distance and angle are approximation in need of measurements, in the orthonormal space
const float ANGLE_FRONT_TO_LEFT=10*pi/36;//50 degrees
const float DISTANCE_SONAR_LEFT_X=-4;
const float DISTANCE_SONAR_LEFT_Y=4;

const float ANGLE_FRONT_TO_RIGHT=-10*pi/36;//-50 degrees
const float DISTANCE_SONAR_RIGHT_X=4;
const float DISTANCE_SONAR_RIGHT_Y=4;

const float ANGLE_FRONT_TO_FRONT=0;
const float DISTANCE_SONAR_FRONT_X=0;
const float DISTANCE_SONAR_FRONT_Y=5;

//TODO adjust the size of the map for computation time (25*25?)
const float WIDTH_ARENA=120;//cm
const float HEIGHT_ARENA=90;//cm

//const int SIZE_MAP=25;
const int NB_CELL_WIDTH=24;
const int NB_CELL_HEIGHT=18;

//position and orientation of the robot when put on the map (ODOMETRY doesn't know those) it's in the robot space
//this configuration suppose that the robot is in the middle of the arena facing up (to be sure you can use print_final_map_with_robot_position
//const float DEFAULT_X=HEIGHT_ARENA/2;
//const float DEFAULT_Y=WIDTH_ARENA/2;
const float DEFAULT_X=20;//lower right
const float DEFAULT_Y=20;//lower right
const float DEFAULT_THETA=0;

//used to create the map 250 represent the 250cm of the square where the robot is tested
//float sizeCell=250/(float)SIZE_MAP;
float sizeCellWidth=WIDTH_ARENA/(float)NB_CELL_WIDTH;
float sizeCellHeight=HEIGHT_ARENA/(float)NB_CELL_HEIGHT;

float map[NB_CELL_WIDTH][NB_CELL_HEIGHT];//contains the log values for each cell
float initialLogValues[NB_CELL_WIDTH][NB_CELL_HEIGHT];

//Diameter of a wheel and distance between the 2
const float RADIUS_WHEELS=3.25;
const float DISTANCE_WHEELS=7.2;

const int MAX_SPEED=200;//TODO TWEAK THE SPEED SO IT DOES NOT FUCK UP

//TODO all those global variables are making me sad
const float KRHO=12, KA=30, KB=-13, KV=150, KH=150; //Kappa values

//CONSTANT FORCE FIELD
const float FORCE_CONSTANT_REPULSION=80;//TODO tweak it
const float FORCE_CONSTANT_ATTRACTION=25;//TODO tweak it
const float RANGE_FORCE=50;//TODO tweak it

//those target are in comparison to the robot (for exemple a robot in 50,50 with a taget of 0,0 would not need to move)
float targetX;//this is in the robot space top left
float targetY;//this is in the robot space top left
float targetXOrtho;
float targetYOrtho;

bool direction;

int main(){
    initialise_parameters();   
    //try to reach the target     
    set_target_to(0,50);//up right
    print_final_map_with_robot_position_and_target();
    try_to_reach_target();
    set_target_to(0,-50);//lower right
    print_final_map_with_robot_position_and_target();
    try_to_reach_target();
    set_target_to(-50,50);//up left
    print_final_map_with_robot_position_and_target();
    try_to_reach_target();
    //print the map forever
    while(1){
         print_final_map_with_robot_position_and_target();
    }
}

void try_to_reach_target(){
    bool reached=false;
    int print=0;
    while (!reached) {
        vff(&reached);
        //test_got_to_line(&reached);
        if(print==10){
            leftMotor(1,0);
            rightMotor(1,0);
            pc.printf("\r\n theta=%f", theta);
            pc.printf("\r\n IN ORTHO:");
            pc.printf("\r\n X Robot=%f", robot_center_x_in_orthonormal_x());
            pc.printf("\r\n Y Robot=%f", robot_center_y_in_orthonormal_y());
            pc.printf("\r\n X Target=%f", targetXOrtho);
            pc.printf("\r\n Y Target=%f", targetYOrtho);
            print_final_map_with_robot_position_and_target();
            print=0;
        }else
            print+=1;
    }
    //Stop at the end
    leftMotor(1,0);
    rightMotor(1,0);
    pc.printf("\r\n target reached");
}

//target in ortho space
void set_target_to(float x, float y){
    targetX=y;
    targetY=-x;
    targetXOrtho=x_robot_in_orthonormal_x(targetX,targetY);
    targetYOrtho=y_robot_in_orthonormal_y(targetX,targetY);
    
    pc.printf("\r\nangletarget= %f", atan2(x,y));
    float angleError = atan2(x,y)-theta;
    if(angleError>pi) angleError-=2*pi;
    if(angleError<-pi) angleError+=2*pi;
        
    if(angleError<(pi/2) && angleError>(-pi/2)) direction=true;
    else direction=false;
    pc.printf("\r\nangleError= %f", angleError);
}

void initialise_parameters(){
    i2c1.frequency(100000);
    initRobot(); //Initializing the robot
    pc.baud(9600); // baud for the pc communication

    measure_always_on();//TODO check if needed
    wait(0.5);
    //fill the map with the initial log values
    fill_initial_log_values();

    theta=DEFAULT_THETA;
    X=DEFAULT_X;
    Y=DEFAULT_Y;
}

//fill initialLogValues with the values we already know (here the bordurs)
void fill_initial_log_values(){
    //Fill map, we know the border are occupied
    for (int i = 0; i<NB_CELL_WIDTH; i++) {
        for (int j = 0; j<NB_CELL_HEIGHT; j++) {
            if(j==0 || j==NB_CELL_HEIGHT-1 || i==0 || i==NB_CELL_WIDTH-1)
                initialLogValues[i][j] = proba_to_log(1);
            else
                initialLogValues[i][j] = proba_to_log(0.5);
        }
    }
}

//generate a position randomly and makes the robot go there while updating the map
void randomize_and_map() {
    //TODO check that it's aurelien's work
    float target_x = (rand()%(int)(HEIGHT_ARENA*10))/10;//for decimal precision
    float target_y = (rand()%(int)(WIDTH_ARENA*10))/10;
    float target_angle = 2*((float)(rand()%31416)-15708)/10000.0;
    
    go_to_point_with_angle(targetX, targetY, target_angle);
}


void do_half_flip(){
    Odometria();
    float theta_plus_h_pi=theta+pi/2;//theta is between -pi and pi
    if(theta_plus_h_pi > pi)
        theta_plus_h_pi=-(2*pi-theta_plus_h_pi);
    leftMotor(0,100);
    rightMotor(1,100);
    while(abs(theta_plus_h_pi-theta)>0.05){
        Odometria();
       // pc.printf("\n\r diff=%f", abs(theta_plus_pi-theta));
    }
    leftMotor(1,0);
    rightMotor(1,0);    
}

//go the the given position while updating the map
//TODO clean this procedure it's ugly as hell and too long
void go_to_point_with_angle(float target_x, float target_y, float target_angle) {
    set_target_to(target_x,target_y);
    Odometria();
    float angleError = atan2((target_y-Y),(target_x-X))-theta;
    if(!cos(angleError))
        angleError = atan(sin(angleError)/cos(angleError));
    else
        angleError=pi/2;
    if(isnan(angleError)) pc.printf("\r\n nan line 264");
    float distanceFromTarget = dist(robot_center_x_in_orthonormal_x(),robot_center_y_in_orthonormal_y(),targetXOrtho,targetYOrtho);
    float beta = -angleError-theta+target_angle;
    //beta = atan(sin(beta)/cos(beta));
    bool keep_going=true;
    float leftMm;
    float frontMm;
    float rightMm;
    float angularLeft=0; 
    float angularRight=0;
    Timer t;
    float dt=0.5;//TODO better name please
    float d2;//TODO better name please
    do {
        //Timer stuff
        dt = t.read();
        t.reset();
        t.start();
        
        //Updating X,Y and theta with the odometry values
        Odometria();
        leftMm = get_distance_left_sensor();
        frontMm = get_distance_front_sensor();
        rightMm = get_distance_right_sensor();

        //pc.printf("\n\r leftMm=%f", leftMm);
        //pc.printf("\n\r frontMm=%f", frontMm);
        //pc.printf("\n\r rightMm=%f", rightMm);
    
        //if in dangerzone 
        if(frontMm < 120 || leftMm <120 || rightMm <120){
            leftMotor(1,0);
            rightMotor(1,0);
            update_sonar_values(leftMm, frontMm, rightMm);
            //TODO Giorgos maybe you can also test the do_half_flip() function
            Odometria();
            //do a flip TODO
            keep_going=false;
            do_half_flip();   
        }else{
            //if not in danger zone continue as usual
            update_sonar_values(leftMm, frontMm, rightMm);
            compute_angles_and_distance(target_x, target_y, target_angle,dt,&angleError,&distanceFromTarget,&d2,&beta);//Compute the angles and the distance from target
            compute_linear_angular_velocities(angleError,distanceFromTarget,beta,&angularLeft,&angularRight); //Using the angles and distance, compute the velocities needed (linear & angular)
            
            //pc.printf("\n\r X=%f", X);
            //pc.printf("\n\r Y=%f", Y);
    
            //pc.printf("\n\r a_r=%f", angularRight);
            //pc.printf("\n\r a_l=%f", angularLeft);
    
            //Updating motor velocities
            leftMotor(sign2(angularLeft),abs(angularLeft));
            rightMotor(sign2(angularRight),abs(angularRight));
    
            wait(0.2);
            //Timer stuff
            t.stop();
        }
    } while(d2>1 && (abs(target_angle-theta)>0.01) && keep_going);

    //Stop at the end
    leftMotor(1,0);
    rightMotor(1,0);
}

//Updates sonar values
void update_sonar_values(float leftMm, float frontMm, float rightMm){
    float currProba;
    float i_in_orthonormal;
    float j_in_orthonormal;
    for(int i=0;i<NB_CELL_WIDTH;i++){
        for(int j=0;j<NB_CELL_HEIGHT;j++){
                //check if the point A(x,y) in the world space is within the range of the sonar (which has the coordinates xs, ys in the world space)
            //check that again
            //compute for front sonar
            i_in_orthonormal=estimated_width_indice_in_orthonormal_x(i);
            j_in_orthonormal=estimated_height_indice_in_orthonormal_y(j);

            currProba=compute_probability_t(i_in_orthonormal,j_in_orthonormal,robot_sonar_front_x_in_orthonormal_x(),robot_sonar_front_y_in_orthonormal_y(),ANGLE_FRONT_TO_FRONT,frontMm/10);
            if(isnan(currProba)) pc.printf("\r\n currProba is nan");
            map[i][j]=map[i][j]+proba_to_log(currProba)+initialLogValues[i][j];//map is filled as map[0][0] get the data for the point closest to the origin
            //compute for right sonar
            currProba=compute_probability_t(i_in_orthonormal,j_in_orthonormal,robot_sonar_right_x_in_orthonormal_x(),robot_sonar_right_y_in_orthonormal_y(),ANGLE_FRONT_TO_RIGHT,rightMm/10);
            map[i][j]=map[i][j]+proba_to_log(currProba)+initialLogValues[i][j];
             //compute for left sonar
            currProba=compute_probability_t(i_in_orthonormal,j_in_orthonormal,robot_sonar_left_x_in_orthonormal_x(),robot_sonar_left_y_in_orthonormal_y(),ANGLE_FRONT_TO_LEFT,leftMm/10);
            if(isnan(currProba)) pc.printf("\r\n nan line 354");
            map[i][j]=map[i][j]+proba_to_log(currProba)+initialLogValues[i][j];
            if(isnan(proba_to_log(currProba))) pc.printf("\r\nnan in line 355");
        }
    }
}

//makes the angle inAngle between pi and minus pi
float rad_angle_check_pi_and_minus_pi(float inAngle){
    //cout<<"before :"<<inAngle;
    if(inAngle > 0){
        while(inAngle > (pi))
            inAngle-=pi;
    }else{
        while(inAngle < 0)
            inAngle+=pi;
    }
    //cout<<" after :"<<inAngle<<endl;
    return inAngle;
}

//ODOMETRIA MUST HAVE BEEN CALLED
//function that check if a cell A(x,y) is in the range of the front sonar S(xs,ys) (with an angle depending on the sonar used, front 0, left pi/3, right -pi/3) returns the probability it's occupied/empty [0;1]
float compute_probability_t(float x, float y,float xs,float ys, float angleFromSonarPosition, float distanceObstacleDetected){

    float anglePointToSonar=compute_angle_between_vectors(x,y,xs,ys);//angle beetween the point and the sonar beam
    float alphaBeforeAdjustment=anglePointToSonar-theta-angleFromSonarPosition;
    anglePointToSonar=rad_angle_check(alphaBeforeAdjustment);//TODO I feel you don't need to do that but I m not sure
    alphaBeforeAdjustment=rad_angle_check_pi_and_minus_pi(alphaBeforeAdjustment);
    //if(abs(alphaBeforeAdjustment)>ANGLE_SONAR/2) pc.printf("\r\n it is!");
    float distancePointToSonar=sqrt(pow(x-xs,2)+pow(y-ys,2));

    //check if the distance between the cell and the robot is within the circle of range RADIUS_WHEELS
    //check if absolute difference between the angles is no more than Omega/2
    if( distancePointToSonar < (RANGE_SONAR)&& (anglePointToSonar <= ANGLE_SONAR/2 || anglePointToSonar >= rad_angle_check(-ANGLE_SONAR/2))){
        if( distancePointToSonar < (distanceObstacleDetected - INCERTITUDE_SONAR)){
        //point before obstacle, probably empty
        /*****************************************************************************/
            float Ea=1.f-pow((2*alphaBeforeAdjustment)/ANGLE_SONAR,2);
            float Er;
            if(distancePointToSonar < RANGE_SONAR_MIN){
                //point before minimum sonar range
                Er=0.f;
            }else{
                //point after minimum sonar range
                Er=1.f-pow((distancePointToSonar-RANGE_SONAR_MIN)/(distanceObstacleDetected-INCERTITUDE_SONAR-RANGE_SONAR_MIN),2);
            }
         /*****************************************************************************/
            if((1.f-Er*Ea)/2.f>1) pc.printf("\r\n E>1");
            if((1.f-Er*Ea)/2.f<0) pc.printf("\r\n E<0");
            return (1.f-Er*Ea)/2.f;
        }else{
            //probably occupied
        /*****************************************************************************/
            float Oa=1.f-pow((2*alphaBeforeAdjustment)/ANGLE_SONAR,2);
            float Or;
            if( distancePointToSonar <= (distanceObstacleDetected + INCERTITUDE_SONAR)){
                //point between distanceObstacleDetected +- INCERTITUDE_SONAR
                Or=1-pow((distancePointToSonar-distanceObstacleDetected)/(INCERTITUDE_SONAR),2);
            }else{
                //point after in range of the sonar but after the zone detected
                Or=0;
            }
        /*****************************************************************************/
            if((1+Or*Oa)/2>1) pc.printf("\r\n O>1");
            if((1+Or*Oa)/2<0) pc.printf("\r\n O<0");
            return (1+Or*Oa)/2;
        }
    }
   //not checked by the sonar
   return 0.5;
}

void print_final_map() {
    float currProba;
    pc.printf("\n\r");
    for (int y = NB_CELL_HEIGHT -1; y>-1; y--) {
        for (int x= 0; x<NB_CELL_WIDTH; x++) {
                currProba=log_to_proba(map[x][y]);
            if ( currProba < 0.5) {
                pc.printf("   ");
            } else {
                if(currProba==0.5)
                    pc.printf(" . ");
                else
                    pc.printf(" X ");
            }
        }
        pc.printf("\n\r");
    }
}

void print_final_map_with_robot_position() {
    float currProba;
    Odometria();
    float Xrobot=robot_center_x_in_orthonormal_x();
    float Yrobot=robot_center_y_in_orthonormal_y();
    
    float heightIndiceInOrthonormal;
    float widthIndiceInOrthonormal;
    
    float widthMalus=-(3*sizeCellWidth/2);
    float widthBonus=sizeCellWidth/2;
    
    float heightMalus=-(3*sizeCellHeight/2);
    float heightBonus=sizeCellHeight/2;

    pc.printf("\n\r");
    for (int y = NB_CELL_HEIGHT -1; y>-1; y--) {
        for (int x= 0; x<NB_CELL_WIDTH; x++) {
            heightIndiceInOrthonormal=estimated_height_indice_in_orthonormal_y(y);
            widthIndiceInOrthonormal=estimated_width_indice_in_orthonormal_x(x);
            if(Yrobot >= (heightIndiceInOrthonormal+heightMalus) && Yrobot <= (heightIndiceInOrthonormal+heightBonus) && Xrobot >= (widthIndiceInOrthonormal+widthMalus) && Xrobot <= (widthIndiceInOrthonormal+widthBonus))                    
                pc.printf(" R ");
            else{
                currProba=log_to_proba(map[x][y]);
                if ( currProba < 0.5)
                    pc.printf("   ");
                else{
                    if(currProba==0.5)
                        pc.printf(" . ");
                    else
                        pc.printf(" X ");
                } 
            }
        }
        pc.printf("\n\r");
    }
}

void print_final_map_with_robot_position_and_target() {
    float currProba;
    Odometria();
    float Xrobot=robot_center_x_in_orthonormal_x();
    float Yrobot=robot_center_y_in_orthonormal_y();
    
    float heightIndiceInOrthonormal;
    float widthIndiceInOrthonormal;
    
    float widthMalus=-(3*sizeCellWidth/2);
    float widthBonus=sizeCellWidth/2;
    
    float heightMalus=-(3*sizeCellHeight/2);
    float heightBonus=sizeCellHeight/2;

    pc.printf("\n\r");
    for (int y = NB_CELL_HEIGHT -1; y>-1; y--) {
        for (int x= 0; x<NB_CELL_WIDTH; x++) {
            heightIndiceInOrthonormal=estimated_height_indice_in_orthonormal_y(y);
            widthIndiceInOrthonormal=estimated_width_indice_in_orthonormal_x(x);
            if(Yrobot >= (heightIndiceInOrthonormal+heightMalus) && Yrobot <= (heightIndiceInOrthonormal+heightBonus) && Xrobot >= (widthIndiceInOrthonormal+widthMalus) && Xrobot <= (widthIndiceInOrthonormal+widthBonus))
                pc.printf(" R ");
            else{
                if(targetYOrtho >= (heightIndiceInOrthonormal+heightMalus) && targetYOrtho <= (heightIndiceInOrthonormal+heightBonus) && targetXOrtho >= (widthIndiceInOrthonormal+widthMalus) && targetXOrtho <= (widthIndiceInOrthonormal+widthBonus))                    
                    pc.printf(" T ");
                else{
                    currProba=log_to_proba(map[x][y]);
                    if ( currProba < 0.5)
                        pc.printf("   ");
                    else{
                        if(currProba==0.5)
                            pc.printf(" . ");
                        else
                            pc.printf(" X ");
                    } 
                }
            }
        }
        pc.printf("\n\r");
    }
}

//MATHS heavy functions
/**********************************************************************/
//Distance computation function
float dist(float robot_x, float robot_y, float target_x, float target_y){
    return sqrt(pow(target_y-robot_y,2) + pow(target_x-robot_x,2));
}

//returns the probability [0,1] that the cell is occupied from the log value lt
float log_to_proba(float lt){
    float temp=1-1/(1+exp(lt));
    if(isnan(temp)){
        //pc.printf("\r\n nan in line 514");
        //pc.printf("\r\nlt= %f, 1+exp(lt)= %f", lt, 1+exp(lt));
    }
    return temp;
}

//returns the log value that the cell is occupied from the probability value [0,1]
float proba_to_log(float p){
    float temp;
    if(p==1) temp=log(0.99/(1-0.99));
    else temp=log(p/(1-p));
    if(isnan(temp)) pc.printf("\r\n temp=%f, p=%f", temp,p);
    return temp;
}

//returns the new log value
float compute_log_estimation_lt(float previousLogValue,float currentProbability,float originalLogvalue ){
    return previousLogValue+proba_to_log(currentProbability)-originalLogvalue;
}

//makes the angle inAngle between 0 and 2pi
float rad_angle_check(float inAngle){
    //cout<<"before :"<<inAngle;
    if(inAngle > 0){
        while(inAngle > (2*pi))
            inAngle-=2*pi;
    }else{
        while(inAngle < 0)
            inAngle+=2*pi;
    }
    //cout<<" after :"<<inAngle<<endl;
    return inAngle;
}

//returns the angle between the vectors (x,y) and (xs,ys)
float compute_angle_between_vectors(float x, float y,float xs,float ys){
    //alpha angle between ->x and ->SA
    //vector S to A ->SA
    float vSAx=x-xs;
    float vSAy=y-ys;
    //norme SA
    float normeSA=sqrt(pow(vSAx,2)+pow(vSAy,2));
    //vector ->x (1,0)
    float cosAlpha=1*vSAy/*+0*vSAx*//normeSA;;
    //vector ->y (0,1)
    float sinAlpha=/*0*vSAy+*/1*vSAx/normeSA;//+0*vSAx;
    if (sinAlpha < 0)
        return -acos(cosAlpha);
    else
        return acos(cosAlpha);
}
/*


Robot space:      orthonormal space:
      ^                 ^
      |x                |y
   <- R                 O ->
    y                     x
*/
//Odometria must bu up to date
float x_robot_in_orthonormal_x(float x, float y){
    return robot_center_x_in_orthonormal_x()-y;
}

//Odometria must bu up to date
float y_robot_in_orthonormal_y(float x, float y){
    return robot_center_y_in_orthonormal_y()+x;
}

float robot_center_x_in_orthonormal_x(){
    return NB_CELL_WIDTH*sizeCellWidth-Y;
}

float robot_center_y_in_orthonormal_y(){
    return X;
}

float robot_sonar_front_x_in_orthonormal_x(){
    return robot_center_x_in_orthonormal_x()+DISTANCE_SONAR_FRONT_X;
}
float robot_sonar_front_y_in_orthonormal_y(){
    return robot_center_y_in_orthonormal_y()+DISTANCE_SONAR_FRONT_Y;
}

float robot_sonar_right_x_in_orthonormal_x(){
    return robot_center_x_in_orthonormal_x()+DISTANCE_SONAR_RIGHT_X;
}
float robot_sonar_right_y_in_orthonormal_y(){
    return robot_center_y_in_orthonormal_y()+DISTANCE_SONAR_RIGHT_Y;
}

float robot_sonar_left_x_in_orthonormal_x(){
    return robot_center_x_in_orthonormal_x()+DISTANCE_SONAR_LEFT_X;
}
float robot_sonar_left_y_in_orthonormal_y(){
    return robot_center_y_in_orthonormal_y()+DISTANCE_SONAR_LEFT_Y;
}

float estimated_width_indice_in_orthonormal_x(int i){
    return sizeCellWidth/2+i*sizeCellWidth;
}
float estimated_height_indice_in_orthonormal_y(int j){
    return sizeCellHeight/2+j*sizeCellHeight;
}

//update angleError,distanceFromTarget,d2, beta
void compute_angles_and_distance(float target_x, float target_y, float target_angle,float dt,float* angleError,float* distanceFromTarget,float* d2,float* beta){
    *angleError = atan2((target_y-Y),(target_x-X))-theta;
    if(!cos(*angleError))
        *angleError = atan(sin(*angleError)/cos(*angleError));
    else
        *angleError=pi/2;
    if(isnan(*angleError)) pc.printf("\r\n nan line 613");
    *distanceFromTarget = dist(robot_center_x_in_orthonormal_x(),robot_center_y_in_orthonormal_y(),targetXOrtho,targetYOrtho);
    *d2 = *distanceFromTarget;
    *beta = -*angleError-theta+target_angle;        
    
    //Computing angle error and distance towards the target value
    *distanceFromTarget += dt*(-KRHO*cos(*angleError)**distanceFromTarget);
    float temp = *angleError;
    *angleError += dt*(KRHO*sin(*angleError)-KA**angleError-KB**beta);
    *beta += dt*(-KRHO*sin(temp));
   //pc.printf("\n\r d2=%f", d2);
    //pc.printf("\n\r dt=%f", dt);
}

//update angularLeft and angularRight
void compute_linear_angular_velocities(float angleError,float distanceFromTarget,float beta,float* angularLeft, float* angularRight){
    //Computing linear and angular velocities
    float linear;
    float angular;
    if(angleError>=-1.5708 && angleError<=1.5708){
        linear=KRHO*distanceFromTarget;
        angular=KA*angleError+KB*beta;
    }
    else{
        linear=-KRHO*distanceFromTarget;
        angular=-KA*angleError-KB*beta;
    }
    //TODO check those signs
    *angularLeft=(linear-0.5*DISTANCE_WHEELS*angular)/RADIUS_WHEELS;
    *angularRight=(linear+0.5*DISTANCE_WHEELS*angular)/RADIUS_WHEELS;
    
    float aL=*angularLeft;
    float aR=*angularRight;
    //Normalize speed for motors
    if(abs(*angularLeft)>abs(*angularRight)) {  
        *angularRight=MAX_SPEED*abs(aR/aL)*sign1(aR);
        *angularLeft=MAX_SPEED*sign1(aL);
    }
    else {
        *angularLeft=MAX_SPEED*abs(aL/aR)*sign1(aL);
        *angularRight=MAX_SPEED*sign1(aR);
    }    
}

void update_force(int widthIndice, int heightIndice, float range, float* forceX, float* forceY, float xRobotOrtho, float yRobotOrtho ){
    //get the coordonate of the map and the robot in the ortonormal space
    float xCenterCell=estimated_width_indice_in_orthonormal_x(widthIndice);
    float yCenterCell=estimated_height_indice_in_orthonormal_y(heightIndice);
    //compute the distance beetween the cell and the robot
    float distanceCellToRobot=sqrt(pow(xCenterCell-xRobotOrtho,2)+pow(yCenterCell-yRobotOrtho,2));
    //check if the cell is in range
    if(distanceCellToRobot <= range) {
        float probaCell=log_to_proba(map[widthIndice][heightIndice]);
        //if(isnan(probaCell)) pc.printf("\r\nnan in probaCell");
        float xForceComputed=FORCE_CONSTANT_REPULSION*probaCell*(xCenterCell-xRobotOrtho)/pow(distanceCellToRobot,3);
        //if(isnan(xForceComputed)) pc.printf("\r\nnan in line 673");
        float yForceComputed=FORCE_CONSTANT_REPULSION*probaCell*(yCenterCell-yRobotOrtho)/pow(distanceCellToRobot,3);
        //if(isnan(yForceComputed)) pc.printf("\r\nnan in line 675");
        *forceX+=xForceComputed;
        *forceY+=yForceComputed;
    }
}

//compute the force on X and Y
void compute_forceX_and_forceY(float* forceX, float* forceY){
     //we put the position of the robot in an orthonormal space
     float xRobotOrtho=robot_center_x_in_orthonormal_x();
     float yRobotOrtho=robot_center_y_in_orthonormal_y();

     float forceRepulsionComputedX=0;
     float forceRepulsionComputedY=0;
     //for each cell of the map we compute a force of repulsion
     for(int i=0;i<NB_CELL_WIDTH;i++){
        for(int j=0;j<NB_CELL_HEIGHT;j++){
            update_force(i,j,RANGE_FORCE,&forceRepulsionComputedX,&forceRepulsionComputedY,xRobotOrtho,yRobotOrtho);
        }
    }
    //update with attraction force
    *forceX=-forceRepulsionComputedX;
    *forceY=-forceRepulsionComputedY;
    float distanceTargetRobot=sqrt(pow(targetXOrtho-xRobotOrtho,2)+pow(targetYOrtho-yRobotOrtho,2));
    if(distanceTargetRobot != 0){
        *forceX+=FORCE_CONSTANT_ATTRACTION*(targetXOrtho-xRobotOrtho)/distanceTargetRobot;
        *forceY+=FORCE_CONSTANT_ATTRACTION*(targetYOrtho-yRobotOrtho)/distanceTargetRobot;
    }
    float amplitude=sqrt(pow(*forceX,2)+pow(*forceY,2));
    if(amplitude!=0){//avoid division by 0 if forceX and forceY  == 0
        *forceX=*forceX/amplitude;
        *forceY=*forceY/amplitude;
    }
}

void test_got_to_line(bool* reached){
    float line_a=1;
    float line_b=2;
    float line_c=-140;
    //we update the odometrie
    Odometria();
    float angularRight=0;
    float angularLeft=0;

    go_to_line(&angularLeft,&angularRight,line_a,line_b,line_c);
    pc.printf("\r\n line: %f x + %f y + %f =0", line_a, line_b, line_c);

    leftMotor(sign2(angularLeft),abs(angularLeft));
    rightMotor(sign2(angularRight),abs(angularRight));
    
    pc.printf("\r\n dist=%f", dist(robot_center_x_in_orthonormal_x(),robot_center_y_in_orthonormal_y(),targetXOrtho,targetYOrtho));

    //wait(0.1);
    Odometria();
    if(dist(robot_center_x_in_orthonormal_x(),robot_center_y_in_orthonormal_y(),targetXOrtho,targetYOrtho)<10)
        *reached=true;
}
void vff(bool* reached){
    float line_a=0;
    float line_b=0;
    float line_c=0;
    //Updating X,Y and theta with the odometry values
    float forceX=0;
    float forceY=0;
    //we update the odometrie
    Odometria();
    //we check the sensors
    float leftMm = get_distance_left_sensor();
    float frontMm = get_distance_front_sensor();
    float rightMm = get_distance_right_sensor();
    float angularRight=0;
    float angularLeft=0;
    //update the probabilities values 
    update_sonar_values(leftMm, frontMm, rightMm);
    //we compute the force on X and Y
    compute_forceX_and_forceY(&forceX, &forceY);
    //we compute a new ine
    calculate_line(forceX, forceY, X, Y,&line_a,&line_b,&line_c);
    go_to_line(&angularLeft,&angularRight,line_a,line_b,line_c);

    //Updating motor velocities
    
    leftMotor(sign2(angularLeft),abs(angularLeft));
    rightMotor(sign2(angularRight),abs(angularRight));

    //wait(0.1);
    Odometria();
    if(dist(robot_center_x_in_orthonormal_x(),robot_center_y_in_orthonormal_y(),targetXOrtho,targetYOrtho)<10)
        *reached=true;
}

//return 1 if positiv, -1 if negativ
float sign1(float value){
    if(value>=0) 
        return 1;
    else 
        return -1;
}

//return 1 if positiv, 0 if negativ
int sign2(float value){
    if(value>=0) 
        return 1;
    else 
        return 0;
}

//currently line_c is not used
void go_to_line(float* angularLeft,float* angularRight,float line_a, float line_b, float line_c){
    float lineAngle;
    float angleError;
    float linear;
    float angular;
    
    if(line_b!=0){
        if(direction)
            lineAngle=atan(-line_a/line_b);
        else
            lineAngle=atan(line_a/-line_b);
    }
    else{
        lineAngle=1.5708;
    }
    
    //Computing angle error
    angleError = lineAngle-theta;
    if(!cos(angleError))
        angleError = atan(sin(angleError)/cos(angleError));
    else
        angleError=pi/2;
    if(isnan(angleError)) pc.printf("\r\n nan line 794");

    //Calculating velocities
    linear=KV*(3.1416);
    angular=KH*angleError;
    //TODO if we put it like the poly says it fails, if we switch the plus and minus it works ...
    *angularLeft=(linear-0.5*DISTANCE_WHEELS*angular)/RADIUS_WHEELS;
    *angularRight=(linear+0.5*DISTANCE_WHEELS*angular)/RADIUS_WHEELS;
    
    float aL=*angularLeft;
    float aR=*angularRight;
    //Normalize speed for motors
    if(abs(*angularLeft)>abs(*angularRight)) {  
        *angularRight=MAX_SPEED*abs(aR/aL)*sign1(aR);
        *angularLeft=MAX_SPEED*sign1(aL);
    }
    else {
        *angularLeft=MAX_SPEED*abs(aL/aR)*sign1(aL);
        *angularRight=MAX_SPEED*sign1(aR);
    }
    pc.printf("\r\n line: %f x + %f y + %f =0 , X=%f; Y=%f", line_a, line_b, line_c,robot_center_x_in_orthonormal_x(),robot_center_y_in_orthonormal_y());
}

//robotX and robotY are from Odometria, calculate line_a, line_b and line_c
void calculate_line(float forceX, float forceY, float robotX, float robotY,float *line_a, float *line_b, float *line_c){
    /*
    in the teachers maths it is 
    
    *line_a=forceY;
    *line_b=-forceX;
    
    because a*x+b*y+c=0
    a impact the vertical and b the horizontal
    and he has to put them like this because
    Robot space:      orthonormal space:
      ^                 ^
      |x                |y
   <- R                 O ->
    y                     x
    but since our forceX, forceY are already computed in the orthonormal space I m not sure we need to 
    */
    *line_a=forceX;
    *line_b=forceY;
    //TODO check that
    //because the line computed always pass by the robot center we dont need lince_c
    //float xRobotOrtho=robot_center_x_in_orthonormal_x();
    //float yRobotOrtho=robot_center_y_in_orthonormal_y();
    //*line_c=forceX*yRobotOrtho+forceY*xRobotOrtho;    
    *line_c=0;
}