better grid drawing
[vrlugburz] / tools / dunger / src / level.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <GL/gl.h>
5 #include "level.h"
6
7 extern int view_width, view_height;
8 extern float view_panx, view_pany, view_zoom;
9
10
11 struct level *create_level(int xsz, int ysz)
12 {
13         struct level *lvl;
14
15         if(!(lvl = malloc(sizeof *lvl))) {
16                 return 0;
17         }
18         if(!(lvl->cells = calloc(xsz * ysz, sizeof *lvl->cells))) {
19                 free(lvl);
20                 return 0;
21         }
22         lvl->width = xsz;
23         lvl->height = ysz;
24         return lvl;
25 }
26
27 void free_level(struct level *lvl)
28 {
29         if(!lvl) return;
30         free(lvl->cells);
31         free(lvl);
32 }
33
34 #define LTHICK  0.5f
35 static void draw_cell(struct level *lvl, struct cell *cell)
36 {
37         int cidx, row, col;
38         float x, y, xsz, ysz, sz;
39         static const float colors[][3] = {{0, 0, 0}, {0.6, 0.6, 0.6}, {0.4, 0.2, 0.1}};
40
41         xsz = view_zoom * view_width / lvl->width;
42         ysz = view_zoom * view_height / lvl->height;
43         sz = xsz > ysz ? ysz : xsz;
44
45         cidx = cell - lvl->cells;
46         row = cidx / lvl->width;
47         col = cidx % lvl->width;
48
49         x = col * sz - view_panx;
50         y = row * sz - view_pany;
51
52         glColor3f(1, 1, 1);
53         glVertex2f(x, y);
54         glVertex2f(x + sz, y);
55         glVertex2f(x + sz, y + sz);
56         glVertex2f(x, y + sz);
57
58         x += LTHICK;
59         y += LTHICK;
60         sz -= LTHICK * 2.0f;
61
62         glColor3fv(colors[cell->type]);
63         glVertex2f(x, y);
64         glVertex2f(x + sz, y);
65         glVertex2f(x + sz, y + sz);
66         glVertex2f(x, y + sz);
67 }
68
69 void draw_level(struct level *lvl)
70 {
71         int i, j;
72         struct cell *cell;
73
74         glBegin(GL_QUADS);
75         cell = lvl->cells;
76         for(i=0; i<lvl->height; i++) {
77                 for(j=0; j<lvl->width; j++) {
78                         draw_cell(lvl, cell++);
79                 }
80         }
81         glEnd();
82 }