Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SDL2/SDL.h>
- #include <SDL2/SDL_ttf.h>
- #include <SDL2/SDL_image.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <math.h>
- #include <string.h>
- #include "estruturas.h"
- // pre-processor definitions
- #define STRING_SIZE 100
- #define MAP_SIZE 1000
- #define WINDOW_POSX 500
- #define WINDOW_POSY 250
- #define EXTRASPACE 150
- #define MARGIN 5
- #define nbytes 101
- #define sizefn 100
- #define sizern 10
- #define OBSTACULO 2
- #define SUJO 0
- #define LIMPO 1
- // function declarations
- void ordenalista(robot *head,robot *tail);
- robot* createList(robot *head,robot *tail);
- robot* delBat(robot *aux,robot *head,robot *tail);
- void lerficheiro(FILE *fp,int nSquareH,int nSquareW,quadrados ***mat,robot *head,robot *tail);
- void MoveRobot(robot* aux,quadrados **mat,int nSquareH,int nSquareW);
- int InitEverything(int , int , SDL_Window** , SDL_Renderer** );
- int InitSDL();
- int InitFont();
- SDL_Window* CreateWindow(int , int );
- SDL_Renderer* CreateRenderer(int , int , SDL_Window* );
- void RenderMap(int , int , SDL_Renderer*,quadrados **mat,int ,robot*head,robot*tail);
- int RenderText(int , int , const char* , TTF_Font *, SDL_Renderer* );
- int RenderLogo(int , int , SDL_Renderer* );
- // some global constant variables
- const char myName[] = "Miguel Nascimento";
- const char myName2[]= "Laura Silva";
- const char myNumber[] = "80785";
- const char myNumber2[] = "81792";
- /**
- * main function: entry point of the program
- */
- int main( int argc, char* args[] )
- {
- int nSquareH=0,nSquareW=0,num_obstaculos=0,num_arg=0,width=0,height=0,SQUARE_SIZE=0,area=0;
- quadrados **mat;
- int max_dropout=0,dropout=0;
- int delay = 1000;
- int key=0;
- SDL_Event event;
- SDL_Window* window = NULL;
- SDL_Renderer* renderer = NULL;
- char *line;
- FILE *fp;
- robot *head = (robot*)malloc(sizeof(robot));
- robot *tail = (robot*)malloc(sizeof(robot));
- robot *aux = head;
- srand(time(NULL));
- if (argc!=3)
- {
- printf("Numero insuficiente de parametros!");
- exit(EXIT_FAILURE);
- }
- sscanf(args[2],"%d",&max_dropout);
- if(max_dropout<0.1)
- {
- printf("Decrescimo de bateria demasiado baixo!");
- exit(EXIT_FAILURE);
- }
- fp=fopen(args[1],"r");
- if (fp==NULL)
- {
- printf("O ficheiro com o nome indicado não existe!");
- exit(EXIT_FAILURE);
- }
- line = (char *) malloc (nbytes * sizeof(char));
- fgets(line,nbytes,fp);
- num_arg=sscanf(line,"%d %d %d",&nSquareW,&nSquareH,&num_obstaculos);
- if (num_arg!=3)
- {
- printf("\nErro! Dados num formato não suportado");
- exit(EXIT_FAILURE);
- }
- head=createList(head,tail);
- lerficheiro(fp,nSquareH,nSquareW,&mat,head,tail);
- area=nSquareH*nSquareW;
- if(area>250)
- SQUARE_SIZE=30;
- else
- SQUARE_SIZE=40;
- // calculate the window size
- width = SQUARE_SIZE*nSquareW;
- height = SQUARE_SIZE*nSquareH;
- // initialize graphics
- if ( !InitEverything(width, height, &window, &renderer) )
- return -1;
- while( 1 )
- {
- // while there's events to handle
- while( SDL_PollEvent( &event ) )
- {
- if( event.type == SDL_QUIT )
- {
- // quit the program
- exit(EXIT_SUCCESS);
- }
- else if ( event.type == SDL_KEYDOWN )
- {
- switch ( event.key.keysym.sym )
- {
- case SDLK_DOWN:
- // speed-down
- delay=delay+50;
- break;
- case SDLK_UP:
- // speed-up
- delay=delay-50;
- if (delay<0)
- delay=0;
- break;
- case SDLK_p:
- //pausa a simulação
- key=1;
- while (key==1)
- {
- while( SDL_PollEvent( &event ) )
- {
- if( event.type == SDL_QUIT )
- {
- // quit the program
- exit(EXIT_SUCCESS);
- }
- else if(event.type == SDL_KEYDOWN)
- {
- switch ( event.key.keysym.sym )
- {
- case SDLK_p:
- key=0;
- break;
- case SDLK_a:
- //adicionar robo
- break;
- case SDLK_q:
- //fecha a simulação
- exit(EXIT_SUCCESS);
- break;
- default:
- break;
- }
- }
- }
- }
- break;
- case SDLK_q:
- //fecha a simulação
- exit(EXIT_SUCCESS);
- break;
- case SDLK_i:
- //reinicializa a simulação
- free(line);
- for(aux=head->next;aux!=tail;aux=aux->next)
- {
- aux->prev=aux->next;
- free(aux);
- }
- free(mat);
- fp=fopen(args[1],"r");
- if (fp==NULL)
- {
- printf("O ficheiro com o nome indicado não existe!");
- exit(EXIT_FAILURE);
- }
- line = (char *) malloc (nbytes * sizeof(char));
- fgets(line,nbytes,fp);
- num_arg=sscanf(line,"%d %d %d",&nSquareW,&nSquareH,&num_obstaculos);
- if (num_arg!=3)
- {
- printf("\nErro! Dados num formato não suportado");
- exit(EXIT_FAILURE);
- }
- head=createList(head,tail);
- lerficheiro(fp,nSquareH,nSquareW,&mat,head,tail);
- area=nSquareH*nSquareW;
- if(area>250)
- SQUARE_SIZE=30;
- else
- SQUARE_SIZE=40;
- break;
- default:
- break;
- }
- }
- }
- for(aux=head->next;aux!=tail;aux=aux->next)
- {
- RenderMap(nSquareW, nSquareH, renderer,mat,SQUARE_SIZE,head,tail);
- MoveRobot(aux,mat,nSquareH,nSquareW);
- dropout=(max_dropout+0.1)*10;
- dropout=(rand()%dropout)/10;
- aux->bateria=(aux->bateria)-dropout;
- head=delBat(aux,head,tail);
- }
- // add a delay
- SDL_Delay( delay );
- }
- SDL_DestroyRenderer(renderer);
- SDL_DestroyWindow(window);
- SDL_Quit();
- return 1;
- }
- void addrobot(robot *head, robot *tail, int SQUARE_SIZE, int nSquareW, int nSquareH)
- {
- char *novonome=(char *)malloc(3 * sizeof(char));
- novonome[0]='R';
- novonome[1]=(char)( event.key.keysym.sym );
- novonome[2]='\0';
- }
- void ordenalista(robot *head,robot *tail)
- {
- robot *aux;
- for (aux=head->next;aux!=tail;aux=aux->next)
- {
- if(aux->prev==head)
- {
- if(aux->nome[1]>(aux->next)->nome[1])
- {
- (aux->next)->next=aux;
- (aux->next)->prev=head;
- aux->next=(aux->next)->next;
- }
- }
- else
- {
- if(aux->nome[1]<(aux->prev)->nome[1])
- {
- (aux->prev)->prev=aux;
- (aux->prev)->next=aux->next;
- aux->next=aux->prev;
- }
- }
- if(aux->next==tail)
- {
- if(aux->nome[1]<(aux->prev)->nome[1])
- {
- (aux->prev)->prev=aux;
- (aux->prev)->next=tail;
- aux->next=aux->prev;
- }
- }
- }
- }
- robot* delBat(robot *aux,robot *head,robot *tail)
- {
- if(aux->bateria<=0 && head->next!=tail)
- {
- (aux->prev)->next=aux->next;
- (aux->next)->prev=aux->prev;
- free(aux);
- }
- return head;
- }
- void MoveRobot(robot* aux,quadrados **mat,int nSquareH,int nSquareW)
- {
- double angle;
- int atualx=(aux->atual).x,atualy=(aux->atual).y;
- while((aux->target).x==(aux->atual).x && (aux->target).y==(aux->atual).y) //Quando é atingido a posição destino
- {
- (aux->target).x=rand()%nSquareW;
- (aux->target).y=rand()%nSquareH;
- }
- // calculate the angle
- angle = atan2((double)((aux->atual).y-(aux->target).y), (double)((aux->target).x)-(aux->atual).x);
- // calculate the new position
- (aux->atual).x = floor((aux->atual).x + cos(angle)+0.5);
- (aux->atual).y = floor((aux->atual).y - sin(angle)+0.5);
- if(mat[(aux->atual).y][(aux->atual).x].estarobot==1)//Quando a próxima posição está ocupada por um robô
- {
- (aux->target).x=rand()%nSquareW;
- (aux->target).y=rand()%nSquareH;
- }
- if(mat[(aux->atual).y][(aux->atual).x].estado==OBSTACULO)//Quando a próxima posição está ocupada por um obstáculo
- {
- (aux->atual).x=atualx;
- (aux->atual).y=atualy;
- (aux->target).x=rand()%nSquareW;
- (aux->target).y=rand()%nSquareH;
- }
- mat[(aux->atual).y][(aux->atual).x].estado=LIMPO;
- mat[(aux->atual).y][(aux->atual).x].estarobot=1;
- }
- robot* createList(robot *head,robot *tail)
- {
- head->prev = head;
- head->next = tail;
- tail->prev = head;
- tail->next = NULL;
- return head;
- }
- void lerficheiro(FILE *fp,int nSquareH,int nSquareW,quadrados***mat,robot*head,robot*tail)
- {
- char nome_robot[sizern];/*nome_robot- armazena o nome do robot */
- char *line;
- robot *aux=head;
- int num_arg=0;
- int xobst,yobst,num_robots,xrobot,yrobot,bat,i=0;
- (*mat) = (quadrados**)calloc(nSquareH, sizeof(quadrados*)); //alocar memoria na matriz sobre as linhas
- if((*mat) == NULL)
- {
- printf("Sem memoria\n");
- exit(EXIT_FAILURE);
- }
- for(i = 0; i < nSquareH; i++) //alocar para cada linha
- {
- (*mat)[i] = (quadrados *)calloc(nSquareW, sizeof(quadrados));
- if((*mat)[i] == NULL)
- {
- printf("Sem memoria\n");
- exit(EXIT_FAILURE);
- }
- }
- line = (char *) malloc (nbytes * sizeof(char));
- while(fgets(line,nbytes,fp)!=NULL)
- {
- if(sscanf(line,"[%d, %d]",&xobst,&yobst))
- {
- (*mat)[yobst][xobst].estado=2;
- }
- if(sscanf(line,"%d",&num_robots))
- {
- printf("%d\n",num_robots);
- }
- num_arg=sscanf(line,"%s [%d, %d] %d",nome_robot,&xrobot,&yrobot,&bat);
- if(sscanf(line,"%s [%d, %d] %d",nome_robot,&xrobot,&yrobot,&bat) && num_arg==4)
- {
- (*mat)[yrobot][xrobot].estado=1;
- (*mat)[yrobot][xrobot].estarobot=1;
- robot *node = (robot*)malloc(sizeof(robot));
- node->next=aux->next;
- (node->next)->prev=node;
- aux->next=node;
- node->prev=aux;
- node->bateria=bat;
- (node->atual).x=xrobot;
- (node->atual).y=yrobot;
- strcpy(node->nome,nome_robot);
- (node->target).x=rand()%nSquareW;
- (node->target).y=rand()%nSquareH;
- aux=aux->next;
- }
- }
- fclose(fp);
- //ordenalista(head,tail);
- }
- /**
- * RenderLogo function: Renders the IST Logo on the window screen
- * \param x X coordinate of the Logo
- * \param y Y coordinate of the Logo
- * \param _renderer renderer to handle all rendering in a window
- */
- int RenderLogo(int x, int y, SDL_Renderer* _renderer)
- {
- SDL_Texture *text_IST;
- SDL_Surface *img_IST;
- SDL_Rect boardPos;
- // renders IST Logo
- img_IST = SDL_LoadBMP("ist_logo.bmp");
- if (img_IST == NULL)
- {
- printf("Unable to load bitmap: %s\n", SDL_GetError());
- exit(-5);
- }
- // square where the Logo is placed
- boardPos.x = x;
- boardPos.y = y;
- boardPos.w = img_IST->w;
- boardPos.h = img_IST->h;
- // creates a texture and renders it in the screen
- text_IST = SDL_CreateTextureFromSurface(_renderer, img_IST);
- SDL_RenderCopy(_renderer, text_IST, NULL, &boardPos);
- // destroy texture and surface
- SDL_DestroyTexture(text_IST);
- SDL_FreeSurface(img_IST);
- return img_IST->h;
- }
- /**
- * RenderText function: Renders the IST Logo on the window screen
- * \param x X coordinate of the text
- * \param y Y coordinate of the text
- * \param text string where the text is written
- * \param font TTF font used to render the text
- * \param _renderer renderer to handle all rendering in a window
- */
- int RenderText(int x, int y, const char *text, TTF_Font *font, SDL_Renderer* _renderer)
- {
- SDL_Color color = { 0, 0, 0 };
- SDL_Surface *text_surface;
- SDL_Texture *text_texture;
- SDL_Rect solidRect;
- solidRect.x = x;
- solidRect.y = y;
- // creates a surface with some text
- text_surface = TTF_RenderText_Blended(font,text,color);
- if(!text_surface)
- {
- printf("TTF_RenderText_Blended: %s\n", TTF_GetError());
- exit(-5);
- }
- // creates a texture from the surface and renders it !
- text_texture = SDL_CreateTextureFromSurface(_renderer, text_surface);
- SDL_QueryTexture( text_texture, NULL, NULL, &solidRect.w, &solidRect.h );
- SDL_RenderCopy(_renderer, text_texture, NULL, &solidRect);
- // destroy texture and surface
- SDL_DestroyTexture(text_texture);
- SDL_FreeSurface(text_surface);
- return solidRect.h;
- }
- /**
- * RenderMap function: Renders the map on the window screen according to their size
- * \param nSquareW number of squares to render (width)
- * \param nSquareH number of squares to render (height)
- * \param pos_robot position of the robot (ID of the square)
- * \param robot_name name of the robot (max. 2 letters)
- * \param _renderer renderer to handle all rendering in a window
- */
- void RenderMap(int nSquareW, int nSquareH, SDL_Renderer* _renderer,quadrados**mat, int SQUARE_SIZE,robot *head,robot *tail)
- {
- TTF_Font *sans;
- TTF_Font *serif;
- SDL_Rect gridPos;
- int i,j, height;
- robot *aux=head;
- char bateria[3];
- // set color of renderer to some color
- SDL_SetRenderDrawColor( _renderer, 255, 255, 255, 255 );
- // clear the window
- SDL_RenderClear( _renderer );
- // opens a font style and sets a size
- sans = TTF_OpenFont("FreeSans.ttf", 24);
- serif = TTF_OpenFont("FreeSerif.ttf", 16);
- if(!sans || !serif)
- {
- printf("TTF_OpenFont: %s\n", TTF_GetError());
- exit(-5);
- }
- // render the IST Logo
- height = RenderLogo(nSquareW*SQUARE_SIZE, 0, _renderer);
- // render the student name
- height += RenderText(nSquareW*SQUARE_SIZE+3*MARGIN, height, myName, serif, _renderer);
- height += RenderText(nSquareW*SQUARE_SIZE+3*MARGIN, height, myName2, serif, _renderer);
- // render the student number
- height += RenderText(nSquareW*SQUARE_SIZE+3*MARGIN, height, myNumber, serif, _renderer);
- height += RenderText(nSquareW*SQUARE_SIZE+3*MARGIN, height, myNumber2, serif, _renderer);
- for (aux=head->next;aux!=tail;aux=aux->next)
- {
- sprintf(bateria,"%s:%d",aux->nome,aux->bateria);
- height += RenderText(nSquareW*SQUARE_SIZE+3*MARGIN, height,bateria, serif, _renderer);
- }
- // grid position
- gridPos.w = SQUARE_SIZE;
- gridPos.h = SQUARE_SIZE;
- gridPos.y = 0;
- // iterate over all squares
- for (i = 0; i < nSquareH; i++)
- {
- gridPos.x = 0;
- for (j = 0; j < nSquareW; j++)
- {
- if (mat[i][j].estado==SUJO)
- {
- // writes a dirty square
- SDL_SetRenderDrawColor( _renderer, 221, 161, 135, 255 );
- SDL_RenderFillRect( _renderer, &gridPos );
- SDL_SetRenderDrawColor( _renderer, 0, 0, 0, 255 );
- SDL_RenderDrawRect( _renderer, &gridPos );
- }
- else if (mat[i][j].estado==LIMPO)
- {
- // cleans a dirty square
- SDL_SetRenderDrawColor( _renderer, 255, 255, 255, 255 );
- SDL_RenderFillRect( _renderer, &gridPos );
- SDL_SetRenderDrawColor( _renderer, 0, 0, 0, 255 );
- SDL_RenderDrawRect( _renderer, &gridPos );
- }
- else if (mat[i][j].estado==OBSTACULO)
- {
- //coloca um obstaculo
- SDL_SetRenderDrawColor( _renderer, 0, 0, 0, 255 );
- SDL_RenderFillRect( _renderer, &gridPos );
- SDL_SetRenderDrawColor( _renderer, 0, 0, 0, 255 );
- SDL_RenderDrawRect( _renderer, &gridPos );
- }
- for(aux=head->next;aux!=tail;aux=aux->next)
- {
- if((aux->target).x==j && (aux->target).y==i)
- {
- //coloca o target
- SDL_SetRenderDrawColor( _renderer, 25, 25, 112, 255 );
- SDL_RenderFillRect( _renderer, &gridPos );
- SDL_SetRenderDrawColor( _renderer, 0, 0, 0, 255 );
- SDL_RenderDrawRect( _renderer, &gridPos );
- }
- if((aux->atual).x==j && (aux->atual).y==i)
- {
- RenderText(gridPos.x+MARGIN, gridPos.y, aux->nome, sans, _renderer);
- }
- }
- gridPos.x += SQUARE_SIZE;
- }
- gridPos.y += SQUARE_SIZE;
- }
- // render the changes above
- SDL_RenderPresent( _renderer);
- // destroy everything
- TTF_CloseFont(sans);
- TTF_CloseFont(serif);
- }
- /**
- * InitEverything: Initializes the SDL2 library and all graphical components: font, window, renderer
- * \param width width in px of the window
- * \param height height in px of the window
- * \param _window represents the window of the application
- * \param _renderer renderer to handle all rendering in a window
- */
- int InitEverything(int width, int height, SDL_Window** _window, SDL_Renderer** _renderer)
- {
- SDL_Window* window = NULL;
- SDL_Renderer* renderer = NULL;
- if ( !InitSDL() )
- return 0;
- if ( !InitFont() )
- return 0;
- window = CreateWindow(width, height);
- if ( window == NULL )
- return 0;
- renderer = CreateRenderer(width, height, window);
- if ( renderer == NULL )
- return 0;
- *_window = window;
- *_renderer = renderer;
- return 1;
- }
- /**
- * InitSDL: Initializes the SDL2 graphic library
- */
- int InitSDL()
- {
- // init SDL library
- if ( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
- {
- printf(" Failed to initialize SDL : %s\n", SDL_GetError());
- return 0;
- }
- return 1;
- }
- /**
- * InitFont: Initializes the SDL2_ttf font library
- */
- int InitFont()
- {
- // init font library
- if(TTF_Init()==-1)
- {
- printf("TTF_Init: %s\n", TTF_GetError());
- return 0;
- }
- return 1;
- }
- /**
- * CreateWindow: Creates a window for the application
- * \param width width in px of the window
- * \param height height in px of the window
- * \return pointer to the window created
- */
- SDL_Window* CreateWindow(int width, int height)
- {
- SDL_Window* window = NULL;
- // init window
- window = SDL_CreateWindow( "iClean", WINDOW_POSX, WINDOW_POSY, width+EXTRASPACE, height, 0 );
- if ( window == NULL )
- {
- printf("Failed to create window : %s\n", SDL_GetError());
- return NULL;
- }
- return window;
- }
- /**
- * CreateRenderer: Creates a renderer for the application
- * \param width width in px of the window
- * \param height height in px of the window
- * \param _window represents the window for which the renderer is associated
- * \return pointer to the renderer created
- */
- SDL_Renderer* CreateRenderer(int width, int height, SDL_Window* _window)
- {
- SDL_Renderer* renderer;
- // init renderer
- renderer = SDL_CreateRenderer( _window, -1, 0 );
- if ( renderer == NULL )
- {
- printf("Failed to create renderer : %s", SDL_GetError());
- return NULL;
- }
- // set size of renderer to the same as window
- SDL_RenderSetLogicalSize( renderer, width+EXTRASPACE, height );
- return renderer;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement