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
|
#include <rgl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#define crashErrno() RGL_CRASH(strerror(errno))
#define assertErrno(cond) RGL_ASSERT(cond, strerror(errno))
void BufferAlloc(RGL_Buffer *buf) {
unsigned int size = buf->width * buf->height * 4;
buf->data = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assertErrno(buf->data != MAP_FAILED);
}
void BufferDestroy(RGL_Buffer *buf) {
unsigned int size = buf->width * buf->height * 4;
if (munmap(buf->data, size) < 0) {
crashErrno();
}
}
void ArenaInit(RGL_Arena *arena, unsigned int capacity) {
if (capacity) {
arena->capacity = capacity;
} else {
arena->capacity = 4096;
}
arena->data = mmap(0, arena->capacity, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
if (arena->data == MAP_FAILED) {
crashErrno();
}
arena->size = 0;
}
void ArenaDestroy(RGL_Arena *arena) {
if (munmap(arena->data, arena->capacity) < 0) {
crashErrno();
}
}
int WritePPM(RGL_Buffer buf, const char *filename) {
int i;
FILE *f = fopen(filename, "wb");
RGL_ASSERT(f, "failed to open file");
fprintf(f, "P6\n%d %d\n255\n", buf.width, buf.height);
for (i = 0; i < buf.width * buf.height; ++i) {
unsigned int pixel = buf.data[i];
unsigned char r = (pixel >> 16) & 0xFF;
unsigned char g = (pixel >> 8) & 0xFF;
unsigned char b = pixel & 0xFF;
fputc(r, f);
fputc(g, f);
fputc(b, f);
}
fclose(f);
return 0;
}
|