Browse Source

Add convenient rendering utilities

rexim 4 years ago
parent
commit
1fb4233f96
2 changed files with 61 additions and 2 deletions
  1. 1 1
      Makefile
  2. 60 1
      main.c

+ 1 - 1
Makefile

@@ -1,5 +1,5 @@
 CFLAGS=-Wall -Wextra -std=c11 -pedantic `pkg-config --cflags sdl2`
-LIBS=`pkg-config --libs sdl2`
+LIBS=`pkg-config --libs sdl2` -lm
 
 bezier: main.c
 	$(CC) $(CFLAGS) -o bezier main.c $(LIBS)

+ 60 - 1
main.c

@@ -5,7 +5,9 @@
 
 #define SCREEN_WIDTH 800
 #define SCREEN_HEIGHT 600
-#define BACKGROUND_COLOR 0x000000FF
+#define BACKGROUND_COLOR 0x353535FF
+#define LINE_COLOR 0xDA2C38FF
+#define RECT_COLOR 0x87C38FFF
 
 #define HEX_COLOR(hex)                      \
     ((hex) >> (3 * 8)) & 0xFF,              \
@@ -33,6 +35,47 @@ void *check_sdl_ptr(void *ptr)
     return ptr;
 }
 
+typedef struct {
+    float x;
+    float y;
+} Vec2;
+
+Vec2 vec2(float x, float y)
+{
+    return (Vec2){x, y};
+}
+
+void render_line(SDL_Renderer *renderer,
+                 Vec2 begin, Vec2 end,
+                 uint32_t color)
+{
+    check_sdl_code(
+        SDL_SetRenderDrawColor(renderer, HEX_COLOR(color)));
+
+    check_sdl_code(
+        SDL_RenderDrawLine(
+            renderer,
+            (int) floorf(begin.x),
+            (int) floorf(begin.y),
+            (int) floorf(end.x),
+            (int) floorf(end.y)));
+}
+
+void fill_rect(SDL_Renderer *renderer, Vec2 pos, Vec2 size, uint32_t color)
+{
+    check_sdl_code(
+        SDL_SetRenderDrawColor(renderer, HEX_COLOR(color)));
+
+    const SDL_Rect rect = {
+        (int) floorf(pos.x),
+        (int) floorf(pos.y),
+        (int) floorf(size.x),
+        (int) floorf(size.y),
+    };
+
+    check_sdl_code(SDL_RenderFillRect(renderer, &rect));
+}
+
 int main(void)
 {
     check_sdl_code(
@@ -52,6 +95,9 @@ int main(void)
             SDL_CreateRenderer(
                 window, -1, SDL_RENDERER_ACCELERATED));
 
+    check_sdl_code(
+        SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT));
+
     int quit = 0;
     while (!quit) {
         SDL_Event event;
@@ -71,6 +117,19 @@ int main(void)
         check_sdl_code(
             SDL_RenderClear(renderer));
 
+        render_line(
+            renderer,
+            vec2(0.0f, 0.0f),
+            vec2(SCREEN_WIDTH, SCREEN_HEIGHT),
+            LINE_COLOR);
+        render_line(
+            renderer,
+            vec2(SCREEN_WIDTH, 0.0f),
+            vec2(0.0f, SCREEN_HEIGHT),
+            LINE_COLOR);
+
+        fill_rect(renderer, vec2(0.0f, 0.0f), vec2(100.0f, 100.0f), RECT_COLOR);
+
         SDL_RenderPresent(renderer);
     }