3 This file is part of libmspgl
4 Copyright © 2009-2011 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=0; i<=size*2; ++i)\n"
39 " gl_FragColor += texture2D(source, texcoord+delta*float(i-size))*factors[i];\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 blur_shdata_common(blur_shader),
68 blur_shdata_x(blur_shader),
69 blur_shdata_y(blur_shader),
70 combine_shader(combine_vs, combine_fs),
71 combine_shdata(combine_shader),
74 int loc = blur_shader.get_uniform_location("delta");
75 blur_shdata_x.uniform(loc, 1.0f/w, 0.0f);
76 blur_shdata_y.uniform(loc, 0.0f, 1.0f/h);
78 blur_shdata_common.uniform("source", 0);
79 for(unsigned i=0; i<2; ++i)
81 tex[i].set_min_filter(NEAREST);
82 tex[i].storage(RGB16F, w, h);
85 combine_shdata.uniform("source", 1);
86 combine_shdata.uniform("blurred", 0);
88 combine_texturing.attach(0, tex[1]);
93 MeshBuilder mbld(quad);
94 mbld.begin(TRIANGLE_STRIP);
102 void Bloom::set_radius(float r)
105 throw InvalidParameterValue("Radius must be positive");
107 int size = min(static_cast<int>(r*3.0f), 9);
108 blur_shdata_common.uniform("size", size);
110 vector<float> factors(size*2+1);
113 for(int i=-size; i<=size; ++i)
114 sum += (factors[size+i] = exp(-i*i/r));
116 for(int i=0; i<=size*2; ++i)
117 blur_shdata_common.uniform(format("factors[%d]", i), factors[i]/sum);
120 void Bloom::set_strength(float s)
123 throw InvalidParameterValue("Strength must be in the range [0.0, 1.0]");
124 combine_shdata.uniform("strength", s);
127 void Bloom::render(const Texture2D &src, const Texture2D &)
129 Bind unbind_dtest(static_cast<DepthTest *>(0), true);
130 Bind unbind_blend(static_cast<Blend *>(0), true);
133 Bind bind_shader(blur_shader);
134 blur_shdata_common.apply();
135 Bind bind_fbo(fbo, true);
136 for(unsigned i=0; i<2; ++i)
138 Bind bind_tex(i ? tex[0] : src);
139 fbo.attach(COLOR_ATTACHMENT0, tex[i], 0);
140 (i ? blur_shdata_y : blur_shdata_x).apply();
145 combine_texturing.attach(1, src);
146 Bind bind_texturing(combine_texturing);
147 Bind bind_shader(combine_shader);
148 combine_shdata.apply();