summaryrefslogtreecommitdiff
path: root/test/test.c
blob: 668dec894ca4c643c7fd4d5a2d33de66129dbe3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <swgfx.h>

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>

typedef struct RGB { uint8_t r, g, b; } RGB;

static bool WritePPM(int width, int height, const RGB* image, const char* path) {
  const size_t num_pixels = width * height;
  
  FILE* file = fopen(path, "wb");
  if (!file) {
    return false;
  }
  
  fprintf(file, "P6\n%d %d\n255\n", width, height);
  if (fwrite(image, sizeof(RGB), num_pixels, file) != num_pixels) {
    fclose(file);
    return false;
  }
  
  fclose(file);
  return true;
}

void ToRGB(int width, int height, const sgPixel* rgba, RGB* rgb) {
  assert(rgba);
  assert(rgb);
  for (int y = 0; y < height; ++y) {
    for (int x = 0; x < width; ++x) {
      const sgPixel p = *rgba++;
      *rgb++ = (RGB){p.r, p.g, p.b};
    }
  }
}

static void Checkerboard(swgfx* gfx, int width, int height) {
  assert(gfx);
  const sgPixel colour = (sgPixel){255, 0, 255, 255};
  for (int y = 0; y < height; ++y) {
    for (int x = 0; x < width; ++x) {
      if (((x ^ y) & 1) == 1) {
        const sgVec2i position = (sgVec2i){x, y};
        sgPixels(gfx, 1, &position, colour);
      }
    }
  }
}

static void TestTriangle(swgfx* gfx) {
  assert(gfx);
  
  const int     BufferWidth  = 160;
  const int     BufferHeight = 120;
  const int     N            = BufferWidth * BufferHeight;
  const sgVec2i BufferDims   = (sgVec2i){.x = BufferWidth, .y = BufferHeight};
  
  sgPixel colour[N];
  RGB     rgb[N];
  
  sgColourBuffer(gfx, BufferDims, colour);
  sgClear(gfx);
  Checkerboard(gfx, BufferWidth, BufferHeight);
  
  const sgVec2 p0  = (sgVec2){20, 20};
  const sgVec2 p1  = (sgVec2){80, 20};
  const sgVec2 p2  = (sgVec2){50, 50};
  const sgTri2 tri = (sgTri2){p0, p1, p2};
  sgTriangles2(gfx, 1, &tri);
  
  ToRGB(BufferWidth, BufferHeight, colour, rgb);
  WritePPM(BufferWidth, BufferHeight, rgb, "triangle.ppm");
}

int main() {
  swgfx* gfx = 0;
  if (!(gfx = sgNew())) {
    fprintf(stderr, "Failed to create swgfx\n");
    return 1;
  }
  
  TestTriangle(gfx);
  
  sgDel(&gfx);
  return 0;
}