Skip to content

Instantly share code, notes, and snippets.

@piusayowale
Last active July 10, 2022 11:02
Show Gist options
  • Save piusayowale/4ec87d3b6c99c341a24d5130da994bb7 to your computer and use it in GitHub Desktop.
Save piusayowale/4ec87d3b6c99c341a24d5130da994bb7 to your computer and use it in GitHub Desktop.
checking button click with SDL and boost geometry
// sdl_opengl.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_surface.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_opengl.h>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/box.hpp>
struct my_point
{
int x, y;
};
struct my_box
{
int left, top, right, bottom;
};
BOOST_GEOMETRY_REGISTER_POINT_2D(my_point, int, cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_BOX_2D_4VALUES(my_box, my_point, left, top, right, bottom)
SDL_Rect Box_To_SDL_Rect(my_box& box) {
SDL_Rect rect{};
rect.x = box.left;
rect.y = box.top;
rect.w = box.right - box.left;
rect.h = box.bottom - box.top;
return rect;
}
my_box SDL_Rect_To_Box(SDL_Rect& rect) {
my_box box;
box.left = rect.x;
box.top = rect.y;
box.bottom = rect.h + box.top;
box.right = rect.w + box.left;
return box;
}
int main(int argc, char ** argv)
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* window = SDL_CreateWindow("Home", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 500, 500, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Event event;
my_box b = boost::geometry::make<my_box>(0, 0, 40, 40);
SDL_Rect rect = Box_To_SDL_Rect(b);
std::cout << std::boolalpha << boost::geometry::intersects(b, b);
int posx, posy;
while (true)
{
SDL_SetRenderDrawColor(renderer, 200, 100, 20, 200);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 20, 10, 150, 200);
SDL_RenderDrawRect(renderer, &rect);
if (SDL_PollEvent(&event) == 1) {
switch (event.type)
{
case SDL_QUIT:
goto QUIT;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_GetMouseState(&posx, &posy);
std::cout << posx << " " << posy << "\n";
std::cout << std::boolalpha << boost::geometry::intersects(SDL_Rect_To_Box(rect), boost::geometry::make<my_box>(posx, posy, posx + 5, posy + 5));
}
else if (event.button.button == SDL_BUTTON_RIGHT) {
SDL_GetMouseState(&posx, &posy);
rect.x = posx;
rect.y = posy;
}
default:
break;
}
}
SDL_RenderPresent(renderer);
}
QUIT:
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment