本文整理汇总了C++中IMG_Load函数的典型用法代码示例。如果您正苦于以下问题:C++ IMG_Load函数的具体用法?C++ IMG_Load怎么用?C++ IMG_Load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IMG_Load函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: read_image
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;
}
示例2: main
//.........这里部分代码省略.........
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;
}
示例3: main
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))
//.........这里部分代码省略.........
示例4: glGenTextures
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++)
//.........这里部分代码省略.........
示例5: main
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 ++;
//.........这里部分代码省略.........
示例6: MenuError
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");
}
示例7: LoadCubeVerticalCross
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;
}
}
//.........这里部分代码省略.........
示例8: main
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);
//.........这里部分代码省略.........
示例9: main
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;
}
示例10: LancerJeu
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
//.........这里部分代码省略.........
示例11: main
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));
//.........这里部分代码省略.........
示例12: main
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;
//.........这里部分代码省略.........
示例13: main
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 ) )
{
//.........这里部分代码省略.........
示例14: main
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);
//.........这里部分代码省略.........
示例15: loadBackground
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()