void Image::reload(SDL_Surface *surface) { m_filename = ""; if(m_texture) SDL_DestroyTexture(m_texture); m_width = surface->w; m_height = surface->h; m_texture = SDL_CreateTextureFromSurface(GameWindow::main->renderer(), surface); SDL_SetTextureBlendMode(m_texture, SDL_BLENDMODE_BLEND); SDL_FreeSurface(surface); m_clipRect.x = 0; m_clipRect.y = 0; m_clipRect.w = m_width; m_clipRect.h = m_height; m_posRect.x = 0; m_posRect.y = 0; m_posRect.w = m_width; m_posRect.h = m_height; m_hidden = false; }
Planet::Planet(std::string name): Object(), Drawable(), Touchable(), weaponAim_(0, 0) { type_ = Assets::instance().info("Planet", name); b2BodyDef temp; temp.position = b2Vec2(0.0, 0.0); temp.type = b2_staticBody; CreateBody(temp, type_.def); laser_ = new Laser(GetBody()); SDL_Log("Planet m=%f", GetMass()); SDL_Surface* surface = Screen::CreateSurface(1, 1, 32); Uint32 color = SDL_MapRGBA(surface->format, 255, 90, 255, 250); SDL_FillRect(surface, NULL, color); texture_ = SDL_CreateTextureFromSurface(Screen::instance().renderer(), surface); }
void Image::reload(const char *filename) { m_filename = filename; if(m_texture) SDL_DestroyTexture(m_texture); SDL_RWops *image = SDL_RWFromFile(filename, "rb"); SDL_Surface *surface = IMG_Load_RW(image, 1); if(!surface) { error("Failed to load image \"%s\": %s\n", filename, IMG_GetError()); exit(EXIT_FAILURE); } m_width = surface->w; m_height = surface->h; m_texture = SDL_CreateTextureFromSurface(GameWindow::main->renderer(), surface); if(!m_texture) { error("Failed to create texture from image: %s", SDL_GetError()); exit(EXIT_FAILURE); } SDL_SetTextureBlendMode(m_texture, SDL_BLENDMODE_BLEND); SDL_FreeSurface(surface); m_clipRect.x = 0; m_clipRect.y = 0; m_clipRect.w = m_width; m_clipRect.h = m_height; m_posRect.x = 0; m_posRect.y = 0; m_posRect.w = m_width; m_posRect.h = m_height; m_hidden = false; }
int draw_msg(SDL_Surface *screen, int x, int y, const char *msg) { //SDL_Color bg={0x19,0x19,0x19,0x40}; SDL_Color bg={0,0,0,0}; SDL_Color fg={238,238,230,0x40}; //defaultTextColor.setAllColors(238, 238, 230, 0x40); //colorDefaultWidgetBackground.setAllColors(0x19, 0x19, 0x19, 0x40); //SDL_Color bg={0,0,0,0}; //SDL_Color fg={255,255,255,255}; SDL_Surface *surf= TTF_RenderText_Shaded(font,msg,fg, bg); SDL_TextureID text = SDL_CreateTextureFromSurface(0, surf); //Central alignment for subtitle //x=(int) ((320.0*fs_screen_width/640.0) -(surf->w/2.0)); SDL_Rect rect = {x, y, surf->w, surf->h }; SDL_RenderCopy(text, NULL, &rect); SDL_FreeSurface(surf); SDL_DestroyTexture(text); }
/* Set the Text */ SDL_Texture* Font::RenderText(const std::string &message, SDL_Color color, int fontSize, SDL_Renderer *renderer) { font = TTF_OpenFont(this->fontPath.c_str(), fontSize); if (!font){ logging(TTF_GetError()); return NULL; } surf = TTF_RenderText_Blended(font, message.c_str(), color); if (!surf){ logging(TTF_GetError()); return NULL; } SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf); if (!texture){ logging(TTF_GetError()); return NULL; } TTF_CloseFont(font); font = NULL; SDL_FreeSurface(surf); return texture; }
void cGame::mWorldMapLoad(string path){ if (!mIsLoaded()){ if (!loadMedia(path.c_str())){ printf("Failed to load media!\n"); } else{ mSetLoaded(true); //Set up player quad player1.mPlayerQuad.x = player1.getPlayerX(); player1.mPlayerQuad.y = player1.getPlayerY(); player1.mPlayerQuad.w = player1.getPlayerWidth(); player1.mPlayerQuad.h = player1.getPlayerHeight(); player1.mPlayerSurface = IMG_Load("Images/Character/hero_jimmy.png"); player1.mPlayerTexture = SDL_CreateTextureFromSurface(mRenderer, player1.mPlayerSurface); player1.mPlayerSteps = 0; mRandomEncounter = rand() % 500; if (mRandomEncounter < 30) mRandomEncounter = rand() % 500; } mWorldMapUpdate(); } }
bool ResourceFontTexture::LoadResource(const std::string& text, ResourceFont font, SDL_Renderer * renderer, Color color) { if (initialized) { DEBUG_LOG("Trying to load resource in already initialized instantion."); return false; } SDL_Surface * surface = TTF_RenderText_Solid(font.getFont(), text.c_str(), {color.r,color.g,color.b,color.a}); if (surface == nullptr) { DEBUG_LOG("Error loading surface from font."); return false; } texture.reset(SDL_CreateTextureFromSurface(renderer, surface), SDL_DestroyTexture); SDL_FreeSurface(surface); if (texture == nullptr) { DEBUG_LOG("Failed to create texture from surface"); return false; } initialized = true; return true; }
Renderer::Renderer() { assertf(SDL_Init(SDL_INIT_VIDEO) >= 0, "Failed to initialize SDL: %s", SDL_GetError()); _window = SDL_CreateWindow("Water Simulator", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0); assertf(_window != NULL, "Failed to create window: %s", SDL_GetError()); _renderer = SDL_CreateRenderer(_window, -1, 0); assertf(_renderer != NULL, "Failed to create renderer: %s", SDL_GetError()); SDL_SetRenderDrawColor(_renderer, 20, 20, 20, 255); SDL_RenderClear(_renderer); SDL_Surface *squareSurf = SDL_LoadBMP("square.bmp"); assertf(squareSurf != NULL, "Failed to load image \"square.bmp\": %s", SDL_GetError()); _square = SDL_CreateTextureFromSurface(_renderer, squareSurf); SDL_FreeSurface(squareSurf); }
// ouvrir un fichier png et le placer dans une texture SDL_Texture *SDLS_loadImage( char *name) { SDL_Surface *loadedImage = NULL; SDL_Texture *texture = NULL; // Charge les images avec SDL Image dans une SDL_Surface // pour PNG loadedImage = IMG_Load(name); // pour BMP // SDL_Surface * image = SDL_LoadBMP(name); //Color key image, le fond blanc est enlevé... Pas besoin de détourrer l'image SDL_SetColorKey( loadedImage, SDL_TRUE, SDL_MapRGB( loadedImage->format, 0xFF, 0xFF, 0xFF ) ); if (loadedImage != NULL) { // Conversion de l'image en texture texture = SDL_CreateTextureFromSurface(gRenderer, loadedImage); // On se débarrasse du pointeur vers une surface SDL_FreeSurface(loadedImage); loadedImage = NULL; } else printf("L'image n'a pas pu être chargée! SDL_Error : %s\n", SDL_GetError()); return texture; }
bool RenderManagerSDL::setBackground(const std::string& filename) { try { SDL_Surface *tempBackgroundSurface = loadSurface(filename); SDL_Texture *tempBackgroundTexture = SDL_CreateTextureFromSurface(mRenderer, tempBackgroundSurface); BufferedImage* oldBackground = mImageMap["background"]; SDL_DestroyTexture(oldBackground->sdlImage); delete oldBackground; BufferedImage* newImage = new BufferedImage; newImage->w = tempBackgroundSurface->w; newImage->h = tempBackgroundSurface->h; newImage->sdlImage = tempBackgroundTexture; SDL_FreeSurface(tempBackgroundSurface); mBackground = newImage->sdlImage; mImageMap["background"] = newImage; } catch (FileLoadException) { return false; } return true; }
bool Texture::loadFromFile(std::string path, SDL_Renderer* mR) { //Get rid of preexisting texture free(); //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == NULL) { printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError()); } else { //Color key image SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF)); //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface(mR, loadedSurface); if (newTexture == NULL) { printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError()); } else { //Get image dimensions mWidth = loadedSurface->w; mHeight = loadedSurface->h; } //Get rid of old loaded surface SDL_FreeSurface(loadedSurface); } //Return success mTexture = newTexture; return mTexture != NULL; }
void Images::Load(int i_id, string i_path, int i_x, int i_y, int i_mtime, int i_a, int i_atime) { //detect that if it exist an images,unload it for (auto it = m_imgs.begin(); it != m_imgs.end(); ++it) if (it->id == i_id) Unload(i_id); //create a new texture struct and add it to the vector Image newImg; if (m_files->ReadRW(i_path, &(newImg.rw), newImg.index)){ if (!(newImg.sur = IMG_Load_RW(newImg.rw, AUTOFREE))){ SekaiAlert("cannot analyse the picture file from " + i_path); return; } newImg.tex = SDL_CreateTextureFromSurface(m_ren, newImg.sur); SDL_FreeSurface(newImg.sur); newImg.id = i_id; SDL_QueryTexture(newImg.tex, NULL, NULL, &(newImg.rect.w), &newImg.rect.h); newImg.rect.x = i_x; newImg.rect.y = i_y; newImg.a = i_a; newImg.path = i_path; m_imgs.push_back(newImg); } }
void maj_panneau(SDL_Renderer* ren, int nb_fleche[]){ SDL_Texture *texture_directions = NULL; SDL_Surface *Directions = IMG_Load("IMG/Directions.png"); texture_directions = SDL_CreateTextureFromSurface(ren,Directions); SDL_FreeSurface(Directions); SDL_Rect dst_directions; dst_directions.x = 730; dst_directions.y = 80; SDL_QueryTexture(texture_directions, NULL, NULL, &dst_directions.w, &dst_directions.h); SDL_RenderCopy(ren, texture_directions, NULL, &dst_directions); SDL_DestroyTexture(texture_directions); affichage_nb(ren,768,210,nb_fleche[0]);//d1 affichage_nb(ren,818,210,nb_fleche[1]);//d2 affichage_nb(ren,868,210,nb_fleche[2]);//d3 affichage_nb(ren,768,160,nb_fleche[3]);//d4 affichage_nb(ren,868,160,nb_fleche[5]);//d6 affichage_nb(ren,768,110,nb_fleche[6]);//d7 affichage_nb(ren,818,110,nb_fleche[7]);//d8 affichage_nb(ren,868,110,nb_fleche[8]);//d9 SDL_RenderPresent(ren); }
bool Player::LoadTexture(std::string textureFile) { m_surface = SDL_LoadBMP(textureFile.c_str()); if (!m_surface) { return false; } m_texture = SDL_CreateTextureFromSurface(m_sdlRenderer, m_surface); // centre the player on screen SDL_Rect displayRect; SDL_GetDisplayBounds(0, &displayRect); m_xPos = displayRect.w / 2; m_yPos = displayRect.h / 2; UpdateTexturePos(); m_textureRect.w = m_surface->w; m_textureRect.h = m_surface->h; return true; }
bool Texture::Load(const std::string &Path, SDL_Renderer *const Renderer) { Free(); SDL_Texture *New=NULL; SDL_Surface *Surface=NULL; // Load the surface Surface=IMG_Load(Path.c_str()); if(Surface==NULL) { Print("Failed to load file \""+Path+"\"."); return false; } // Create texture New=SDL_CreateTextureFromSurface(Renderer, Surface); if(New==NULL) { SDL_FreeSurface(Surface); Print("Failed to create texture from Surface from file \""+Path+"\"."); return false; } // Store the texture dimensions Width=Surface->w; Height=Surface->h; // Free up the memory SDL_FreeSurface(Surface); // Store the fully loaded texture Image=New; Print("Loaded image from \""+Path+"\"."); return true; }
SDL_Texture* MySDL2::loadTexture(string path) { SDL_Texture* newTexture = NULL; SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == NULL) { cout << "Unable to load image, SDL Error: " << path.c_str() << ", " << SDL_GetError(); } else { newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface); if (newTexture == NULL) { cout << "Unable to optimize image SDL Error: " << path.c_str() << ", " << SDL_GetError(); } SDL_FreeSurface(loadedSurface); } return newTexture; }
//Initialization void Bola::Init(SDL_Renderer *renderer){ rect.h = BOLA_SIZE; rect.w = BOLA_SIZE; rect.y = WIN_HEIGHT/2; rect.x = WIN_WIDTH/2; //Iniciar con un angulo random, pero que nunca sea completamente horizontal o vertical int type = rand() % 4; switch (type) { case 0: //15-75 angle = rand() % 60 + 15; break; case 1: //105-165 angle = rand() % 60 + 105; break; case 2: //195-255 angle = rand() % 60 + 195; break; case 3://285-345 angle = rand() % 60 + 285; break; } SDL_Surface *surf = IMG_Load("assets/pelota.png"); imagen = SDL_CreateTextureFromSurface(renderer, surf); dx = dy = 0.0f; speed = 0.4f; rebotandoY = rebotandoX = false; speedX = (float)cos(angle*M_PI / 180.0f) * speed; speedY = (float)sin(angle*M_PI / 180.0f) * speed; MAX_speed = speed *2; InitMedia(); }
/* this function loads our font into an SDL_Texture and returns the SDL_Texture */ SDL_Texture* loadFont(void) { SDL_Surface *surface = SDL_LoadBMP("kromasky_16x16.bmp"); if (!surface) { printf("Error loading bitmap: %s\n", SDL_GetError()); return 0; } else { /* set the transparent color for the bitmap font (hot pink) */ SDL_SetColorKey(surface, 1, SDL_MapRGB(surface->format, 238, 0, 252)); /* now we convert the surface to our desired pixel format */ int format = SDL_PIXELFORMAT_ABGR8888; /* desired texture format */ Uint32 Rmask, Gmask, Bmask, Amask; /* masks for desired format */ int bpp; /* bits per pixel for desired format */ SDL_PixelFormatEnumToMasks(format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); SDL_Surface *converted = SDL_CreateRGBSurface(0, surface->w, surface->h, bpp, Rmask, Gmask, Bmask, Amask); SDL_BlitSurface(surface, NULL, converted, NULL); /* create our texture */ texture = SDL_CreateTextureFromSurface(renderer, converted); if (texture == 0) { printf("texture creation failed: %s\n", SDL_GetError()); } else { /* set blend mode for our texture */ SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); } SDL_FreeSurface(surface); SDL_FreeSurface(converted); return texture; } }
SDL_Texture * Painter::textToTexture(std::string text) { SDL_Surface *surface = getFont()->toSurface(text, getPen()); return SDL_CreateTextureFromSurface(renderer, surface); }
void Painter::paintSurface(SDL_Surface *surface, SDL_Rect r) { SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface); paintTexture(texture, r); }
int main(int, char**) { // inicia SDL SDL_Init(SDL_INIT_VIDEO); if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cerr << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } // crea la ventana SDL_Window *win = SDL_CreateWindow("Gestor de eventos de teclado y raton", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN); if (win == nullptr){ std::cerr << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } // crea el "renderer" SDL_Renderer *ren = SDL_CreateRenderer(win, -1, 1); if (ren == nullptr){ cleanup(win); // SDL_DestroyWindow(win); std::cerr << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } std::string imagePath1 = "panel3.bmp"; SDL_Surface *panel = SDL_LoadBMP(imagePath1.c_str()); //SDL_Surface *screen = SDL_CreateRGBSurface(0, 640, 480, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); SDL_Texture *texPanel = SDL_CreateTextureFromSurface(ren, panel); //SDL_Texture * tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 640, 480); // Select the color for drawing. It is set to red here. SDL_SetRenderDrawColor(ren, 0, 204, 255, 255); SDL_RenderClear(ren); //SDL_DrawLine(screen, 20, 10, 70, 90, 255, 0, 0, 255); SDL_SetRenderDrawColor(ren, 255, 0, 0, 255); SDL_RenderDrawLine(ren, 10, 10, 200, 200); // Up until now everything was drawn behind the scenes. // This will show the new, red contents of the window. SDL_RenderCopy(ren, texPanel, NULL, NULL); SDL_RenderPresent(ren); //Our event structure SDL_Event e; //For tracking if we want to quit bool quit = false; SDL_SetRenderDrawColor(ren, 255, 0, 0, 255); ///Variables int i=0; bool pinta=false; ///Variables END while (!quit){ //Read any events that occurred, for now we'll just quit if any event occurs while (SDL_PollEvent(&e)){ //If user closes the window if (e.type == SDL_QUIT){ quit = true; } //If user presses any key if (e.type == SDL_KEYDOWN) { SDL_Keycode key = e.key.keysym.sym; std::cout << "Tecla pulsada: " << SDL_GetKeyName(key) << std::endl; if (key == SDLK_ESCAPE){ quit = true; } } //If user clicks the mouse if (e.type == SDL_MOUSEBUTTONDOWN){ std::cout << "Boton de raton pulsado en X = " << e.button.x << "\tY = " << e.button.y << std::endl; //SDL_DrawLine(screen, 20, 10, 70, 90, 255, 0, 0, 255); //APAĂ‘AR EL BUCLE CON LOS 2 CLICKS DE RATON <<<GUILLER>>> APAĂ‘ADO ;) //BOTON DE CERRAR if ((e.button.x > 708 && e.button.x < 800) & (e.button.y > 0 && e.button.y < 55)){ quit = true; } //BOTON CREAR LINEA if ((e.button.x > 708 && e.button.x < 800) & (e.button.y > 115 && e.button.y < 168)){ if (pinta == false) pinta=true; else pinta=false; } if ((pinta == true) & (e.button.x > 12 && e.button.x < 692) & (e.button.y > 77 && e.button.y < 588)){ int x1; int y1; int x2; int y2; if (i==0){ std::cout <<" 1 "; x1 = e.button.x; y1 = e.button.y; } if (i==1){ std::cout <<" 2 "; x2 = e.button.x; y2 = e.button.y; SDL_RenderDrawLine(ren, x1, y1, x2, y2); } i++; if (i==2) i=0; } /* for(int i=0; i<2; i++){ x1 = e.button.x; y1 = e.button.y; std::cout << "e1 = "<< e.button.x<< std::endl; if (x1!=0){ x2 = e.button.x; y2 = e.button.y; std::cout << "e2 = "<< e.button.x << std::endl; i++; } }*/ } } //Update the screen SDL_RenderPresent(ren); //Take a quick break after all that hard work } // limpia y termina cleanup(ren, win); // SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); std::cout << "Todo correcto. Bye!" << std::endl; SDL_Quit(); return 0; }
void ui_init() { // Init SDL if(SDL_Init(SDL_INIT_VIDEO) < 0) FAIL("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); ww = config.ui.window_width; wh = config.ui.window_height; window = SDL_CreateWindow("Radiance", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ww, wh, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); if(window == NULL) FAIL("Window could not be created: %s\n", SDL_GetError()); context = SDL_GL_CreateContext(window); if(context == NULL) FAIL("OpenGL context could not be created: %s\n", SDL_GetError()); if(SDL_GL_SetSwapInterval(1) < 0) fprintf(stderr, "Warning: Unable to set VSync: %s\n", SDL_GetError()); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if(renderer == NULL) FAIL("Could not create renderer: %s\n", SDL_GetError()); if(TTF_Init() < 0) FAIL("Could not initialize font library: %s\n", TTF_GetError()); // Init OpenGL GLenum e; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0, 0, 0, 0); if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e)); // Make framebuffers glGenFramebuffersEXT(1, &select_fb); glGenFramebuffersEXT(1, &pat_fb); glGenFramebuffersEXT(1, &crossfader_fb); glGenFramebuffersEXT(1, &pat_entry_fb); glGenFramebuffersEXT(1, &spectrum_fb); glGenFramebuffersEXT(1, &waveform_fb); glGenFramebuffersEXT(1, &strip_fb); if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e)); // Init select texture glGenTextures(1, &select_tex); glBindTexture(GL_TEXTURE_2D, select_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ww, wh, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindTexture(GL_TEXTURE_2D, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, select_fb); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, select_tex, 0); // Init pattern textures pattern_textures = calloc(config.ui.n_patterns, sizeof(GLuint)); if(pattern_textures == NULL) MEMFAIL(); pattern_name_textures = calloc(config.ui.n_patterns, sizeof(SDL_Texture *)); pattern_name_width = calloc(config.ui.n_patterns, sizeof(int)); pattern_name_height = calloc(config.ui.n_patterns, sizeof(int)); if(pattern_name_textures == NULL || pattern_name_width == NULL || pattern_name_height == NULL) MEMFAIL(); glGenTextures(config.ui.n_patterns, pattern_textures); if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e)); for(int i = 0; i < config.ui.n_patterns; i++) { glBindTexture(GL_TEXTURE_2D, pattern_textures[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.pattern_width, config.ui.pattern_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); } // Init crossfader texture glGenTextures(1, &crossfader_texture); glBindTexture(GL_TEXTURE_2D, crossfader_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.crossfader_width, config.ui.crossfader_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, crossfader_fb); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, crossfader_texture, 0); // Init pattern entry texture glGenTextures(1, &pat_entry_texture); glBindTexture(GL_TEXTURE_2D, pat_entry_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.pat_entry_width, config.ui.pat_entry_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, pat_entry_fb); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, pat_entry_texture, 0); // Spectrum data texture glGenTextures(1, &tex_spectrum_data); glBindTexture(GL_TEXTURE_1D, tex_spectrum_data); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, config.audio.spectrum_bins, 0, GL_RED, GL_FLOAT, NULL); // Spectrum UI element glGenTextures(1, &spectrum_texture); glBindTexture(GL_TEXTURE_2D, spectrum_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.spectrum_width, config.ui.spectrum_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, spectrum_fb); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, spectrum_texture, 0); // Waveform data texture glGenTextures(1, &tex_waveform_data); glBindTexture(GL_TEXTURE_1D, tex_waveform_data); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, config.audio.waveform_length, 0, GL_RGBA, GL_FLOAT, NULL); glGenTextures(1, &tex_waveform_beats_data); glBindTexture(GL_TEXTURE_1D, tex_waveform_beats_data); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, config.audio.waveform_length, 0, GL_RGBA, GL_FLOAT, NULL); // Waveform UI element glGenTextures(1, &waveform_texture); glBindTexture(GL_TEXTURE_2D, waveform_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.waveform_width, config.ui.waveform_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, waveform_fb); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, waveform_texture, 0); // Strip indicators glGenTextures(1, &strip_texture); glBindTexture(GL_TEXTURE_2D, strip_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.pattern.master_width, config.pattern.master_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, strip_fb); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, strip_texture, 0); // Done allocating textures & FBOs, unbind and check for errors glBindTexture(GL_TEXTURE_2D, 0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e)); if((blit_shader = load_shader("resources/blit.glsl")) == 0) FAIL("Could not load blit shader!\n%s", load_shader_error); if((main_shader = load_shader("resources/ui_main.glsl")) == 0) FAIL("Could not load UI main shader!\n%s", load_shader_error); if((pat_shader = load_shader("resources/ui_pat.glsl")) == 0) FAIL("Could not load UI pattern shader!\n%s", load_shader_error); if((crossfader_shader = load_shader("resources/ui_crossfader.glsl")) == 0) FAIL("Could not load UI crossfader shader!\n%s", load_shader_error); if((text_shader = load_shader("resources/ui_text.glsl")) == 0) FAIL("Could not load UI text shader!\n%s", load_shader_error); if((spectrum_shader = load_shader("resources/ui_spectrum.glsl")) == 0) FAIL("Could not load UI spectrum shader!\n%s", load_shader_error); if((waveform_shader = load_shader("resources/ui_waveform.glsl")) == 0) FAIL("Could not load UI waveform shader!\n%s", load_shader_error); if((strip_shader = load_shader("resources/strip.glsl")) == 0) FAIL("Could not load strip indicator shader!\n%s", load_shader_error); // Stop text input SDL_StopTextInput(); // Open the font font = TTF_OpenFont(config.ui.font, config.ui.fontsize); if(font == NULL) FAIL("Could not open font %s: %s\n", config.ui.font, SDL_GetError()); // Init statics pat_entry = false; SDL_Surface * surf; surf = TTF_RenderText_Blended(font, "wtf, why is this necessary", font_color); if(surf == NULL) FAIL("Could not create surface: %s\n", SDL_GetError()); SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf); if(texture == NULL) FAIL("Could not create texture: %s\n", SDL_GetError()); SDL_FreeSurface(surf); SDL_DestroyTexture(texture); }
void button::texture(SDL_Renderer *R) { tp = SDL_CreateTextureFromSurface(R, image_p); tt = SDL_CreateTextureFromSurface(R, image_t); tu = SDL_CreateTextureFromSurface(R, image_u); }
static bool loadTileset(struct Tileset *tileset, SDL_Renderer *renderer, const struct Turbo_Value *tilesetValue, struct Map *reuse_images){ unsigned i; assert(tilesetValue); assert(tileset); memset(tileset, 0, sizeof(struct Tileset)); if(tilesetValue->type == TJ_Error){ Turbo_WriteError(tilesetValue, stderr, 0); return false; } if(tilesetValue->type != TJ_Object){ fprintf(stderr, "Invalid tileset object\n"); return false; } { const struct Turbo_Value *const atlasWidth = jsonFindObjectValue(tilesetValue, "columns"), *const tileCount = jsonFindObjectValue(tilesetValue, "tilecount"), *const tileWidth = jsonFindObjectValue(tilesetValue, "tilewidth"), *const tileHeight = jsonFindObjectValue(tilesetValue, "tileheight"), *const tileData = jsonFindObjectValue(tilesetValue, "tiles"), *const imagePath = jsonFindObjectValue(tilesetValue, "image"); if(!atlasWidth || atlasWidth->type != TJ_Number || !tileCount || tileCount->type != TJ_Number || !tileWidth || tileWidth->type != TJ_Number || !tileHeight || tileHeight->type != TJ_Number || !tileData || tileData->type != TJ_Object || !imagePath || imagePath->type != TJ_String){ fprintf(stderr, "Invalid tileset format\n"); return false; } tileset->tileWidth = (int)tileWidth->value.number; tileset->tileHeight = (int)tileHeight->value.number; tileset->atlasWidth = (int)atlasWidth->value.number; tileset->atlasHeight = ((int)tileCount->value.number) / tileset->atlasWidth; if(imagePath->length >= 0xFF - 1){ fprintf(stderr, "Overlength tileset image path.\n"); return false; } memcpy(tileset->imagePath, imagePath->value.string, imagePath->length); tileset->imagePath[imagePath->length] = '\0'; // Normalize the path, because Tiled's JSON exporter is a bit jacked. { char *path = tileset->imagePath; while(*path){ if(path[0] == '\\' && path[1] == '/'){ char *iter = path; iter[0] = '/'; while(*iter){ iter[0] = iter[1]; iter++; } } path++; } } tileset->obstruction = calloc(1, (int)tileCount->value.number); // Get obstruction data. for(i = 0; i < tileData->length; i++){ // HACK: The Tiled JSON exporter will only print the names of tiles with attributes. const int index = atoi(tileData->value.object[i].name); assert(index < (int)tileCount->value.number); tileset->obstruction[index] = true; } tileset->tileHeight = (int)tileHeight->value.number; } // Load the tileset image, or reuse it from the map. if(reuse_images){ for(i = 0; i < reuse_images->numTilesets; i++){ if(strncmp(tileset->imagePath, reuse_images->tilesets[i].imagePath, 0xFF) == 0){ tileset->image = reuse_images->tilesets[i].image; break; } } } if(!tileset->image){ SDL_Surface *const surface = IMG_Load(tileset->imagePath); if(!surface){ fprintf(stderr, "Could not load image %i for tileset\n", tileset->imagePath); return false; } tileset->image = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } return true; }
int main (int argc, char *argv[]) { int i = 0; int j = 0; SDL_Surface *sur = NULL; SDL_Rect tile[NUM_TILES]; SDL_Rect target; int scale = 32; /* HANDLE ARGUMENTS *//*{{{*/ for(i = 1; i < argc; i++) { if(strncmp(argv[i], "-d", 3) == 0) { i++; d_sel = atoi(argv[i]); }else if(strncmp(argv[i], "-s", 3) == 0) { i++; scale = atoi(argv[i]); } }/*}}}*/ init(); /* DEFINE TILE-ATLAS SRC_RECTS *//*{{{*/ for(i = 0; i < NUM_TILES; i++) { tile[i].x = i * 16; tile[i].y = 0; tile[i].h = 16; tile[i].w = 16; }/*}}}*/ /* LOAD THE ATLAS */ /*{{{*/ sur = SDL_LoadBMP("tiles.bmp"); atlas = SDL_CreateTextureFromSurface(rend, sur); SDL_FreeSurface(sur);/*}}}*/ SDL_Event e; while(!game_quit) { if(SDL_PollEvent(&e))/*{{{*/ { switch(e.type) { case SDL_QUIT: SDL_Log("Program quit after %i ticks", e.quit.timestamp); game_quit = true; break; } }/*}}}*/ // UPDATE GAME BASED ON TIME! // RENDER ONLY WHAT NEEDS TO CHANGE! /* CLEAR RENDERER *//*{{{*/ SDL_SetRenderDrawColor(rend,0,0,0,255); SDL_RenderClear(rend);/*}}}*/ /* PAINT TILES TO THE RENDERER *//*{{{*/ for(i = 0; i < 10; i++) { for(j = 0; j < 10; j++) { target.x = j * scale; target.y = i * scale; target.h = scale; target.w = scale; SDL_RenderCopy(rend, atlas, &tile[brush], &target); } }/*}}}*/ SDL_RenderPresent(rend); } tini(); printf("I ran till the end\n"); return 0; }
int main(int argc, const char * argv[]) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL init error: " << SDL_GetError() << std::endl; return 1; } SDL_Window *win = SDL_CreateWindow("SpaceThing", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (win == nullptr) { std::cout << "SDL create window error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { SDL_DestroyWindow(win); std::cout << "SDL create renderer error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } char * basePath = SDL_GetBasePath(); std::string imagePath = std::string(basePath) + "Assets/farback.gif"; std::cout << "Image path is: " << imagePath << std::endl; SDL_Surface *bg = IMG_Load(imagePath.c_str()); if (bg == nullptr) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); std::cout << "SDL load bmp error loading background: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } SDL_free(basePath); SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bg); SDL_FreeSurface(bg); if (tex == nullptr) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); std::cout << "SDL create background texture error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } int w, h; SDL_QueryTexture(tex, nullptr, nullptr, &w, &h); SDL_Event e; bool quit = false; while (!quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { quit = true; } } // Render the scene SDL_RenderClear(ren); SDL_Rect dst; dst.x = 0; dst.y = 0; dst.w = w; dst.h = h; SDL_RenderCopy(ren, tex, nullptr, &dst); SDL_RenderPresent(ren); } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); std::cout << "SDL Sample Exiting\n"; return 0; }
list<SDL_Texture*> createSheet(const char* file, int frames, int delay) { if(frames <= 0) { //return NULL; SDL_Log("Graphics::createSheet Frames cannot <= 0!"); } list<SDL_Texture*> frameList; //list<SDL_Texture*> dummy; //list<SDL_Texture*>* frameList = &dummy; SDL_Surface* surface; SDL_Surface* tempSurface; SDL_Rect surfaceRect; SDL_Rect tempRect; int frameWidth; surface = IMG_Load(file); if(surface != NULL) { //SDL_Log("Sprite sheet is not null"); SDL_Log("Height: %d", surface->h); SDL_Log("Width: %d", surface->w); frameWidth = (surface->w)/frames; SDL_Log("frameWidth: %d", frameWidth); for (int i = 0; i < frames; i++) { Uint32 rmask = 0x000000ff; Uint32 gmask = 0x0000ff00; Uint32 bmask = 0x00ff0000; Uint32 amask = 0xff000000; tempSurface = SDL_CreateRGBSurface(0, (surface->w/frames), surface->h, 32, rmask, gmask, bmask, amask); SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE); SDL_Log("Frame: %d", i); surfaceRect.x = i * (surface->w)/frames; surfaceRect.y = 0; surfaceRect.h = surface->h; surfaceRect.w = (surface->w)/frames; tempRect.x = 0; tempRect.y = 0; tempRect.h = surface->h; tempRect.w = (surface->w)/frames; SDL_Log("sourceRect.x = %d", surfaceRect.x); if(surface != NULL) { SDL_BlitSurface(surface, &surfaceRect, tempSurface, &tempRect); if(tempSurface != NULL) { SDL_Texture* frame = SDL_CreateTextureFromSurface(mainRender, tempSurface); for (int i = 0; i < delay; i++) { frameList.push_back(frame); } } else { SDL_Log("tempSurface = NULL Error: %s", SDL_GetError()); } } else { SDL_Log("Sheet Sprite Surface was Null Error: %s", SDL_GetError()); } } if(!frameList.empty()) { SDL_Log("Returning Framelist"); return frameList; } else { SDL_Log("frameList is equal to NULL!"); } } else { SDL_Log("Couldn't load sprite sheet"); SDL_Log(SDL_GetError()); } }
int main() { die_if(SDL_Init(SDL_INIT_VIDEO), "unable to init SDL"); die_if(!(g_window = SDL_CreateWindow(WIN_TITLE, WIN_X, WIN_Y, WIN_WIDTH, WIN_HEIGHT, 0)), "unable to create window"); die_if(!(g_screen = SDL_GetWindowSurface(g_window)), "unable to create window surface"); die_if(!(g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED)), "unable to create renderer"); die_if(SDL_SetRenderDrawColor( g_renderer, 0x0, 0x0, 0x0, 0xFF ), "unable to set draw color"); g_perf_freq = SDL_GetPerformanceFrequency(); // init textures { SDL_Surface *srfc = NULL; for(unsigned int i = 0; i < NUM_TEX; ++i) { die_if(!(srfc = SDL_LoadBMP((char*)g_tex[i])), "unable to load bitmap"); die_if(!(g_tex[i] = SDL_CreateTextureFromSurface(g_renderer, srfc)) , "unable to create bmp texture"); g_tex_w[i] = srfc->w; g_tex_h[i] = srfc->h; SDL_FreeSurface(srfc); } } alloc_obj(SHIP_TID); int nufos = NUM_UFOS; for(int i = 0; i < nufos; ++i) { alloc_obj(UFO_TID); } Uint64 t0 = SDL_GetPerformanceCounter(); /* used to optimize (minimize) calls to rand() */ #define HASBITS(x,y) (((x) & (y)) == (y)) /* int foo = 0; */ /* for(int i = 0; i < 100000; ++i) */ /* { */ /* int r = rand(); */ /* if (HASBITS(r,0x7) || HASBITS(r,0x70)) ++foo; */ /* } */ // printf("%d\n", foo); // exit(-1); while (1) { // SDL_Delay(10); SDL_Event e; Uint64 t1 = SDL_GetPerformanceCounter(); float dt; dt = (float)(t1 - t0)/g_perf_freq; t0 = t1; /* user events */ if (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { exit_cleanup(0); } if (e.type == SDL_KEYDOWN) { SDL_Keycode sym = e.key.keysym.sym; if(sym == SDLK_SPACE) { alloc_timer_1s(alloc_obj(PHOTON_TID), t1); } g_obj_ax[0] = sym == SDLK_LEFT ? -(X_ACC) : (sym == SDLK_RIGHT ? X_ACC : 0.0f); g_obj_ay[0] = sym == SDLK_UP ? -(Y_ACC) : (sym == SDLK_DOWN ? Y_ACC : 0.0f); } } /* ai events */ for(int i = 1; i < nufos + 1; ++i) { int r = rand(); #define RAND_FREQ 0xf g_obj_ax[i] = HASBITS(r,RAND_FREQ) ? X_ACC : 0.0f; g_obj_ax[i] += HASBITS(r,RAND_FREQ << 8) ? -(X_ACC) : 0.0f; g_obj_ax[i] /= 100.0f; g_obj_ay[i] = HASBITS(r,RAND_FREQ << 16) ? Y_ACC : 0.0f; g_obj_ay[i] += HASBITS(r,RAND_FREQ << 24) ? -(Y_ACC) : 0.0f; g_obj_ay[i] /= 100.0f; } /* timer events */ for(int i = 0; i < g_ntimers; ++i) { if(t1 >= g_timer_expire[i]) { dealloc_timer_1s(i); } } /* physics update */ for(int i = g_nobjs - 1; i >= 0 ; --i) { update(&g_obj_x[i], &g_obj_vx[i], &g_obj_ax[i], dt, -OBJ_W(i), WIN_WIDTH); update(&g_obj_y[i], &g_obj_vy[i], &g_obj_ay[i], dt, -OBJ_H(i), WIN_HEIGHT); } /* collisions */ for(int i = g_nobjs - 1; i >= 0 ; --i) { for(int j = i - 1; j >= 0 ; --j) { if (colliding(i,j)) { } } } /* rendering */ SDL_RenderClear(g_renderer); /* ignore return */ SDL_Texture *tex = g_tex[UFO_TID]; for(int i = 1; i < nufos + 1; ++i) { render(i, tex); } render(0, g_tex[SHIP_TID]); tex = g_tex[PHOTON_TID]; for(int i = 1 + nufos; i < 1 + nufos + g_ntimers; ++i) { render(i, tex); } SDL_RenderPresent(g_renderer); } return 0; }
int main() { Invader invaders[ROWS][COLS]; Defender player; Bullet playerBullet; Ship spaceShip; Bullet invaderBullet[bulletNumber]; Shelter shelter[shelterNumber]; initializeInvaders(invaders); //Initialise playerBullet and initial invader bullet firing setting playerBullet.fire=0; playerBullet.invaderCount=0; playerBullet.score=0; playerBullet.lives=3; playerBullet.bulletHitPlayer=0; for(int i=0; i<bulletNumber; ++i) { invaderBullet[i].fire=1; invaderBullet[i].active=1; } // initialise SDL and check that it worked otherwise exit // see here for details http://wiki.libsdl.org/CategoryAPI if (SDL_Init(SDL_INIT_EVERYTHING) == -1) { printf("%s\n",SDL_GetError()); return EXIT_FAILURE; } // we are now going to create an SDL window SDL_Window *win = 0; win = SDL_CreateWindow("Invaders", 100, 100, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (win == 0) { printf("%s\n",SDL_GetError()); return EXIT_FAILURE; } // the renderer is the core element we need to draw, each call to SDL for drawing will need the // renderer pointer SDL_Renderer *ren = 0; ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); // check to see if this worked if (ren == 0) { printf("%s\n",SDL_GetError() ); return EXIT_FAILURE; } // this will set the background colour to white. // however we will overdraw all of this so only for reference SDL_SetRenderDrawColor(ren, 255, 255, 255, 255); // // SDL image is an abstraction for all images SDL_Surface *image; // // we are going to use the extension SDL_image library to load a png, documentation can be found here // // http://www.libsdl.org/projects/SDL_image/ image=IMG_Load("invaders.png"); if(!image) { printf("IMG_Load: %s\n", IMG_GetError()); return EXIT_FAILURE; } // // SDL texture converts the image to a texture suitable for SDL rendering / blitting // // once we have the texture it will be store in hardware and we don't need the image data anymore SDL_Texture *tex = 0; tex = SDL_CreateTextureFromSurface(ren, image); // free the image SDL_FreeSurface(image); // Initialise player player.move = NONE; player.pos.x = WIDTH/2; player.pos.y = HEIGHT - 30; player.pos.w = DEFENDERSIZE; player.pos.h = DEFENDERSIZE/2; player.srcDefender.w=188; player.srcDefender.h=105; player.srcDefender.x=0; player.srcDefender.y=0; // Initialise player bullet playerBullet.pos.x = (WIDTH/2)+(DEFENDERSIZE/2); playerBullet.pos.y = HEIGHT - 50; playerBullet.pos.w = 2; playerBullet.pos.h = 15; playerBullet.srcBullet.w=bulletWidth; playerBullet.srcBullet.h=250; playerBullet.srcBullet.x=0; playerBullet.srcBullet.y=0; // Initialise invader bullet for(int i=0; i<bulletNumber; ++i) { //a random column is chosen, it then goes through the invaders one by one starting with the bottom one //if the invader is active then it will shoot and break the loop //otherwise it will go to the next invader up until it finds the top //so only the bottom invader for each column is firing int x = 0; int y = rand()%(COLS-2); y +=2; for(int j=ROWS-1; j>=0; j--) { if(invaders[j][y].active==1) { invaders[j][y].shooting=1; x=j; break; } } //if the invader rnadomly chosen is active then the bullet is placed at it's x and y coordinates and fired if(invaders[x][y].shooting==1) { invaderBullet[i].pos.y=invaders[x][y].pos.y; invaderBullet[i].pos.x=((SPRITEWIDTH/2)-(5))+invaders[x][y].pos.x; } else if(invaders[x][y].shooting==0) { invaderBullet[i].fire=0; } invaderBullet[i].pos.w = 10; invaderBullet[i].pos.h = 20; invaderBullet[i].srcBullet.w=24; invaderBullet[i].srcBullet.h=56; invaderBullet[i].srcBullet.x=0; invaderBullet[i].srcBullet.y=0; } //randomise spaceship start direction //will end up either appearing from the right or the left //if its from the left the shipDelay has to be minus so the image is off screen and the opposite for the right srand(time(NULL)); spaceShip.randomDir = rand()%2; int x; if (spaceShip.randomDir==0) { x=-shipDelay; } else if (spaceShip.randomDir==1) { x=shipDelay; } //initialise shelter for(int j=0; j<shelterNumber; j++) { shelter[j].pos.y=500; shelter[j].pos.x=(j*200)+50; shelter[j].pos.w=75; shelter[j].pos.h=25; shelter[j].srcShelter.y=0; shelter[j].srcShelter.w=shelterWidth; shelter[j].srcShelter.h=shelterHeight; } //initialise space ship spaceShip.pos.x=(spaceShip.randomDir*(WIDTH-spaceShipWidth)+x); spaceShip.pos.y=20; spaceShip.pos.w=spaceShipWidth; spaceShip.pos.h=25; spaceShip.srcShip.x=0; spaceShip.srcShip.y=204; spaceShip.srcShip.w=196; spaceShip.srcShip.h=88; int quit=0; // now we are going to loop forever, process the keys then draw //loading in the Defender spritesheet SDL_Surface *imageDefender; imageDefender=IMG_Load("Defender.png"); if(!imageDefender) { printf("IMG_Load: %s\n", IMG_GetError()); return EXIT_FAILURE; } SDL_Texture *texDefender = 0; texDefender = SDL_CreateTextureFromSurface(ren, imageDefender); SDL_FreeSurface(imageDefender); //loading in the enemy fire spritesheet SDL_Surface *imageenemyFire; imageenemyFire=IMG_Load("EnemyShot1.png"); if(!imageenemyFire) { printf("IMG_Load: %s\n", IMG_GetError()); return EXIT_FAILURE; } SDL_Texture *texEnemyFire = 0; texEnemyFire = SDL_CreateTextureFromSurface(ren, imageenemyFire); SDL_FreeSurface(imageenemyFire); //loading in the Shelter spritesheet SDL_Surface *imageShelter; imageShelter=IMG_Load("bunker.png"); if(!imageShelter) { printf("IMG_Load: %s\n", IMG_GetError()); return EXIT_FAILURE; } SDL_Texture *texShelter = 0; texShelter = SDL_CreateTextureFromSurface(ren, imageShelter); SDL_FreeSurface(imageShelter); //loading in the laser spritesheet SDL_Surface *imageBullet; imageBullet=IMG_Load("laser.png"); if(!imageBullet) { printf("IMG_Load: %s\n", IMG_GetError()); return EXIT_FAILURE; } SDL_Texture *texBullet = 0; texBullet = SDL_CreateTextureFromSurface(ren, imageBullet); SDL_FreeSurface(imageBullet); while (quit !=1) { SDL_Event event; // grab the SDL even (this will be keys etc) while (SDL_PollEvent(&event)) { player.move=NONE; playerBullet.start=NONE; // look for the x of the window being clicked and exit if (event.type == SDL_QUIT) quit = 1; // check for a key down if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { // if we have an escape quit case SDLK_ESCAPE : { quit=1; break; } //if we have a right key then the defender moves right along with the bullet before its fired case SDLK_RIGHT : case SDLK_d : { player.move=RIGHT; playerBullet.start=RIGHT; break; } //if we have a left key then the defender moves left along with the bullet before its fired case SDLK_LEFT : case SDLK_a : { player.move=LEFT; playerBullet.start=LEFT; break; } //if we have a space key then the player bullet is fired case SDLK_SPACE : { playerBullet.fire=1; break; } } } } // now we clear the screen (will use the clear colour set previously) SDL_SetRenderDrawColor(ren, 0, 0, 0, 255); SDL_RenderClear(ren); updateInvaders(invaders); drawInvaders(ren,tex,invaders); // Up until now everything was drawn behind the scenes. // This will show the new, red contents of the window. moveDefender(ren, texDefender, &player); playerFire(ren, texBullet, &playerBullet, &player, shelter); invaderFire(ren, texEnemyFire, shelter, invaderBullet, &playerBullet, &player); invaderHit(&playerBullet, invaders); drawSpaceShip(ren, tex, &spaceShip); spaceShipHit(&playerBullet, &spaceShip); invaderReachBottom(&player,invaders, &playerBullet); drawShelter(ren, texShelter, shelter); SDL_RenderPresent(ren); //if the player is hit or the bullet has gone offscreen, or has hit the shelter then //the random position for the next invader is chosen for(int i=0; i<bulletNumber; ++i) { if((invaderBullet[i].bulletHitPlayer==1)|| (invaderBullet[i].bulletOffScreen==1)|| (invaderBullet[i].bulletHitShelter==1)) { //a random column is chosen, it then goes through the invaders one by one starting with the bottom one //if the invader is active then it will shoot and break the loop //otherwise it will go to the next invader up until it finds the top //so only the bottom invader for each column is firing int x = 0; int y = rand()%COLS; for(int j=ROWS-1; j>=0; j--) { invaders[j][y].shooting=0; if(invaders[j][y].active==1) { invaders[j][y].shooting=1; x=j; break; } } //only if the invader is active and is the bottom of it's column will the shooting value be set to 1 //then the bullet is placed at the coordinates of the random invader chosen if(invaders[x][y].shooting==1) { invaderBullet[i].pos.y=invaders[x][y].pos.y; invaderBullet[i].pos.x=((SPRITEWIDTH/2)-(5))+invaders[x][y].pos.x; invaderBullet[i].active=1; invaderBullet[i].fire=1; } else if(invaders[x][y].shooting==0) { invaderBullet[i].fire=0; } invaderBullet[i].bulletOffScreen=0; invaderBullet[i].bulletHitPlayer=0; } } //when the invaders shot = the amount of invaders on screen then they redraw and // reset themselves at the top of the screen along with the counter //shelters do not reset if(playerBullet.invaderCount==ROWS*COLS) { initializeInvaders(invaders); updateInvaders(invaders); drawInvaders(ren,tex,invaders); playerBullet.invaderCount=0; playerBullet.lives+=1; } //if the escpae button is hit or player loses all of their lives then the game ends if((playerBullet.lives<=0)||(player.gameOver==1)) { printf("you lose!\n"); quit=1; } } printf("Your score = [%d]\n",playerBullet.score); printf("Your lives = [%d]\n",playerBullet.lives); SDL_Quit(); return 0; }
BTexture loadTextTexture(char *text, SDL_Color color) { // Convert *text to string before calling this function SDL_Surface *textSurface = TTF_RenderText_Solid(font, text, color); BTexture textTexture; if (textSurface == NULL) printf("Unable to render text surface! Error: %s\n", TTF_GetError()); else { textTexture.texture = SDL_CreateTextureFromSurface(renderer, textSurface); if (textTexture.texture == NULL) printf("Unable to create texture from renderer text! Error: %s\n", SDL_GetError()); else { textTexture.w = textSurface->w; textTexture.h = textSurface->h; } SDL_FreeSurface(textSurface); } return textTexture; }