3 This file is part of libmspgl
4 Copyright © 2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
9 #include <msp/strings/formatter.h>
12 #include "meshbuilder.h"
21 static const char blur_vs[]=
22 "varying vec2 texcoord;\n"
25 " gl_Position = vec4(gl_Vertex.xy*2.0-1.0, 0.0, 1.0);\n"
26 " texcoord = gl_Vertex.xy;\n"
29 static const char blur_fs[]=
30 "uniform sampler2D source;\n"
31 "uniform vec2 delta;\n"
32 "uniform float factors[19];\n"
34 "varying vec2 texcoord;\n"
37 " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n"
38 " for(int i=-size; i<=size; ++i)\n"
39 " gl_FragColor += texture2D(source, texcoord+delta*i)*factors[i+size];\n"
42 static const char combine_vs[]=
43 "varying vec2 texcoord;\n"
46 " gl_Position = vec4(gl_Vertex.xy*2.0-1.0, 0.0, 1.0);\n"
47 " texcoord = gl_Vertex.xy;\n"
50 static const char combine_fs[]=
51 "uniform sampler2D source;\n"
52 "uniform sampler2D blurred;\n"
53 "uniform float strength;\n"
54 "varying vec2 texcoord;\n"
57 " gl_FragColor = mix(texture2D(source, texcoord), texture2D(blurred, texcoord), strength);\n"
65 Bloom::Bloom(unsigned w, unsigned h):
66 blur_shader(blur_vs, blur_fs),
67 combine_shader(combine_vs, combine_fs),
70 int loc = blur_shader.get_uniform_location("delta");
71 blur_shdata[0].uniform(loc, 1.0f/w, 0.0f);
72 blur_shdata[1].uniform(loc, 0.0f, 1.0f/h);
74 loc = blur_shader.get_uniform_location("source");
75 for(unsigned i=0; i<2; ++i)
77 blur_shdata[i].uniform(loc, 0);
78 tex[i].set_min_filter(NEAREST);
79 tex[i].storage(RGB16F, w, h);
82 combine_shdata.uniform(combine_shader.get_uniform_location("source"), 1);
83 combine_shdata.uniform(combine_shader.get_uniform_location("blurred"), 0);
88 MeshBuilder mbld(quad);
97 void Bloom::set_radius(float r)
100 throw InvalidParameterValue("Radius must be positive");
102 int size = min(static_cast<int>(r*3.0f), 9);
103 int loc = blur_shader.get_uniform_location("size");
104 blur_shdata[0].uniform(loc, size);
105 blur_shdata[1].uniform(loc, size);
107 vector<float> factors(size*2+1);
110 for(int i=-size; i<=size; ++i)
111 sum += (factors[size+i] = exp(-i*i/r));
113 for(int i=0; i<=size*2; ++i)
115 loc = blur_shader.get_uniform_location(format("factors[%d]", i));
116 float f = factors[i]/sum;
117 blur_shdata[0].uniform(loc, f);
118 blur_shdata[1].uniform(loc, f);
122 void Bloom::set_strength(float s)
125 throw InvalidParameterValue("Strength must be in the range [0.0, 1.0]");
126 combine_shdata.uniform(combine_shader.get_uniform_location("strength"), s);
129 void Bloom::render(const Texture2D &src)
131 const Framebuffer *dest = Framebuffer::current();
135 Bind unbind_dtest(static_cast<DepthTest *>(0), true);
136 Bind unbind_blend(static_cast<Blend *>(0), true);
137 for(unsigned i=0; i<2; ++i)
139 fbo.attach(COLOR_ATTACHMENT0, tex[i], 0);
140 blur_shdata[i].apply();
148 Framebuffer::unbind();
150 combine_shader.bind();
151 combine_shdata.apply();
155 Texture::unbind_from(1);
156 Texture::unbind_from(0);