Image read_image( const char *filename ) { printf("loading image '%s'...\n", filename); // importer le fichier en utilisant SDL_image SDL_Surface *surface= IMG_Load(filename); if(surface == NULL) { printf("loading image '%s'... sdl_image failed.\n", filename); return create_image(2, 2, 4, make_color(1, 0, 0)); } // verifier le format, rgb ou rgba const SDL_PixelFormat format= *surface->format; if(format.BitsPerPixel != 24 && format.BitsPerPixel != 32) { printf("loading image '%s'... format failed. (bpp %d)\n", filename, format.BitsPerPixel); SDL_FreeSurface(surface); return create_image(2, 2, 4, make_color(1, 0, 0)); } int height= surface->h; int width= surface->w; int channels= (format.BitsPerPixel == 32) ? 4 : 3; Image im; im.data.resize(width*height*channels); im.width= width; im.height= height; im.channels= channels; // converti les donnees en pixel rgba, et retourne l'image, openGL utilise une origine en bas a gauche. if(format.BitsPerPixel == 32) { int py= 0; for(int y= height -1; y >= 0; y--, py++) { unsigned char *data= &im.data.front() + im.width * y * im.channels; Uint8 *pixel= (Uint8 *) surface->pixels + py * surface->pitch; for(int x= 0; x < width; x++, pixel+= format.BytesPerPixel, data+= 4) { Uint8 r= pixel[format.Rshift / 8]; Uint8 g= pixel[format.Gshift / 8]; Uint8 b= pixel[format.Bshift / 8]; Uint8 a= pixel[format.Ashift / 8]; data[0]= r; data[1]= g; data[2]= b; data[3]= a; } } } else if(format.BitsPerPixel == 24) { int py= 0; for(int y= height -1; y >= 0; y--, py++) { unsigned char *data= &im.data.front() + im.width * y * im.channels; Uint8 *pixel= (Uint8 *) surface->pixels + py * surface->pitch; for(int x= 0; x < width; x++, pixel+= format.BytesPerPixel, data+= 3) { const Uint8 r= pixel[format.Rshift / 8]; const Uint8 g= pixel[format.Gshift / 8]; const Uint8 b= pixel[format.Bshift / 8]; data[0]= r; data[1]= g; data[2]= b; } } } SDL_FreeSurface(surface); return im; }
int main(int argc, char* argv[]) { // Init initPath(argv[0]); SDL_Surface* screen = NULL; SDL_Event event; int *seed; srand((int)seed); int previousTime = 0, currentTime = 0; Events *flags = createEventFlags(); SDL_Init(SDL_INIT_VIDEO); SDL_SetEventFilter(eventFilter); screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_DOUBLEBUF | SDL_NOFRAME); SDL_WM_SetCaption("Tower Defense", NULL); Action *actionList = initAction(); Map* map = createMap(getPath("resources/Forest.png")); _map = map; SDL_Rect surface = {0, 0, 720, 600}; Viewport* viewport = createViewport(screen, surface, map); _viewport = viewport; // FIXME uh? what's this thing? surface.x = 800 - 80; surface.y = 0; surface.h = 80; surface.w = 600; // Creation of the enemies TypeEn *whiteCat = createTypeEn(100, 5, false, true, true, false, 1,getPath("resources/white_transparent_cat.png")); TypeEn *blackCat = createTypeEn(100, 5, false, true, true, false, 1,getPath("resources/black_transparent_cat.png")); Enemy *cat1 = createEnemy(1,1,whiteCat); Enemy *cat2 = createEnemy(1,10,whiteCat); Enemy *cat3 = createEnemy(5,5,blackCat); Enemy *cat4 = createEnemy(21,4,blackCat); TypeEn *zombie = createTypeEn(100,5,false,true,true,false,1,getPath("resources/zombie.png")); Enemy *zombie1 = createEnemy(4,4,zombie); Enemy *zombie2 = createEnemy(9,4,zombie); Enemy *zombie3 = createEnemy(9,9,zombie); Enemy *zombie4 = createEnemy(7,14,zombie); //Add enemy in the List List *catList = newList(cat4); pushList((void*)catList,cat2); pushList((void*)catList,cat3); // pushList((void*)catList,cat1); List *zombieList = newList(zombie1); /* pushList((void*)zombieList,zombie2);*/ /* pushList((void*)zombieList,zombie3);*/ /* pushList((void*)zombieList,zombie4);*/ // removeEnemyFromList(cat4,catList); //TOWER TypeBul *bullet = createTypeBul(getPath("resources/bullet.png"), 1); TypeTo *tower = createTypeTo(0,5,0,0,false,false,false,false,bullet,NULL,getPath("resources/tower.png")); upgradeTypeTo(tower,0.5,getPath("resources/towerUP.png")); flags->selectedTower = tower->nextType; Tower *tower1 = createTower(7,7,tower); List *towerList = newList(tower1); flags->towerList = towerList; // Create and Renders the right panel game menu SDL_Rect surfaceMenu = {720, 0, 800, 600}; Menu* menu = menu_create(screen, surfaceMenu); menu_loadBackground(menu, "resources/enemyFont.gif"); // For testing only, we add a few random buttons menu_addButton(menu, button_createBuildButton(tower)); menu_addButton(menu, button_createBuildButton(tower)); menu_addButton(menu, button_createBuildButton(tower)); menu_render(menu); _cell = *getCase(20,11); // Main loop while(actionList[QUIT].boolean == NULL) { // Managing the events manageEvents(viewport, flags,actionList); for(int i=1; i<ACTION_LENGTH; i++) { if(actionList[i].boolean) { int repeat = (*actionList[i].action)(viewport,flags,actionList[i].boolean); if(!repeat) { actionList[i].boolean = NULL; } } } // Redraws the map (viewport contents) before blitting stuff on it updateViewport(viewport); ///////////////////////////// DEBUG WALL ///////////////////////////// SDL_Rect position; for(int i=0; i < _map->nbCaseW; i++) { for(int j=0; j < _map->nbCaseH; j++) { Case cell = *getCase(i,j); position.x = cell.x; position.y = cell.y; if(map->matrice[i][j].hasTower == 2) { SDL_Surface *wall = IMG_Load(getPath("resources/brick.png")); blitToViewport(viewport, wall, NULL, &position); } } } position.x = _cell.x; position.y = _cell.y; blitToViewport(viewport, IMG_Load(getPath("resources/candy_cane.png")), NULL, &position); ///////////////////////////////////////////////////////////////////// // Move enemies if(flags->enemy_Path_Calculation) { pathReCalculation(catList); pathReCalculation(zombieList); flags->enemy_Path_Calculation = false; } moveEnemyList(zombieList); moveEnemyList(catList); // Blit enemies drawEnemyList(zombieList); drawEnemyList(catList); //Blit TOWER /* if(event.key.keysym.sym == SDLK_u){*/ /* upgrade(tower1);*/ /* }*/ Bullet *bullet1 = createBullet(tower1); animateBullet(bullet1); drawTowerList(towerList); /* This should be handled by event.c switch(event.key.keysym.sym){ case SDLK_a: flags->selectedTower = tower; break; case SDLK_b: flags->selectedTower = tower->nextType; break; default: break; }*/ /* */ // Ask SDL to swap framebuffers to update the displayed screen SDL_Flip(screen); // Managing frames currentTime = SDL_GetTicks(); if (currentTime - previousTime <= 20) { SDL_Delay(20 - (currentTime - previousTime)); } // DEBUG printf("Frame %i : %ims\n", framecounter++, currentTime - previousTime); previousTime = SDL_GetTicks(); } free(actionList); SDL_Quit(); return EXIT_SUCCESS; }
int main() { if(SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); exit(1); } SDL_Window *win = SDL_CreateWindow("Moving start", 100, 100, SCREEN_HEIGHT, SCREEN_WIDTH, SDL_WINDOW_SHOWN); if(!win) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } if(!IMG_Init(IMG_INIT_PNG)) //*** { fprintf(stderr, "IMG_Init Error: %s\n", IMG_GetError()); SDL_DestroyWindow(win); SDL_Quit(); exit(1); } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!ren) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); exit(1); } //SDL_Surface *png = IMG_Load("../../MediaResources/star.png"); //*** SDL_Surface *png = IMG_Load("../../MediaResources/lips.png"); if(!png) { fprintf(stderr, "IMG_Load Error: %s\n", IMG_GetError()); SDL_DestroyRenderer(ren); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); exit(1); } SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, png); SDL_FreeSurface(png); if(!tex) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(ren); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); exit(1); } /* SDL_Rect dstRect = {SCREEN_HEIGHT / 2 - 32, SCREEN_WIDTH / 2 - 32, 64, 64}; SDL_SetRenderDrawColor(ren, 0x00, 0xFF, 0xFF, 0xFF); */ /* SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, &dstRect); SDL_RenderPresent(ren); SDL_Delay(4000); */ /* for(int i = 0; i < 10; ++i) { dstRect.h *= 1.5; dstRect.w *= 1.5; dstRect.x = SCREEN_HEIGHT / 2 - dstRect.h / 2; dstRect.y = SCREEN_WIDTH / 2 - dstRect.w / 2; SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, &dstRect); SDL_RenderPresent(ren); SDL_Delay(50); } */ bool quit = false; SDL_Event e; SDL_Rect destRect = {0, 0, 256, 256}; SDL_Rect rectFrom = {0, 0, 256, 256}; SDL_SetRenderDrawColor(ren, 0xFF, 0xFF, 0xFF, 0xFF); while(!quit) { while(SDL_PollEvent(&e)) { switch(e.type) { case SDL_QUIT: case SDL_MOUSEBUTTONDOWN: case SDL_KEYDOWN: quit = true; break; } } SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, &rectFrom, &destRect); SDL_RenderPresent(ren); SDL_Delay(500); rectFrom.x = (rectFrom.x + 256) % 512; } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); IMG_Quit(); //*** SDL_DestroyWindow(win); SDL_Quit(); return 0; }
bool TEXTURE::LoadCubeVerticalCross(const std::string & path, const TEXTUREINFO & info, std::ostream & error) { std::string cubefile = path; GLuint new_handle = 0; glGenTextures(1, &new_handle); OPENGL_UTILITY::CheckForOpenGLErrors("Cubemap ID generation", error); id = new_handle; glBindTexture(GL_TEXTURE_CUBE_MAP, new_handle); SDL_Surface * texture_surface = IMG_Load(cubefile.c_str()); if (texture_surface) { for (int i = 0; i < 6; ++i) { w = texture_surface->w/3; h = texture_surface->h/4; //detect channels int format = GL_RGB; switch (texture_surface->format->BytesPerPixel) { case 1: format = GL_LUMINANCE; break; case 2: format = GL_LUMINANCE_ALPHA; break; case 3: format = GL_RGB; break; case 4: format = GL_RGBA; break; default: error << "Texture has unknown format: " + path << std::endl; return false; break; } if (format != GL_RGB) { //throw EXCEPTION(__FILE__, __LINE__, "Cube map texture format isn't GL_RGB (this causes problems for some reason): " + texture_path + " (" + cubefile + ")"); //game.WriteDebuggingData("Warning: Cube map texture format isn't GL_RGB (this causes problems for some reason): " + texture_path + " (" + cubefile + ")"); } int offsetx = 0; int offsety = 0; GLenum targetparam; if (i == 0) { targetparam = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; offsetx = 0; offsety = h; } else if (i == 1) { targetparam = GL_TEXTURE_CUBE_MAP_POSITIVE_X; offsetx = w*2; offsety = h; } else if (i == 2) { targetparam = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; offsetx = w; offsety = h*2; } else if (i == 3) { targetparam = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; offsetx = w; offsety = 0; } else if (i == 4) { targetparam = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; offsetx = w; offsety = h*3; } else if (i == 5) { targetparam = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; offsetx = w; offsety = h; } else { error << "Texture has unknown format: " + path << std::endl; return false; } unsigned char * cubeface = new unsigned char[w*h*texture_surface->format->BytesPerPixel]; if (i == 4) //special case for negative z { for (unsigned int yi = 0; yi < h; yi++) { for (unsigned int xi = 0; xi < w; xi++) { for (unsigned int ci = 0; ci < texture_surface->format->BytesPerPixel; ci++) { int idx1 = ((h-yi-1)+offsety)*texture_surface->w*texture_surface->format->BytesPerPixel + (w-xi-1+offsetx)*texture_surface->format->BytesPerPixel + ci; int idx2 = yi*w*texture_surface->format->BytesPerPixel+xi*texture_surface->format->BytesPerPixel+ci; cubeface[idx2] = ((unsigned char *)(texture_surface->pixels))[idx1]; //cout << idx1 << "," << idx2 << endl; } } } } else { for (unsigned int yi = 0; yi < h; yi++) { for (unsigned int xi = 0; xi < w; xi++) { for (unsigned int ci = 0; ci < texture_surface->format->BytesPerPixel; ci++) { int idx1 = (yi+offsety)*texture_surface->w*texture_surface->format->BytesPerPixel+(xi+offsetx)*texture_surface->format->BytesPerPixel+ci; int idx2 = yi*w*texture_surface->format->BytesPerPixel+xi*texture_surface->format->BytesPerPixel+ci; cubeface[idx2] = ((unsigned char *)(texture_surface->pixels))[idx1]; //cout << idx1 << "," << idx2 << endl; } } } } glTexImage2D( targetparam, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, cubeface ); delete [] cubeface; } } else { error << "Error loading texture file: " + path << std::endl; return false; } if (texture_surface) { // Free up any memory we may have used SDL_FreeSurface( texture_surface ); texture_surface = NULL; } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if (info.mipmap) { glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP,GL_TEXTURE_MAG_FILTER,GL_LINEAR); if (GLEW_ARB_framebuffer_object) { glGenerateMipmap(GL_TEXTURE_CUBE_MAP); } } glDisable(GL_TEXTURE_CUBE_MAP); OPENGL_UTILITY::CheckForOpenGLErrors("Cubemap creation", error); return true; }
int main(int argc, char *argv[]) { // Erectin' a display SDL_Surface *screen; SDL_Init(SDL_INIT_EVERYTHING); screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_HWSURFACE); SDL_WM_SetCaption("Smuggler Demo", "Smuggler Demo"); bool quit = false; // Setting up text TTF_Font* Font=NULL; TTF_Init(); SDL_Surface* TextSurface = NULL; Font=TTF_OpenFont("DejaVuSansMono.ttf",16); SDL_Color color; color.r=255; color.g=255; color.b=255; int FontSize = 10; bool growing = true; // Rendering surfaces // Set background surface to display optimized SDL_Surface *background; SDL_Surface *oldface; oldface = IMG_Load("backimage.png"); background = SDL_DisplayFormat(oldface); SDL_FreeSurface(oldface); // Set player's image to Player player1("ana.png"); Player player2("character.png"); player2.coordX(500); player2.coordY(500); // Load overlay surface and set transparency color to 0 SDL_Surface *overlay = &map(); SDL_SetColorKey(overlay, SDL_SRCCOLORKEY,0); // Instantiate timer object Timer fps; int walkFrames = 2; while(!quit){ // Start the timer for frame rate limiting fps.start(); // The input handling function returns a bool. While quit == false, the game will continue to run quit = input(&player1, movementspeed); // This function animates through the cycle, using an iterating number that triggers the different frames // TODO: The walkframes integer should be tucked into the object it is manipulating, in this case, player. walkFrames=animate(player1.xvel(), player1.yvel(), movementspeed, walkFrames, walkFrameInterval, &player1); // Renders the background on the bottom SDL_BlitSurface(background, NULL, screen, NULL); // Puts the player underneath the overlay, which is basically the map SDL_BlitSurface(&player1.image(), &player1.frame(), screen, &player1.location()); // Checks for collisions if (collision(&player1.image(), player1.coordX(), player1.coordY(), 100, &player2.image(), player2.coordX(), player2.coordY(), 100)) { cout << "COLLIDE!\n"; player2.xvel(0); player2.yvel(0); } else { cout << "NO COLLIDE!\n"; player2.ai(player1); } // Puts the NPC underneath the overlay walkFrames=animate(player2.xvel(), player2.yvel(), movementspeed/2, walkFrames, walkFrameInterval, &player2); SDL_BlitSurface(&player2.image(), &player2.frame(), screen, &player2.location()); // Renders the map SDL_BlitSurface(overlay, NULL, screen, NULL); // Renders the text if (growing == true) { FontSize ++; } else { FontSize --; } if (FontSize == 25) { growing = false; } if (FontSize == 1) { growing = true; } Font=TTF_OpenFont("DejaVuSansMono.ttf",FontSize); TextSurface=TTF_RenderText_Solid(Font,"I love poop!!",color); SDL_BlitSurface(TextSurface, NULL, screen, &player2.speech_bubble()); TTF_CloseFont(Font); SDL_FreeSurface(TextSurface); // Renders it all to the display SDL_Flip(screen); // For performance measuring purposes, this line spits out the max framerate possible if this rate of animation is sustained. // printf("Max Frames per second: %d\n", 1000/fps.get_ticks()); // Hard locks the frame rate to 60 frames per second or less if(fps.get_ticks() < 1000 / FPS) { SDL_Delay ((1000/FPS) - fps.get_ticks()); } } SDL_Quit(); }
texture::texture() { if (TTF_Init() == -1) throw MenuError(TTF_GetError()); if (!(_font = TTF_OpenFont("src_graphic/res/DejaVuSans.ttf", 50))) throw ResError(TTF_GetError()); addImage(IMG_Load("src_graphic/res/hud.png"), "HUD"); int i = 0; std::string s; while (i < 300) { s = std::to_string(i); TextTotexture(s); i += 1; } TextTotexture("lvl:"); TextTotexture("time:"); addImage(IMG_Load("src_graphic/res/ground/Grass.png"), "GROUND"); addImage(IMG_Load("src_graphic/res/ground/Gcorner.png"), "GCORNER"); addImage(IMG_Load("src_graphic/res/ground/GEdge.png"), "GEDGE"); addImage(IMG_Load("src_graphic/res/bg2.jpg"), "BG"); addImage(IMG_Load("src_graphic/res/broadcast.png"), "BROADCAST"); addImage(IMG_Load("src_graphic/res/lvlup.png"), "LVLUP"); addImage(IMG_Load("src_graphic/res/gemme/food.png"), "food"); addImage(IMG_Load("src_graphic/res/gemme/cyan.png"), "linemate"); addImage(IMG_Load("src_graphic/res/gemme/green.png"), "deraumere"); addImage(IMG_Load("src_graphic/res/gemme/lopez.png"), "sibur"); addImage(IMG_Load("src_graphic/res/gemme/purple.png"), "Mendiane"); addImage(IMG_Load("src_graphic/res/gemme/red.png"), "Phiras"); addImage(IMG_Load("src_graphic/res/gemme/yellow.png"), "Thystame"); }
bool TEXTURE::LoadCube(const std::string & path, const TEXTUREINFO & info, std::ostream & error) { if (info.verticalcross) { return LoadCubeVerticalCross(path, info, error); } std::string cubefiles[6]; cubefiles[0] = path+"-xp.png"; cubefiles[1] = path+"-xn.png"; cubefiles[2] = path+"-yn.png"; cubefiles[3] = path+"-yp.png"; cubefiles[4] = path+"-zn.png"; cubefiles[5] = path+"-zp.png"; GLuint new_handle = 0; glGenTextures(1, &new_handle); OPENGL_UTILITY::CheckForOpenGLErrors("Cubemap texture ID generation", error); id = new_handle; glBindTexture(GL_TEXTURE_CUBE_MAP, new_handle); for (unsigned int i = 0; i < 6; ++i) { SDL_Surface * texture_surface = IMG_Load(cubefiles[i].c_str()); if (texture_surface) { //store dimensions if (i != 0 && (w != (unsigned int) texture_surface->w || h != (unsigned int) texture_surface->h)) { error << "Cube map sides aren't equal sizes" << std::endl; return false; } w = texture_surface->w; h = texture_surface->h; //detect channels int format = GL_RGB; switch (texture_surface->format->BytesPerPixel) { case 1: format = GL_LUMINANCE; break; case 2: format = GL_LUMINANCE_ALPHA; break; case 3: format = GL_RGB; break; case 4: format = GL_RGBA; break; default: error << "Texture has unknown format: " + path + " (" + cubefiles[i] + ")" << std::endl; return false; break; } if (format != GL_RGB) { error << "Cube map texture format isn't GL_RGB (this causes problems for some reason): " + path + " (" + cubefiles[i] + ")" << std::endl; return false; } // Create MipMapped Texture GLenum targetparam; if (i == 0) targetparam = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; else if (i == 1) targetparam = GL_TEXTURE_CUBE_MAP_POSITIVE_X; else if (i == 2) targetparam = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; else if (i == 3) targetparam = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; else if (i == 4) targetparam = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; else if (i == 5) targetparam = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; else { error << "Iterated too far: " + path + " (" + cubefiles[i] + ")" << std::endl; assert(0); } glTexImage2D( targetparam, 0, format,texture_surface->w, texture_surface->h, 0, format, GL_UNSIGNED_BYTE, texture_surface->pixels ); } else { error << "Error loading texture file: " + path + " (" + cubefiles[i] + ")" << std::endl; return false; } if (texture_surface) { // Free up any memory we may have used SDL_FreeSurface( texture_surface ); texture_surface = NULL; } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glDisable(GL_TEXTURE_CUBE_MAP); OPENGL_UTILITY::CheckForOpenGLErrors("Cubemap creation", error); return true; }
int main(int argc, char *argv[]) { SDL_Event ev,az; SDL_Surface *screen; SDL_Surface *kep; SDL_TimerID id; FILE *fp; int x, y,click=0,clicktwo=0,aut=0,quit=0,gomb=0,egerx,egery,nothinghappened=1; cell cells[MAX][MAX]={0}; kep=IMG_Load("sejt.png"); if(!kep) fprintf(stderr, "Nem sikerult betolteni a kepfajlt!\n"); /* SDL inicializálása és ablak megnyitása */ SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER); screen=SDL_SetVideoMode(MAX*MERET+KERET*2+100, MAX*MERET+KERET*2-100, 0, SDL_FULLSCREEN); if (!screen) { fprintf(stderr, "Nem sikerult megnyitni az ablakot!\n"); exit(1); } SDL_WM_SetCaption("Game Of Life", "Game Of Life"); SDL_FillRect(screen, NULL, 0x433e3f); boxColor(screen,KERET/3,KERET/3,MAX*MERET+KERET*2-KERET/3,MAX*MERET+KERET*2-KERET/3,KERETSZIN); drawcell(cells,screen,kep); while(!quit) { boxColor(screen, MAX*MERET+KERET*2+10,KERET+5,MAX*MERET+KERET*2+90,KERET+40,0xFFDFD2FF); boxColor(screen, MAX*MERET+KERET*2+14,KERET+9,MAX*MERET+KERET*2+86,KERET+36,0xE5C8BDFF); stringRGBA(screen, MAX*MERET+KERET*2+20, KERET+19, "Leptetes", 255, 255, 255, 255); boxColor(screen, MAX*MERET+KERET*2+10,KERET+5+HEZAG,MAX*MERET+KERET*2+90,KERET+40+HEZAG,0xFFDFD2FF); boxColor(screen, MAX*MERET+KERET*2+14,KERET+9+HEZAG,MAX*MERET+KERET*2+86,KERET+36+HEZAG,0xE5C8BDFF); if(aut==0) stringRGBA(screen, MAX*MERET+KERET*2+15, KERET+69, "Szimul.be", 255, 255, 255, 255); else stringRGBA(screen, MAX*MERET+KERET*2+15, KERET+69, "Szimul.ki", 255, 255, 255, 255); boxColor(screen, MAX*MERET+KERET*2+10,KERET+5+HEZAG*2,MAX*MERET+KERET*2+90,KERET+40+HEZAG*2,0xFFDFD2FF); boxColor(screen, MAX*MERET+KERET*2+14,KERET+9+HEZAG*2,MAX*MERET+KERET*2+86,KERET+36+HEZAG*2,0xE5C8BDFF); stringRGBA(screen, MAX*MERET+KERET*2+26, KERET+19+HEZAG*2, "Torles", 255, 255, 255, 255); boxColor(screen, MAX*MERET+KERET*2+10,KERET+5+HEZAG*3,MAX*MERET+KERET*2+90,KERET+40+HEZAG*3,0xFFDFD2FF); boxColor(screen, MAX*MERET+KERET*2+14,KERET+9+HEZAG*3,MAX*MERET+KERET*2+86,KERET+36+HEZAG*3,0xE5C8BDFF); stringRGBA(screen, MAX*MERET+KERET*2+27, KERET+19+HEZAG*3, "Kilovo", 255, 255, 255, 255); filledCircleColor(screen,MAX*MERET+2*KERET+80,9,8,0xFFDFD2FF); filledCircleColor(screen,MAX*MERET+2*KERET+80,9,6,0xE5C8BDFF); stringRGBA(screen,MAX*MERET+KERET*2+77,6,"X",255,255,255,255); SDL_Flip(screen); while(SDL_PollEvent(&ev)){ switch(ev.type) { /*case SDL_KEYDOWN: switch(ev.key.keysym.sym) { case SDLK_s: mentes(cells); break; case SDLK_l: fp=fopen("save.txt","r"); for(y=0;y<MAX;y++) for(x=0;x<MAX;x++) fscanf(fp,"%d ",&cells[y][x].alive); fclose (fp); drawcell(cells,screen,kep); SDL_Flip(screen); break; } break;*/ case SDL_MOUSEBUTTONDOWN: if(ev.button.button==SDL_BUTTON_LEFT) { if(ev.button.x<=MAX*MERET+KERET){ egerx=holazeger(ev.button.x); egery=holazeger(ev.button.y); if(cells[egery][egerx].alive==1) cells[egery][egerx].alive=0; else cells[egery][egerx].alive=1; } else if(incircle(ev.button.x,ev.button.y,MAX*MERET+2*KERET+80,9,8)) quit=1; else if((ev.button.x<=MAX*MERET+KERET*2+90 && ev.button.x>=MAX*MERET+KERET*2+10) && (ev.button.y<=KERET+40 && ev.button.y>=KERET+5))//egyes lépés { round(cells); } else if((ev.button.x<=MAX*MERET+KERET*2+90 && ev.button.x>=MAX*MERET+KERET*2+10) && (ev.button.y<=KERET+90 && ev.button.y>=KERET+55))//szimulálás { if(aut==0) aut=1; else aut=0; } else if((ev.button.x<=MAX*MERET+KERET*2+90 && ev.button.x>=MAX*MERET+KERET*2+10) && (ev.button.y<=KERET+40+HEZAG*2 && ev.button.y>=KERET+5+HEZAG*2))//egyes lépés { for(y=0;y<MAX;y++) for(x=0;x<MAX;x++) cells[y][x].alive=0; } else if((ev.button.x<=MAX*MERET+KERET*2+90 && ev.button.x>=MAX*MERET+KERET*2+10) && (ev.button.y<=KERET+40+HEZAG*3 && ev.button.y>=KERET+5+HEZAG*3))//egyes lépés { fp=fopen("save.txt","r"); for(y=0;y<MAX;y++) for(x=0;x<MAX;x++) fscanf(fp,"%d ",&cells[y][x].alive); fclose (fp); drawcell(cells,screen,kep); SDL_Flip(screen); } drawcell(cells,screen,kep); SDL_Flip(screen); } break; case SDL_MOUSEBUTTONUP: if(ev.button.button==SDL_BUTTON_LEFT) { click=0; clicktwo=0; } break; case SDL_QUIT: quit=1; break; } } if(aut) { SDL_Delay(100); round(cells); drawcell(cells,screen,kep); SDL_Flip(screen); } } SDL_FreeSurface(kep); SDL_Quit(); exit(0); return 0; }
int main(int argc, char *argv[]) { if(argc < 3) { printf("Usage: converter source.png target.raw [target bpp = 16 or 32]\n"); return 1; } SDL_Surface * src = IMG_Load(argv[1]); if(!src) return 1; bool perPixeAlpha = true; bool target32bpp = false; if( argc >= 3 && strcmp(argv[3], "32") == 0 ) target32bpp = true; /* if( src->format->BitsPerPixel == 32 ) { for( int i = 0; i < src->h; i++ ) { for( int ii = 0; ii < src->w; ii++ ) { Uint32 alpha = (* (Uint32 *) ((Uint8 *)src->pixels + i*src->pitch + ii*4)) & src->format->Amask; if( src->format->Amask >= 0x000000ff ) alpha /= 0x1000000; if( alpha > 15 && alpha < 240 ) { perPixeAlpha = true; break; } } } } */ printf("Converter: %s BPP %d %dx%d perPixeAlpha %d target %d bpp\n", argv[1], src->format->BitsPerPixel, src->w, src->h, (int)perPixeAlpha, target32bpp ? 32 : 16); SDL_Surface * format1 = SDL_CreateRGBSurface( SDL_SWSURFACE|SDL_SRCALPHA, 1, 1, 16, 0xF800, 0x7C0, 0x3E, 0x1 ); if( perPixeAlpha ) format1 = SDL_CreateRGBSurface( SDL_SWSURFACE|SDL_SRCALPHA, 1, 1, 16, 0xF000, 0xF00, 0xF0, 0xF ); if( target32bpp ) format1 = SDL_CreateRGBSurface( SDL_SWSURFACE|SDL_SRCALPHA, 1, 1, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000 ); if(!format1) return 1; SDL_Surface * dst = SDL_ConvertSurface(src, format1->format, SDL_SWSURFACE|SDL_SRCALPHA); if(!dst) return 1; FILE * ff = fopen(argv[2], "wb"); if(!ff) return 1; int w = htonl(dst->w); fwrite( &w, 1, 4, ff ); int h = htonl(dst->h); fwrite( &h, 1, 4, ff ); int format = htonl(target32bpp ? 2 : (perPixeAlpha ? 1 : 0)); fwrite( &format, 1, 4, ff ); for( int i = 0; i < dst->h; i++ ) { for( int ii = 0; ii < dst->w; ii++ ) { if( (!target32bpp) && ( * (Uint16 *) ((Uint8 *)dst->pixels + i*dst->pitch + ii*2) & 0x1 == 0 && ! perPixeAlpha) ) * (Uint16 *) ((Uint8 *)dst->pixels + i*dst->pitch + ii*2) = 0; fwrite( (Uint8 *)dst->pixels + i*dst->pitch + ii*(target32bpp?4:2), 1, (target32bpp?4:2), ff ); } } fclose(ff); return 0; }
int LancerJeu(gpointer *pData) { /* Cette fonction va appeler les fonctions d'initialisations de la SDL et lancer le jeu ou l'éditeur */ SDL_Renderer *pMoteurRendu = NULL; //Pointeurs sur le moteur de rendu SDL_Window *pFenetre = NULL; //Pointeur sur la fenêtre FMOD_CHANNEL *channelEnCours = NULL; //Pour le contrôle des différents canaux audios Sprite images[50] = {{NULL}, {0,0}}; //Tableau des images (textures + positions) TTF_Font *polices[10] = {NULL}; //Tableau des polices Options *pOptions = NULL; //Pointeur sur une structure Options FILE *pFichierErreur = fopen("ressources/ErreursLog.txt", "a"); //Pointeur sur le fichier d'erreurs SDL_Surface *surf = NULL; //Pointeur sur une surface SDL_Texture *pEcranChargement = NULL; //Pointeur sur une texture pour l'écran de chargement Animation anim[10]; //Tableau de structures Animation int erreur=0; //Code d'erreur Joueur *pJoueur = (Joueur *)g_slist_nth_data((GSList*)pData, 6); //On récupère le pointeur vers la structure Joueur dans la liste chaînée Sons *pSons = (Sons*)g_slist_nth_data((GSList*)pData, 4); //De même avec celui vers la structure Sons FMOD_SYSTEM *pMoteurSon = (FMOD_SYSTEM *)g_slist_nth_data((GSList*)pData, 3); //De même avec celui vers la structure FMOD_SYSTEM if(pFichierErreur == NULL) //Vérification { exit(EXIT_FAILURE); } /* On lit les options et on remplit la structure */ pOptions = DefinirOptions(); Initialisation(&pMoteurRendu, pFichierErreur, &pFenetre, pOptions); //Initialisation des principaux éléments (SDL, fenêtre, moteur de rendu) FMOD_System_GetChannel(pMoteurSon, M_MENU, &channelEnCours); //On met en pause la musique du menu FMOD_Channel_SetPaused(channelEnCours, true); if(BMusique) //S'il y a de la musique { FMOD_System_PlaySound(pMoteurSon, M_LOAD, pSons->music[M_LOAD], true, NULL); // On lit la musique de chargement FMOD_System_GetChannel(pMoteurSon, M_LOAD, &channelEnCours); FMOD_Channel_SetVolume(channelEnCours, (float)(Volume/100.0)); FMOD_Channel_SetPaused(channelEnCours, false); } /* On charge l'image de chargement et on vérifie */ surf = IMG_Load("ressources/img/load.png"); if (surf == NULL) { fprintf(pFichierErreur, "Erreur: impossible d'ouvrir le fichier ressources/img/load.png"); exit(EXIT_FAILURE); } /* On transforme la surface en texture pour l'affichage et on libère la mémoire occupée par la surface */ pEcranChargement = SDL_CreateTextureFromSurface(pMoteurRendu, surf); SDL_FreeSurface(surf); SDL_ShowCursor(false); //On masque le curseur pendant le jeu (on affichera un curseur personnalisé dans l'éditeur) /* On efface l'écran et on colle l'image de chargement */ SDL_SetRenderDrawColor(pMoteurRendu, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(pMoteurRendu); SDL_RenderCopy(pMoteurRendu, pEcranChargement, NULL, NULL); SDL_RenderPresent(pMoteurRendu); SDL_EventState(SDL_TEXTEDITING, SDL_DISABLE); //Désactivation des événements dont on a pas besoin. SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE); SDL_DisableScreenSaver(); //Désactivation de l'écran de veille. erreur = Chargements(images, pMoteurRendu, polices, anim); //On charge tout ! /* Traitement des éventuelles erreurs */ if(erreur == 1) { fprintf(pFichierErreur, "Erreur lors du chargement des images. Veuillez vérifier ressources\\img\\... \n"); exit(EXIT_FAILURE); } else if (erreur == 2) { fprintf(pFichierErreur, "Erreur lors du chargement des polices. Veuillez vérifier ressources\\fonts\\... \n"); exit(EXIT_FAILURE); } else if (erreur == 3) { fprintf(pFichierErreur, "Erreur lors du chargement des animations. Veuillez vérifier ressources\\anim\\... \n"); exit(EXIT_FAILURE); } if (BMusique) { FMOD_System_GetChannel(pMoteurSon, M_LOAD, &channelEnCours); //On arrête la musique du chargement FMOD_Channel_SetPaused(channelEnCours, true); FMOD_Sound_SetLoopCount(pSons->music[M_JEU], -1); // On active la lecture en boucle FMOD_System_PlaySound(pMoteurSon, M_JEU, pSons->music[M_JEU], true, NULL); // On lit la musique du jeu FMOD_System_GetChannel(pMoteurSon, M_JEU, &channelEnCours); FMOD_Channel_SetVolume(channelEnCours, (float)(Volume/100.0)); FMOD_Channel_SetPaused(channelEnCours, false); } /* On regarde si on a appelé la fonction en mode jeu ou en mode éditeur */ if (pJoueur->mode == MODE_CAMPAGNE) { InitialiserInfos(pOptions, pJoueur); //On définit les infos sur la partie en cours erreur = BouclePrincipale(pJoueur, images, anim, pMoteurRendu, pMoteurSon, pSons, polices); //Boucle du jeu if(erreur == JEU_FIN_ERREUR_CHARGEMENT) { MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL); } SauverMySql(pJoueur); //On sauvegarde l'avancée du joueur } else if(pJoueur->mode == MODE_PERSO) { InitialiserInfos(pOptions, pJoueur); //On définit les infos sur la partie en cours erreur = BouclePrincipale(pJoueur, images, anim, pMoteurRendu, pMoteurSon, pSons, polices); //Boucle du jeu if(erreur == JEU_FIN_ERREUR_CHARGEMENT) { MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL); } } else if (pJoueur->mode == MODE_EDITEUR) { erreur = Editeur(pMoteurRendu, images, pMoteurSon, pSons, polices, pJoueur); //On lance la boucle de l'éditeur if(erreur == JEU_FIN_ERREUR_CHARGEMENT) { MessageInformations("Erreur lors du chargement d'un niveau, consultez le fichier erreurs.txt", polices, pMoteurRendu, NULL); } } /* Libération de la mémoire */ LibererMemoire(pMoteurRendu, images, anim, polices, pFenetre, pOptions); fclose(pFichierErreur); //On ferme le fichier d'erreur return 0; }
int main ( int argc, char** argv ) { //make sure we have all the necessary arguments if( argc < 4 ) { fprintf(stderr, "Usage: %s (input texture filename) (texton neighborhood diameter) \n", argv[0]); fprintf(stderr, " (output size) [number threads] [r weight] [g weight] [b weight]\n"); fprintf(stderr, " Options in () are required, options in [] are optional.\n"); fprintf(stderr, " Note that if you want to set r weight, number threads must be set too.\n"); fprintf(stderr, " Input texture reading is handled by SDL_Image so the file can be tga, bmp, \n"); fprintf(stderr, " pnm, xpm, xcf, pcx, gif, jpg, lbm, or png.\n"); fprintf(stderr, " If [number threads] is set to 0, no threads will be generated. If it is set\n"); fprintf(stderr, " to 1, one thread will be generated to do all the work. Default is %d.\n", TEX_SYN_THREADS); fprintf(stderr, " [rgb weight] defines how much weight to give to the r, g, and b channels\n"); fprintf(stderr, " when calculating the similarity between two neighborhoods.\n"); fprintf(stderr, " These values are only used if rgb weighting is enabled in the code.\n"); fprintf(stderr, " Default Values are %f, %f, and %f respectively.\n", TEX_SYN_RED_WEIGHT, TEX_SYN_GREEN_WEIGHT, TEX_SYN_BLUE_WEIGHT); exit(EXIT_FAILURE); } //looks good, start loading values: //diameter textonDiameter = atoi(argv[2]); //make sure textonDiameter is odd, add one to it if it is even. if(textonDiameter % 2 == 0) textonDiameter++; //output size outputSize = atoi(argv[3]); //# threads if(argc >= 5) TEX_SYN_THREADS = atoi(argv[4]); //r weight if(argc >= 6) TEX_SYN_RED_WEIGHT = atof(argv[5]); //g weight if(argc >= 7) TEX_SYN_GREEN_WEIGHT = atof(argv[6]); //b weight if(argc >= 8) TEX_SYN_BLUE_WEIGHT = atof(argv[7]); debug("Will generate texture using file %s as a kernel and\n", argv[1]); debug("\tneighborhood size %d to generate unique %d x %d texture\n", textonDiameter, outputSize, outputSize); #ifdef TEX_SYN_USE_MULTIRESOLUTION debug("\twith a multi-resolution synthesis algorithm.\n"); #else debug("\twith a single-resolution synthesis algorithm.\n"); #endif if(TEX_SYN_THREADS == 0) debug("No threads will be generated to compare neighborhoods.\n"); else debug("%d threads will be generated to compare neighborhoods.\n", TEX_SYN_THREADS); #ifdef TEX_SYN_WEIGHTED_COLORS debug("When comparing neighborhoods, red, green, and blue will be weighted\n"); debug("\twith the values %f, %f, and %f respectively\n", TEX_SYN_RED_WEIGHT, TEX_SYN_GREEN_WEIGHT, TEX_SYN_BLUE_WEIGHT); #else debug("When comparing neighborhoods, red, green, and blue will not be weighted\n"); #endif //initialize SDL debug("Initializing SDL\n"); initSDL(outputSize, outputSize); // load an image debug("Loading Image %s\n", argv[1]); SDL_Surface *loadedTexture = IMG_Load(argv[1]); if (!loadedTexture) { printf("Unable to load image %s: %s\n", argv[1], SDL_GetError()); return 1; } //convert to be the same format as the display (32 bit) debug("Convert input texture to useable format\n"); inputTexture = SDL_DisplayFormat(loadedTexture); SDL_FreeSurface(loadedTexture); //run the texture synthesis SDL_Surface *outputTexture = textureSynthesis(inputTexture, outputSize, outputSize); //this is the texture that will be rendered on screen: SDL_Surface *renderTexture = outputTexture; // centre the bitmap on screen SDL_Rect dstrect; dstrect.x = (screen->w - renderTexture->w) / 2; dstrect.y = (screen->h - renderTexture->h) / 2; // program main loop debug("Entering display loop...\n"); while (!checkEvents()) { // DRAWING STARTS HERE // clear screen SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 255, 255, 255)); // draw bitmap SDL_BlitSurface(renderTexture, 0, screen, &dstrect); // DRAWING ENDS HERE // finally, update the screen :) SDL_Flip(screen); } // end main loop //save output texture char stripped[256]; char outName[256]; int start = 0, end = 0; for(int i = strlen(argv[1]) - 1; i>=0; i--) { if( argv[1][i] == '/' && i > start ) start = i + 1; if( argv[1][i] == '.' && i > end ) end = i; } int i = 0; for( int n = start; n < end; n++, i++) stripped[i] = argv[1][n]; stripped[i] = '\0'; sprintf(outName, "synthesizedTextures/%s-%dx%d,%d.bmp", stripped, outputSize, outputSize, textonDiameter); debug("Saving the output image to %s\n", outName); if(SDL_SaveBMP(outputTexture, outName) < 0) { fprintf(stderr, "ERROR saving output texture to file %s: %s\n", outName, SDL_GetError()); exit(EXIT_FAILURE); } debug("Cleaning up\n"); // free loaded bitmap SDL_FreeSurface(inputTexture); SDL_FreeSurface(outputTexture); //note, sdl_quit doesn't need to be here because it's told to run //on quit in the init function. return 0; }
int main(int argc, char* argv[]) { const unsigned int windowWidth = 640; const unsigned int windowHeight = 480; SDL_Window* pWindow = NULL; // Ecran principal SDL_Surface* pImage = NULL; // Logo char mustContinue = 1; // Indicateur boolean pour la boucle principale int imgFlags = IMG_INIT_JPG|IMG_INIT_PNG|IMG_INIT_TIF; // Flags pour charger le support du JPG, PNG et TIF const char* imagePath = "./data/logo.jpg"; SDL_Rect blitDestination; TTF_Font* pFont = NULL; const char* fontPath = "./data/font.ttf"; SDL_Color fontColor = {99, 140, 222}; SDL_Surface* pFontSurface = NULL; SDL_Rect texteDestination; // Demarre SDL if ( SDL_Init(SDL_INIT_VIDEO) == -1 ) { fprintf(stderr,"Erreur lors de l'initialisation de la SDL\n"); return -1; } if ( IMG_Init(imgFlags) != imgFlags ) { fprintf(stderr,"Erreur lors de l'initialisation de la SDL_image : '%s'\n",IMG_GetError()); cleanup(); return -1; } if ( TTF_Init() == -1 ) { fprintf(stderr,"Erreur lors de l'initialisation de la SDL_TTF : '%s'\n",TTF_GetError()); cleanup(); return -1; } /* Création de la fenêtre */ pWindow = SDL_CreateWindow("Ma première application SDL2",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN); if ( pWindow != NULL ) { pImage = IMG_Load(imagePath); if ( pImage == NULL ) { fprintf(stderr,"Erreur de chargement de l'image %s : %s\n",imagePath,IMG_GetError()); SDL_DestroyWindow(pWindow); cleanup(); return -3; } // Charge la police pFont = TTF_OpenFont(fontPath,32); if ( pFont == NULL ) { fprintf(stderr,"Erreur de chargement de la police %s : %s\n",fontPath,TTF_GetError()); SDL_DestroyWindow(pWindow); cleanup(); return -3; } // Genere la SDL_Surface a partir de la police pFontSurface = TTF_RenderText_Solid(pFont,"Developpez.com",fontColor); if ( !pFontSurface ) { fprintf(stderr,"Erreur pour generer le texte '%s'\n",TTF_GetError()); SDL_DestroyWindow(pWindow); cleanup(); return -4; } // Une fois l'image chargée, nous pouvons calculer une position relative à celle-ci // Nous centrons l'image dans la fenêtre blitDestination.x = windowWidth/2 - pImage->w/2; blitDestination.y = windowHeight/2 - pImage->h/2; blitDestination.w = pImage->w; blitDestination.h = pImage->h; // Nous avons notre surface pour le texte donc nous calculons la position relative // Le texte est à un quart de la hauteur de l'ecran texteDestination.x = windowWidth/2 - pFontSurface->w/2; texteDestination.y = windowHeight/4; texteDestination.w = pFontSurface->w; texteDestination.h = pFontSurface->h; // Boucle principale while ( mustContinue ) { // Affiche le logo au centre de la fenêtre if ( SDL_BlitSurface(pImage,NULL,SDL_GetWindowSurface(pWindow),&blitDestination) != 0 ) { fprintf(stderr,"Erreur de copie de la surface sur l'écran\n"); mustContinue=0; } // Affiche le texte if ( SDL_BlitSurface(pFontSurface,NULL,SDL_GetWindowSurface(pWindow),&texteDestination) != 0 ) { fprintf(stderr,"Erreur de copie du texte sur l'écran\n"); mustContinue=0; } SDL_UpdateWindowSurface(pWindow); SDL_Event event; SDL_WaitEvent(&event); // Detecte si on clique sur la croix if( event.type == SDL_QUIT ) { //On quitte le programme mustContinue = 0; } // Detecte si une touche est appuyee else if( event.type == SDL_KEYDOWN ) { if ( event.key.keysym.sym == SDLK_ESCAPE ) { mustContinue = 0; } } } SDL_DestroyWindow(pWindow); SDL_FreeSurface(pFontSurface); TTF_CloseFont(pFont); SDL_FreeSurface(pImage); } else { fprintf(stderr,"Erreur de création de la fenêtre: %s\n",SDL_GetError()); cleanup(); return -3; } cleanup(); return 0; }
int main( int argc, char* args[] ) { //Initialize init(); update=new Timer(); update->start(); SDL_Surface * game_over = IMG_Load( "game_over.png" ); Background background(screen); Player player(screen); Enemy enemy(screen); Enemy enemy2(screen); Llama Llama(screen); SDL_Event event; //Quit flag bool quit = false; while( quit == false ) { //If there's an event to handle if( SDL_PollEvent( &event ) ) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { //Set the proper message surface switch( event.key.keysym.sym ) { case SDLK_ESCAPE: quit = true; break; case SDLK_UP: if (! player.isJumping){ player.jump(); break; } } } //If the user has Xed out the window else if( event.type == SDL_QUIT ) { //Quit the program quit = true; } } background.logic(); player.logic(); enemy.logic(); enemy2.logic2(); Llama.logic(); if(player.x-enemy.x<50 && player.x-enemy.x>-50 && player.y-enemy.y<50 && player.y-enemy.y>-50 or player.x-Llama.x<50 && player.x-Llama.x>-50 && player.y-Llama.y<50 && player.y-Llama.y>-50) { player.perder(); } if(player.x-enemy2.x<50 && player.x-enemy2.x>-50 && player.y-enemy2.y<50 && player.y-enemy2.y>-50 or player.x-Llama.x<50 && player.x-Llama.x>-50 && player.y-Llama.y<50 && player.y-Llama.y>-50) { player.perder(); } if (player.murio) break; background.render(); player.render(); enemy.render(); enemy2.render(); Llama.render(); frameCap(); //Update the screen if( SDL_Flip( screen ) == -1 ) { return 1; } } while( quit == false ) { //If there's an event to handle if( SDL_PollEvent( &event ) ) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { //Set the proper message surface switch( event.key.keysym.sym ) { case SDLK_ESCAPE: quit = true; break; } } //If the user has Xed out the window else if( event.type == SDL_QUIT ) { //Quit the program quit = true; } } //SDL_Rect offset; offset.x = 0; offset.y = 0; SDL_BlitSurface( game_over, NULL, screen, &offset ); frameCap(); //Update the screen if( SDL_Flip( screen ) == -1 ) { return 1; } } //SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { printf ("\nDemarage du programme\n"); // Declaration de variables. SDL_Surface *ecran = NULL, *Fond = NULL, *titre = NULL, *texte1 = NULL, *texte2 = NULL, *texte3 = NULL, *texte4 = NULL; SDL_Rect positionFond; SDL_Rect positiontitre; SDL_Rect positiontexte1; SDL_Rect positiontexte2; SDL_Rect positiontexte3; SDL_Rect positiontexte4; SDL_Event event; positionFond.x = 0; positionFond.y = 0; TTF_Font *police = NULL, *police1 = NULL; SDL_Color blanc = {255, 255, 255}; int continuer = 1; int enpause = 0; struct options options = {0}; // Fin de la declaration de variables SDL_Init(SDL_INIT_VIDEO); TTF_Init(); SDL_WM_SetCaption("CHESS", NULL); SDL_WM_SetIcon(IMG_Load("img/icon.gif"), NULL); ecran = SDL_SetVideoMode(400, 400, 32, SDL_HWSURFACE); Fond = IMG_Load("img/background.png"); police = TTF_OpenFont("img/police.ttf", 15); police1 = TTF_OpenFont("img/police.ttf", 50); chargeroption (&options); while (continuer) { SDL_BlitSurface(Fond, NULL, ecran, &positionFond); if ( enpause == 0) { titre = TTF_RenderText_Blended(police1, "CHESS", blanc); } else if ( enpause == 1 ) { titre = TTF_RenderText_Blended(police1, "PAUSE", blanc); } positiontitre.x = (( 400 - titre->w) / 2); positiontitre.y = 20; SDL_BlitSurface(titre, NULL, ecran, &positiontitre); texte1 = TTF_RenderText_Blended(police, "[A] Nouvelle partie", blanc); texte2 = TTF_RenderText_Blended(police, "[Z] Continuer", blanc); texte3 = TTF_RenderText_Blended(police, "[E] Options", blanc); texte4 = TTF_RenderText_Blended(police, "[R] Quitter", blanc); positiontexte1.x = (( 400 - texte1->w) / 2); positiontexte1.y = 100; positiontexte2.x = positiontexte1.x; positiontexte2.y = 150; positiontexte3.x = positiontexte1.x; positiontexte3.y = 200; positiontexte4.x = positiontexte1.x; positiontexte4.y = 250; SDL_BlitSurface(texte1, NULL, ecran, &positiontexte1); SDL_BlitSurface(texte2, NULL, ecran, &positiontexte2); SDL_BlitSurface(texte3, NULL, ecran, &positiontexte3); SDL_BlitSurface(texte4, NULL, ecran, &positiontexte4); SDL_Flip(ecran); SDL_WaitEvent(&event); // Récupèration de l'évènement dans event switch(event.type) // Test du type d'évènement { case SDL_QUIT: // Si c'est un évènement de type "Quitter" continuer = 0; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: // ECHAP continuer = 0; break; case SDLK_SPACE: // (SPACE) ==> Jouer if (options.o2 > 0) {printf ("\nLancement d'une nouvelle partie.\n"); } jouer(ecran, options, &enpause, 0); break; case SDLK_o: //(O) ==> Options option(ecran, &options); break; case SDLK_a: // (A) ==> Jouer if (options.o2 > 0) {printf ("\nLancement d'une nouvelle partie.\n"); } jouer(ecran, options, &enpause, 0); break; case SDLK_z: // (E) ==> Continuer if (options.o2 > 0) {printf ("\nReprise d'une partie en cours.\n"); } jouer(ecran, options, &enpause, 1); break; case SDLK_e: // (E) ==> Option option(ecran, &options); break; case SDLK_r: //(R) ==> Quitter if (options.o2 > 0) { printf ("\nFermeture du programme.\n"); } continuer = 0; break; } break; } } SDL_FreeSurface(Fond); SDL_Quit(); return EXIT_SUCCESS; }
void loadBackground(SDL_Renderer* renderer, Gamestate* game, SDL_Surface* surface) { surface = IMG_Load("images/terraria_background.png"); game->background = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } // void loadBackground()
int main(void) { // int good = 0; // int numeroMap = 0; // do{ // printf("Quelle map?\n"); // printf("1 - Original\n"); // printf("2 - Hard\n"); // printf("3 - Lol\n"); // printf("4 - Rez De chaussez Aile Sud Telecom Nancy\n"); // scanf("%d", &numeroMap); // switch(numeroMap){ // case 1: // loadMap("../projec/map/original.map"); // good = 1; // break; // case 2: // loadMap("../projec/map/hard.map"); // good = 1; // break; // case 3: // loadMap("../projec/map/maplol.map"); // good = 1; // break; // case 4: // loadMap("../projec/map/rdastn.map"); // good = 1; // break; // case 42: // loadMap("../projec/map/rdastn.map"); // good = 1; // setQ(); // break; // } // }while(!good); //Create SDL objects SDL_Window *window = 0; SDL_Event event; SDL_Renderer *renderer = 0; int terminate = 0; //Initialise SDL if(SDL_Init(SDL_INIT_VIDEO) < 0){ printf("Error with SDL : %s\n", SDL_GetError()); SDL_Quit(); return EXIT_FAILURE; } window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 544, 344, SDL_WINDOW_SHOWN); terminate = 0; renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_Surface *menu = IMG_Load("../projec/texture/menu/menu.jpg"); SDL_Texture *menuTexture = SDL_CreateTextureFromSurface(renderer, menu); SDL_FreeSurface(menu); SDL_RenderClear(renderer); int x, y; while(!terminate){ SDL_Rect dest = {0, 0, 544, 344}; SDL_RenderCopy(renderer, menuTexture, NULL, &dest); SDL_RenderPresent(renderer); SDL_WaitEvent(&event); switch(event.type){ case SDL_MOUSEBUTTONDOWN: x = event.motion.x; y = event.motion.y; if(x >= 57 && x <= (57+54) && y >= 94 && y <= (94 + 74)){ loadMap("../projec/map/original.map"); terminate = 1; } if(x >= 124 && x <= (124+53) && y >= 208 && y <= (208 + 73)){ loadMap("../projec/map/hard.map"); terminate = 1; } if(x >= 221 && x <= (221+59) && y >= 95 && y <= (95 + 80)){ loadMap("../projec/map/maplol.map"); terminate = 1; } if(x >= 311 && x <= (311+63) && y >= 208 && y <= (208 + 76)){ loadMap("../projec/map/rdastn.map"); terminate = 1; } if(x >= 350 && x <= (350+124) && y >= 73 && y <= (73 + 109)){ loadMap("../projec/map/rdastn.map"); terminate = 1; setQ(); } break; } SDL_Delay(1000 / FPS); } SDL_DestroyTexture(menuTexture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); //Search the pacman on the map and create him Pacman *pacman = getPacmanInstance(); unsigned int initialX = pacman->x; unsigned int initialY = pacman->y; Map *map = getMapInstance(); //If the pacman is not found if(!pacman){ printf("Pacman not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Pacman found !\n"); Ghost *clyde = searchAndCreateGhost(CLYDE); if(!clyde){ printf("Clyde not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Clyde found !\n"); Ghost *blinky = searchAndCreateGhost(BLINKY); if(!blinky){ printf("Blinky not found on map\n"); freeMap(map); freeGhost(clyde); exit(EXIT_FAILURE); } printf("Blinky found !\n"); Ghost *inky = searchAndCreateGhost(INKY); if(!inky){ printf("Inky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); exit(EXIT_FAILURE); } printf("Inky found !\n"); Ghost *pinky = searchAndCreateGhost(PINKY); if(!pinky){ printf("Pinky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); exit(EXIT_FAILURE); } printf("Pinky found !\n"); printf("SDL initialisation\n"); if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1){ printf("%s", Mix_GetError()); } Mix_Music *music = NULL; music = Mix_LoadMUS("../projec/pacman.wav"); if(!music){ printf("Erreur de chargement de la musique %s \n", Mix_GetError()); }else{ Mix_VolumeMusic(MIX_MAX_VOLUME); Mix_PlayMusic(music, -1); } if(TTF_Init() == -1){ printf("Error during TTF initialization : %s\n", TTF_GetError()); } TTF_Font *police = NULL; police = TTF_OpenFont("../projec/monof.ttf", 65); if(!police){ printf("Error during font load : %s\n", TTF_GetError()); } SDL_Color color = { 255, 255, 255, 255}; //Create the window window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TILE_SIZE * map->col, TILE_SIZE * map->row + TILE_SIZE, SDL_WINDOW_SHOWN); //If there is an error if(window == 0){ printf("Error during window creation : %s \n", SDL_GetError()); SDL_Quit(); freeMap(map); return EXIT_FAILURE; } int j; printf("SDL init success\n"); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //NEED gerer erreurs loadTextures(renderer); SDL_Surface *score = TTF_RenderText_Solid(police, "Score : ", color); SDL_Texture *scoreT = SDL_CreateTextureFromSurface(renderer, score); SDL_FreeSurface(score); char scoreString[15]; SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_Surface *scoreN; SDL_Texture *scoreTN; int open = 0; int konami[10] = {0,0,0,0,0,0,0,0,0,0}; //Infinite loop until we want to stop the game terminate = 0; while(!terminate){ SDL_Rect dest2 = {map->row * TILE_SIZE / 6, map->row * TILE_SIZE, map->row * TILE_SIZE / 15, 20}; sprintf(scoreString, "%d", pacman->point); scoreN = TTF_RenderText_Solid(police, scoreString, color); scoreTN = SDL_CreateTextureFromSurface(renderer, score); renderMap(renderer); open = renderPacman(open, renderer); renderClyde(clyde, renderer); renderBlinky(blinky, renderer); renderPinky(pinky, renderer); renderInky(inky, renderer); changeDirectionGhost(blinky); changeDirectionGhost(clyde); changeDirectionGhost(inky); changeDirectionGhost(pinky); SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_RenderCopy(renderer, scoreTN, NULL, &dest2); SDL_RenderPresent(renderer); //Event handling SDL_PollEvent(&event); switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.scancode){ case SDL_SCANCODE_UP: setPacmanDirection(NORTH); if(konami[0]){ if(konami[1]){ for(j = 0 ; j < 10 ; j++){ konami[j] = 0; } // printf("Déjà deux\n"); }else{ konami[1] = 1; } }else{ konami[0] = 1; } break; case SDL_SCANCODE_DOWN: setPacmanDirection(SOUTH); break; case SDL_SCANCODE_RIGHT: setPacmanDirection(EAST); break; case SDL_SCANCODE_LEFT: setPacmanDirection(WEST); break; default: break; } break; } terminate = update(clyde, blinky, inky, pinky); if(terminate){ if(pacman->life > 0 ){ pacman->life--; terminate = 0; pacman->x = initialX; pacman->y = initialY; } } if(event.window.event == SDL_WINDOWEVENT_CLOSE){ terminate = 1; } SDL_Delay(1000 / FPS); SDL_DestroyTexture(scoreTN); SDL_FreeSurface(scoreN); } printf("Score final : %d\n", pacman->point); Mix_FreeMusic(music); Mix_CloseAudio(); freeTextures(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); SDL_DestroyTexture(scoreT); freePacman(); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); freeGhost(pinky); freeMap(); TTF_CloseFont(police); TTF_Quit(); return EXIT_SUCCESS; }
SDL_Surface* Graphics::loadImage(const std::string &filePath) { if (this->_spriteSheets.count(filePath) == 0) { this->_spriteSheets[filePath] = IMG_Load(filePath.c_str()); } return this->_spriteSheets[filePath]; }
Sprite *sprite_load(char *filename, int frameW, int frameH) { int i; SDL_Surface *temp; if(!sprite_list) { slog("error: using sprite system uninitialized"); return NULL; } /*first search to see if the requested sprite image is alreday loaded*/ for(i = 0; i < SPRITE_MAX; i++) { if (sprite_list[i].refCount == 0) { continue; } if(strcmp(filename, sprite_list[i].filename) == 0) { sprite_list[i].refCount++; return &sprite_list[i]; } } /*makesure we have the room for a new sprite*/ if(sprite_num + 1 >= SPRITE_MAX) { slog("Maximum Sprites Reached.\n"); exit(1); } sprite_num++; /*if its not already in memory, then load it.*/ for(i = 0; i <= sprite_num; i++) { if(!sprite_list[i].refCount) break; } temp = IMG_Load(filename); if(!temp) { slog("unable to load a vital sprite: %s\n", SDL_GetError()); exit(0); } /*sets a transparent color for blitting.*/ //SDL_SetColorKey(temp, SDL_TRUE, SDL_MapRGB(temp->format, 255,255,255)); sprite_list[i].image = SDL_CreateTextureFromSurface(graphics_renderer, temp); SDL_FreeSurface(temp); /*then copy the given information to the sprite*/ strcpy(sprite_list[i].filename, filename); /*now sprites don't have to be 16 frames per line, but most will be.*/ sprite_list[i].fpl = 16; sprite_list[i].frameSize.x = frameW; sprite_list[i].frameSize.y = frameH; sprite_list[i].refCount++; return &sprite_list[i]; }
void ZCursor::Init() { int i,j; char filename_c[500]; SDL_Surface *temp_surface; //load up the null cursors for(j=0;j<4;j++) { sprintf(filename_c, "assets/cursors/cursor_null_n%02d.png", j); cursor[CURSOR_C][0][j].LoadBaseImage(filename_c); sprintf(filename_c, "assets/cursors/placed_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[PLACED_C][0][j].LoadBaseImage(temp_surface, false); cursor[PLACE_C][0][j].LoadBaseImage(temp_surface); //cursor[PLACED_C][0][j] = IMG_Load_Error(filename_c); //cursor[PLACE_C][0][j] = cursor[PLACED_C][0][j]; sprintf(filename_c, "assets/cursors/attacked_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[ATTACKED_C][0][j].LoadBaseImage(temp_surface, false); cursor[ATTACK_C][0][j].LoadBaseImage(temp_surface); //cursor[ATTACKED_C][0][j] = IMG_Load_Error(filename_c); //cursor[ATTACK_C][0][j] = cursor[ATTACKED_C][0][j]; sprintf(filename_c, "assets/cursors/grabbed_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[GRABBED_C][0][j].LoadBaseImage(temp_surface, false); cursor[GRAB_C][0][j].LoadBaseImage(temp_surface); //cursor[GRABBED_C][0][j] = IMG_Load_Error(filename_c); //cursor[GRAB_C][0][j] = cursor[GRABBED_C][0][j]; sprintf(filename_c, "assets/cursors/grenaded_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[GRENADED_C][0][j].LoadBaseImage(temp_surface, false); cursor[GRENADE_C][0][j].LoadBaseImage(temp_surface); //cursor[GRENADED_C][0][j] = IMG_Load_Error(filename_c); //cursor[GRENADE_C][0][j] = cursor[GRENADED_C][0][j]; sprintf(filename_c, "assets/cursors/repaired_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[REPAIRED_C][0][j].LoadBaseImage(temp_surface, false); cursor[REPAIR_C][0][j].LoadBaseImage(temp_surface); //cursor[REPAIRED_C][0][j] = IMG_Load_Error(filename_c); //cursor[REPAIR_C][0][j] = cursor[REPAIRED_C][0][j]; sprintf(filename_c, "assets/cursors/entered_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[ENTERED_C][0][j].LoadBaseImage(temp_surface, false); cursor[ENTER_C][0][j].LoadBaseImage(temp_surface); //cursor[ENTERED_C][0][j] = IMG_Load_Error(filename_c); //cursor[ENTER_C][0][j] = cursor[ENTERED_C][0][j]; sprintf(filename_c, "assets/cursors/exited_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[EXITED_C][0][j].LoadBaseImage(temp_surface, false); cursor[EXIT_C][0][j].LoadBaseImage(temp_surface); //cursor[EXITED_C][0][j] = IMG_Load_Error(filename_c); //cursor[EXIT_C][0][j] = cursor[EXITED_C][0][j]; sprintf(filename_c, "assets/cursors/cannoned_n%02d.png", j); temp_surface = IMG_Load(filename_c); cursor[CANNONED_C][0][j].LoadBaseImage(temp_surface, false); cursor[CANNON_C][0][j].LoadBaseImage(temp_surface); //cursor[CANNONED_C][0][j] = IMG_Load_Error(filename_c); //cursor[CANNON_C][0][j] = cursor[CANNONED_C][0][j]; } for(i=1;i<MAX_TEAM_TYPES;i++) for(j=0;j<4;j++) { sprintf(filename_c, "assets/cursors/cursor_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[CURSOR_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[CURSOR_C][ZTEAM_BASE_TEAM][j], cursor[CURSOR_C][i][j], filename_c); sprintf(filename_c, "assets/cursors/place_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[PLACE_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[PLACE_C][ZTEAM_BASE_TEAM][j], cursor[PLACE_C][i][j], filename_c); //cursor[PLACED_C][i][j] = cursor[PLACED_C][0][j]; cursor[PLACED_C][i][j].LoadBaseImage(cursor[PLACED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/attack_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[ATTACK_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[ATTACK_C][ZTEAM_BASE_TEAM][j], cursor[ATTACK_C][i][j], filename_c); //cursor[ATTACKED_C][i][j] = cursor[ATTACKED_C][0][j]; cursor[ATTACKED_C][i][j].LoadBaseImage(cursor[ATTACKED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/grab_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[GRAB_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[GRAB_C][ZTEAM_BASE_TEAM][j], cursor[GRAB_C][i][j], filename_c); //cursor[GRABBED_C][i][j] = cursor[GRABBED_C][0][j]; cursor[GRABBED_C][i][j].LoadBaseImage(cursor[GRABBED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/grenade_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[GRENADE_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[GRENADE_C][ZTEAM_BASE_TEAM][j], cursor[GRENADE_C][i][j], filename_c); //cursor[GRENADED_C][i][j] = cursor[GRENADED_C][0][j]; cursor[GRENADED_C][i][j].LoadBaseImage(cursor[GRENADED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/repair_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[REPAIR_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[REPAIR_C][ZTEAM_BASE_TEAM][j], cursor[REPAIR_C][i][j], filename_c); //cursor[REPAIRED_C][i][j] = cursor[REPAIRED_C][0][j]; cursor[REPAIRED_C][i][j].LoadBaseImage(cursor[REPAIRED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/nono_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[NONO_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[NONO_C][ZTEAM_BASE_TEAM][j], cursor[NONO_C][i][j], filename_c); sprintf(filename_c, "assets/cursors/cannon_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[CANNON_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[CANNON_C][ZTEAM_BASE_TEAM][j], cursor[CANNON_C][i][j], filename_c); //cursor[CANNONED_C][i][j] = cursor[CANNONED_C][0][j]; cursor[CANNONED_C][i][j].LoadBaseImage(cursor[CANNONED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/enter_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[ENTER_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[ENTER_C][ZTEAM_BASE_TEAM][j], cursor[ENTER_C][i][j], filename_c); //cursor[ENTERED_C][i][j] = cursor[ENTERED_C][0][j]; cursor[ENTERED_C][i][j].LoadBaseImage(cursor[ENTERED_C][0][j].GetBaseSurface() ,false); sprintf(filename_c, "assets/cursors/exit_%s_n%02d.png", team_type_string[i].c_str(), j); //cursor[EXIT_C][i][j].LoadBaseImage(filename_c);// = IMG_Load_Error(filename_c); ZTeam::LoadZSurface(i, cursor[EXIT_C][ZTEAM_BASE_TEAM][j], cursor[EXIT_C][i][j], filename_c); //cursor[EXITED_C][i][j] = cursor[EXITED_C][0][j]; cursor[EXITED_C][i][j].LoadBaseImage(cursor[EXITED_C][0][j].GetBaseSurface() ,false); } }
void jouer(SDL_Surface* ecran){ SDL_Surface *mario[4] = {NULL}; SDL_Surface *mur = NULL, *caisse = NULL, *caisseOK = NULL, *objectif = NULL, *marioActuel = NULL; SDL_Rect position, positionJoueur; SDL_Event event; char continuer = 1, objectifsRestants = 0, i = 0, j = 0; char carte[NB_BLOCS_LARGEUR][NB_BLOCS_HAUTEUR] = {0}; mur = IMG_Load("images/mur.jpg"); caisse = IMG_Load("images/caisse.jpg"); caisseOK = IMG_Load("images/caisse_ok.jpg"); objectif = IMG_Load("images/objectif.png"); mario[BAS] = IMG_Load("images/mario_bas.gif"); mario[GAUCHE] = IMG_Load("images/mario_gauche.gif"); mario[HAUT] = IMG_Load("images/mario_haut.gif"); mario[DROITE] = IMG_Load("images/mario_droite.gif"); marioActuel = mario[BAS]; if (!chargerNiveau(carte)) exit(EXIT_FAILURE); for (i = 0; i < NB_BLOCS_LARGEUR; i++) { for (j = 0; j < NB_BLOCS_LARGEUR; j++) { if (carte[i][j] == MARIO) { positionJoueur.x = i; positionJoueur.y = j; carte[i][j] = VIDE; } } } SDL_EnableKeyRepeat(100, 100); while (continuer) { SDL_WaitEvent(&event); switch (event.type) { case SDL_QUIT: continuer = 0; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: continuer = 0; break; case SDLK_UP: marioActuel = mario[HAUT]; deplacerJoueur(carte, &positionJoueur, HAUT); break; case SDLK_DOWN: marioActuel = mario[BAS]; deplacerJoueur(carte, &positionJoueur, BAS); break; case SDLK_RIGHT: marioActuel = mario[DROITE]; deplacerJoueur(carte, &positionJoueur, DROITE); break; case SDLK_LEFT: marioActuel = mario[GAUCHE]; deplacerJoueur(carte, &positionJoueur, GAUCHE); break; default: break; } break; default: break; } SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255)); objectifsRestants = 0; for (i = 0; i < NB_BLOCS_LARGEUR; i++) { for (j = 0; j < NB_BLOCS_HAUTEUR; j++) { position.x = i * TAILLE_BLOC; position.y = j * TAILLE_BLOC; switch (carte[i][j]) { case MUR: SDL_BlitSurface(mur, NULL, ecran, &position); break; case CAISSE: SDL_BlitSurface(caisse, NULL, ecran, &position); break; case CAISSE_OK: SDL_BlitSurface(caisseOK, NULL, ecran, &position); break; case OBJECTIF: SDL_BlitSurface(objectif, NULL, ecran, &position); objectifsRestants = 1; break; } } } if (!objectifsRestants) continuer = 0; position.x = positionJoueur.x * TAILLE_BLOC; position.y = positionJoueur.y * TAILLE_BLOC; SDL_BlitSurface(marioActuel, NULL, ecran, &position); SDL_Flip(ecran); } SDL_EnableKeyRepeat(0, 0); SDL_FreeSurface(mur); SDL_FreeSurface(caisse); SDL_FreeSurface(caisseOK); SDL_FreeSurface(objectif); for (i = 0; i < 4; i++) { SDL_FreeSurface(mario[i]); } }
bool TEXTURE::Load(const std::string & path, const TEXTUREINFO & info, std::ostream & error) { if (id) { error << "Tried to double load texture " << path << std::endl; return false; } if (path.empty() && !info.surface) { error << "Tried to load a texture with an empty name" << std::endl; return false; } id = 0; if (info.cube) { cube = true; return LoadCube(path, info, error); } SDL_Surface * orig_surface = info.surface; if (!orig_surface) { orig_surface = IMG_Load(path.c_str()); if (!orig_surface) { error << "Error loading texture file: " << path << std::endl; return false; } } SDL_Surface * texture_surface(orig_surface); if (orig_surface) { origw = texture_surface->w; origh = texture_surface->h; //scale to power of two if necessary bool norescale = (IsPowerOfTwo(orig_surface->w) && IsPowerOfTwo(orig_surface->h)) || (info.npot && (GLEW_VERSION_2_0 || GLEW_ARB_texture_non_power_of_two)); if (!norescale) { int newx = orig_surface->w; int maxsize = 2048; if (!IsPowerOfTwo(orig_surface->w)) { for (newx = 1; newx <= maxsize && newx <= orig_surface->w; newx = newx * 2) { } } int newy = orig_surface->h; if (!IsPowerOfTwo(orig_surface->h)) { for (newy = 1; newy <= maxsize && newy <= orig_surface->h; newy = newy * 2) { } } float scalew = ((float)newx+0.5) / orig_surface->w; float scaleh = ((float)newy+0.5) / orig_surface->h; SDL_Surface * pot_surface = zoomSurface (orig_surface, scalew, scaleh, SMOOTHING_ON); assert(IsPowerOfTwo(pot_surface->w)); assert(IsPowerOfTwo(pot_surface->h)); SDL_FreeSurface(orig_surface); orig_surface = pot_surface; texture_surface = orig_surface; } //scale texture down if necessary scale = Scale(info.size, orig_surface->w, orig_surface->h); if (scale < 1.0) { texture_surface = zoomSurface (orig_surface, scale, scale, SMOOTHING_ON); } //store dimensions w = texture_surface->w; h = texture_surface->h; GenTexture(texture_surface, info, id, alpha, error); } //free the texture surface separately if it's a scaled copy of the original if (texture_surface != orig_surface && texture_surface) { SDL_FreeSurface(texture_surface); } //free the original surface if it's not a custom surface (used for the track map) if (!info.surface && orig_surface) { SDL_FreeSurface(orig_surface); } return true; }
Surface::Surface(const char* pFilename) { // Create the surface from a loaded image file. mSurface = IMG_Load(pFilename); }
int Menu ( ) { bool salir = false; SDL_Event evento; char opcion; // 0:JUGAR, 1:CONTINUAR_PARTIDA, 2:SALIR // cargamos la imagen del puntero, y creamos la superficie y el SDL_Rect correspondientes SDL_Rect *posPuntero = new SDL_Rect; SDL_Surface *imagenPuntero; imagenPuntero = IMG_Load ( (ConfigManager::gamedataPath+string("punteromenu.png")).c_str() ); posPuntero->h = imagenPuntero->h; posPuntero->w = imagenPuntero->w; posPuntero->x = screen->w / 2 - imagenPuntero->w / 2 + ConfigManager::H_RES / 4; SDL_SetColorKey ( imagenPuntero, SDL_SRCCOLORKEY, SDL_MapRGB ( screen->format, 0, 0, 0 ) ); // cargamos la imagen de fondo del men˙ y creamos la superficie correspondiente SDL_Surface * fondoMenu = IMG_Load( (ConfigManager::gamedataPath+string("mainmenu.jpg")).c_str()); SDL_Rect *rectFondoMenu = new SDL_Rect; rectFondoMenu->x = ConfigManager::H_RES/2 - fondoMenu->w/2; rectFondoMenu->y = ConfigManager::V_RES/2 - fondoMenu->h/2; rectFondoMenu->w = fondoMenu->w; rectFondoMenu->h = fondoMenu->h; // realizamos todo el trabajo de las fuentes de letras TTF TTF_Font *fuenteMenu; if ( !( fuenteMenu = TTF_OpenFont ( (ConfigManager::gamedataPath+string("FreeSerifBold.ttf")).c_str(),42 ) ) ) { printf ( "Error, no se pudo abrir la fuente de letras.\n" ); exit ( 3 ); } SDL_Color colorLetras; colorLetras.r = 255; colorLetras.g = 255; colorLetras.b = 255; colorLetras.unused=0; SDL_Rect *rectTitulo = new SDL_Rect; SDL_Rect *rectOpcion1 = new SDL_Rect; SDL_Rect *rectOpcion2 = new SDL_Rect; SDL_Rect *rectOpcion3 = new SDL_Rect; TTF_SetFontStyle ( fuenteMenu, TTF_STYLE_UNDERLINE ); SDL_Surface *tituloMenu = TTF_RenderText_Solid ( fuenteMenu, "GeekFibres - Menú Principal", colorLetras ); TTF_SetFontStyle ( fuenteMenu, TTF_STYLE_NORMAL ); SDL_Surface *menuOpcion1 = TTF_RenderText_Solid ( fuenteMenu, "Empezar partida", colorLetras ); SDL_Surface *menuOpcion2 = TTF_RenderText_Solid ( fuenteMenu, "Editar mundo", colorLetras ); SDL_Surface *menuOpcion3 = TTF_RenderText_Solid ( fuenteMenu, "Salir", colorLetras ); rectTitulo->h = tituloMenu->h; rectTitulo->w = tituloMenu->w; rectTitulo->x = ConfigManager::H_RES / 3; rectTitulo->y = ConfigManager::V_RES / 10; rectOpcion1->h = menuOpcion1->h; rectOpcion1->w = menuOpcion1->w; rectOpcion1->x = ConfigManager::H_RES / 2 - rectOpcion1->w / 2 + ConfigManager::H_RES / 4; rectOpcion1->y = int ( 2 * ConfigManager::V_RES / 7.0 ); rectOpcion2->h = menuOpcion2->h; rectOpcion2->w = menuOpcion2->w; rectOpcion2->x = ConfigManager::H_RES / 2 - rectOpcion2->w / 2 + ConfigManager::H_RES / 4; rectOpcion2->y = int ( 3 * ConfigManager::V_RES / 7.0 ); rectOpcion3->h = menuOpcion3->h; rectOpcion3->w = menuOpcion3->w; rectOpcion3->x = ConfigManager::H_RES / 2 - rectOpcion3->w / 2 + ConfigManager::H_RES / 4; rectOpcion3->y = int ( 4 * ConfigManager::V_RES / 7.0 ); // bucle principal del menu opcion = 0; int cuentaCiclos = 0; const Uint32 tiempoPorBucle = 1000/50; Uint32 tiempoInicioBucle; while ( !salir ) { tiempoInicioBucle = SDL_GetTicks ( ); // Hacemos el control del teclado while ( SDL_PollEvent ( &evento ) ) { switch ( evento.type ) { case SDL_KEYDOWN: switch ( evento.key.keysym.sym ) { case SDLK_UP: opcion--; break; case SDLK_DOWN: opcion++; break; case SDLK_ESCAPE: opcion = 2; salir = true; break; case SDLK_RETURN: case SDLK_SPACE: salir = true; break; default: break; } break; default: break; } } // controlamos la salida del puntero de las opciones posibles if ( opcion < 0 ){ opcion = 0; } if ( opcion > 2 ){ opcion = 2; } // situamos el puntero seg˙n la opciÛn elegida posPuntero->y = int ( ConfigManager::V_RES / 7.0 * ( opcion + 2 ) + 10 ); cuentaCiclos++; rectTitulo->x = int ( ConfigManager::H_RES / 2 + 30.0 * sin ( cuentaCiclos / 20.0 ) - rectTitulo->w / 2 ); // pintamos el men˙ SDL_FillRect ( screen, NULL, ConfigManager::GetIntProperty("menuBackground") ); SDL_BlitSurface ( fondoMenu, NULL, screen, rectFondoMenu ); SDL_BlitSurface ( imagenPuntero, NULL, screen, posPuntero ); SDL_BlitSurface ( tituloMenu, NULL, screen, rectTitulo ); SDL_BlitSurface ( menuOpcion1, NULL, screen, rectOpcion1 ); SDL_BlitSurface ( menuOpcion2, NULL, screen, rectOpcion2 ); SDL_BlitSurface ( menuOpcion3, NULL, screen, rectOpcion3 ); SDL_UpdateRect ( screen, 0, 0, 0, 0 ); while ( SDL_GetTicks ( ) - tiempoInicioBucle < tiempoPorBucle ){ SDL_Delay(tiempoPorBucle - SDL_GetTicks() + tiempoInicioBucle); } } SDL_FreeSurface ( tituloMenu ); SDL_FreeSurface ( menuOpcion1 ); SDL_FreeSurface ( menuOpcion2 ); SDL_FreeSurface ( menuOpcion3 ); SDL_FreeSurface ( fondoMenu ); SDL_FreeSurface ( imagenPuntero ); delete rectOpcion1; delete rectOpcion2; delete rectOpcion3; delete rectTitulo; delete posPuntero; TTF_CloseFont ( fuenteMenu ); return opcion; }
int Engine::loadGLImage(std::string filename) { SDL_Surface* loadedImage = NULL; SDL_Surface* optimizedImage = NULL; SDL_Surface* conv; float GLSize=1.0; unsigned texture; ListCounter++; loadedImage = IMG_Load(filename.c_str()); if(loadedImage != NULL) { optimizedImage = SDL_DisplayFormatAlpha(loadedImage); SDL_FreeSurface(loadedImage); } if(optimizedImage == NULL) std::cout << "Error, maybe Picture not found: " << filename.c_str() << std::endl; conv = SDL_CreateRGBSurface(SDL_SWSURFACE, optimizedImage->w, optimizedImage->h, 32, #if SDL_BYTEORDER == SDL_BIG_ENDIAN 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff); #else 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000); #endif SDL_BlitSurface(optimizedImage, 0, conv, 0); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, conv->pitch / conv->format->BytesPerPixel); glTexImage2D(GL_TEXTURE_2D, 0, 3, conv->w, conv->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, conv->pixels); glNewList(ListCounter,GL_COMPILE); glColor3ub(255, 255, 255); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glEnable(GL_TEXTURE_2D); // glEnable(GL_BLEND); // glBlendFunc(GL_ONE, GL_ONE); glBindTexture(GL_TEXTURE_2D, texture); glBegin(GL_QUADS); // float factor = 0.1; glTexCoord2f(0, 1); glVertex2d(0, 0); glTexCoord2f(1, 1); glVertex2d( conv->w*GLSize,0); glTexCoord2f(1, 0); glVertex2d( conv->w*GLSize,conv->h*GLSize); glTexCoord2f(0, 0); glVertex2d(0,conv->h*GLSize); glEnd(); glDisable(GL_TEXTURE_2D); // glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); glEndList(); std::cout << "GL-image load: " << filename << ", " << ListCounter << std::endl; return ListCounter; }
void GameOverPanel::enable(int currentScore) { SceneObject::enable(); animTime = 0; score = currentScore; newHighScore = currentScore > highScore; if(newHighScore) { highScore = currentScore; } // copy texts to texture SDL_Surface *panelSurface = IMG_Load("panel.png"); if(panelSurface == NULL) { throw std::logic_error("Couldn't load texture panel.png"); } SDL_Surface *scoreSurface = Text::getSurface(scoreFont, intToString(score), Vector3::one, 2, Vector3::zero); SDL_Surface *highScoreSurface = Text::getSurface(scoreFont, intToString(highScore), Vector3::one, 2, Vector3::zero); SDL_Rect scoreDstRect = { panelSurface->w - scoreSurface->w - 25, panelSurface->h / 2 - 50, scoreSurface->w, scoreSurface->h }; SDL_Rect highScoreDstRect = { panelSurface->w - highScoreSurface->w - 25, panelSurface->h / 2 + 30, highScoreSurface->w, highScoreSurface->h }; if(SDL_BlitSurface(scoreSurface, NULL, panelSurface, &scoreDstRect) < 0) { throw SceneError::fromSDLError("Couldn't copy surface"); } if(SDL_BlitSurface(highScoreSurface, NULL, panelSurface, &highScoreDstRect) < 0) { throw SceneError::fromSDLError("Couldn't copy surface"); } if(newHighScore) { SDL_Surface *newSurface = IMG_Load("new.png"); if(newSurface == NULL) { throw std::logic_error("Couldn't load texture new.png"); } SDL_Rect newDstRect = { panelSurface->w / 2 - 35, panelSurface->h / 2 - 5, highScoreSurface->w, highScoreSurface->h }; if(SDL_BlitSurface(newSurface, NULL, panelSurface, &newDstRect) < 0) { throw SceneError::fromSDLError("Couldn't copy surface"); } SDL_FreeSurface(newSurface); } SDL_FreeSurface(scoreSurface); SDL_FreeSurface(highScoreSurface); glDeleteTextures(texture); texture = Texture(panelSurface); }
void Gestion_Jeux(SDL_Surface **ecran, SDL_Surface **carte, char JeuxDeCarte[MAX][MAX], SDL_Rect *position_carte, int* MainJouer[NB_CARTE],FLAG *FLAG, int *Selection_Carte[NB_CARTE], int *JeuxActuel[NB_CARTE], char **JeuxActuel1, int MainGagnante[NB_CARTE], int *MainGarder[NB_CARTE], int *Credit) { SDL_Surface *initialisation = NULL; SDL_Rect position_initialisation; TTF_Font *police_contenu = NULL; int selection = 0; int compteur = 0; int MainEnCours[5] = RAZ_CARTE; int nombre; /* Le flag permet de vérifier que nous somme au debut d'une partie */ if (FLAG->FLAG_JEUX == 1){ MainGarder[0] = 0; MainGarder[1] = 0; MainGarder[2] = 0; MainGarder[3] = 0; MainGarder[4] = 0; MainGarder[5] = 0; MainJouer[0] = 7; MainJouer[1] = 7; MainJouer[2] = 7; MainJouer[3] = 7; MainJouer[4] = 7; MainJouer[5] = 7; /* Géneration des cartes aléatoire pour le premier tour*/ for (compteur = 0 ; compteur <= 4 ; compteur++) { if (MainJouer[compteur] == 7){ if (compteur == 0){ MainEnCours[compteur] = Random (1,52); }else{ do { MainEnCours[compteur] = Random (1,52); nombre = MainEnCours[compteur]; JeuxActuel[compteur] = nombre; } while(!isvalid(nombre, &MainEnCours, 4, compteur)); } } } for (compteur = 0 ; compteur <= 4 ; compteur++) { selection = MainEnCours[compteur]; MainGagnante[compteur] = selection; JeuxActuel[compteur] = selection; JeuxActuel1[compteur] = JeuxDeCarte[selection]; carte[compteur] = IMG_Load(JeuxDeCarte[selection]); } /*Blit du jeu generé */ for (compteur = 0 ; compteur <= 4 ; compteur++) { SDL_BlitSurface(carte[compteur], NULL, *ecran, &position_carte[compteur]); } } /* Le flag permet de vérifier que nous somme au second tour de la partie */ if (FLAG->FLAG_GAIM == 1){ for (compteur = 0 ; compteur <= 4 ; compteur++) { if (MainJouer[compteur]==7){ do { MainEnCours[compteur] = Random(1,52); nombre = MainEnCours[compteur]; JeuxActuel[compteur] = nombre; } while(!isvalid(nombre, JeuxActuel, 4, compteur)); } } for (compteur = 0 ; compteur <= 4 ; compteur++) { if (MainJouer[compteur]==7){ selection = MainEnCours[compteur]; MainGagnante[compteur] = selection; JeuxActuel1[compteur] = JeuxDeCarte[selection]; carte[compteur] = IMG_Load(JeuxDeCarte[selection]); } } /*Blit du jeu generé */ for (compteur = 0 ; compteur <= 4 ; compteur++) { SDL_BlitSurface(carte[compteur], NULL, *ecran, &position_carte[compteur]); } Affichage_Main(&initialisation, &police_contenu, &position_initialisation, JeuxActuel1, MainGagnante, Credit); SDL_BlitSurface(initialisation, NULL, *ecran, &position_initialisation); /*RAZ Flag permettant de reprendre une nouvelle partie */ FLAG->FLAG_GAIM = 0; FLAG->FLAG_INI = 1; FLAG->FLAG_JEUX = 0; FLAG->FLAG_SELECTION = 0; //FLAG permetant d'afficher le GAIN FLAG->FLAG_RESULTAT = 1; /* Remise a zéro des cartes */ MainJouer[0] = 7; MainJouer[1] = 7; MainJouer[2] = 7; MainJouer[3] = 7; MainJouer[4] = 7; } /* Mise en place des parametres afin de passer au second tour */ if (FLAG->FLAG_JEUX == 1){ FLAG->FLAG_JEUX = 0; FLAG->FLAG_SELECTION = 1; FLAG->FLAG_GAIM = 1; FLAG->FLAG_RESULTAT = 0; Selection_Carte[0] = 1; Selection_Carte[1] = 1; Selection_Carte[2] = 1; Selection_Carte[3] = 1; Selection_Carte[4] = 1; } /*Mise a jour de l'écran */ SDL_Flip(*ecran); }
gui_options::gui_options(app_wiiradio* _theapp) : logo(0), media_free_space_desc("unknown"), last_time_ds(0) { theapp = _theapp; fnts = theapp->GetFonts(); guibuffer = theapp->ui->guibuffer; logo = IMG_Load(make_path("data/imgs/def_logo.png")); loopi(O_MAX) b_option_item[i] = 0; loopi(OB_MAX) option_buts[i] = 0; //quit option_buts[OB_QUIT] = new gui_button(theapp, 20,425,0,0,false); option_buts[OB_QUIT]->set_images((char*)"data/imgs/button_out.png",(char*)"data/imgs/button_over.png",0,0); option_buts[OB_QUIT]->set_text(theapp->GetVariables()->search_var("$LANG_TXT_EXIT")); option_buts[OB_QUIT]->pad_y = 5; option_buts[OB_QUIT]->text_color = 0x000000; option_buts[OB_QUIT]->text_color_over = 0xff0044; option_buts[OB_QUIT]->font_sz = FS_SYSTEM; option_buts[OB_QUIT]->center_text = true; option_buts[OB_QUIT]->bind_screen = S_OPTIONS; option_buts[OB_QUIT]->parent = (gui_object*)this; //return option_buts[OB_RETURN] = new gui_button(theapp,150,425,0,0,false); option_buts[OB_RETURN]->set_images((char*)"data/imgs/button_out.png",(char*)"data/imgs/button_over.png",0,0); option_buts[OB_RETURN]->set_text(theapp->GetVariables()->search_var("$LANG_TXT_OK")); option_buts[OB_RETURN]->pad_y = 5; option_buts[OB_RETURN]->text_color = 0x000000; option_buts[OB_RETURN]->text_color_over = 0xff0044; option_buts[OB_RETURN]->font_sz = FS_SYSTEM; option_buts[OB_RETURN]->center_text = true; option_buts[OB_RETURN]->bind_screen = S_OPTIONS; option_buts[OB_RETURN]->parent = (gui_object*)this; //more /* option_buts[OB_MORE] = new gui_button(theapp,500,425,0,0,false); option_buts[OB_MORE]->set_images((char*)"data/imgs/button_out.png",(char*)"data/imgs/button_over.png",0,0); option_buts[OB_MORE]->set_text("More >>>");//theapp->vars->search_var("$LANG_TXT_OK")); option_buts[OB_MORE]->pad_y = 5; option_buts[OB_MORE]->text_color = 0x000000; option_buts[OB_MORE]->text_color_over = 0xff0044; option_buts[OB_MORE]->font_sz = FS_SYSTEM; option_buts[OB_MORE]->center_text = true; option_buts[OB_MORE]->bind_screen = S_OPTIONS; option_buts[OB_MORE]->parent = (gui_object*)this; */ int y = 90; service_group = new gui_group(theapp,2,220,y,41,26,143,NULL); service_group->set_on(theapp->GetSettings()->oservicetype); y += 35; /* Removed for now this is kinda annoying to most b_option_item[O_SCROLL_TEXT] = new gui_button(theapp,220,y,0,0,0); b_option_item[O_SCROLL_TEXT]->set_images((char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_on.png"); b_option_item[O_SCROLL_TEXT]->bind_screen = S_OPTIONS; b_option_item[O_SCROLL_TEXT]->set_image_onout((char*)"data/imgs/toggle_on.png"); b_option_item[O_SCROLL_TEXT]->parent = (gui_object*)this; */ b_option_item[O_WIDESCREEN] = new gui_button(theapp,403,y,0,0,0); b_option_item[O_WIDESCREEN]->set_images((char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_on.png"); b_option_item[O_WIDESCREEN]->bind_screen = S_OPTIONS; b_option_item[O_WIDESCREEN]->parent = (gui_object*)this; b_option_item[O_WIDESCREEN]->set_image_onout((char*)"data/imgs/toggle_on.png"); y += 35; b_option_item[O_STARTFROMLAST] = new gui_button(theapp,220,y,0,0,0); b_option_item[O_STARTFROMLAST]->set_images((char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_on.png"); b_option_item[O_STARTFROMLAST]->bind_screen = S_OPTIONS; b_option_item[O_STARTFROMLAST]->parent = (gui_object*)this; b_option_item[O_STARTFROMLAST]->set_image_onout((char*)"data/imgs/toggle_on.png"); b_option_item[O_RIPMUSIC] = new gui_button(theapp,403,y,0,0,0); b_option_item[O_RIPMUSIC]->set_images((char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_out.png",(char*)"data/imgs/toggle_on.png"); b_option_item[O_RIPMUSIC]->bind_screen = S_OPTIONS; b_option_item[O_RIPMUSIC]->parent = (gui_object*)this; b_option_item[O_RIPMUSIC]->set_image_onout((char*)"data/imgs/toggle_on.png"); y += 50; saver_group = new gui_group(theapp,4,220,y,41,26,20,NULL); saver_group->set_on(theapp->GetSettings()->oscreensavetime); saver_group->bind_screen = S_OPTIONS; y += 45; sleep_timer_group = new gui_group(theapp,6,220,y,41,26,20,&sleep_timer_callback); sleep_timer_group->set_on(theapp->GetSettings()->osleep_timer_time); sleep_timer_group->bind_screen = S_OPTIONS; sleep_timer_group->parent = (gui_object*)this; y += 45; // visual type visuals_group = new gui_group(theapp,2,220,y,41,26,40,NULL); visuals_group->set_on(theapp->GetSettings()->ovisual_mode); visuals_group->bind_screen = S_OPTIONS; visuals_group->parent = (gui_object*)this; y += 35; // next skin option_buts[OB_NEXT_SKIN] = new gui_button(theapp, 420,y,0,0,false); option_buts[OB_NEXT_SKIN]->set_images((char*)"data/imgs/button_out.png",(char*)"data/imgs/button_out.png",0,0); option_buts[OB_NEXT_SKIN]->set_text(theapp->GetVariables()->search_var("$LANG_TXT_NEXT_SKIN")); option_buts[OB_NEXT_SKIN]->pad_y = 5; option_buts[OB_NEXT_SKIN]->text_color = 0x000000; option_buts[OB_NEXT_SKIN]->text_color_over = 0xff0044; option_buts[OB_NEXT_SKIN]->font_sz = FS_SYSTEM; option_buts[OB_NEXT_SKIN]->center_text = true; option_buts[OB_NEXT_SKIN]->bind_screen = S_OPTIONS; option_buts[OB_NEXT_SKIN]->parent = (gui_object*)this; y += 50; // next lang option_buts[OB_NEXT_LANG] = new gui_button(theapp,420,y,0,0,false); option_buts[OB_NEXT_LANG]->set_images((char*)"data/imgs/button_out.png",(char*)"data/imgs/button_out.png",0,0); option_buts[OB_NEXT_LANG]->set_text(theapp->GetVariables()->search_var("$LANG_TXT_NEXT_LANG")); option_buts[OB_NEXT_LANG]->pad_y = 5; option_buts[OB_NEXT_LANG]->text_color = 0x000000; option_buts[OB_NEXT_LANG]->text_color_over = 0xff0044; option_buts[OB_NEXT_LANG]->font_sz = FS_SYSTEM; option_buts[OB_NEXT_LANG]->center_text = true; option_buts[OB_NEXT_LANG]->bind_screen = S_OPTIONS; option_buts[OB_NEXT_LANG]->parent = (gui_object*)this; //#ifdef _WII_ // reinir network option_buts[OB_NET_REINIT] = new gui_button(theapp,280,425,0,0,false); option_buts[OB_NET_REINIT]->set_images((char*)"data/imgs/button_out.png",(char*)"data/imgs/button_out.png",0,0); option_buts[OB_NET_REINIT]->set_text(theapp->GetVariables()->search_var("$LANG_REINTNET")); option_buts[OB_NET_REINIT]->pad_y = 5; option_buts[OB_NET_REINIT]->text_color = 0x000000; option_buts[OB_NET_REINIT]->text_color_over = 0xff0044; option_buts[OB_NET_REINIT]->font_sz = FS_SYSTEM; option_buts[OB_NET_REINIT]->center_text = true; option_buts[OB_NET_REINIT]->bind_screen = S_OPTIONS; option_buts[OB_NET_REINIT]->parent = (gui_object*)this; //#endif // set options // theapp->GetSettings()->oscrolltext ? b_option_item[O_SCROLL_TEXT]->obj_sub_state = B_ON : b_option_item[O_SCROLL_TEXT]->obj_sub_state = B_OFF; theapp->GetSettings()->owidescreen ? b_option_item[O_WIDESCREEN]->obj_sub_state = B_ON : b_option_item[O_WIDESCREEN]->obj_sub_state = B_OFF; theapp->GetSettings()->oripmusic ? b_option_item[O_RIPMUSIC]->obj_sub_state = B_ON : b_option_item[O_RIPMUSIC]->obj_sub_state = B_OFF; // GetSYSVariable(SYS_RIPPING) ? b_option_item[O_RIPMUSIC]->obj_sub_state = B_ON : b_option_item[O_RIPMUSIC]->obj_sub_state = B_OFF; theapp->GetSettings()->ostartfromlast ? b_option_item[O_STARTFROMLAST]->obj_sub_state = B_ON : b_option_item[O_STARTFROMLAST]->obj_sub_state = B_OFF; // Try calc. ds on construction media_free_space_desc = get_media_free_space_desc(); };
void loadBalloon(SDL_Renderer* renderer, Gamestate* game, SDL_Surface* surface) { surface = IMG_Load("images/HotAirBalloon.png"); game->balloonTex = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } // void loadBalloon
int main(int argc, char ** argv) { int finp = 0,first = 1; SDL_Surface * menu = NULL; SDL_Surface * ecran = NULL; SDL_Rect position_menu; SDL_Event event; FSOUND_STREAM * musique = NULL; SDL_Init(SDL_INIT_VIDEO); TTF_Init(); FSOUND_Init(44100,32,0); ecran = SDL_SetVideoMode(800,800,32,SDL_HWSURFACE | SDL_DOUBLEBUF); if(ecran == NULL) exit(EXIT_FAILURE); SDL_WM_SetCaption("Prozet zz1",NULL); menu = IMG_Load("./dessin/menu.jpg"); if(menu == NULL) exit(EXIT_FAILURE); position_menu.x = 0; position_menu.y = 0; musique = FSOUND_Stream_Open("./son/jourdefoot.mp3",0,0,0); if(musique == NULL) exit(EXIT_FAILURE); while(finp == 0) { if(first == 1) { SDL_BlitSurface(menu,NULL,ecran,&position_menu); SDL_Flip(ecran); FSOUND_Stream_Play(FSOUND_FREE,musique); first = 0; } SDL_WaitEvent(&event); switch(event.type) { case SDL_QUIT: finp = 1; break; case SDL_MOUSEBUTTONDOWN: if(event.button.button == SDL_BUTTON_LEFT) { if(event.button.x >= 250 && event.button.x <= 550) { if(event.button.y >= 300 && event.button.y <= 400) { FSOUND_Stream_Stop(musique); mode_solo(ecran); first = 1; } else { if(event.button.y >= 450 && event.button.y <= 550) { FSOUND_Stream_Stop(musique); mode_local_serveur(ecran); first = 1; } else { if(event.button.y >= 600 && event.button.y <= 700) { FSOUND_Stream_Stop(musique); mode_local_client(ecran); first = 1; } } } } } break; } } FSOUND_Stream_Stop(musique); FSOUND_Stream_Close(musique); FSOUND_Close(); SDL_FreeSurface(menu); SDL_FreeSurface(ecran); TTF_Quit(); SDL_Quit(); return(EXIT_SUCCESS); }
int main(int argc, char **argv) { char romName[150]; #ifdef GIZMONDO strcpy(romName, "\\SD Card\\GizRACE\\"); strcat(romName, argv[1]); #else #ifndef TEST_CFC2_ONLY if(argc == 1) { dbg_printf("Defaulting to runme.ngp\n"); strncpy(romName, "runme.ngp", 50); //dbg_printf("Defaulting to runme.ws\n"); //strncpy(romName, "runme.ws", 50); } else if(argc != 2) { fprintf(stderr, "argc != 2\n"); return -1; } else strncpy(romName, argv[1], 50); dbg_printf("romName=%s\n", romName); #endif #endif // Initialize SDL #if defined (TARGET_GP2X) || defined (GIZMONDO) if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_JOYSTICK) < 0) #else if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0) #endif { fprintf(stderr, "SDL_Init failed!\n"); return -1;//Log::Instance()->die(1, SV_FATALERROR, "Couldn't initialize SDL: %s\n", SDL_GetError()); } #ifdef TARGET_GP2X GP2X_JoystickOpen(); #else #ifdef GIZMONDO joystick = SDL_JoystickOpen(0); #else SDL_WM_SetCaption("RACE!", 0); #endif #endif // Set up quiting so that it automatically runs on exit. atexit (SDL_Quit); //#define DO_HWDBLBUF #ifdef DO_HWDBLBUF screen = SDL_SetVideoMode (SIZEX, SIZEY, 16, SDL_HWSURFACE | SDL_DOUBLEBUF); #else //screen = SDL_SetVideoMode (SIZEX, SIZEY, 8, SDL_SWSURFACE | SDL_HWPALETTE); //screen = SDL_SetVideoMode (SIZEX, SIZEY, 16, SDL_SWSURFACE); #ifdef GIZMONDO screen = SDL_SetVideoMode (320, 240, 16, SDL_HWSURFACE | SDL_HWPALETTE | SDL_FULLSCREEN); #else screen = SDL_SetVideoMode (320, 240, 16, SDL_SWSURFACE); #endif #endif if (screen == NULL) { fprintf(stderr, "SDL_SetVideoMode failed!\n"); return -1; } else { dbg_print("screen params: bpp=%d\n", screen->format->BitsPerPixel); } SDL_ShowCursor(0); //disable the cursor /* Set up the SDL_TTF */ TTF_Init(); atexit(TTF_Quit); #if !defined(GIZMONDO) && !defined(TARGET_WIZ) SDL_AudioSpec wav,retFmt; SDL_Surface *splash = IMG_Load("splash.jpg"); if(splash) { SDL_BlitSurface(splash, NULL, screen, NULL); SDL_Flip(screen); } else { SDL_Surface *splash = IMG_Load("splash.bmp"); if(splash) { SDL_BlitSurface(splash, NULL, screen, NULL); SDL_Flip(screen); } } InitInput(NULL); if(SDL_LoadWAV("intro.wav", &wav, &audio_buf, &audio_len) == NULL) { printf("Unable to open intro wav!\n"); } else { wav.callback = introAudioCallback; wav.userdata = NULL; if ( SDL_OpenAudio(&wav, &retFmt) < 0 ) { fprintf(stderr, "Unable to open audio: %s\n", SDL_GetError()); exit(1); } SDL_PauseAudio(0); while (played<audio_len) { UpdateInputState(); if (ngpInputState & 0x70) break; } while (ngpInputState & 0x70) { UpdateInputState(); } } SDL_PauseAudio(0); SDL_CloseAudio(); SDL_FreeSurface(splash); SDL_FreeWAV(audio_buf); if(LoadRomFromGP2X(romName, screen) <= 0) { dbg_print("LoadRomFromPSP failed!\n"); exit(1); } #else InitInput(NULL); if(LoadRomFromGP2X(romName, screen) <= 0) { dbg_print("LoadRomFromPSP failed!\n"); exit(1); } #endif //dbg_print("openNgp(%s)\n", romName); //emulate //see ngpc.cpp and ngpcDoc.cpp //system_sound_init(); sound_system_init(); handleInputFile(romName); #if defined(TARGET_GP2X) && !defined(TARGET_WIZ) system("/sbin/rmmod mmuhack"); system("/sbin/insmod mmuhack.o"); int mmufd = open("/dev/mmuhack", O_RDWR); if(mmufd < 0) { printf("MMU hack failed\n"); } else { printf("MMU hack loaded\n"); close(mmufd); } #endif dbg_print("Running NGPC Emulation\n"); ngpc_run(); flashShutdown(); #if defined(TARGET_GP2X) && !defined(TARGET_WIZ) system("/sbin/rmmod mmuhack"); #endif return 0; }