#include #include #include "/usr/local/include/SDL11/SDL.h" #include "gui.hh" #include "map.hh" #include "antsim.hh" Gui::Gui() : w(0), h(0), screen(NULL) { } Gui::~Gui() { if (screen != NULL) delete screen; } bool Gui::load(int w_, int h_, char* title) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { cout << "Unable to init SDL: " << SDL_GetError() << endl; return false; } screen = SDL_SetVideoMode(w_, h_, 8, SDL_HWSURFACE | SDL_DOUBLEBUF);// | SDL_FULLSCREEN); if (screen == NULL) { cout << "Unable to set video mode: " << SDL_GetError() << endl; return false; } w = w_; h = h_; SDL_WM_SetCaption(title, NULL); atexit(SDL_Quit); return true; } void Gui::write(int x, int y, Uint8 r, Uint8 g, Uint8 b) { if (x < 0 || x >= w || y < 0 || y >= h) return; Uint32 color = SDL_MapRGB(screen->format, r, g, b); int bpp = screen->format->BytesPerPixel; /* Here p is the address to the pixel we want to set */ Uint8 *p = (Uint8 *)screen->pixels + y * screen->pitch + x * bpp; switch(bpp) { case 1: *p = color; break; case 2: *(Uint16 *)p = color; break; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (color >> 16) & 0xff; p[1] = (color >> 8) & 0xff; p[2] = color & 0xff; } else { p[0] = color & 0xff; p[1] = (color >> 8) & 0xff; p[2] = (color >> 16) & 0xff; } break; case 4: *(Uint32 *)p = color; break; } } void Gui::lock() { if (SDL_MUSTLOCK(screen)) if (SDL_LockSurface(screen) < 0) return; } void Gui::unlock() { if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); } void Gui::draw(Map* map, bool showPheromones) { lock(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int nestScent = min(map->getNestScent(x, y) >> 6, 255); int foodScent = min(map->getFoodScent(x, y) >> 6, 255); int food = min(map->getFood(x, y) << 4, 255); if (map->getWall(x, y)) write(x, y, 0, 255, 255); else if (map->getNest(x, y)) write(x, y, 0, 255, 0); else if (food > 0) write(x, y, 0, 0, food); else if (map->getAnts(x, y) > 0) write(x, y, 255, 0, 0); else { if (showPheromones) write(x, y, nestScent, foodScent, nestScent + foodScent >> 1); else write(x, y, 0, 0, 0); } } } unlock(); SDL_Flip(screen); }