Debian Codegraph @

src/backend/gl/blur.c

raw symbols SCIP
1 #include <locale.h>
2 #include <stdbool.h>
3
4 #include "backend/backend_common.h"
5 #include "utils/misc.h"
6
7 #include "gl_common.h"
8
9 struct gl_blur_context {
10 struct gl_shader *blur_shader;
11
12 /// Temporary textures used for blurring
13 GLuint *blur_textures;
14 /// Temporary fbos used for blurring
15 GLuint *blur_fbos;
16
17 int blur_texture_count;
18 int blur_fbo_count;
19
20 /// Cached dimensions of each blur_texture. They keep growing to accommodate each
21 /// source image it gets. The hope is soon it gets big enough and we stop
22 /// resizing.
23 /// Turns out calling glTexImage to resize is expensive, so we avoid that.
24 struct texture_size {
25 int width;
26 int height;
27 } *texture_sizes;
28
29 /// Final render target size, used to detect root size change and triggers
30 /// blur_texture shrinking to reduce memory usage.
31 uint64_t root_size;
32
33 /// Cached dimensions of the offscreen framebuffer. It's the same size as the
34 /// target but is expanded in either direction by resize_width / resize_height.
35 int fb_width, fb_height;
36
37 /// How much do we need to resize the damaged region for blurring.
38 int resize_width, resize_height;
39
40 int npasses;
41
42 enum backend_image_format format;
43
44 enum blur_method method;
45 };
46
47 // TODO(yshui) small optimization for kernel blur, if source and target are different,
48 // single pass blur can paint directly from source to target. Currently a temporary
49 // texture is always used.
50
51 /**
52 * Blur contents in a particular region.
53 */
54 static bool
55 gl_kernel_blur(double opacity, struct gl_blur_context *bctx,
56 const struct backend_mask_image *mask, vec2 mask_scale,
57 const GLuint vao[2], const int vao_nelems[2], struct gl_texture *source,
58 GLuint blur_sampler, GLuint target_fbo, GLuint default_mask) {
59 int curr = 0;
60 for (int i = 0; i < bctx->npasses; ++i) {
61 auto p = &bctx->blur_shader[i];
62 assert(p->prog);
63
64 assert(bctx->blur_textures[curr]);
65
66 // The origin to use when sampling from the source texture
67 GLint tex_width, tex_height;
68 GLuint src_texture;
69
70 if (i == 0) {
71 src_texture = source->texture;
72 tex_width = source->width;
73 tex_height = source->height;
74 } else {
75 src_texture = bctx->blur_textures[curr];
76 auto src_size = bctx->texture_sizes[curr];
77 tex_width = src_size.width;
78 tex_height = src_size.height;
79 }
80
81 glActiveTexture(GL_TEXTURE0);
82 glBindTexture(GL_TEXTURE_2D, src_texture);
83 glBindSampler(0, blur_sampler);
84 glUseProgram(p->prog);
85 if (p->uniform_bitmask & (1 << UNIFORM_PIXEL_NORM_LOC)) {
86 // If the last pass is a trivial blend pass, it will not have
87 // pixel_norm.
88 glUniform2f(UNIFORM_PIXEL_NORM_LOC, 1.0F / (GLfloat)tex_width,
89 1.0F / (GLfloat)tex_height);
90 }
91
92 glActiveTexture(GL_TEXTURE1);
93 glBindTexture(GL_TEXTURE_2D, default_mask);
94
95 glUniform1i(UNIFORM_MASK_TEX_LOC, 1);
96 glUniform2f(UNIFORM_MASK_OFFSET_LOC, 0.0F, 0.0F);
97 glUniform1i(UNIFORM_MASK_INVERTED_LOC, 0);
98 glUniform1f(UNIFORM_MASK_CORNER_RADIUS_LOC, 0.0F);
99 glUniform2f(UNIFORM_MASK_SCALE_LOC, 1.0F, 1.0F);
100
101 // The number of indices in the selected vertex array
102 GLsizei nelems;
103
104 if (i < bctx->npasses - 1) {
105 assert(bctx->blur_fbos[0]);
106 assert(bctx->blur_textures[!curr]);
107
108 // not last pass, draw into framebuffer, with resized regions
109 glBindVertexArray(vao[1]);
110 nelems = vao_nelems[1];
111 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[0]);
112
113 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
114 GL_TEXTURE_2D, bctx->blur_textures[!curr], 0);
115 glDrawBuffer(GL_COLOR_ATTACHMENT0);
116 if (!gl_check_fb_complete(GL_FRAMEBUFFER)) {
117 return false;
118 }
119
120 glUniform1f(UNIFORM_OPACITY_LOC, 1.0F);
121 } else {
122 // last pass, draw directly into the back buffer, with origin
123 // regions. And apply mask if requested
124 if (mask != NULL) {
125 auto inner = (struct gl_texture *)mask->image;
126 log_trace("Mask texture is %d", inner->texture);
127 glActiveTexture(GL_TEXTURE1);
128 glBindTexture(GL_TEXTURE_2D, inner->texture);
129 glUniform1i(UNIFORM_MASK_INVERTED_LOC, mask->inverted);
130 glUniform1f(UNIFORM_MASK_CORNER_RADIUS_LOC,
131 (float)mask->corner_radius);
132 glUniform2f(UNIFORM_MASK_OFFSET_LOC,
133 (float)mask->origin.x, (float)mask->origin.y);
134 glUniform2f(UNIFORM_MASK_SCALE_LOC, (float)mask_scale.x,
135 (float)mask_scale.y);
136 }
137 glBindVertexArray(vao[0]);
138 nelems = vao_nelems[0];
139 glBindFramebuffer(GL_FRAMEBUFFER, target_fbo);
140
141 glUniform1f(UNIFORM_OPACITY_LOC, (float)opacity);
142 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
143 }
144
145 glDrawElements(GL_TRIANGLES, nelems, GL_UNSIGNED_INT, NULL);
146
147 // XXX use multiple draw calls is probably going to be slow than
148 // just simply blur the whole area.
149
150 curr = !curr;
151 }
152
153 return true;
154 }
155
156 /// Do dual-kawase blur.
157 ///
158 /// @param vao two vertex array objects.
159 /// [0]: for sampling from blurred result into the target fbo.
160 /// [1]: for sampling from the source texture into blurred textures.
161 bool gl_dual_kawase_blur(double opacity, struct gl_blur_context *bctx,
162 const struct backend_mask_image *mask, vec2 mask_scale,
163 const GLuint vao[2], const int vao_nelems[2], struct gl_texture *source,
164 GLuint blur_sampler, GLuint target_fbo, GLuint default_mask) {
165 int iterations = bctx->blur_texture_count;
166 int scale_factor = 1;
167
168 // Kawase downsample pass
169 auto down_pass = &bctx->blur_shader[0];
170 assert(down_pass->prog);
171 glUseProgram(down_pass->prog);
172
173 glBindVertexArray(vao[1]);
174 int nelems = vao_nelems[1];
175
176 for (int i = 0; i < iterations; ++i) {
177 // Scale output width / height by half in each iteration
178 scale_factor <<= 1;
179
180 GLuint src_texture;
181 int tex_width, tex_height;
182
183 if (i == 0) {
184 // first pass: copy from back buffer
185 src_texture = source->texture;
186 tex_width = source->width;
187 tex_height = source->height;
188 } else {
189 // copy from previous pass
190 src_texture = bctx->blur_textures[i - 1];
191 auto src_size = bctx->texture_sizes[i - 1];
192 tex_width = src_size.width;
193 tex_height = src_size.height;
194 }
195
196 assert(src_texture);
197 assert(bctx->blur_fbos[i]);
198
199 glActiveTexture(GL_TEXTURE0);
200 glBindTexture(GL_TEXTURE_2D, src_texture);
201 glBindSampler(0, blur_sampler);
202 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[i]);
203 glDrawBuffer(GL_COLOR_ATTACHMENT0);
204
205 glUniform1f(UNIFORM_SCALE_LOC, (GLfloat)scale_factor);
206
207 glUniform2f(UNIFORM_PIXEL_NORM_LOC, 1.0F / (GLfloat)tex_width,
208 1.0F / (GLfloat)tex_height);
209
210 glDrawElements(GL_TRIANGLES, nelems, GL_UNSIGNED_INT, NULL);
211 }
212
213 // Kawase upsample pass
214 auto up_pass = &bctx->blur_shader[1];
215 assert(up_pass->prog);
216 glUseProgram(up_pass->prog);
217
218 glActiveTexture(GL_TEXTURE1);
219 glBindTexture(GL_TEXTURE_2D, default_mask);
220
221 glUniform1i(UNIFORM_MASK_TEX_LOC, 1);
222 glUniform2f(UNIFORM_MASK_OFFSET_LOC, 0.0F, 0.0F);
223 glUniform1i(UNIFORM_MASK_INVERTED_LOC, 0);
224 glUniform1f(UNIFORM_MASK_CORNER_RADIUS_LOC, 0.0F);
225 glUniform2f(UNIFORM_MASK_SCALE_LOC, 1.0F, 1.0F);
226 glUniform1f(UNIFORM_OPACITY_LOC, 1.0F);
227
228 for (int i = iterations - 1; i >= 0; --i) {
229 // Scale output width / height back by two in each iteration
230 scale_factor >>= 1;
231
232 const GLuint src_texture = bctx->blur_textures[i];
233 assert(src_texture);
234
235 // Calculate normalized half-width/-height of a src pixel
236 auto src_size = bctx->texture_sizes[i];
237 int tex_width = src_size.width;
238 int tex_height = src_size.height;
239
240 glActiveTexture(GL_TEXTURE0);
241 glBindTexture(GL_TEXTURE_2D, src_texture);
242 glBindSampler(0, blur_sampler);
243
244 if (i > 0) {
245 assert(bctx->blur_fbos[i - 1]);
246
247 // not last pass, draw into next framebuffer
248 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[i - 1]);
249 glDrawBuffer(GL_COLOR_ATTACHMENT0);
250 } else {
251 // last pass, draw directly into the target fbo
252 if (mask != NULL) {
253 auto inner = (struct gl_texture *)mask->image;
254 log_trace("Mask texture is %d", inner->texture);
255 glActiveTexture(GL_TEXTURE1);
256 glBindTexture(GL_TEXTURE_2D, inner->texture);
257 glUniform1i(UNIFORM_MASK_INVERTED_LOC, mask->inverted);
258 glUniform1f(UNIFORM_MASK_CORNER_RADIUS_LOC,
259 (float)mask->corner_radius);
260 glUniform2f(UNIFORM_MASK_OFFSET_LOC, (float)(mask->origin.x),
261 (float)(mask->origin.y));
262 glUniform2f(UNIFORM_MASK_SCALE_LOC, (float)mask_scale.x,
263 (float)mask_scale.y);
264 }
265 glBindVertexArray(vao[0]);
266 nelems = vao_nelems[0];
267 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target_fbo);
268
269 glUniform1f(UNIFORM_OPACITY_LOC, (GLfloat)opacity);
270 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
271 }
272
273 glUniform1f(UNIFORM_SCALE_LOC, (GLfloat)scale_factor);
274 glUniform2f(UNIFORM_PIXEL_NORM_LOC, 1.0F / (GLfloat)tex_width,
275 1.0F / (GLfloat)tex_height);
276
277 glDrawElements(GL_TRIANGLES, nelems, GL_UNSIGNED_INT, NULL);
278 }
279
280 return true;
281 }
282
283 static bool gl_blur_context_preallocate_textures(struct gl_blur_context *bctx,
284 ivec2 source_size, uint64_t root_size) {
285 if (root_size != bctx->root_size) {
286 bctx->root_size = root_size;
287 bctx->fb_width = 0;
288 bctx->fb_height = 0;
289 }
290
291 if (source_size.width > bctx->fb_width || source_size.height > bctx->fb_height) {
292 // Resize the temporary textures used for blur in case the source image
293 // can't fit.
294 bctx->fb_width = max2(bctx->fb_width, source_size.width);
295 bctx->fb_height = max2(bctx->fb_height, source_size.height);
296
297 for (int i = 0; i < bctx->blur_texture_count; ++i) {
298 auto tex_size = bctx->texture_sizes + i;
299 if (bctx->method == BLUR_METHOD_DUAL_KAWASE) {
300 // Use smaller textures for each iteration (quarter of the
301 // previous texture)
302 tex_size->width = 1 + ((bctx->fb_width - 1) >> (i + 1));
303 tex_size->height = 1 + ((bctx->fb_height - 1) >> (i + 1));
304 } else {
305 tex_size->width = bctx->fb_width;
306 tex_size->height = bctx->fb_height;
307 }
308
309 glBindTexture(GL_TEXTURE_2D, bctx->blur_textures[i]);
310 GLint format;
311 switch (bctx->format) {
312 case BACKEND_IMAGE_FORMAT_PIXMAP_HIGH: format = GL_RGBA16; break;
313 case BACKEND_IMAGE_FORMAT_PIXMAP: format = GL_RGBA8; break;
314 case BACKEND_IMAGE_FORMAT_MASK: format = GL_R8; break;
315 default: unreachable();
316 }
317 glTexImage2D(GL_TEXTURE_2D, 0, format, tex_size->width,
318 tex_size->height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
319
320 if (bctx->method == BLUR_METHOD_DUAL_KAWASE) {
321 // Attach texture to FBO target
322 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, bctx->blur_fbos[i]);
323 glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
324 GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
325 bctx->blur_textures[i], 0);
326 if (!gl_check_fb_complete(GL_FRAMEBUFFER)) {
327 glBindFramebuffer(GL_FRAMEBUFFER, 0);
328 return false;
329 }
330 }
331 }
332 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
333 }
334 return true;
335 }
336
337 bool gl_blur(struct backend_base *base, ivec2 origin, image_handle target_,
338 const struct backend_blur_args *args) {
339 auto gd = (struct gl_data *)base;
340 auto target = (struct gl_texture *)target_;
341 auto source = (struct gl_texture *)args->source_image;
342 auto bctx = (struct gl_blur_context *)args->blur_context;
343 log_trace("Blur size: %dx%d, method: %d", source->width, source->height, bctx->method);
344 bool ret = false;
345
346 // Remainder: regions are in Xorg coordinates
347 auto reg_blur_resized =
348 resize_region(args->target_mask, bctx->resize_width, bctx->resize_height);
349 const rect_t *extent = pixman_region32_extents(args->target_mask);
350 int width = extent->x2 - extent->x1, height = extent->y2 - extent->y1;
351 if (width == 0 || height == 0) {
352 return true;
353 }
354
355 int nrects, nrects_resized;
356 const rect_t *rects = pixman_region32_rectangles(args->target_mask, &nrects),
357 *rects_resized =
358 pixman_region32_rectangles(&reg_blur_resized, &nrects_resized);
359 if (!nrects || !nrects_resized) {
360 return true;
361 }
362
363 uint64_t root_size = (uint64_t)gd->back_image.height * (uint64_t)gd->back_image.width;
364 if (!gl_blur_context_preallocate_textures(
365 bctx, (ivec2){source->width, source->height}, root_size)) {
366 return false;
367 }
368
369 // Original region for the final compositing step from blur result to target.
370 auto coord = ccalloc(nrects * 16, GLfloat);
371 auto indices = ccalloc(nrects * 6, GLuint);
372 gl_mask_rects_to_coords(origin, nrects, rects, SCALE_IDENTITY, coord, indices);
373 if (!target->y_inverted) {
374 gl_y_flip_target(nrects, coord, target->height);
375 }
376
377 // Resize region for sampling from source texture, and for blur passes
378 auto coord_resized = ccalloc(nrects_resized * 16, GLfloat);
379 auto indices_resized = ccalloc(nrects_resized * 6, GLuint);
380 gl_mask_rects_to_coords(origin, nrects_resized, rects_resized, SCALE_IDENTITY,
381 coord_resized, indices_resized);
382 pixman_region32_fini(&reg_blur_resized);
383 // FIXME(yshui) In theory we should handle blurring a non-y-inverted source, but
384 // we never actually use that capability anywhere.
385 assert(source->y_inverted);
386
387 glBlendFunc(GL_ONE, GL_ZERO);
388 glBindVertexArray(gd->vertex_array_objects[0]);
389 glBindBuffer(GL_ARRAY_BUFFER, gd->buffer_objects[0]);
390 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gd->buffer_objects[1]);
391 glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord) * nrects * 16, coord, GL_STREAM_DRAW);
392 glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(*indices) * nrects * 6,
393 indices, GL_STREAM_DRAW);
394 glEnableVertexAttribArray(vert_coord_loc);
395 glEnableVertexAttribArray(vert_in_texcoord_loc);
396 glVertexAttribPointer(vert_coord_loc, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, NULL);
397 glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_FLOAT, GL_FALSE,
398 sizeof(GLfloat) * 4, (void *)(sizeof(GLfloat) * 2));
399
400 glBindVertexArray(gd->vertex_array_objects[1]);
401 glBindBuffer(GL_ARRAY_BUFFER, gd->buffer_objects[2]);
402 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gd->buffer_objects[3]);
403 glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord_resized) * nrects_resized * 16,
404 coord_resized, GL_STREAM_DRAW);
405 glBufferData(GL_ELEMENT_ARRAY_BUFFER,
406 (long)sizeof(*indices_resized) * nrects_resized * 6, indices_resized,
407 GL_STREAM_DRAW);
408 glEnableVertexAttribArray(vert_coord_loc);
409 glEnableVertexAttribArray(vert_in_texcoord_loc);
410 glVertexAttribPointer(vert_coord_loc, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 4, NULL);
411 glVertexAttribPointer(vert_in_texcoord_loc, 2, GL_FLOAT, GL_FALSE,
412 sizeof(GLfloat) * 4, (void *)(sizeof(GLfloat) * 2));
413
414 int vao_nelems[2] = {nrects * 6, nrects_resized * 6};
415
416 auto target_fbo = gl_bind_image_to_fbo(gd, (image_handle)target);
417 if (bctx->method == BLUR_METHOD_DUAL_KAWASE) {
418 ret = gl_dual_kawase_blur(
419 args->opacity, bctx, args->source_mask, args->source_mask_scale,
420 gd->vertex_array_objects, vao_nelems, source,
421 gd->samplers[GL_SAMPLER_BLUR], target_fbo, gd->default_mask_texture);
422 } else {
423 ret = gl_kernel_blur(args->opacity, bctx, args->source_mask,
424 args->source_mask_scale, gd->vertex_array_objects,
425 vao_nelems, source, gd->samplers[GL_SAMPLER_BLUR],
426 target_fbo, gd->default_mask_texture);
427 }
428
429 glBindFramebuffer(GL_FRAMEBUFFER, 0);
430 glActiveTexture(GL_TEXTURE1);
431 glBindTexture(GL_TEXTURE_2D, 0);
432 glActiveTexture(GL_TEXTURE0);
433 glBindTexture(GL_TEXTURE_2D, 0);
434
435 // Invalidate buffer data
436 glBindBuffer(GL_ARRAY_BUFFER, gd->buffer_objects[0]);
437 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gd->buffer_objects[1]);
438 glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord) * nrects * 16, NULL, GL_STREAM_DRAW);
439 glBufferData(GL_ELEMENT_ARRAY_BUFFER, (long)sizeof(*indices) * nrects * 6, NULL,
440 GL_STREAM_DRAW);
441 glBindBuffer(GL_ARRAY_BUFFER, gd->buffer_objects[2]);
442 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gd->buffer_objects[3]);
443 glBufferData(GL_ARRAY_BUFFER, (long)sizeof(*coord_resized) * nrects_resized * 16,
444 NULL, GL_STREAM_DRAW);
445 glBufferData(GL_ELEMENT_ARRAY_BUFFER,
446 (long)sizeof(*indices_resized) * nrects_resized * 6, NULL,
447 GL_STREAM_DRAW);
448
449 // Cleanup vertex array states
450 glBindBuffer(GL_ARRAY_BUFFER, 0);
451 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
452 glBindVertexArray(0);
453 glUseProgram(0);
454
455 free(indices);
456 free(coord);
457 free(indices_resized);
458 free(coord_resized);
459
460 gl_check_err();
461 return ret;
462 }
463
464 static inline void gl_free_blur_shader(struct gl_shader *shader) {
465 if (shader->prog) {
466 glDeleteProgram(shader->prog);
467 }
468
469 shader->prog = 0;
470 }
471
472 void gl_destroy_blur_context(backend_t *base attr_unused, void *ctx) {
473 auto bctx = (struct gl_blur_context *)ctx;
474 // Free GLSL shaders/programs
475 for (int i = 0; i < bctx->npasses; ++i) {
476 gl_free_blur_shader(&bctx->blur_shader[i]);
477 }
478 free(bctx->blur_shader);
479
480 if (bctx->blur_texture_count && bctx->blur_textures) {
481 glDeleteTextures(bctx->blur_texture_count, bctx->blur_textures);
482 free(bctx->blur_textures);
483 }
484 if (bctx->blur_texture_count && bctx->texture_sizes) {
485 free(bctx->texture_sizes);
486 }
487 if (bctx->blur_fbo_count && bctx->blur_fbos) {
488 glDeleteFramebuffers(bctx->blur_fbo_count, bctx->blur_fbos);
489 free(bctx->blur_fbos);
490 }
491
492 bctx->blur_texture_count = 0;
493 bctx->blur_fbo_count = 0;
494
495 free(bctx);
496
497 gl_check_err();
498 }
499
500 /**
501 * Initialize GL blur filters.
502 */
503 bool gl_create_kernel_blur_context(void *blur_context, GLfloat *projection,
504 enum blur_method method, void *args) {
505 bool success = false;
506 auto ctx = (struct gl_blur_context *)blur_context;
507
508 struct conv **kernels;
509
510 int nkernels;
511 ctx->method = BLUR_METHOD_KERNEL;
512 if (method == BLUR_METHOD_KERNEL) {
513 nkernels = ((struct kernel_blur_args *)args)->kernel_count;
514 kernels = ((struct kernel_blur_args *)args)->kernels;
515 } else {
516 kernels = generate_blur_kernel(method, args, &nkernels);
517 }
518
519 if (!nkernels) {
520 ctx->method = BLUR_METHOD_NONE;
521 return true;
522 }
523
524 // Specify required textures and FBOs
525 ctx->blur_texture_count = 2;
526 ctx->blur_fbo_count = 1;
527
528 ctx->blur_shader = ccalloc(max2(2, nkernels), struct gl_shader);
529
530 char *lc_numeric_old = strdup(setlocale(LC_NUMERIC, NULL));
531 // Enforce LC_NUMERIC locale "C" here to make sure decimal point is sane
532 // Thanks to hiciu for reporting.
533 setlocale(LC_NUMERIC, "C");
534
535 // clang-format off
536 static const char *FRAG_SHADER_BLUR = GLSL(330,
537 %s\n // other extension pragmas
538 layout(location = UNIFORM_TEX_SRC_LOC)
539 uniform sampler2D tex_src;
540 layout(location = UNIFORM_PIXEL_NORM_LOC)
541 uniform vec2 pixel_norm;
542 layout(location = UNIFORM_OPACITY_LOC)
543 uniform float opacity;
544 in vec2 texcoord;
545 out vec4 out_color;
546 float mask_factor();
547 void main() {
548 vec2 uv = texcoord * pixel_norm;
549 vec4 sum = vec4(0.0, 0.0, 0.0, 0.0);
550 %s //body of the convolution
551 out_color = sum / float(%.7g) * opacity * mask_factor();
552 }
553 );
554 static const char *FRAG_SHADER_BLUR_ADD = QUOTE(
555 sum += float(%.7g) * texture2D(tex_src, uv + pixel_norm * vec2(%.7g, %.7g));
556 );
557 // clang-format on
558
559 const char *shader_add = FRAG_SHADER_BLUR_ADD;
560 char *extension = strdup("");
561
562 for (int i = 0; i < nkernels; i++) {
563 auto kern = kernels[i];
564 // Build shader
565 int width = kern->w, height = kern->h;
566 int nele = width * height;
567 // '%.7g' is at most 14 characters, inserted 3 times
568 size_t body_len = (strlen(shader_add) + 42) * (uint)nele;
569 char *shader_body = ccalloc(body_len, char);
570 char *pc = shader_body;
571
572 // Make use of the linear interpolation hardware by sampling 2 pixels with
573 // one texture access by sampling between both pixels based on their
574 // relative weight. Easiest done in a single dimension as 2D bilinear
575 // filtering would raise additional constraints on the kernels. Therefore
576 // only use interpolation along the larger dimension.
577 double sum = 0.0;
578 if (width > height) {
579 // use interpolation in x dimension (width)
580 for (int j = 0; j < height; ++j) {
581 for (int k = 0; k < width; k += 2) {
582 double val1, val2;
583 val1 = kern->data[j * width + k];
584 val2 = (k + 1 < width)
585 ? kern->data[j * width + k + 1]
586 : 0;
587
588 double combined_weight = val1 + val2;
589 if (combined_weight == 0) {
590 continue;
591 }
592 sum += combined_weight;
593
594 double offset_x =
595 k + (val2 / combined_weight) - (width / 2);
596 double offset_y = j - (height / 2);
597 pc += snprintf(
598 pc, body_len - (ulong)(pc - shader_body),
599 shader_add, combined_weight, offset_x, offset_y);
600 assert(pc < shader_body + body_len);
601 }
602 }
603 } else {
604 // use interpolation in y dimension (height)
605 for (int j = 0; j < height; j += 2) {
606 for (int k = 0; k < width; ++k) {
607 double val1, val2;
608 val1 = kern->data[j * width + k];
609 val2 = (j + 1 < height)
610 ? kern->data[(j + 1) * width + k]
611 : 0;
612
613 double combined_weight = val1 + val2;
614 if (combined_weight == 0) {
615 continue;
616 }
617 sum += combined_weight;
618
619 double offset_x = k - (width / 2);
620 double offset_y =
621 j + (val2 / combined_weight) - (height / 2);
622 pc += snprintf(
623 pc, body_len - (ulong)(pc - shader_body),
624 shader_add, combined_weight, offset_x, offset_y);
625 assert(pc < shader_body + body_len);
626 }
627 }
628 }
629
630 auto pass = ctx->blur_shader + i;
631 size_t shader_len = strlen(FRAG_SHADER_BLUR) + strlen(extension) +
632 strlen(shader_body) + 10 /* sum */ +
633 1 /* null terminator */;
634 char *shader_str = ccalloc(shader_len, char);
635 auto real_shader_len = snprintf(shader_str, shader_len, FRAG_SHADER_BLUR,
636 extension, shader_body, sum);
637 CHECK(real_shader_len >= 0);
638 CHECK((size_t)real_shader_len < shader_len);
639 free(shader_body);
640
641 // Build program
642 pass->prog = gl_create_program_from_strv(
643 (const char *[]){vertex_shader, NULL},
644 (const char *[]){shader_str, scaled_masking_glsl, NULL});
645 free(shader_str);
646 if (!pass->prog) {
647 log_error("Failed to create GLSL program.");
648 success = false;
649 goto out;
650 }
651 pass->uniform_bitmask = 1 << UNIFORM_PIXEL_NORM_LOC;
652 glBindFragDataLocation(pass->prog, 0, "out_color");
653
654 // Setup projection matrix
655 glUseProgram(pass->prog);
656 glUniformMatrix4fv(UNIFORM_PROJECTION_LOC, 1, false, projection);
657 glUseProgram(0);
658
659 ctx->resize_width += kern->w / 2;
660 ctx->resize_height += kern->h / 2;
661 }
662
663 if (nkernels == 1) {
664 // Generate an extra null pass so we don't need special code path for
665 // the single pass case
666 auto pass = &ctx->blur_shader[1];
667 pass->prog = gl_create_program_from_strv(
668 (const char *[]){vertex_shader, NULL},
669 (const char *[]){blend_with_mask_frag, scaled_masking_glsl, NULL});
670
671 // Setup projection matrix
672 glUseProgram(pass->prog);
673 glUniformMatrix4fv(UNIFORM_PROJECTION_LOC, 1, false, projection);
674 glUseProgram(0);
675
676 ctx->npasses = 2;
677 } else {
678 ctx->npasses = nkernels;
679 }
680
681 success = true;
682 out:
683 if (method != BLUR_METHOD_KERNEL) {
684 // We generated the blur kernels, so we need to free them
685 for (int i = 0; i < nkernels; i++) {
686 free(kernels[i]);
687 }
688 free(kernels);
689 }
690
691 free(extension);
692 // Restore LC_NUMERIC
693 setlocale(LC_NUMERIC, lc_numeric_old);
694 free(lc_numeric_old);
695
696 return success;
697 }
698
699 bool gl_create_dual_kawase_blur_context(void *blur_context, GLfloat *projection,
700 enum blur_method method, void *args) {
701 bool success = false;
702 auto ctx = (struct gl_blur_context *)blur_context;
703
704 ctx->method = method;
705
706 auto blur_params = generate_dual_kawase_params(args);
707
708 // Specify required textures and FBOs
709 ctx->blur_texture_count = blur_params->iterations;
710 ctx->blur_fbo_count = blur_params->iterations;
711
712 ctx->resize_width += blur_params->expand;
713 ctx->resize_height += blur_params->expand;
714
715 ctx->npasses = 2;
716 ctx->blur_shader = ccalloc(ctx->npasses, struct gl_shader);
717
718 char *lc_numeric_old = strdup(setlocale(LC_NUMERIC, NULL));
719 // Enforce LC_NUMERIC locale "C" here to make sure decimal point is sane
720 // Thanks to hiciu for reporting.
721 setlocale(LC_NUMERIC, "C");
722
723 // Dual-kawase downsample shader / program
724 auto down_pass = ctx->blur_shader;
725 {
726 // clang-format off
727 static const char *FRAG_SHADER_DOWN = GLSL(330,
728 layout(location = UNIFORM_TEX_SRC_LOC)
729 uniform sampler2D tex_src;
730 layout(location = UNIFORM_SCALE_LOC)
731 uniform float scale = 1.0;
732 layout(location = UNIFORM_PIXEL_NORM_LOC)
733 uniform vec2 pixel_norm;
734 in vec2 texcoord;
735 out vec4 out_color;
736 void main() {
737 vec2 offset = %.7g * pixel_norm;
738 vec2 uv = texcoord * pixel_norm * (2.0 / scale);
739 vec4 sum = texture2D(tex_src, uv) * 4.0;
740 sum += texture2D(tex_src, uv - vec2(0.5, 0.5) * offset);
741 sum += texture2D(tex_src, uv + vec2(0.5, 0.5) * offset);
742 sum += texture2D(tex_src, uv + vec2(0.5, -0.5) * offset);
743 sum += texture2D(tex_src, uv - vec2(0.5, -0.5) * offset);
744 out_color = sum / 8.0;
745 }
746 );
747 // clang-format on
748
749 // Build shader
750 size_t shader_len =
751 strlen(FRAG_SHADER_DOWN) + 10 /* offset */ + 1 /* null terminator */;
752 char *shader_str = ccalloc(shader_len, char);
753 auto real_shader_len =
754 snprintf(shader_str, shader_len, FRAG_SHADER_DOWN, blur_params->offset);
755 CHECK(real_shader_len >= 0);
756 CHECK((size_t)real_shader_len < shader_len);
757
758 // Build program
759 down_pass->prog = gl_create_program_from_str(vertex_shader, shader_str);
760 free(shader_str);
761 if (!down_pass->prog) {
762 log_error("Failed to create GLSL program.");
763 success = false;
764 goto out;
765 }
766 glBindFragDataLocation(down_pass->prog, 0, "out_color");
767
768 // Setup projection matrix
769 glUseProgram(down_pass->prog);
770 glUniformMatrix4fv(UNIFORM_PROJECTION_LOC, 1, false, projection);
771 glUseProgram(0);
772 }
773
774 // Dual-kawase upsample shader / program
775 auto up_pass = ctx->blur_shader + 1;
776 {
777 // clang-format off
778 static const char *FRAG_SHADER_UP = GLSL(330,
779 layout(location = UNIFORM_TEX_SRC_LOC)
780 uniform sampler2D tex_src;
781 layout(location = UNIFORM_SCALE_LOC)
782 uniform float scale = 1.0;
783 layout(location = UNIFORM_PIXEL_NORM_LOC)
784 uniform vec2 pixel_norm;
785 layout(location = UNIFORM_OPACITY_LOC)
786 uniform float opacity;
787 in vec2 texcoord;
788 out vec4 out_color;
789 float mask_factor();
790 void main() {
791 vec2 offset = %.7g * pixel_norm;
792 vec2 uv = texcoord * pixel_norm / (2 * scale);
793 vec4 sum = texture2D(tex_src, uv + vec2(-1.0, 0.0) * offset);
794 sum += texture2D(tex_src, uv + vec2(-0.5, 0.5) * offset) * 2.0;
795 sum += texture2D(tex_src, uv + vec2(0.0, 1.0) * offset);
796 sum += texture2D(tex_src, uv + vec2(0.5, 0.5) * offset) * 2.0;
797 sum += texture2D(tex_src, uv + vec2(1.0, 0.0) * offset);
798 sum += texture2D(tex_src, uv + vec2(0.5, -0.5) * offset) * 2.0;
799 sum += texture2D(tex_src, uv + vec2(0.0, -1.0) * offset);
800 sum += texture2D(tex_src, uv + vec2(-0.5, -0.5) * offset) * 2.0;
801 out_color = sum / 12.0 * opacity * mask_factor();
802 }
803 );
804 // clang-format on
805
806 // Build shader
807 size_t shader_len =
808 strlen(FRAG_SHADER_UP) + 10 /* offset */ + 1 /* null terminator */;
809 char *shader_str = ccalloc(shader_len, char);
810 auto real_shader_len =
811 snprintf(shader_str, shader_len, FRAG_SHADER_UP, blur_params->offset);
812 CHECK(real_shader_len >= 0);
813 CHECK((size_t)real_shader_len < shader_len);
814
815 // Build program
816 up_pass->prog = gl_create_program_from_strv(
817 (const char *[]){vertex_shader, NULL},
818 (const char *[]){shader_str, scaled_masking_glsl, NULL});
819 free(shader_str);
820 if (!up_pass->prog) {
821 log_error("Failed to create GLSL program.");
822 success = false;
823 goto out;
824 }
825 glBindFragDataLocation(up_pass->prog, 0, "out_color");
826
827 // Setup projection matrix
828 glUseProgram(up_pass->prog);
829 glUniformMatrix4fv(UNIFORM_PROJECTION_LOC, 1, false, projection);
830 glUseProgram(0);
831 }
832
833 success = true;
834 out:
835 free(blur_params);
836
837 if (!success) {
838 ctx = NULL;
839 }
840
841 // Restore LC_NUMERIC
842 setlocale(LC_NUMERIC, lc_numeric_old);
843 free(lc_numeric_old);
844
845 return success;
846 }
847
848 void *gl_create_blur_context(backend_t *base, enum blur_method method,
849 enum backend_image_format format, void *args) {
850 bool success;
851 auto gd = (struct gl_data *)base;
852
853 auto ctx = ccalloc(1, struct gl_blur_context);
854
855 if (!method || method >= BLUR_METHOD_INVALID) {
856 ctx->method = BLUR_METHOD_NONE;
857 return ctx;
858 }
859
860 // Set projection matrix to gl viewport dimensions so we can use screen
861 // coordinates for all vertices
862 // Note: OpenGL matrices are column major
863 GLint viewport_dimensions[2];
864 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, viewport_dimensions);
865 GLfloat projection_matrix[4][4] = {{2.0F / (GLfloat)viewport_dimensions[0], 0, 0, 0},
866 {0, 2.0F / (GLfloat)viewport_dimensions[1], 0, 0},
867 {0, 0, 0, 0},
868 {-1, -1, 0, 1}};
869
870 if (method == BLUR_METHOD_DUAL_KAWASE) {
871 success = gl_create_dual_kawase_blur_context(ctx, projection_matrix[0],
872 method, args);
873 } else {
874 success =
875 gl_create_kernel_blur_context(ctx, projection_matrix[0], method, args);
876 }
877 if (!success || ctx->method == BLUR_METHOD_NONE) {
878 goto out;
879 }
880
881 // Texture size will be defined by gl_blur
882 ctx->blur_textures = ccalloc(ctx->blur_texture_count, GLuint);
883 ctx->texture_sizes = ccalloc(ctx->blur_texture_count, struct texture_size);
884 ctx->format = format;
885 glGenTextures(ctx->blur_texture_count, ctx->blur_textures);
886
887 // Generate FBO and textures when needed
888 ctx->blur_fbos = ccalloc(ctx->blur_fbo_count, GLuint);
889 glGenFramebuffers(ctx->blur_fbo_count, ctx->blur_fbos);
890
891 for (int i = 0; i < ctx->blur_fbo_count; ++i) {
892 if (!ctx->blur_fbos[i]) {
893 log_error("Failed to generate framebuffer objects for blur");
894 success = false;
895 goto out;
896 }
897 }
898
899 out:
900 if (!success) {
901 gl_destroy_blur_context(&gd->base, ctx);
902 ctx = NULL;
903 }
904
905 gl_check_err();
906 return ctx;
907 }
908
909 void gl_get_blur_size(void *blur_context, int *width, int *height) {
910 auto ctx = (struct gl_blur_context *)blur_context;
911 *width = ctx->resize_width;
912 *height = ctx->resize_height;
913 }