tavli
view src/shadow.cc @ 18:986c0b76513f
shadows, not completed
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 29 Jun 2015 01:29:36 +0300 |
parents | |
children | 37dead56f01e |
line source
1 #include <assert.h>
2 #include "opengl.h"
3 #include "shadow.h"
4 #include "vmath/vmath.h"
6 static int tex_sz, prev_vp[4];
7 static unsigned int fbo, depth_tex, rb_color;
8 static Matrix4x4 shadow_mat;
10 bool init_shadow(int sz)
11 {
12 if(!glcaps.fbo) {
13 return true;
14 }
16 tex_sz = sz;
18 glGenFramebuffers(1, &fbo);
19 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
21 glGenTextures(1, &depth_tex);
22 glBindTexture(GL_TEXTURE_2D, depth_tex);
23 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
24 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
25 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
26 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
27 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
28 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, tex_sz, tex_sz, 0,
29 GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
30 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_tex, 0);
32 assert(glGetError() == GL_NO_ERROR);
34 glDrawBuffer(GL_FALSE);
35 glReadBuffer(GL_FALSE);
37 if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
38 fprintf(stderr, "incomplete framebuffer\n");
39 return false;
40 }
42 glBindFramebuffer(GL_FRAMEBUFFER, 0);
43 glDrawBuffer(GL_BACK);
44 glReadBuffer(GL_BACK);
45 assert(glGetError() == GL_NO_ERROR);
47 return true;
48 }
50 void destroy_shadow()
51 {
52 glDeleteTextures(1, &depth_tex);
53 glDeleteRenderbuffers(1, &rb_color);
54 glDeleteFramebuffers(1, &fbo);
55 }
57 void begin_shadow_pass(const Vector3 &lpos, const Vector3 <arg, float lfov)
58 {
59 Matrix4x4 viewmat, projmat;
61 glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);
62 glDisable(GL_LIGHTING);
63 glColorMask(0, 0, 0, 0);
64 glDepthMask(1);
66 projmat.set_perspective(DEG_TO_RAD(lfov) * 2.0, 1.0, 0.5, 500.0);
67 viewmat.set_lookat(lpos, ltarg, Vector3(0, 1, 0));
68 shadow_mat = viewmat * projmat;
70 glMatrixMode(GL_PROJECTION);
71 glPushMatrix();
72 glLoadTransposeMatrixf(projmat[0]);
73 glMatrixMode(GL_MODELVIEW);
74 glPushMatrix();
75 glLoadTransposeMatrixf(viewmat[0]);
77 glGetIntegerv(GL_VIEWPORT, prev_vp);
78 glViewport(0, 0, tex_sz, tex_sz);
80 glCullFace(GL_FRONT);
81 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
82 }
85 void end_shadow_pass()
86 {
87 glBindFramebuffer(GL_FRAMEBUFFER, 0);
88 glCullFace(GL_BACK);
90 glViewport(prev_vp[0], prev_vp[1], prev_vp[2], prev_vp[3]);
92 glMatrixMode(GL_PROJECTION);
93 glPopMatrix();
94 glMatrixMode(GL_MODELVIEW);
95 glPopMatrix();
97 glPopAttrib();
98 }
100 Matrix4x4 get_shadow_matrix()
101 {
102 return shadow_mat;
103 }
105 unsigned int get_shadow_tex()
106 {
107 return depth_tex;
108 }