Пример #1
0
SDL_Texture* Image::Load(SDL_Renderer* renderer, std::string fname) {
	Free();

	//load the file into a surface
	SDL_Surface* surface = IMG_Load(fname.c_str());
	if (!surface) {
		std::ostringstream msg;
		msg << "Failed to load an image file: " << fname;
		msg << "; " << IMG_GetError();
		throw(std::runtime_error(msg.str()));
	}

	//create a texture from this surface
	texture = SDL_CreateTextureFromSurface(renderer, surface);
	if (!texture) {
		std::ostringstream msg;
		msg << "Failed to convert a newly loaded image file: " << fname;
		msg << "; " << SDL_GetError();
		throw(std::runtime_error(msg.str()));
	}

	//set the metadata
	clip.x = 0;
	clip.y = 0;
	if (SDL_QueryTexture(texture, nullptr, nullptr, &clip.w, &clip.h)) {
		std::ostringstream msg;
		msg << "Failed to record metadata for a newly loaded image file: " << fname;
		msg << "; " << SDL_GetError();
		throw(std::runtime_error(msg.str()));
	}
	local = true;

	//free the surface & return
	SDL_FreeSurface(surface);
	return texture;
}
Пример #2
0
SDL_Texture* Image::Create(SDL_Renderer* renderer, Uint16 w, Uint16 h, SDL_Color blank) {
	Free();

	//make the texture
	texture = SDL_CreateTexture(renderer,
		SDL_PIXELFORMAT_RGBA8888,
		SDL_TEXTUREACCESS_TARGET,
		w, h);

	//check
	if (!texture) {
		std::ostringstream msg;
		msg << "Failed to create a texture; " << SDL_GetError();
		throw(std::runtime_error(msg.str()));
	}

	//set the metadata
	clip.x = 0;
	clip.y = 0;
	if (SDL_QueryTexture(texture, nullptr, nullptr, &clip.w, &clip.h)) {
		std::ostringstream msg;
		msg << "Failed to record metadata for a newly created image";
		msg << "; " << SDL_GetError();
		throw(std::runtime_error(msg.str()));
	}
	local = true;

	//blank (black) texture
	SDL_SetRenderTarget(renderer, texture);
	SDL_SetRenderDrawColor(renderer, blank.r, blank.g, blank.b, blank.a);
	SDL_RenderFillRect(renderer, nullptr);
	SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
	SDL_SetRenderTarget(renderer, nullptr);

	return texture;
}
Пример #3
0
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);
	}
}
Пример #4
0
Sprite::Sprite(SDL_Renderer* passed_renderer, SDL_Texture* passed_image, int x, int y, int w, int h, CollisionRectangle passed_collision_rect)
{
    renderer = passed_renderer;
    image = NULL;
    image = passed_image;
    collision_rect = passed_collision_rect;
    collisionSDLRect = collision_rect.GetRectangle();

    //location and size
    rect.x = x;
    rect.y = y;
    rect.w = w;
    rect.h = h;

    SDL_QueryTexture(image, NULL, NULL, &img_width, &img_height);

    //cropped location and size (used for sprite animation)
    crop.x = 0;
    crop.y = 0;
    crop.w = img_width;
    crop.h = img_height;

    //position as double (for distance function)
    X_pos = x;
    Y_pos = y;

    //allows for unit to stand directly on top of target, instead of offset
    origin_x = 0;
    origin_y = 0;

    currentFrame = 0;
    animationDelay = 0;
    amount_frame_x = 0;
    amount_frame_y = 0;

}
Пример #5
0
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);
}
Пример #6
0
// //EXERCISE 1 ---------------------------------------------------
ScrollBar::ScrollBar(const int& x, const int& y, const SDL_Rect* s_b, const SDL_Rect* s_t, SDL_Texture* t_b, SDL_Texture* t_t, bool d, j1Module* l, UIelement* p)
{
	thumb = App->gui->CreateImage(50, 0, *s_t, t_t, true, l, this);
	texture = t_b;
	if (s_b != NULL)
	{
		section = *s_b;
		pos.w = section.w;
		pos.h = section.h;
	}
	else
	{
		section = { 0, 0, 0, 0 };
		SDL_QueryTexture(texture, NULL, NULL, &pos.w, &pos.h);
	}
	pos.x = x;
	pos.y = y;
	type = SCROLL_BAR;
	listener = l;
	parent = p;
	was_cursor_inside = false;
	dragable = false;
	moving_thumb = false;
}
Пример #7
0
void Block::change_type(int tipo)
{

    SDL_DestroyTexture(this->texture);

    switch(tipo)
    {
    case 0:
        this->texture = IMG_LoadTexture(renderer, "FLOOR.png");
        this->isFloor = true;
        this->isWall = false;
        this->is_mino = false;
        break;
    case 1:
        this->texture = IMG_LoadTexture(renderer, "WALL.png");
        this->isFloor = false;
        this->isWall = true;
        this->is_mino = false;
        break;
    case 2:
        this->texture = IMG_LoadTexture(renderer, "TILE_STAR.png");
        this->isFloor = true;
        this->isWall = false;
        this->is_exit = true;
        this->is_mino = false;
        break;
    case 3:
        this->texture = IMG_LoadTexture(renderer, "FLOOR.png");
        this->isFloor = true;
        this->isWall = false;
        this->is_mino = true;
        break;

    }
    SDL_QueryTexture(this->texture,NULL,NULL,&rect_block.w,&rect_block.h);
}
Пример #8
0
void SpriteBatch::sbDrawTextureScaled(SDL_Texture *tex, int x, int y, float scale)
{
    if(!drawingInProgress)
        throw std::runtime_error("sbBegin must be called.");

    SDL_Rect dst;
    if(mainGameCamera == NULL)
    {
        dst.x = x;
        dst.y = y;
    }
    else
    {
        dst.x = x + mainGameCamera->getCameraX();
        dst.y = y + mainGameCamera->getCameraY();
    }

    SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);

    dst.w = int(float(dst.w) * scale);
    dst.h = int(float(dst.h) * scale);

    SDL_RenderCopy(__renderer, tex, NULL, &dst);
}
Пример #9
0
Code print_absolute(const int x, const int y, const char *string, const ColorPair color_pair, Renderer *renderer) {
  char log_buffer[MAXIMUM_STRING_SIZE];
  const SDL_Color foreground = to_sdl_color(color_pair.foreground);
  const SDL_Color background = to_sdl_color(color_pair.background);
  Font *font = global_monospaced_font;
  SDL_Surface *surface;
  SDL_Texture *texture;
  SDL_Rect position;
  position.x = x;
  position.y = y;
  if (string == NULL || string[0] == '\0') {
    return CODE_OK;
  }
  /* Validate that x and y are nonnegative. */
  if (x < 0 || y < 0) {
    return CODE_ERROR;
  }
  surface = TTF_RenderText_Shaded(font, string, foreground, background);
  if (surface == NULL) {
    sprintf(log_buffer, CREATE_SURFACE_FAIL, "print_absolute()");
    log_message(log_buffer);
    return CODE_ERROR;
  }
  texture = SDL_CreateTextureFromSurface(renderer, surface);
  if (texture == NULL) {
    sprintf(log_buffer, CREATE_TEXTURE_FAIL, "print_absolute()");
    log_message(log_buffer);
    return CODE_ERROR;
  }
  /* Copy destination width and height from the texture. */
  SDL_QueryTexture(texture, NULL, NULL, &position.w, &position.h);
  SDL_RenderCopy(renderer, texture, NULL, &position);
  SDL_DestroyTexture(texture);
  SDL_FreeSurface(surface);
  return CODE_OK;
}
Пример #10
0
bool ActorBase::loadTexture(const std::string& imgPath, const SDL_Rect& _clip/* = { 0,0,0,0 }*/)
{
    if (texture)
    {
        SDL_DestroyTexture(texture);
        texture = nullptr;
        position = { 0, 0, 0, 0 };
    }

    texture = engine->loadTexture(imgPath);
    if (!texture)
        return false;
    else
    {
        if (SDL_QueryTexture(texture, &textureFormat, &textureAccess, &textureWidth, &textureHeight) != static_cast<Uint32>(0))
        {
            log << warnlvl << full_log << "Error quarying the texture: " << SDL_GetError() << el;
            throw;
        }
        setClip(_clip);

        return true;
    }
}
Пример #11
0
   void GraphicsManager::RenderTexture (const std::string& id, int srcLeft, int srcTop, int srcRight, int srcBottom, int dstLeft, int dstTop, int dstRight, int dstBottom)
   {
      SDL_Rect* srcRect = nullptr;
      SDL_Rect* dstRect = nullptr;

      ScopeGuard guard([&srcRect, &dstRect] () {
         if (srcRect != nullptr) { delete srcRect; srcRect = nullptr; }
         if (dstRect != nullptr) { delete dstRect; dstRect = nullptr; }
      });

      auto texture = Texture(id);

      if (srcLeft != -1 || srcTop != -1 || srcRight != -1 || srcBottom != -1) {
         srcRect    = new SDL_Rect;
         srcRect->x = srcLeft;
         srcRect->y = srcTop;
         srcRect->w = srcRight - srcLeft;
         srcRect->h = srcBottom - srcTop;
      }

      if (dstLeft != -1 || dstTop != -1 || dstRight != -1 || dstBottom != -1) {
         dstRect    = new SDL_Rect;
         dstRect->x = dstLeft;
         dstRect->y = dstTop;

         if (dstRight != -1 || dstBottom != -1) {
            dstRect->w = dstRight - dstLeft;
            dstRect->h = dstBottom - dstTop;
         }
         else {
            SDL_QueryTexture(texture, nullptr, nullptr, &dstRect->w, &dstRect->h);
         }
      }

      SDL_RenderCopy(device, Texture(id), srcRect, dstRect);
   }
Пример #12
0
// Tank creation Method
Tank::Tank(SDL_Renderer *renderer, int pNum, string filePath, string audioPath, float x, float y)
{
	// activate the player
	active = true;

	// set the player number 0 or 1
	playerNum = pNum;

	// set float for player speed
	speed = 200.0f;

	fire = Mix_LoadWAV((audioPath + "fire.wav").c_str());

	// see if this is player 1, or player 2, and create the correct file path
	if(playerNum == 0){
		//Create the red Tank texture
		playerPath = filePath + "redTank.png";
	}else{
		//Create the blue Tank texture
		playerPath = filePath + "blueTank.png";
	}

	// load the surface into the texture
	texture = IMG_LoadTexture(renderer, playerPath.c_str());

	// set the SDL_Rect X and Y for the player
	posRect.x = x;
	posRect.y = y;

	// Use SDL_QueryTexture to get the W and H of the player's texture
	int w, h;
	SDL_QueryTexture(texture, NULL, NULL, &w, &h);
	posRect.w = w;
	posRect.h = h;

	// Set the movement floats to the players original X and Y
	pos_X = x;
	pos_Y = y;

	// set the xDir and yDir for the joysticks
	xDir = 0;
	yDir = 0;

	// set initial values so the tank can shoot
	xDirOld = 1;
	yDirOld = 0;

	// find the center of the texture
	center.x = posRect.w/2;
	center.y = posRect.h/2;

	// String to create the path to the player's bullet image
	string bulletPath;

	// see if this is player 1, or player 2, and create the correct file path
	if(playerNum == 0){
		//Create the bullet 1 texture
		bulletPath = filePath + "redBullet.png";
	}else{
		//Create the bullet 2 texture
		bulletPath = filePath + "blueBullet.png";
	}

	//Create the player's bullet pool
	for (int i = 0; i < 10; i++)
	{
		// create the bullet and move offscreen, out of the game play area
		TankBullet tmpBullet(renderer, bulletPath, -1000, -1000, 0, 0);

		// add to bulletlist
		bulletList.push_back(tmpBullet);
	}
}
Пример #13
0
int main(int argc,char** argv)
{
    Uint8 num_pictures;
    LoadedPicture* pictures;
    int i, j;
    SDL_PixelFormat* format = NULL;
    SDL_Window *window;
    SDL_Renderer *renderer;
    SDL_Color black = {0,0,0,0xff};
    SDL_Event event;
    int event_pending = 0;
    int should_exit = 0;
    unsigned int current_picture;
    int button_down;
    Uint32 pixelFormat = 0;
    int access = 0;
    SDL_Rect texture_dimensions;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if(argc < 2) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Shape requires at least one bitmap file as argument.");
        exit(-1);
    }

    if(SDL_VideoInit(NULL) == -1) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not initialize SDL video.");
        exit(-2);
    }

    num_pictures = argc - 1;
    pictures = (LoadedPicture *)SDL_malloc(sizeof(LoadedPicture)*num_pictures);
    if (!pictures) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not allocate memory.");
        exit(1);
    }
    for(i=0;i<num_pictures;i++)
        pictures[i].surface = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].surface = SDL_LoadBMP(argv[i+1]);
        pictures[i].name = argv[i+1];
        if(pictures[i].surface == NULL) {
            for(j=0;j<num_pictures;j++)
                SDL_FreeSurface(pictures[j].surface);
            SDL_free(pictures);
            SDL_VideoQuit();
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not load surface from named bitmap file: %s", argv[i+1]);
            exit(-3);
        }

        format = pictures[i].surface->format;
        if(SDL_ISPIXELFORMAT_ALPHA(format->format)) {
            pictures[i].mode.mode = ShapeModeBinarizeAlpha;
            pictures[i].mode.parameters.binarizationCutoff = 255;
        }
        else {
            pictures[i].mode.mode = ShapeModeColorKey;
            pictures[i].mode.parameters.colorKey = black;
        }
    }

    window = SDL_CreateShapedWindow("SDL_Shape test",
        SHAPED_WINDOW_X, SHAPED_WINDOW_Y,
        SHAPED_WINDOW_DIMENSION,SHAPED_WINDOW_DIMENSION,
        0);
    SDL_SetWindowPosition(window, SHAPED_WINDOW_X, SHAPED_WINDOW_Y);
    if(window == NULL) {
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        SDL_free(pictures);
        SDL_VideoQuit();
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create shaped window for SDL_Shape.");
        exit(-4);
    }
    renderer = SDL_CreateRenderer(window,-1,0);
    if (!renderer) {
        SDL_DestroyWindow(window);
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        SDL_free(pictures);
        SDL_VideoQuit();
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create rendering context for SDL_Shape window.");
        exit(-5);
    }

    for(i=0;i<num_pictures;i++)
        pictures[i].texture = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].texture = SDL_CreateTextureFromSurface(renderer,pictures[i].surface);
        if(pictures[i].texture == NULL) {
            for(i=0;i<num_pictures;i++)
                if(pictures[i].texture != NULL)
                    SDL_DestroyTexture(pictures[i].texture);
            for(i=0;i<num_pictures;i++)
                SDL_FreeSurface(pictures[i].surface);
            SDL_free(pictures);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(window);
            SDL_VideoQuit();
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create texture for SDL_shape.");
            exit(-6);
        }
    }

    event_pending = 0;
    should_exit = 0;
    event_pending = SDL_PollEvent(&event);
    current_picture = 0;
    button_down = 0;
    texture_dimensions.h = 0;
    texture_dimensions.w = 0;
    texture_dimensions.x = 0;
    texture_dimensions.y = 0;
    SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Changing to shaped bmp: %s", pictures[current_picture].name);
    SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
    SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
    SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
    while(should_exit == 0) {
        event_pending = SDL_PollEvent(&event);
        if(event_pending == 1) {
            if(event.type == SDL_KEYDOWN) {
                button_down = 1;
                if(event.key.keysym.sym == SDLK_ESCAPE) {
                    should_exit = 1;
                    break;
                }
            }
            if(button_down && event.type == SDL_KEYUP) {
                button_down = 0;
                current_picture += 1;
                if(current_picture >= num_pictures)
                    current_picture = 0;
                SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Changing to shaped bmp: %s", pictures[current_picture].name);
                SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
                SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
                SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
            }
            if(event.type == SDL_QUIT)
                should_exit = 1;
            event_pending = 0;
        }
        render(renderer,pictures[current_picture].texture,texture_dimensions);
        SDL_Delay(10);
    }

    /* Free the textures. */
    for(i=0;i<num_pictures;i++)
        SDL_DestroyTexture(pictures[i].texture);
    SDL_DestroyRenderer(renderer);
    /* Destroy the window. */
    SDL_DestroyWindow(window);
    /* Free the original surfaces backing the textures. */
    for(i=0;i<num_pictures;i++)
        SDL_FreeSurface(pictures[i].surface);
    SDL_free(pictures);
    /* Call SDL_VideoQuit() before quitting. */
    SDL_VideoQuit();

    return 0;
}
int
main(int argc, char *argv[])
{
    int i, done;
    const char *driver;
    SDL_Window *window;
    SDL_Texture *sprite;
    int window_w, window_h;
    int sprite_w, sprite_h;
    SDL_Event event;

    if (SDL_VideoInit(NULL, 0) < 0) {
        fprintf(stderr, "Couldn't initialize SDL video: %s\n",
                SDL_GetError());
        exit(1);
    }
    driver = SDL_GetCurrentVideoDriver();

    /* Find a native window driver and create a native window */
    for (i = 0; factories[i]; ++i) {
        if (SDL_strcmp(driver, factories[i]->tag) == 0) {
            factory = factories[i];
            break;
        }
    }
    if (!factory) {
        fprintf(stderr, "Couldn't find native window code for %s driver\n",
                driver);
        quit(2);
    }
    printf("Creating native window for %s driver\n", driver);
    native_window = factory->CreateNativeWindow(WINDOW_W, WINDOW_H);
    if (!native_window) {
        fprintf(stderr, "Couldn't create native window\n");
        quit(3);
    }
    window = SDL_CreateWindowFrom(native_window);
    if (!window) {
        fprintf(stderr, "Couldn't create SDL window: %s\n", SDL_GetError());
        quit(4);
    }
    SDL_SetWindowTitle(window, "SDL Native Window Test");

    /* Create the renderer */
    if (SDL_CreateRenderer(window, -1, 0) < 0) {
        fprintf(stderr, "Couldn't create renderer: %s\n", SDL_GetError());
        quit(5);
    }

    /* Clear the window, load the sprite and go! */
    SDL_SelectRenderer(window);
    SDL_SetRenderDrawColor(0xA0, 0xA0, 0xA0, 0xFF);
    SDL_RenderClear();

    sprite = LoadSprite(window, "icon.bmp");
    if (!sprite) {
        quit(6);
    }

    /* Allocate memory for the sprite info */
    SDL_GetWindowSize(window, &window_w, &window_h);
    SDL_QueryTexture(sprite, NULL, NULL, &sprite_w, &sprite_h);
    positions = (SDL_Rect *) SDL_malloc(NUM_SPRITES * sizeof(SDL_Rect));
    velocities = (SDL_Rect *) SDL_malloc(NUM_SPRITES * sizeof(SDL_Rect));
    if (!positions || !velocities) {
        fprintf(stderr, "Out of memory!\n");
        quit(2);
    }
    srand(time(NULL));
    for (i = 0; i < NUM_SPRITES; ++i) {
        positions[i].x = rand() % (window_w - sprite_w);
        positions[i].y = rand() % (window_h - sprite_h);
        positions[i].w = sprite_w;
        positions[i].h = sprite_h;
        velocities[i].x = 0;
        velocities[i].y = 0;
        while (!velocities[i].x && !velocities[i].y) {
            velocities[i].x = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
            velocities[i].y = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
        }
    }

    /* Main render loop */
    done = 0;
    while (!done) {
        /* Check for events */
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_WINDOWEVENT:
                switch (event.window.event) {
                case SDL_WINDOWEVENT_EXPOSED:
                    SDL_SelectRenderer(event.window.windowID);
                    SDL_SetRenderDrawColor(0xA0, 0xA0, 0xA0, 0xFF);
                    SDL_RenderClear();
                    break;
                }
                break;
            case SDL_QUIT:
                done = 1;
                break;
            default:
                break;
            }
        }
        MoveSprites(window, sprite);
    }

    quit(0);
}
Пример #15
0
int BEE::Background::load_from_surface(SDL_Surface* tmp_surface) {
    if (!is_loaded) {
        if (game->options->renderer_type != BEE_RENDERER_SDL) {
            width = tmp_surface->w;
            height = tmp_surface->h;

            glGenVertexArrays(1, &vao);
            glBindVertexArray(vao);

            GLfloat texcoords[] = {
                0.0, 0.0,
                1.0, 0.0,
                1.0, 1.0,
                0.0, 1.0,
            };
            glGenBuffers(1, &vbo_texcoords);
            glBindBuffer(GL_ARRAY_BUFFER, vbo_texcoords);
            glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords, GL_STATIC_DRAW);

            GLfloat vertices[] = {
                0.0,            0.0,
                (GLfloat)width, 0.0,
                (GLfloat)width, (GLfloat)height,
                0.0,            (GLfloat)height,
            };
            glGenBuffers(1, &vbo_vertices);
            glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices);
            glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

            GLushort elements[] = {
                0, 1, 2,
                2, 3, 0,
            };
            glGenBuffers(1, &ibo);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

            glEnableVertexAttribArray(game->vertex_location);
            glBindBuffer(GL_ARRAY_BUFFER, vbo_vertices);
            glVertexAttribPointer(
                game->vertex_location,
                2,
                GL_FLOAT,
                GL_FALSE,
                0,
                0
            );

            glGenTextures(1, &gl_texture);
            glBindTexture(GL_TEXTURE_2D, gl_texture);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexImage2D(
                GL_TEXTURE_2D,
                0,
                GL_RGBA,
                width,
                height,
                0,
                GL_RGBA,
                GL_UNSIGNED_BYTE,
                tmp_surface->pixels
            );

            glBindVertexArray(0);

            is_loaded = true;
            has_draw_failed = false;
        } else {
            texture = SDL_CreateTextureFromSurface(game->renderer, tmp_surface);
            if (texture == nullptr) {
                game->messenger_send({"engine", "background"}, BEE_MESSAGE_WARNING, "Failed to create texture from surface: " + get_sdl_error());
                return 1;
            }

            SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);

            is_loaded = true;
            has_draw_failed = false;
        }
    } else {
        game->messenger_send({"engine", "background"}, BEE_MESSAGE_WARNING, "Failed to load background from surface because it has already been loaded");
        return 1;
    }

    return 0;
}
Пример #16
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;
}
Пример #17
0
int main( int argc, char* args[] )
{
//Init SDL
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        return 10;
    }
//Creates a SDL Window
    if((window = SDL_CreateWindow("Image Loading", 100, 100, 500/*WIDTH*/, 250/*HEIGHT*/, SDL_WINDOW_RESIZABLE | SDL_RENDERER_PRESENTVSYNC)) == NULL)
    {
        return 20;
    }
//SDL Renderer
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED );
    if (renderer == NULL)
    {
        std::cout << SDL_GetError() << std::endl;
        return 30;
    }

//Init textures
    int w=0,h=0;
    background = IMG_LoadTexture(renderer,"fondo.png");
    SDL_QueryTexture(background, NULL, NULL, &w, &h);
    rect_background.x = 0;
    rect_background.y = 0;
    rect_background.w = w;
    rect_background.h = h;

    w=0,h=0;
    background = IMG_LoadTexture(renderer,"Fresh.png");
    SDL_QueryTexture(background, NULL, NULL, &w, &h);
    rect_background.x = 0;
    rect_background.y = 0;
    rect_background.w = w;
    rect_background.h = h;

    character = IMG_LoadTexture(renderer, "personaje.png");
    SDL_QueryTexture(character, NULL, NULL, &w, &h);
    rect_character.x = 0;
    rect_character.y = 100;
    rect_character.w = w;
    rect_character.h = h;

//Main Loop
    while(true)
    {
        while(SDL_PollEvent(&Event))
        {
            if(Event.type == SDL_QUIT)
            {
                return 0;
            }
            if(Event.type == SDL_KEYDOWN)
            {
                if(Event.key.keysym.sym == SDLK_d)
                    rect_character.x++;
                else if(Event.key.keysym.sym == SDLK_w)
                    rect_character.y--;
                else if(Event.key.keysym.sym == SDLK_s)
                    rect_character.y++;
                else if(Event.key.keysym.sym == SDLK_a)
                    rect_character.x--;
            }
            const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
            if( currentKeyStates[ SDL_SCANCODE_UP ] )
            {
                rect_character.y--;
            }
            else if( currentKeyStates[ SDL_SCANCODE_DOWN ] )
            {
                rect_character.y++;
            }
            else if( currentKeyStates[ SDL_SCANCODE_LEFT ] )
            {
                rect_character.x--;
            }
            else if( currentKeyStates[ SDL_SCANCODE_RIGHT ] )
            {
                rect_character.x++;
            }
            else if( currentKeyStates[ SDL_SCANCODE_Q ] )
            {
                rect_character.x--;
                rect_character.y--;
            }
            else if( currentKeyStates[ SDL_SCANCODE_E ] )
            {
                rect_character.x++;
                rect_character.y--;
            }

        }

        SDL_RenderCopy(renderer, background, NULL, &rect_background);
        SDL_RenderCopy(renderer, character, NULL, &rect_character);
        SDL_RenderPresent(renderer);
    }

    return 0;
}
Пример #18
0
//=============================================================================
void Draw()
{
	// clear render
	SDL_RenderClear(renderer);

	// viewport
	SDL_Rect view;
	view.w = 32*20;
	view.h = 32*20;
	view.x = 0;
	view.y = 0;
	SDL_RenderSetViewport(renderer, &view);
	
	// tiles
	SDL_Rect r, r4;
	r4.w = r.w = 32;
	r4.h = r.h = 32;
	int start_x = cam_pos.x/32,
		start_y = cam_pos.y/32,
		end_x = min((cam_pos.x+SCREEN_SIZE.x)/32+1, MAP_W),
		end_y = min((cam_pos.y+SCREEN_SIZE.y)/32+1, MAP_H);
	for(int y=start_y; y<end_y; ++y)
	{
		for(int x=start_x; x<end_x; ++x)
		{
			r.x = x*32 - cam_pos.x;
			r.y = y*32 - cam_pos.y;
			Tile& tile = mapa[x+y*MAP_W];
			if(tile.building)
			{
				if(tile.building_tile == BT_DOOR)
				{
					r4.x = door_offset.x*32;
					r4.y = door_offset.y*32;
				}
				else if(tile.building_tile == BT_WALL)
				{
					r4.x = wall_offset.x*32;
					r4.y = wall_offset.y*32;
				}
				else
				{
					r4.x = wall_offset.x*32;
					r4.y = wall_offset.y*32;
					SDL_RenderCopy(renderer, tBuilding, &r4, &r);
					const INT2& offset = tile.building->base->offset;
					r4.x = offset.x*32;
					r4.y = offset.y*32;
				}
				SDL_RenderCopy(renderer, tBuilding, &r4, &r);
			}
			else
				SDL_RenderCopy(renderer, tTiles, &tiles[mapa[x+y*MAP_W].type].rect, &r);
		}
	}
	
	// unit
	for(vector<Unit*>::iterator it = units.begin(), end = units.end(); it != end; ++it)
	{
		Unit& u = **it;
		if(u.inside_building)
			continue;
		INT2 pos = u.GetPos();
		r.x = pos.x-cam_pos.x;
		r.y = pos.y-cam_pos.y;
		SDL_Rect rr;
		rr.w = 32;
		rr.h = 32;
		rr.x = u.base->offset.x*32;
		rr.y = u.base->offset.y*32;
		SDL_RenderCopy(renderer, tUnit, &rr, &r);
		
		// hp bar
		if(u.hp != u.base->hp)
		{
			Uint8 cr, g, b = 0;
			float hpp = float(u.hp)/u.base->hp;
			if(hpp <= 0.5f)
			{
				float t = hpp*2;
				cr = lerp(255, 255, t);
				g = lerp(0, 216, t);
			}
			else
			{
				float t = (hpp-0.5f)*2;
				cr = lerp(255, 76, t);
				g = lerp(216, 255, t);
			}
			SDL_SetTextureColorMod(tHpBar, cr, g, b);
			SDL_Rect r2;
			r2.w = int(float(u.hp)/u.base->hp*32);
			if(r2.w <= 0)
				r2.w = 1;
			r2.h = 2;
			r2.x = 0;
			r2.y = 0;
			SDL_Rect r3;
			r3.w = r2.w;
			r3.h = r2.h;
			r3.x = r.x;
			r3.y = r.y;
			SDL_RenderCopy(renderer, tHpBar, &r2, &r3);
		}
	}

	// attack image
	for(vector<Hit>::iterator it = hits.begin(), end = hits.end(); it != end; ++it)
	{
		r.x = it->pos.x - cam_pos.x;
		r.y = it->pos.y - cam_pos.y;
		SDL_RenderCopy(renderer, tHit, NULL, &r);
	}

	// selected unit border
	if(CheckRef(selected))
	{
		INT2 pos = selected->GetRef().GetPos();
		r.x = pos.x - cam_pos.x;
		r.y = pos.y - cam_pos.y;
		SDL_RenderCopy(renderer, tSelected, NULL, &r);
	}

	SDL_RenderSetViewport(renderer, NULL);
	
	// text
	if(player)
		text[0].Set(player->GetText());
	SDL_QueryTexture(text[0].tex, NULL, NULL, &r.w, &r.h);
	r.x = 32*(MAP_W+1);
	r.y = 32;
	SDL_RenderCopy(renderer, text[0].tex, NULL, &r);

	// selected unit text
	if(CheckRef(selected))
	{
		text[1].Set(selected->GetRef().GetText());
		SDL_QueryTexture(text[1].tex, NULL, NULL, &r.w, &r.h);
		r.y = 232;
		SDL_RenderCopy(renderer, text[1].tex, NULL, &r);
	}

	// building
	if(player && player->alive && player->inside_building)
	{
		// text
		text[2].Set(Format("Inside building: %s", inn->base->name));
		SDL_QueryTexture(text[2].tex, NULL, NULL, &r.w, &r.h);
		r.x = 32;
		r.y = 672;
		SDL_RenderCopy(renderer, text[2].tex, NULL, &r);

		// button
		r.x = 32;
		r.y = 700;
		r.w = 16;
		r.h = 16;
		r4.x = 0;
		r4.y = 0;
		r4.w = 16;
		r4.h = 16;
		SDL_RenderCopy(renderer, tButton, &r4, &r);

		// button text
		bool draw_text = false;
		if(cursor_pos.x >= 32 && cursor_pos.y >= 700 && cursor_pos.x < 32+16 && cursor_pos.y < 700+16)
		{
			draw_text = true;
			text[3].Set("Sleep inside inn for 10 gp.");
		}

		if(draw_text)
		{
			SDL_QueryTexture(text[3].tex, NULL, NULL, &r.w, &r.h);
			r.x = 32;
			r.y = 728;
			SDL_RenderCopy(renderer, text[3].tex, NULL, &r);
		}
	}

	// display render
	SDL_RenderPresent(renderer);
}
Пример #19
0
void Sprite::setTexture(const Texture &texture)
{
    m_texture = &texture;
    SDL_QueryTexture(*m_texture, nullptr, nullptr, &m_rect.w, &m_rect.h);
}
Пример #20
0
void ApplySurface(int32_t x, int32_t y, SDL_Texture *tex, SDL_Renderer *rend, const double angle) {
	SDL_Rect pos;
	SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h);
	ApplySurface(x, y, tex, rend, pos.w, pos.h, angle);
}
Пример #21
0
void UI::setTexture(string textureDir)
{
  texture = IMG_LoadTexture(renderer, textureDir.c_str());
  SDL_QueryTexture(texture, 0, 0, &bounds.w, &bounds.h);
}
Пример #22
0
void DemoState::DrawInstructions() {
  SDL_Rect rect = {0, 0, 0, 0};
  SDL_QueryTexture(instructions_texture_, nullptr, nullptr, &rect.w, &rect.h);
  SDL_RenderCopy(renderer_, instructions_texture_, nullptr, &rect);
}
Пример #23
0
int main (void) { //int argv, char **argc
	int x, y, i, j, bW, bH, fW, fH, sW, sH;
	int curClip = 0;
	bool quit = 0;
	const Uint8 *kbState = SDL_GetKeyboardState(NULL);
	char **imgFromSrc;

	SDL_Event e;
	SDL_Window *win;
	SDL_Renderer *ren;
	SDL_Texture *bg;
	SDL_Texture *fg;

	SDL_Rect wall;
	SDL_Rect clips[CLIPS_AMOUNT];

	if (SDL_Init(SDL_INIT_VIDEO) != 0 || (IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG) {
		logSDLError("Init");
		return 1;
	}

	win = SDL_CreateWindow("Hello World!", WINDOW_OFFSET_X, WINDOW_OFFSET_Y, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
	if (win == NULL) {
		logSDLError("CreateWindow");
		return 2;
	}

	ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == NULL) {
		logSDLError("CreateRenderer");
		return 3;
	}

	imgFromSrc = bmp_xpm;
	bg = loadHeader(imgFromSrc, ren);
	fg = loadTexture("../SDL/sprites/sprite.png", ren);
	if (bg == NULL || fg == NULL) {
		logSDLError("loadTexture");
		return 4;
	}

	SDL_RenderClear(ren);

	SDL_QueryTexture(bg, NULL, NULL, &bW, &bH);

	bW /= 2;
	bH /= 2;

	for (i = 0; i < WINDOW_WIDTH / bW; i++) {
		for (j = 0; j <= WINDOW_HEIGHT / bH; j++) {
			renderTextureS(bg, ren, i * bW, j * bH, bW, bH);
		}
	}

	fW = 95;
	fH = 95;
	x = WINDOW_WIDTH / 2 - fW / 2;
	y = WINDOW_WIDTH / 2 - fH / 2;

	for (i = 0; i < CLIPS_AMOUNT; i++) {
		clips[i].x = i / 2 * fW;
		clips[i].y = i % 2 * fH;

		clips[i].w = fW;
		clips[i].h = fH;
	}

	SDL_QueryTexture(fg, NULL, NULL, &sW, &sH);
	renderTexture(fg, ren, x, y);

	SDL_RenderPresent(ren);

	SDL_Delay(2000);

	while (!quit) {
		while (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT) quit = 1;
			//if (e.type == SDL_MOUSEBUTTONDOWN) quit = 1;
		}

		if (kbState[SDL_SCANCODE_W] || kbState[SDL_SCANCODE_UP]) {
			x -= 5; curClip = 3;
			if (x < -sW) x = WINDOW_WIDTH - sW;
		}
		
		if (kbState[SDL_SCANCODE_A] || kbState[SDL_SCANCODE_LEFT]) {
			y -= 5; curClip = 0;
			if (y < -sH) y = WINDOW_HEIGHT + sH;
		}
		
		if (kbState[SDL_SCANCODE_S] || kbState[SDL_SCANCODE_DOWN]) {
			x += 5; curClip = 1;
			if (x > WINDOW_WIDTH - sW) x = 0 -sW;
		}
		
		if (kbState[SDL_SCANCODE_D] || kbState[SDL_SCANCODE_RIGHT]) {
			y += 5; curClip = 2;
			if (y > WINDOW_HEIGHT + sH) y = 0 -sH;
		}

		SDL_RenderClear(ren);

		for (i = 0; i < WINDOW_WIDTH / bW; i++) {
			for (j = 0; j <= WINDOW_HEIGHT / bH; j++) {
				renderTextureS(bg, ren, i * bW, j * bH, bW, bH);
			}
		}

		renderSprite(fg, ren, x, y, &clips[curClip]);
		SDL_RenderPresent(ren);
	}

	SDL_DestroyTexture(bg);
	SDL_DestroyTexture(fg);
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);

	cleanUp();

	return 0;
}
Пример #24
0
 TexturePrivate(SDL_Texture *texture) : texture_(texture){
   int32_t w, h;
   SDL_QueryTexture(texture, NULL, NULL, &w, &h);
   src_rect_ = Rect(0,0,w,h);
 }
Пример #25
0
int main(int argc, char **argv){
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		logSDLError(std::cout, "SDL_Init");
		return 1;
	}

	if (TTF_Init() != 0){
	logSDLError(std::cout, "TTF_Init");
	return 1;
	}

	SDL_Window *window = SDL_CreateWindow("Hello World!", 100, 100, SCREEN_WIDTH, GRID_HEIGHT + HUD_HEIGHT,
	SDL_WINDOW_SHOWN);
	if (window == nullptr){
		logSDLError(std::cout, "CreateWindow");
		SDL_Quit();
		return 2;
	}

	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (renderer == nullptr){
		logSDLError(std::cout, "CreateRenderer");
		SDL_DestroyWindow(window);
		SDL_Quit();
		return 3;
	}

	//The textures we'll be using
	SDL_Texture *background = loadTexture("res/game_bg.jpg", renderer);
	SDL_Texture *image = loadTexture("res/Blue.png", renderer);
	SDL_Texture *blueGem = loadTexture("res/Blue.png", renderer);
	SDL_Texture *greenGem = loadTexture("res/Green.png", renderer);
	SDL_Texture *purpleGem = loadTexture("res/Purple.png", renderer);
	SDL_Texture *redGem = loadTexture("res/Red.png", renderer);
	SDL_Texture *yellowGem = loadTexture("res/Yellow.png", renderer);
	SDL_Texture *gems[] = {blueGem, greenGem, purpleGem, redGem, yellowGem};
	SDL_Texture *cursorYellowImg = loadTexture("res/cursor_yellow.png", renderer);
	SDL_Texture *cursorGreenImg = loadTexture("res/cursor_green.png", renderer);
	//Make sure they both loaded ok
	if (background == nullptr || image == nullptr){
		SDL_DestroyRenderer(renderer);
		SDL_DestroyWindow(window);
		SDL_Quit();
		return 4;
	}

	//We'll render the string "TTF fonts are cool!" in white
	//Color is in RGB format
	SDL_Color color = { 255, 255, 255 };
	SDL_Texture *textImage;
	TTF_Font* font = loadFont("res/sample.ttf", 32);

	//Our event structure
	SDL_Event e;
	//For tracking if we want to quit
	bool quit = false;
	int gameState = GAMESTATE_TITLE_SCREEN;
	int** pGridArray;
	gem* pGemsArray = new gem[NUM_ROWS * NUM_COLUMNS];

	int score;

	int mouseX = 0;
	int mouseY = 0;
	int numGemsSelected = 0;
	int selectedGems[2][2] = {{-1, -1}, {-1, -1}};
	bool gemSelected = false;
	int cursorRow = 0;
	int cursorColumn = 0;
	bool foundMatch = false;
	int thisRow, thisColumn;
	bool gemsDropping;
	bool cancelSwap = false;
	bool mouseDown = false;
	int dragStartX;
	int dragStartY;
	bool dragStarted = false;
	time_t timer;
	time_t startTime;
	std::ostringstream os;

	while (!quit)
	{
		switch (gameState)
		{
			case GAMESTATE_TITLE_SCREEN:
			break;

			case GAMESTATE_INIT:
				for (int i = 0; i < NUM_ROWS*NUM_COLUMNS; i++)
				{
					pGemsArray[i].state = GEMSTATE_IDLE;
				}
				pGridArray = initGrid(pGemsArray);
				score = 0;
				startTime = time(0);
				gameState = GAMESTATE_INITIAL_CHECK_MATCH;
			break;

			case GAMESTATE_INITIAL_CHECK_MATCH:
				SDL_Delay(1000);
				checkMatchAllRows(pGridArray, pGemsArray, &score);
				gameState = GAMESTATE_CHECKDROP;
			break;

			case GAMESTATE_CHECK_MATCH:

				foundMatch = false;
				for (int row = NUM_ROWS-1; row >= 0; row--)
				{
					for (int column = 0; column < NUM_COLUMNS; column++)
					{
						if (pGemsArray[pGridArray[row][column]].prevState == GEMSTATE_FALL)
						{
							foundMatch = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[row][column]], &score);
						}
					}
				}

				gameState = GAMESTATE_CHECKDROP;

				for (int row = NUM_ROWS-1; row >= 0; row--)
				{
					for (int column = 0; column < NUM_COLUMNS; column++)
					{
						pGemsArray[pGridArray[row][column]].prevState = -1;
					}
				}

			break;

			case GAMESTATE_AWAIT_INPUT:

				if (gemSelected)
				{
					if (numGemsSelected < 2)
					{
						numGemsSelected++;
					}
					else
					{
						numGemsSelected = 0;
					}
					cursorRow = (mouseY-HUD_HEIGHT) / ROW_HEIGHT;
					cursorColumn = mouseX / COLUMN_WIDTH;

					// Store the location of the selected gem
					selectedGems[numGemsSelected-1][ROW] = cursorRow;
					selectedGems[numGemsSelected-1][COLUMN] = cursorColumn; 

					gemSelected = false;

					// Check if ready to swap
					if (numGemsSelected == 2)
					{
						int state = checkSwapGems((int*)selectedGems);
						state = setSwapGems(state, pGemsArray, pGridArray, selectedGems[0][ROW], selectedGems[0][COLUMN], selectedGems[1][ROW], selectedGems[1][COLUMN]);
						if (state == -1)
						{

							// Remove all cursors
							numGemsSelected = 0;

							// Set new cursor to this position
							cursorRow = (mouseY-HUD_HEIGHT) / ROW_HEIGHT;
							cursorColumn = mouseX / COLUMN_WIDTH;

							// Store the location of the selected gem
							selectedGems[numGemsSelected-1][ROW] = cursorRow;
							selectedGems[numGemsSelected-1][COLUMN] = cursorColumn; 
							gemSelected = true;
						}
						else
						{
							gameState = state;
						}
					}
				}
				
			break;


			case GAMESTATE_SWAP_LEFT:
			case GAMESTATE_SWAP_RIGHT:

				thisRow = selectedGems[0][ROW];
				if (gameState == GAMESTATE_SWAP_LEFT)
					thisColumn = selectedGems[0][COLUMN];
				else
					thisColumn = selectedGems[1][COLUMN];

				pGemsArray[pGridArray[thisRow][thisColumn]].x += pGemsArray[pGridArray[thisRow][thisColumn]].velocity;
				pGemsArray[pGridArray[thisRow][thisColumn-1]].x += pGemsArray[pGridArray[thisRow][thisColumn-1]].velocity;
				
				if (pGemsArray[pGridArray[thisRow][thisColumn]].x <= -COLUMN_WIDTH)
				{
					numGemsSelected = 0;

					// Swap with other gem
					int temp = pGridArray[thisRow][thisColumn];
					pGridArray[thisRow][thisColumn] = pGridArray[thisRow][thisColumn-1];
					pGridArray[thisRow][thisColumn-1] = temp;

					pGemsArray[pGridArray[thisRow][thisColumn]].velocity = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].x = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].column++;
					pGemsArray[pGridArray[thisRow][thisColumn]].state = GEMSTATE_IDLE;
					
					pGemsArray[pGridArray[thisRow][thisColumn-1]].velocity = 0;
					pGemsArray[pGridArray[thisRow][thisColumn-1]].x = 0;
					pGemsArray[pGridArray[thisRow][thisColumn-1]].column--;
					pGemsArray[pGridArray[thisRow][thisColumn-1]].state = GEMSTATE_IDLE;

					bool foundMatch = false;
					bool foundMatch2 = false;
					if (!cancelSwap)
					{
						foundMatch = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow][thisColumn]], &score);
						foundMatch2 = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow][thisColumn-1]], &score);
					}

					if (foundMatch || foundMatch2)
					{
						gameState = GAMESTATE_CHECKDROP;
					}
					else
					{
						if (cancelSwap)
						{
							// Gems have gone back to their original positions after cancelling the swap
							cancelSwap = false;
							gameState = GAMESTATE_AWAIT_INPUT;
						}
						else
						{
							// Swap the gems back to their original positions
							gameState = setSwapGems(gameState, pGemsArray, pGridArray, selectedGems[0][ROW], selectedGems[0][COLUMN], selectedGems[1][ROW], selectedGems[1][COLUMN]);
							cancelSwap = true;
						}
	
					}
				}					
			break;

			case GAMESTATE_SWAP_UP:
			case GAMESTATE_SWAP_DOWN:

				thisColumn = selectedGems[0][COLUMN];
				if (gameState == GAMESTATE_SWAP_UP)
					thisRow = selectedGems[0][ROW];
				else
					thisRow = selectedGems[1][ROW];

				pGemsArray[pGridArray[thisRow][thisColumn]].y += pGemsArray[pGridArray[thisRow][thisColumn]].velocity;
				pGemsArray[pGridArray[thisRow-1][thisColumn]].y += pGemsArray[pGridArray[thisRow-1][thisColumn]].velocity;
				
				if (pGemsArray[pGridArray[thisRow][thisColumn]].y <= -ROW_HEIGHT)
				{
					numGemsSelected = 0;
					
					// Swap with other gem
					int temp = pGridArray[thisRow][thisColumn];
					pGridArray[thisRow][thisColumn] = pGridArray[thisRow-1][thisColumn];
					pGridArray[thisRow-1][thisColumn] = temp;

					pGemsArray[pGridArray[thisRow][thisColumn]].velocity = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].y = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].row++;
					pGemsArray[pGridArray[thisRow][thisColumn]].state = GEMSTATE_IDLE;

					pGemsArray[pGridArray[thisRow-1][thisColumn]].velocity = 0;
					pGemsArray[pGridArray[thisRow-1][thisColumn]].y = 0;
					pGemsArray[pGridArray[thisRow-1][thisColumn]].row--;
					pGemsArray[pGridArray[thisRow-1][thisColumn]].state = GEMSTATE_IDLE;

					bool foundMatch = false;
					bool foundMatch2 = false;
					if (!cancelSwap)
					{
						foundMatch = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow][thisColumn]], &score);
						foundMatch2 = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow-1][thisColumn]], &score);
					}

					if (foundMatch || foundMatch2)
					{
						gameState = GAMESTATE_CHECKDROP;
					}
					else
					{					
						if (cancelSwap)
						{
							// Gems have gone back to their original positions after cancelling the swap
							cancelSwap = false;
							gameState = GAMESTATE_AWAIT_INPUT;
						}
						else
						{
							// Swap the gems back to their original positions
							gameState = setSwapGems(gameState, pGemsArray, pGridArray, selectedGems[0][ROW], selectedGems[0][COLUMN], selectedGems[1][ROW], selectedGems[1][COLUMN]);
							cancelSwap = true;
						}
					}
				}					
			break;

			case GAMESTATE_CHECKDROP:

				if (checkDrop(pGridArray, pGemsArray))
				{
					gameState = GAMESTATE_DROP;
				}
				else
				{
					gameState = GAMESTATE_ADD_GEMS;
				}

			break;

			case GAMESTATE_DROP:

				// Check if any more gems are dropping
				gemsDropping = false;
				for (int i = 0; i < NUM_ROWS * NUM_COLUMNS; i++)
				{
					if (pGemsArray[i].state == GEMSTATE_FALL || pGemsArray[i].state == GEMSTATE_ENTER || pGemsArray[i].state == GEMSTATE_BOUNCE)
					{
						gemsDropping = true;
						break;
					}
				}

				if (!gemsDropping)
				{
					gameState = GAMESTATE_CHECK_MATCH;
				}
			break;


			case GAMESTATE_GAME_OVER:

				if (timer - startTime >= GAME_OVER_TIMEOUT)
				{
					gameState = GAMESTATE_TITLE_SCREEN;
					startTime = time(0);
				}
			break;

			case GAMESTATE_ADD_GEMS:

				srand(time(NULL));
				bool gemsAdded = false;
				// Find empty columns
				for (int column = 0; column < NUM_COLUMNS; column++)
				{
					// Find empty spaces in this column starting from top
					int row = 0;
					
					while (pGemsArray[pGridArray[row][column]].type == -1)
					{
						pGemsArray[pGridArray[row][column]].type = rand() % NUM_GEM_TYPES;
						pGemsArray[pGridArray[row][column]].state = GEMSTATE_ENTER;
						pGemsArray[pGridArray[row][column]].row = 0;
						pGemsArray[pGridArray[row][column]].column = column;
						pGemsArray[pGridArray[row][column]].y = -(ROW_HEIGHT+10)*(NUM_ROWS - row);
						pGemsArray[pGridArray[row][column]].velocity = 1;
						pGemsArray[pGridArray[row][column]].dropToRow = row;
						pGemsArray[pGridArray[row][column]].prevState = GEMSTATE_FALL;
						row++;
						gemsAdded = true;
					}
				}

				numGemsSelected = 0;
				if (gemsAdded)
				{
					gameState = GAMESTATE_DROP;
				}
				else
				{
					gameState = GAMESTATE_AWAIT_INPUT;
				}
			break;

		}

		if (gameState != GAMESTATE_TITLE_SCREEN)
		{

			for (int row = NUM_ROWS-1; row >= 0; row--)
			{
				for (int column = 0; column < NUM_COLUMNS; column++)
				{
					gem* thisGem = &pGemsArray[pGridArray[row][column]];

					switch (pGemsArray[pGridArray[row][column]].state)
					{
						case GEMSTATE_IDLE:
						break;

						case GEMSTATE_FALL:
						case GEMSTATE_ENTER:

							if ((pGemsArray[pGridArray[row][column]].type != -1 && pGemsArray[pGridArray[row+1][column]].type == -1) ||
								pGemsArray[pGridArray[row][column]].state == GEMSTATE_ENTER)
							{
								dropGem(pGridArray, &pGemsArray[pGridArray[row][column]], pGemsArray);
							}
						break;

						case GEMSTATE_BOUNCE:

							thisGem->y += thisGem->velocity;
							thisGem->velocity--;		

							if (thisGem->y <= 0)
							{
								thisGem->y = 0;
								thisGem->velocity = 0;
								thisGem->state = GEMSTATE_IDLE;
							}
						break;
					}	
				}
			}
		}
	

		timer = time(0);

		if (gameState != GAMESTATE_TITLE_SCREEN && gameState != GAMESTATE_GAME_OVER && timer - startTime >= TIMEOUT)
		{
			gameState = GAMESTATE_GAME_OVER;
			startTime = time(0);
		}

		//Read user input & handle it
		//Read any events that occured, 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 clicks the mouse
			if (e.type == SDL_MOUSEBUTTONDOWN){
				if (gameState == GAMESTATE_TITLE_SCREEN)
				{
					gameState = GAMESTATE_INIT;
				}
				else
				{
					mouseX = e.button.x;
					mouseY = e.button.y;
					mouseDown = true;
					dragStartX = mouseX;
					dragStartY = mouseY;
					dragStarted = false;
				}
			}
			if (e.type == SDL_MOUSEBUTTONUP){
				if (gameState != GAMESTATE_TITLE_SCREEN)
				{
					mouseDown = false;
					gemSelected = true;
				}
			}
			if (e.type == SDL_MOUSEMOTION && mouseDown)
			{
				if (e.motion.xrel < 0)		// Dragged left
				{
					if (mouseX - e.motion.x > DRAG_DEAD_ZONE && !dragStarted)
					{
						// Start a new selection
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (mouseX - e.motion.x > DRAG_DEAD_ZONE && dragStarted)
					{
						// Select next gem
						mouseX -= COLUMN_WIDTH;
						mouseDown = false;
						gemSelected = true;
					}
				}
				else if (e.motion.xrel > 0)		// Dragged right
				{
					if (e.motion.x - mouseX > DRAG_DEAD_ZONE && !dragStarted)
					{
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (e.motion.x - mouseX > DRAG_DEAD_ZONE && dragStarted)
					{
						mouseX += COLUMN_WIDTH;
						mouseDown = false;
						gemSelected = true;
					}
				}
				else if (e.motion.yrel < 0)		// Dragged up
				{
					if (mouseY - e.motion.y > DRAG_DEAD_ZONE && !dragStarted)
					{
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (mouseY - e.motion.y > DRAG_DEAD_ZONE && dragStarted)
					{
						mouseY -= ROW_HEIGHT;
						mouseDown = false;
						gemSelected = true;
					}
				}
				else if (e.motion.yrel > 0)		// Dragged down
				{
					if (e.motion.y - mouseY > DRAG_DEAD_ZONE && !dragStarted)
					{
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (e.motion.y - mouseY > DRAG_DEAD_ZONE && dragStarted)
					{
						mouseY += ROW_HEIGHT;
						mouseDown = false;
						gemSelected = true;
					}
				}
			}
		}

		//Render scene

		//First clear the renderer
		SDL_RenderClear(renderer);

		//Get the width and height from the texture so we know how much to move x,y by
		//to tile it correctly
		int bW, bH;
		SDL_QueryTexture(background, NULL, NULL, &bW, &bH);

		int x;
		int y;
		//Draw the background
		renderTexture(background, renderer, 0, 0);

		if (gameState != GAMESTATE_TITLE_SCREEN && gameState != GAMESTATE_INIT)
		{
			// Draw the gems
			// int rowHeight = GRID_HEIGHT / NUM_ROWS;
			int gemWidth, gemHeight;
			SDL_QueryTexture(gems[0], NULL, NULL, &gemWidth, &gemHeight);

			// Draw cursors
			if (numGemsSelected > 0)
			{
				int cursorWidth, cursorHeight;
				SDL_QueryTexture(cursorYellowImg, NULL, NULL, &cursorWidth, &cursorHeight);
				renderTexture(cursorYellowImg, renderer, 
					selectedGems[0][COLUMN] * COLUMN_WIDTH + COLUMN_WIDTH/2 - cursorWidth/2, 
					selectedGems[0][ROW] * ROW_HEIGHT + ROW_HEIGHT/2 - cursorHeight/2 + HUD_HEIGHT);
			
				if (numGemsSelected == 2)
				{
					renderTexture(cursorGreenImg, renderer, 
						selectedGems[1][COLUMN] * COLUMN_WIDTH + COLUMN_WIDTH/2 - cursorWidth/2, 
						selectedGems[1][ROW] * ROW_HEIGHT + ROW_HEIGHT/2 - cursorHeight/2 + HUD_HEIGHT);
				}
			}

			for (int i = 0; i < NUM_ROWS * NUM_COLUMNS; i++)
			{
				if (pGemsArray[i].type != -1)
				{
					x = COLUMN_WIDTH * pGemsArray[i].column + COLUMN_WIDTH/2 - gemWidth/2;
					y = ROW_HEIGHT * pGemsArray[i].row + ROW_HEIGHT/2 - gemHeight/2 + HUD_HEIGHT;
					renderTexture(gems[pGemsArray[i].type], renderer, x + pGemsArray[i].x, y + pGemsArray[i].y);
				}
			}
		}

		
		// Draw text
		int iW, iH;
		switch (gameState)
		{
			case GAMESTATE_TITLE_SCREEN:
		
			os.str("");
			os.clear();
			os << "Click mouse to start";

			textImage = renderText(os.str(), font, color, renderer);
			if (textImage == nullptr){
				return 1;
			}

			SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
			SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
			x = SCREEN_WIDTH/2 - iW/2;
			y = GRID_HEIGHT/2;
			renderTexture(textImage, renderer, x, y);

			break;

			case GAMESTATE_GAME_OVER:

				os.str("");
				os.clear();
				os << "GAME OVER. Your score is " << score;

				textImage = renderText(os.str(), font, color, renderer);
				if (textImage == nullptr){
					return 1;
				}

				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				x = SCREEN_WIDTH/2 - iW/2;
				y = GRID_HEIGHT/2;
				renderTexture(textImage, renderer, x, y);

			break;

			default:

				os.str("");
				os.clear();
				os << "Score " << score;

				textImage = renderText(os.str(), font, color, renderer);
				if (textImage == nullptr){
					return 1;
				}
				x = 10;
				y = 10;
				renderTexture(textImage, renderer, x, y);
				// drawText("Score ", score, renderer, textImage, font, color, 10, 10);


				os.str("");
				os.clear();
				os << "Time " << (TIMEOUT - (timer - startTime));
				textImage = renderText(os.str(), font, color, renderer);
				if (textImage == nullptr){
					return 1;
				}
				//Get the texture w/h so we can position it correctly on the screen
				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				x = SCREEN_WIDTH -10 - iW;
				renderTexture(textImage, renderer, x, y);

				// drawText seems to always draw to the left of the screen so commented out
				// drawText("Time ", timer - startTime, renderer, textImage, font, color, 100, 10);

			break;
		}

		//Update the screen
		SDL_RenderPresent(renderer);
	}

	//Clean up our objects and quit
	SDL_DestroyTexture(background);
	SDL_DestroyTexture(image);
	SDL_DestroyTexture(blueGem);
	SDL_DestroyTexture(greenGem);
	SDL_DestroyTexture(purpleGem);
	SDL_DestroyTexture(redGem);
	SDL_DestroyTexture(yellowGem);

	for (int i = 0; i < sizeof(*gems); i++)
	{
		gems[i] = NULL;
	}

	for (int row = 0; row < NUM_ROWS; row++)
	{
		delete [] pGridArray[row];
	}
	delete [] pGridArray;

	delete [] pGemsArray;

	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

	return 0;
}
Пример #26
0
int main(int argc, char *argv[])
{
	// Initializing and loading variables
	SDL_Window *window = nullptr;
	SDL_Renderer *renderTarget = nullptr;
	int currentTime = 0; 
	int prevTime = 0; 
	float delta = 0.0f;
	const Uint8 *keyState;
	SDL_Rect camerRect = { 0, 0, 640, 480 };
	int levelWidth, levelHeight;

	SDL_Init(SDL_INIT_VIDEO);
	
	if(IMG_Init(imgFlags) != imgFlags)
		std::cout << "Error: " << IMG_GetError() << std::endl;

	int data = 10;
	window = SDL_CreateWindow("SDL CodingMadeEasy Series", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
	renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

	Player player1(renderTarget, "image.png", 0, 0, 3, 4);
	Player player2(renderTarget, "image.png", 500, 300, 3, 4);

	SDL_Texture *texture = LoadTexture("rect.png", renderTarget);
	SDL_QueryTexture(texture, NULL, NULL, &levelWidth, &levelHeight);

	bool isRunning = true; 
	SDL_Event ev;

	while(isRunning)
	{
		prevTime = currentTime; 
		currentTime = SDL_GetTicks(); 
		delta = (currentTime - prevTime) / 1000.0f;
		while(SDL_PollEvent(&ev) != 0)
		{
			// Getting the events
			if(ev.type == SDL_QUIT)
				isRunning = false;
		}

		keyState = SDL_GetKeyboardState(NULL);

		player1.Update(delta, keyState); 
		player2.Update(delta, keyState);


		camerRect.x = player1.GetOriginX() - 320; 
		camerRect.y = player1.GetOriginY() - 240;

		if(camerRect.x < 0)
			camerRect.x = 0; 
		if(camerRect.y < 0)
			camerRect.y = 0;

		if(camerRect.x + camerRect.w >= levelWidth)
			camerRect.x = levelWidth - 640; 
		if(camerRect.y + camerRect.h >= levelHeight)
			camerRect.y = levelHeight - 480;


		player1.IntersectsWith(player2);

		SDL_RenderClear(renderTarget);
		SDL_RenderCopy(renderTarget, texture, &camerRect, NULL);
		player1.Draw(renderTarget, camerRect); 
		player2.Draw(renderTarget, camerRect);
		SDL_RenderPresent(renderTarget);
	}

	SDL_DestroyWindow(window);
	SDL_DestroyRenderer(renderTarget);
	SDL_DestroyTexture(texture);

	texture = nullptr;

	window = nullptr;
	renderTarget = nullptr;

	IMG_Quit();
	SDL_Quit();

	return 0;
}
Пример #27
0
/*
* Get the image dimensions associated to the specified texture
* @param spriteID is the sprite
* @return textureWidth is the width size
* @return textureHeight is the height size
*/
void SDLInterface::getTextureDimension(int textureId, int & textureWidth, int & textureHeight) {
	SDL_QueryTexture(textures[textureId], NULL, NULL, &textureWidth, &textureHeight);
}
Пример #28
0
int main (void) {
	int WidthBack, HeightBack, i, j;
	bool quit = 0;
	//const Uint8 *kbState = SDL_GetKeyboardState(NULL);
	char **imgFromSrc;

	SDL_Event e;
	SDL_Window *win;
	SDL_Renderer *ren;
	SDL_Texture *background;

	if (SDL_Init(SDL_INIT_VIDEO) != 0 || (IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG) {
		logSDLError("Init");
		return 1;
	}

	win = SDL_CreateWindow(
			"Generic Title",
			WINDOW_OFFSET_X,
			WINDOW_OFFSET_Y,
			WINDOW_WIDTH,
			WINDOW_HEIGHT,
			SDL_WINDOW_OPENGL
			| SDL_WINDOW_ALLOW_HIGHDPI
			| SDL_WINDOW_BORDERLESS
			| SDL_WINDOW_INPUT_GRABBED
			);
	if (win == NULL) {
		logSDLError("CreateWindow");
		return 2;
	}

	ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == NULL) {
		logSDLError("CreateRenderer");
		return 3;
	}

	imgFromSrc = bmp_xpm;
	background = loadHeader(imgFromSrc, ren);
	//character = loadTexture("char.png", ren);
	if (background == NULL /*|| character == NULL*/) {
		logSDLError("loadTexture");
		return 4;
	}

	SDL_RenderClear(ren);

	SDL_QueryTexture(background, NULL, NULL, &WidthBack, &HeightBack);

	WidthBack /= 2;
	HeightBack /= 2;

	for (i = 0; i < WINDOW_WIDTH / WidthBack; i++) {
		for (j = 0; j <= WINDOW_HEIGHT / HeightBack; j++) {
			renderTextureS(background, ren, i * WidthBack, j * HeightBack, WidthBack, HeightBack);
		}
	}

	SDL_RenderPresent(ren);

	while (!quit) {
		while (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT) quit = 1;
			//if (e.type == SDL_MOUSEBUTTONDOWN) quit = 1;
		}

		SDL_RenderClear(ren);

		for (i = 0; i < WINDOW_WIDTH / WidthBack; i++) {
			for (j = 0; j <= WINDOW_HEIGHT / HeightBack; j++) {
				renderTextureS(background, ren, i * WidthBack, j * HeightBack, WidthBack, HeightBack);
			}
		}

		SDL_RenderPresent(ren);
	}

	SDL_DestroyTexture(background);

	cleanUp(win, ren);

	return 0;
}
Пример #29
0
int main(int argc, char** argv) {
    //Start up SDL and make sure it went ok
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }
    if (TTF_Init() == -1) {
        std::cout << TTF_GetError() << std::endl;
        return 2;
    }

    //Setup our window and renderer
    window = SDL_CreateWindow("Lesson 6", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (window == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 2;
    }
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED
                                  | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 3;
    }

    //The textures we'll be using
    SDL_Texture *image = nullptr;
    try {
        SDL_Color color = { 255, 255, 255 };
        image = RenderText("TTF fonts are cool!", "../res/Lesson6/SourceSansPro-Regular.ttf", color, 64);
    }
    catch (const std::runtime_error &e) {
        std::cout << e.what() << std::endl;
        return 4;
    }
    //Our texture size won't change, so we can get it here
    //instead of constantly allocating/deleting ints in the loop
    int iW, iH;
    SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
    int x = SCREEN_WIDTH / 2 - iW / 2;
    int y = SCREEN_HEIGHT / 2 - iH / 2;

    //Our event type
    SDL_Event e;

    //For tracking if we want to quit
    bool quit = false;
    while (!quit) {
        //Event Polling
        while (SDL_PollEvent(&e)) {
            //If user closes he window
            if (e.type == SDL_QUIT)
                quit = true;
            //If user presses any key
            if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)
                quit = true;
        }
        //Rendering
        SDL_RenderClear(renderer);
        //Draw the image
        ApplySurface(x, y, image, renderer);

        //Update the screen
        SDL_RenderPresent(renderer);
    }

    //Destroy the various items
    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}
Пример #30
0
void drawMenu(  SDL_Window* window,
				SDL_Renderer* renderer,
				List* texture,
				TTF_Font* font[],
				List* users,
				List* meteors,
				List* lasers,
				clock_t* runtime,
				int* screen,
				int* game_type ) {
	SDL_Color color = {255,255,255};
	SDL_Texture* txt[7] = {NULL};
	txt[0] = LoadTxtTexture(renderer, font[FONT_INDEX_BIG], "Menu", &color, texture);
	txt[1] = LoadTxtTexture(renderer, font[FONT_INDEX_MED], "SinglePlayer", &color, texture);
	txt[2] = LoadTxtTexture(renderer, font[FONT_INDEX_MED], "MultiPlayer", &color, texture);
	txt[3] = LoadTxtTexture(renderer, font[FONT_INDEX_MED], "Abrir status", &color, texture);
	txt[4] = LoadTxtTexture(renderer, font[FONT_INDEX_MED], "Salvar status", &color, texture);
	txt[5] = LoadTxtTexture(renderer, font[FONT_INDEX_MED], "Continuar", &color, texture);
	txt[6] = LoadTxtTexture(renderer, font[FONT_INDEX_MED], "Close", &color, texture);

	Dimension dim[7] = {0};
	int i;
	for( i = 0; i < 7; i++ ) {
		if(SDL_QueryTexture(txt[i], NULL, NULL, &(dim[i].w), &(dim[i].h)) < 0) {
			fprintf(stderr, "%s\n", SDL_GetError());
		}
	}

	SDL_Rect rect[7] = {0};
	SDL_Rect background_rect[6] = {0};

	Dimension button_dim;
	getMaxDim(dim, 7, &button_dim);
	button_dim.w += 40;
	button_dim.h -= 20	;
	int selectedButton = -1;

	// título
	rect[0].x = (WINDOW_SIZE_X - dim[0].w)/2;
	rect[0].y = (WINDOW_SIZE_Y - dim[0].h)/2 - dim[0].h*2;
	rect[0].h = dim[0].h;
	rect[0].w = dim[0].w;

	for( i = 1; i < 7; i++ ) { // botões
		rect[i].x = (WINDOW_SIZE_X - dim[i].w)/2;
		rect[i].y = (WINDOW_SIZE_Y - dim[i].h)/2 + dim[i].h*(i-2) + 5*i;
		rect[i].h = dim[i].h;
		rect[i].w = dim[i].w;

		background_rect[i-1].x = rect[i].x + ( rect[i].w - button_dim.w)/2;
		background_rect[i-1].y = rect[i].y + ( rect[i].h - button_dim.h)/2;
		background_rect[i-1].h = button_dim.h;
		background_rect[i-1].w = button_dim.w;
	}

	Point mouse;
	SDL_Event e;

	runtime[1] = SDL_GetTicks();
	ctrlFramerate( runtime[1] - runtime[0] ); // delay para considerar a mudança de página
	while( *screen == SCREEN_MENU ) {
		runtime[0] = SDL_GetTicks();

	    SDL_SetRenderDrawColor( renderer, 26, 26, 26, 255 ); // Fundo
	    SDL_RenderClear( renderer ); // Limpa a tela

		while( SDL_PollEvent(&e) ) {
			switch( e.type ) {
				case SDL_QUIT:
					closeALL(window, renderer, texture, font, users, meteors, lasers);
					exit(0);
				break;
			    case SDL_MOUSEMOTION:
			    	SDL_GetMouseState(&(mouse.x), &(mouse.y));
			    break;
		        case SDL_MOUSEBUTTONUP:
					if( selectedButton == 0 ) {
						printf("SinglePlayer\n");
						*screen = SCREEN_SINGLE;
					} else if( selectedButton == 1 ) {
						printf("MultiPlayer\n");
						*screen = SCREEN_MULTI;
					} else if( selectedButton == 2 ) {
						printf("Return\n");
						*screen = SCREEN_OPEN;
					} else if( selectedButton == 3 ) {
						printf("Save\n");
						*screen = SCREEN_SAVE;
					} else if( selectedButton == 4 ) {
						printf("Continue\n");
						if(users->len > 0)
							*screen = SCREEN_GAME;
					} else if( selectedButton == 5 ) {
						closeALL(window, renderer, texture, font, users, meteors, lasers);
						exit(0);
					}
				break;
			}
		}

		SDL_RenderCopy(renderer, txt[0], NULL, &(rect[0]));
		if( users->len != 1 ) {
			SDL_SetRenderDrawColor(renderer, 30,30,30,255);
			SDL_RenderFillRect(renderer, &(background_rect[4]));
		}
		SDL_RenderCopy(renderer, txt[4], NULL, &(rect[4]));
		SDL_RenderCopy(renderer, txt[5], NULL, &(rect[5]));

		selectedButton = -1;
		for( i = 1; i < 7; i++ ) { // botões
			if( (i == 4) || (i == 5) ) {
				if( users->len <= 0 )  continue;
			}
			if( insidePoint(mouse, &(background_rect[i-1])) ) {
				selectedButton = i-1;
				SDL_SetRenderDrawColor(renderer, 200,0,0,255);
			} else {
				SDL_SetRenderDrawColor(renderer, 50,50,50,255);
			}
			SDL_RenderFillRect(renderer, &(background_rect[i-1]));
			SDL_RenderCopy(renderer, txt[i], NULL, &(rect[i]));
		}
		SDL_RenderPresent(renderer);

		runtime[1] = SDL_GetTicks();
		ctrlFramerate( runtime[1] - runtime[0] ); // delay
	}

	destroyNonMainTexture( texture ); // Destroi texturas criadas nessa função
}