6 #include <SDL2/SDL_error.h>
7 #include <SDL2/SDL_events.h>
8 #include <SDL2/SDL_image.h>
9 #include <SDL2/SDL_keyboard.h>
10 #include <SDL2/SDL_mouse.h>
11 #include <SDL2/SDL_video.h>
23 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
27 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
28 constexpr float patch_overlap_ratio = 0.75f;
29 constexpr unsigned coarsest_level = 5;
30 constexpr unsigned finest_level = 1;
31 constexpr unsigned patch_size_pixels = 12;
33 // Weighting constants for the different parts of the variational refinement.
34 // These don't correspond 1:1 to the values given in the DIS paper,
35 // since we have different normalizations and ranges in some cases.
36 float vr_gamma = 10.0f, vr_delta = 5.0f, vr_alpha = 10.0f;
38 // Some global OpenGL objects.
39 GLuint nearest_sampler, linear_sampler, smoothness_sampler;
42 string read_file(const string &filename)
44 FILE *fp = fopen(filename.c_str(), "r");
46 perror(filename.c_str());
50 int ret = fseek(fp, 0, SEEK_END);
52 perror("fseek(SEEK_END)");
58 ret = fseek(fp, 0, SEEK_SET);
60 perror("fseek(SEEK_SET)");
66 ret = fread(&str[0], size, 1, fp);
72 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
73 size, filename.c_str());
82 GLuint compile_shader(const string &shader_src, GLenum type)
84 GLuint obj = glCreateShader(type);
85 const GLchar* source[] = { shader_src.data() };
86 const GLint length[] = { (GLint)shader_src.size() };
87 glShaderSource(obj, 1, source, length);
90 GLchar info_log[4096];
91 GLsizei log_length = sizeof(info_log) - 1;
92 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
93 info_log[log_length] = 0;
94 if (strlen(info_log) > 0) {
95 fprintf(stderr, "Shader compile log: %s\n", info_log);
99 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
100 if (status == GL_FALSE) {
101 // Add some line numbers to easier identify compile errors.
102 string src_with_lines = "/* 1 */ ";
104 for (char ch : shader_src) {
105 src_with_lines.push_back(ch);
108 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
109 src_with_lines += buf;
113 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
120 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret)
122 SDL_Surface *surf = IMG_Load(filename);
123 if (surf == nullptr) {
124 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
128 // For whatever reason, SDL doesn't support converting to YUV surfaces
129 // nor grayscale, so we'll do it (slowly) ourselves.
130 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA8888, /*flags=*/0);
131 if (rgb_surf == nullptr) {
132 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
136 SDL_FreeSurface(surf);
138 unsigned width = rgb_surf->w, height = rgb_surf->h;
139 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
140 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
142 // Extract the Y component, and convert to bottom-left origin.
143 for (unsigned y = 0; y < height; ++y) {
144 unsigned y2 = height - 1 - y;
145 for (unsigned x = 0; x < width; ++x) {
146 uint8_t r = sptr[(y2 * width + x) * 4 + 3];
147 uint8_t g = sptr[(y2 * width + x) * 4 + 2];
148 uint8_t b = sptr[(y2 * width + x) * 4 + 1];
151 pix[y * width + x] = lrintf(r * 0.2126f + g * 0.7152f + b * 0.0722f);
154 SDL_FreeSurface(rgb_surf);
157 for (int w = width, h = height; w > 1 || h > 1; ) {
164 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
165 glTextureStorage2D(tex, levels, GL_R8, width, height);
166 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
167 glGenerateTextureMipmap(tex);
170 *height_ret = height;
175 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
177 GLuint program = glCreateProgram();
178 glAttachShader(program, vs_obj);
179 glAttachShader(program, fs_obj);
180 glLinkProgram(program);
182 glGetProgramiv(program, GL_LINK_STATUS, &success);
183 if (success == GL_FALSE) {
184 GLchar error_log[1024] = {0};
185 glGetProgramInfoLog(program, 1024, nullptr, error_log);
186 fprintf(stderr, "Error linking program: %s\n", error_log);
192 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
195 glCreateBuffers(1, &vbo);
196 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
197 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
201 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
203 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
208 GLuint vbo = generate_vbo(size, data_size, data);
210 glBindBuffer(GL_ARRAY_BUFFER, vbo);
211 glEnableVertexArrayAttrib(vao, attrib);
212 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
213 glBindBuffer(GL_ARRAY_BUFFER, 0);
218 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
220 if (location == -1) {
224 glBindTextureUnit(texture_unit, tex);
225 glBindSampler(texture_unit, sampler);
226 glProgramUniform1i(program, location, texture_unit);
229 // Compute gradients in every point, used for the motion search.
230 // The DIS paper doesn't actually mention how these are computed,
231 // but seemingly, a 3x3 Sobel operator is used here (at least in
232 // later versions of the code), while a [1 -8 0 8 -1] kernel is
233 // used for all the derivatives in the variational refinement part
234 // (which borrows code from DeepFlow). This is inconsistent,
235 // but I guess we're better off with staying with the original
236 // decisions until we actually know having different ones would be better.
240 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
245 GLuint sobel_program;
248 GLuint uniform_tex, uniform_image_size;
253 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
254 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
255 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
257 // Set up the VAO containing all the required position/texcoord data.
258 glCreateVertexArrays(1, &sobel_vao);
259 glBindVertexArray(sobel_vao);
261 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
262 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
263 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
265 uniform_tex = glGetUniformLocation(sobel_program, "tex");
268 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
270 glUseProgram(sobel_program);
271 glBindTextureUnit(0, tex0_view);
272 glBindSampler(0, nearest_sampler);
273 glProgramUniform1i(sobel_program, uniform_tex, 0);
275 GLuint grad0_fbo; // TODO: cleanup
276 glCreateFramebuffers(1, &grad0_fbo);
277 glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
279 glViewport(0, 0, level_width, level_height);
280 glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
281 glBindVertexArray(sobel_vao);
282 glUseProgram(sobel_program);
284 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
287 // Motion search to find the initial flow. See motion_search.frag for documentation.
291 void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
294 GLuint motion_vs_obj;
295 GLuint motion_fs_obj;
296 GLuint motion_search_program;
297 GLuint motion_search_vao;
299 GLuint uniform_image_size, uniform_inv_image_size, uniform_inv_prev_level_size;
300 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
303 MotionSearch::MotionSearch()
305 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
306 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
307 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
309 // Set up the VAO containing all the required position/texcoord data.
310 glCreateVertexArrays(1, &motion_search_vao);
311 glBindVertexArray(motion_search_vao);
312 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
314 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
315 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
316 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
318 uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
319 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
320 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
321 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
322 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
323 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
324 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
327 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
329 glUseProgram(motion_search_program);
331 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
332 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
333 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
334 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
336 glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
337 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
338 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
340 GLuint flow_fbo; // TODO: cleanup
341 glCreateFramebuffers(1, &flow_fbo);
342 glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
344 glViewport(0, 0, width_patches, height_patches);
345 glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
346 glBindVertexArray(motion_search_vao);
347 glUseProgram(motion_search_program);
348 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
351 // Do “densification”, ie., upsampling of the flow patches to the flow field
352 // (the same size as the image at this level). We draw one quad per patch
353 // over its entire covered area (using instancing in the vertex shader),
354 // and then weight the contributions in the pixel shader by post-warp difference.
355 // This is equation (3) in the paper.
357 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
358 // weight in the B channel. Dividing R and G by B gives the normalized values.
362 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
365 GLuint densify_vs_obj;
366 GLuint densify_fs_obj;
367 GLuint densify_program;
370 GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
371 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
376 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
377 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
378 densify_program = link_program(densify_vs_obj, densify_fs_obj);
380 // Set up the VAO containing all the required position/texcoord data.
381 glCreateVertexArrays(1, &densify_vao);
382 glBindVertexArray(densify_vao);
383 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
385 GLint position_attrib = glGetAttribLocation(densify_program, "position");
386 glEnableVertexArrayAttrib(densify_vao, position_attrib);
387 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
389 uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
390 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
391 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
392 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
393 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
394 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
397 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
399 glUseProgram(densify_program);
401 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
402 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
403 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
405 glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
406 glProgramUniform2f(densify_program, uniform_patch_size,
407 float(patch_size_pixels) / level_width,
408 float(patch_size_pixels) / level_height);
410 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
411 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
412 if (width_patches == 1) patch_spacing_x = 0.0f; // Avoid infinities.
413 if (height_patches == 1) patch_spacing_y = 0.0f;
414 glProgramUniform2f(densify_program, uniform_patch_spacing,
415 patch_spacing_x / level_width,
416 patch_spacing_y / level_height);
418 GLuint dense_flow_fbo; // TODO: cleanup
419 glCreateFramebuffers(1, &dense_flow_fbo);
420 glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
422 glViewport(0, 0, level_width, level_height);
424 glBlendFunc(GL_ONE, GL_ONE);
425 glBindVertexArray(densify_vao);
426 glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
427 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
430 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
431 // I_0 and I_w. The prewarping is what enables us to solve the variational
432 // flow for du,dv instead of u,v.
434 // Also calculates the normalized flow, ie. divides by z (this is needed because
435 // Densify works by additive blending) and multiplies by the image size.
437 // See variational_refinement.txt for more information.
441 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
444 GLuint prewarp_vs_obj;
445 GLuint prewarp_fs_obj;
446 GLuint prewarp_program;
449 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
450 GLuint uniform_image_size;
455 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
456 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
457 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
459 // Set up the VAO containing all the required position/texcoord data.
460 glCreateVertexArrays(1, &prewarp_vao);
461 glBindVertexArray(prewarp_vao);
462 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
464 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
465 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
466 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
468 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
469 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
470 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
472 uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
475 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
477 glUseProgram(prewarp_program);
479 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
480 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
481 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
483 glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
485 GLuint prewarp_fbo; // TODO: cleanup
486 glCreateFramebuffers(1, &prewarp_fbo);
487 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
488 glNamedFramebufferDrawBuffers(prewarp_fbo, 3, bufs);
489 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
490 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
491 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT2, normalized_flow_tex, 0);
493 glViewport(0, 0, level_width, level_height);
495 glBindVertexArray(prewarp_vao);
496 glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
497 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
500 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
501 // central difference filter, since apparently, that's tradition (I haven't
502 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
503 // The coefficients come from
505 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
507 // Also computes β_0, since it depends only on I_x and I_y.
511 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
514 GLuint derivatives_vs_obj;
515 GLuint derivatives_fs_obj;
516 GLuint derivatives_program;
517 GLuint derivatives_vao;
522 Derivatives::Derivatives()
524 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
525 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
526 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
528 // Set up the VAO containing all the required position/texcoord data.
529 glCreateVertexArrays(1, &derivatives_vao);
530 glBindVertexArray(derivatives_vao);
531 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
533 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
534 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
535 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
537 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
540 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
542 glUseProgram(derivatives_program);
544 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
546 GLuint derivatives_fbo; // TODO: cleanup
547 glCreateFramebuffers(1, &derivatives_fbo);
548 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
549 glNamedFramebufferDrawBuffers(derivatives_fbo, 2, bufs);
550 glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT0, I_x_y_tex, 0);
551 glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT1, beta_0_tex, 0);
553 glViewport(0, 0, level_width, level_height);
555 glBindVertexArray(derivatives_vao);
556 glBindFramebuffer(GL_FRAMEBUFFER, derivatives_fbo);
557 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
560 // Calculate the smoothness constraints between neighboring pixels;
561 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
562 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
563 // border color (0,0) later, so that there's zero diffusion out of
566 // See variational_refinement.txt for more information.
567 class ComputeSmoothness {
570 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
573 GLuint smoothness_vs_obj;
574 GLuint smoothness_fs_obj;
575 GLuint smoothness_program;
576 GLuint smoothness_vao;
578 GLuint uniform_flow_tex, uniform_diff_flow_tex;
579 GLuint uniform_alpha;
582 ComputeSmoothness::ComputeSmoothness()
584 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
585 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
586 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
588 // Set up the VAO containing all the required position/texcoord data.
589 glCreateVertexArrays(1, &smoothness_vao);
590 glBindVertexArray(smoothness_vao);
591 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
593 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
594 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
595 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
597 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
598 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
599 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
602 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
604 glUseProgram(smoothness_program);
606 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
607 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
608 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
610 GLuint smoothness_fbo; // TODO: cleanup
611 glCreateFramebuffers(1, &smoothness_fbo);
612 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
613 glNamedFramebufferDrawBuffers(smoothness_fbo, 2, bufs);
614 glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT0, smoothness_x_tex, 0);
615 glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT1, smoothness_y_tex, 0);
617 glViewport(0, 0, level_width, level_height);
620 glBindVertexArray(smoothness_vao);
621 glBindFramebuffer(GL_FRAMEBUFFER, smoothness_fbo);
622 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
624 // Make sure the smoothness on the right and upper borders is zero.
625 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
626 // (we're sampling smoothness with all-zero border color), but we'd
627 // have to adjust the sampling coordinates, which is annoying.
628 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
629 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
632 // Set up the equations set (two equations in two unknowns, per pixel).
633 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
634 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
635 // floats. (Actually, we store the inverse of the diagonal elements, because
636 // we only ever need to divide by them.) This fits into four u32 values;
637 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
638 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
639 // terms that depend on other pixels, are calculated in one pass.
641 // See variational_refinement.txt for more information.
642 class SetupEquations {
645 void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height);
648 GLuint equations_vs_obj;
649 GLuint equations_fs_obj;
650 GLuint equations_program;
651 GLuint equations_vao;
653 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
654 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
655 GLuint uniform_beta_0_tex;
656 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
657 GLuint uniform_gamma, uniform_delta;
660 SetupEquations::SetupEquations()
662 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
663 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
664 equations_program = link_program(equations_vs_obj, equations_fs_obj);
666 // Set up the VAO containing all the required position/texcoord data.
667 glCreateVertexArrays(1, &equations_vao);
668 glBindVertexArray(equations_vao);
669 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
671 GLint position_attrib = glGetAttribLocation(equations_program, "position");
672 glEnableVertexArrayAttrib(equations_vao, position_attrib);
673 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
675 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
676 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
677 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
678 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
679 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
680 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
681 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
682 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
683 uniform_delta = glGetUniformLocation(equations_program, "delta");
686 void SetupEquations::exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint base_flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height)
688 glUseProgram(equations_program);
690 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
691 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
692 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
693 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
694 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
695 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
696 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
697 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
698 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
700 GLuint equations_fbo; // TODO: cleanup
701 glCreateFramebuffers(1, &equations_fbo);
702 glNamedFramebufferTexture(equations_fbo, GL_COLOR_ATTACHMENT0, equation_tex, 0);
704 glViewport(0, 0, level_width, level_height);
706 glBindVertexArray(equations_vao);
707 glBindFramebuffer(GL_FRAMEBUFFER, equations_fbo);
708 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
711 // Actually solve the equation sets made by SetupEquations, by means of
712 // successive over-relaxation (SOR).
714 // See variational_refinement.txt for more information.
718 void exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations);
726 GLuint uniform_diff_flow_tex;
727 GLuint uniform_equation_tex;
728 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
733 sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
734 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
735 sor_program = link_program(sor_vs_obj, sor_fs_obj);
737 // Set up the VAO containing all the required position/texcoord data.
738 glCreateVertexArrays(1, &sor_vao);
739 glBindVertexArray(sor_vao);
740 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
742 GLint position_attrib = glGetAttribLocation(sor_program, "position");
743 glEnableVertexArrayAttrib(sor_vao, position_attrib);
744 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
746 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
747 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
748 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
749 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
752 void SOR::exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations)
754 glUseProgram(sor_program);
756 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
757 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
758 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
759 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
761 GLuint sor_fbo; // TODO: cleanup
762 glCreateFramebuffers(1, &sor_fbo);
763 glNamedFramebufferTexture(sor_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0); // NOTE: Bind to same as we render from!
765 glViewport(0, 0, level_width, level_height);
767 glBindVertexArray(sor_vao);
768 glBindFramebuffer(GL_FRAMEBUFFER, sor_fbo);
770 for (int i = 0; i < num_iterations; ++i) {
771 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
772 if (i != num_iterations - 1) {
778 // Simply add the differential flow found by the variational refinement to the base flow.
779 // The output is in base_flow_tex; we don't need to make a new texture.
783 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
786 GLuint add_flow_vs_obj;
787 GLuint add_flow_fs_obj;
788 GLuint add_flow_program;
791 GLuint uniform_diff_flow_tex;
794 AddBaseFlow::AddBaseFlow()
796 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
797 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
798 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
800 // Set up the VAO containing all the required position/texcoord data.
801 glCreateVertexArrays(1, &add_flow_vao);
802 glBindVertexArray(add_flow_vao);
803 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
805 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
806 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
807 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
809 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
812 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
814 glUseProgram(add_flow_program);
816 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
818 GLuint add_flow_fbo; // TODO: cleanup
819 glCreateFramebuffers(1, &add_flow_fbo);
820 glNamedFramebufferTexture(add_flow_fbo, GL_COLOR_ATTACHMENT0, base_flow_tex, 0);
822 glViewport(0, 0, level_width, level_height);
824 glBlendFunc(GL_ONE, GL_ONE);
825 glBindVertexArray(add_flow_vao);
826 glBindFramebuffer(GL_FRAMEBUFFER, add_flow_fbo);
828 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
834 pair<GLuint, GLuint> begin_timer(const string &name, int level);
840 pair<GLuint, GLuint> query;
842 vector<Timer> timers;
845 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
848 glGenQueries(2, queries);
849 glQueryCounter(queries[0], GL_TIMESTAMP);
854 timer.query.first = queries[0];
855 timer.query.second = queries[1];
856 timers.push_back(timer);
860 // Take a copy of the flow, bilinearly interpolated and scaled up.
864 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
867 GLuint resize_flow_vs_obj;
868 GLuint resize_flow_fs_obj;
869 GLuint resize_flow_program;
870 GLuint resize_flow_vao;
872 GLuint uniform_flow_tex;
873 GLuint uniform_scale_factor;
876 ResizeFlow::ResizeFlow()
878 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
879 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
880 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
882 // Set up the VAO containing all the required position/texcoord data.
883 glCreateVertexArrays(1, &resize_flow_vao);
884 glBindVertexArray(resize_flow_vao);
885 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
887 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
888 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
889 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
891 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
892 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
895 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
897 glUseProgram(resize_flow_program);
899 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
901 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
903 GLuint resize_flow_fbo; // TODO: cleanup
904 glCreateFramebuffers(1, &resize_flow_fbo);
905 glNamedFramebufferTexture(resize_flow_fbo, GL_COLOR_ATTACHMENT0, out_tex, 0);
907 glViewport(0, 0, output_width, output_height);
909 glBindVertexArray(resize_flow_vao);
910 glBindFramebuffer(GL_FRAMEBUFFER, resize_flow_fbo);
912 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
915 void GPUTimers::print()
917 for (const Timer &timer : timers) {
918 // NOTE: This makes the CPU wait for the GPU.
919 GLuint64 time_start, time_end;
920 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
921 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
922 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
923 for (int i = 0; i < timer.level * 2; ++i) {
924 fprintf(stderr, " ");
926 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
930 // A simple RAII class for timing until the end of the scope.
933 ScopedTimer(const string &name, GPUTimers *timers)
934 : timers(timers), level(0)
936 query = timers->begin_timer(name, level);
939 ScopedTimer(const string &name, ScopedTimer *parent_timer)
940 : timers(parent_timer->timers),
941 level(parent_timer->level + 1)
943 query = timers->begin_timer(name, level);
954 glQueryCounter(query.second, GL_TIMESTAMP);
962 pair<GLuint, GLuint> query;
966 int main(int argc, char **argv)
968 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
969 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
972 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
973 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
974 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
975 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
977 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
978 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
979 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
980 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
981 SDL_Window *window = SDL_CreateWindow("OpenGL window",
982 SDL_WINDOWPOS_UNDEFINED,
983 SDL_WINDOWPOS_UNDEFINED,
986 SDL_GLContext context = SDL_GL_CreateContext(window);
987 assert(context != nullptr);
990 unsigned width1, height1, width2, height2;
991 GLuint tex0 = load_texture(argc >= 2 ? argv[1] : "test1499.png", &width1, &height1);
992 GLuint tex1 = load_texture(argc >= 3 ? argv[2] : "test1500.png", &width2, &height2);
994 if (width1 != width2 || height1 != height2) {
995 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
996 width1, height1, width2, height2);
1000 // Make some samplers.
1001 glCreateSamplers(1, &nearest_sampler);
1002 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1003 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1004 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1005 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1007 glCreateSamplers(1, &linear_sampler);
1008 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1009 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1010 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1011 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1013 // The smoothness is sampled so that once we get to a smoothness involving
1014 // a value outside the border, the diffusivity between the two becomes zero.
1015 glCreateSamplers(1, &smoothness_sampler);
1016 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1017 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1018 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1019 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1020 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1021 glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1023 float vertices[] = {
1029 glCreateBuffers(1, &vertex_vbo);
1030 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1031 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1033 // Initial flow is zero, 1x1.
1034 GLuint initial_flow_tex;
1035 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1036 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1037 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1038 int prev_level_width = 1, prev_level_height = 1;
1040 GLuint prev_level_flow_tex = initial_flow_tex;
1043 MotionSearch motion_search;
1046 Derivatives derivatives;
1047 ComputeSmoothness compute_smoothness;
1048 SetupEquations setup_equations;
1050 AddBaseFlow add_base_flow;
1051 ResizeFlow resize_flow;
1054 glGenQueries(1, &query);
1055 glBeginQuery(GL_TIME_ELAPSED, query);
1059 ScopedTimer total_timer("Total", &timers);
1060 for (int level = coarsest_level; level >= int(finest_level); --level) {
1061 char timer_name[256];
1062 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1063 ScopedTimer level_timer(timer_name, &total_timer);
1065 int level_width = width1 >> level;
1066 int level_height = height1 >> level;
1067 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1068 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
1069 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
1071 // Make sure we always read from the correct level; the chosen
1072 // mipmapping could otherwise be rather unpredictable, especially
1073 // during motion search.
1074 // TODO: create these beforehand, and stop leaking them.
1075 GLuint tex0_view, tex1_view;
1076 glGenTextures(1, &tex0_view);
1077 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1078 glGenTextures(1, &tex1_view);
1079 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1081 // Create a new texture; we could be fancy and render use a multi-level
1082 // texture, but meh.
1084 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
1085 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
1087 // Find the derivative.
1089 ScopedTimer timer("Sobel", &level_timer);
1090 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1093 // Motion search to find the initial flow. We use the flow from the previous
1094 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1096 // Create an output flow texture.
1097 GLuint flow_out_tex;
1098 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
1099 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
1103 ScopedTimer timer("Motion search", &level_timer);
1104 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1109 // Set up an output texture (initially zero).
1110 GLuint dense_flow_tex;
1111 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
1112 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
1113 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1117 ScopedTimer timer("Densification", &level_timer);
1118 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1121 // Everything below here in the loop belongs to variational refinement.
1122 ScopedTimer varref_timer("Variational refinement", &level_timer);
1124 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1125 // have to normalize it over and over again, and also save some bandwidth).
1127 // During the entire rest of the variational refinement, flow will be measured
1128 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1129 // This is because variational refinement depends so heavily on derivatives,
1130 // which are measured in intensity levels per pixel.
1131 GLuint I_tex, I_t_tex, base_flow_tex;
1132 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
1133 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
1134 glCreateTextures(GL_TEXTURE_2D, 1, &base_flow_tex);
1135 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
1136 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
1137 glTextureStorage2D(base_flow_tex, 1, GL_RG16F, level_width, level_height);
1139 ScopedTimer timer("Prewarping", &varref_timer);
1140 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1143 // Calculate I_x and I_y. We're only calculating first derivatives;
1144 // the others will be taken on-the-fly in order to sample from fewer
1145 // textures overall, since sampling from the L1 cache is cheap.
1146 // (TODO: Verify that this is indeed faster than making separate
1147 // double-derivative textures.)
1148 GLuint I_x_y_tex, beta_0_tex;
1149 glCreateTextures(GL_TEXTURE_2D, 1, &I_x_y_tex);
1150 glCreateTextures(GL_TEXTURE_2D, 1, &beta_0_tex);
1151 glTextureStorage2D(I_x_y_tex, 1, GL_RG16F, level_width, level_height);
1152 glTextureStorage2D(beta_0_tex, 1, GL_R16F, level_width, level_height);
1154 ScopedTimer timer("First derivatives", &varref_timer);
1155 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1158 // We need somewhere to store du and dv (the flow increment, relative
1159 // to the non-refined base flow u0 and v0). It starts at zero.
1161 glCreateTextures(GL_TEXTURE_2D, 1, &du_dv_tex);
1162 glTextureStorage2D(du_dv_tex, 1, GL_RG16F, level_width, level_height);
1163 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1165 // And for smoothness.
1166 GLuint smoothness_x_tex, smoothness_y_tex;
1167 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_x_tex);
1168 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_y_tex);
1169 glTextureStorage2D(smoothness_x_tex, 1, GL_R16F, level_width, level_height);
1170 glTextureStorage2D(smoothness_y_tex, 1, GL_R16F, level_width, level_height);
1172 // And finally for the equation set. See SetupEquations for
1173 // the storage format.
1174 GLuint equation_tex;
1175 glCreateTextures(GL_TEXTURE_2D, 1, &equation_tex);
1176 glTextureStorage2D(equation_tex, 1, GL_RGBA32UI, level_width, level_height);
1178 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1179 // Calculate the smoothness terms between the neighboring pixels,
1180 // both in x and y direction.
1182 ScopedTimer timer("Compute smoothness", &varref_timer);
1183 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1186 // Set up the 2x2 equation system for each pixel.
1188 ScopedTimer timer("Set up equations", &varref_timer);
1189 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1192 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1193 // Note that these are to/from the same texture.
1195 ScopedTimer timer("SOR", &varref_timer);
1196 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1200 // Add the differential flow found by the variational refinement to the base flow,
1201 // giving the final flow estimate for this level.
1202 // The output is in diff_flow_tex; we don't need to make a new texture.
1203 // You can comment out this part if you wish to test disabling of the variational refinement.
1205 ScopedTimer timer("Add differential flow", &varref_timer);
1206 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1209 prev_level_flow_tex = base_flow_tex;
1210 prev_level_width = level_width;
1211 prev_level_height = level_height;
1217 // Scale up the flow to the final size (if needed).
1219 if (finest_level == 0) {
1220 final_tex = prev_level_flow_tex;
1222 glCreateTextures(GL_TEXTURE_2D, 1, &final_tex);
1223 glTextureStorage2D(final_tex, 1, GL_RG16F, width1, height1);
1224 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width1, height1);
1227 unique_ptr<float[]> dense_flow(new float[width1 * height1 * 2]);
1228 glGetTextureImage(final_tex, 0, GL_RG, GL_FLOAT, width1 * height1 * 2 * sizeof(float), dense_flow.get());
1230 FILE *fp = fopen("flow.ppm", "wb");
1231 FILE *flowfp = fopen("flow.flo", "wb");
1232 fprintf(fp, "P6\n%d %d\n255\n", width1, height1);
1233 fprintf(flowfp, "FEIH");
1234 fwrite(&width1, 4, 1, flowfp);
1235 fwrite(&height1, 4, 1, flowfp);
1236 for (unsigned y = 0; y < unsigned(height1); ++y) {
1237 int yy = height1 - y - 1;
1238 for (unsigned x = 0; x < unsigned(width1); ++x) {
1239 float du = dense_flow[(yy * width1 + x) * 2 + 0];
1240 float dv = dense_flow[(yy * width1 + x) * 2 + 1];
1244 fwrite(&du, 4, 1, flowfp);
1245 fwrite(&dv, 4, 1, flowfp);
1248 flow2rgb(du, dv, &r, &g, &b);
1257 fprintf(stderr, "err = %d\n", glGetError());