aboutsummaryrefslogtreecommitdiff
path: root/09-september/tomcat/not_in_use/fbo.c
blob: 588027652361a7ecb9a14106b74694b6d7eae918 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "fbo.h"
#include "renderer.h"
#include "../util/util.h"

#include <string.h>
#include <stdlib.h>

Fbo *fbo_new(const char *name, GLint width, GLint height)
{
    Fbo *fbo;

    if(strlen(name) >= MAX_PATH_LENGTH)
        Util_FatalError("Fbo name is too long: %s\n", name);

    if(render.num_fbos >= MAX_FBOS)
        return NULL;

    fbo = malloc(sizeof(Fbo));
    memset(fbo, 0, sizeof(Fbo));

    glGenFramebuffers(1, &fbo->frame_buffer);

    return fbo;
}

void fbo_attach_buffer(Fbo *fbo, GLenum format, int index)
{
    GLenum attachment;
    GLuint *buffer;

    switch(format)
	{
		case GL_RGB:
		case GL_RGBA:
			fbo->color_format = format;
			buffer = &fbo->color_buffer[index];
			attachment = GL_COLOR_ATTACHMENT0 + index;
			break;

		case GL_DEPTH_COMPONENT:
			fbo->depth_format = format;
			buffer = &fbo->depth_buffer;
			attachment = GL_DEPTH_ATTACHMENT;
			break;

		default:
			Util_FatalError("Invalid fbo buffer format\n");
	}

	if(*buffer == 0)
	{
        glGenRenderbuffers(1, buffer);
        glBindRenderbuffer(GL_RENDERBUFFER, *buffer);
        glRenderbufferStorage(GL_RENDERBUFFER, format, fbo->width, fbo->height);

        fbo_bind(fbo);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, *buffer);
        fbo_bind(NULL);
        glBindRenderbuffer(GL_RENDERBUFFER, 0);
    }
}

void fbo_attach_texture(Fbo *fbo, Texture *t, GLenum attachment)
{
    int index;

    fbo_bind(fbo);
    if(attachment >= GL_COLOR_ATTACHMENT0 && attachment < GL_COLOR_ATTACHMENT0 + 8)
    {
        glFramebufferTexture(GL_FRAMEBUFFER, attachment, t->tex_id, 0);
        glDrawBuffers(1, &attachment);

        index = attachment - GL_COLOR_ATTACHMENT0;
        fbo->color_textures[index] = t;
    }

    fbo_bind(NULL);
}

void fbo_bind(Fbo *fbo)
{
    if(fbo)
    {
        glBindFramebuffer(GL_FRAMEBUFFER, fbo->frame_buffer);
        glViewport(0, 0, fbo->width, fbo->height);
    }
    else
    {
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glViewport(0, 0, render.window->Width, render.window->Height);
    }
}

void fbo_purge(Fbo *fbo)
{
    int i;

    for(i = 0; i < 8; i++)
        if(fbo->color_buffer[i])
        {
            glDeleteRenderbuffers(1, &fbo->color_buffer[i]);
        }
    if(fbo->depth_buffer)
        glDeleteRenderbuffers(1, &fbo->depth_buffer);

    if(fbo->frame_buffer)
        glDeleteFramebuffers(1, &fbo->frame_buffer);
}