9 #include <SDL2/SDL_error.h>
10 #include <SDL2/SDL_events.h>
11 #include <SDL2/SDL_image.h>
12 #include <SDL2/SDL_keyboard.h>
13 #include <SDL2/SDL_mouse.h>
14 #include <SDL2/SDL_video.h>
25 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
29 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
30 constexpr float patch_overlap_ratio = 0.75f;
31 constexpr unsigned coarsest_level = 5;
32 constexpr unsigned finest_level = 1;
33 constexpr unsigned patch_size_pixels = 12;
35 // Some global OpenGL objects.
36 GLuint nearest_sampler, linear_sampler, smoothness_sampler;
39 string read_file(const string &filename)
41 FILE *fp = fopen(filename.c_str(), "r");
43 perror(filename.c_str());
47 int ret = fseek(fp, 0, SEEK_END);
49 perror("fseek(SEEK_END)");
55 ret = fseek(fp, 0, SEEK_SET);
57 perror("fseek(SEEK_SET)");
63 ret = fread(&str[0], size, 1, fp);
69 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
70 size, filename.c_str());
79 GLuint compile_shader(const string &shader_src, GLenum type)
81 GLuint obj = glCreateShader(type);
82 const GLchar* source[] = { shader_src.data() };
83 const GLint length[] = { (GLint)shader_src.size() };
84 glShaderSource(obj, 1, source, length);
87 GLchar info_log[4096];
88 GLsizei log_length = sizeof(info_log) - 1;
89 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
90 info_log[log_length] = 0;
91 if (strlen(info_log) > 0) {
92 fprintf(stderr, "Shader compile log: %s\n", info_log);
96 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
97 if (status == GL_FALSE) {
98 // Add some line numbers to easier identify compile errors.
99 string src_with_lines = "/* 1 */ ";
101 for (char ch : shader_src) {
102 src_with_lines.push_back(ch);
105 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
106 src_with_lines += buf;
110 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
118 GLuint load_texture(const char *filename, unsigned width, unsigned height)
120 FILE *fp = fopen(filename, "rb");
125 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
126 if (fread(pix.get(), width * height, 1, fp) != 1) {
127 fprintf(stderr, "Short read from %s\n", filename);
132 // Convert to bottom-left origin.
133 for (unsigned y = 0; y < height / 2; ++y) {
134 unsigned y2 = height - 1 - y;
135 swap_ranges(&pix[y * width], &pix[y * width + width], &pix[y2 * width]);
139 for (int w = width, h = height; w > 1 || h > 1; ) {
146 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
147 glTextureStorage2D(tex, levels, GL_R8, width, height);
148 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
149 glGenerateTextureMipmap(tex);
154 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
156 GLuint program = glCreateProgram();
157 glAttachShader(program, vs_obj);
158 glAttachShader(program, fs_obj);
159 glLinkProgram(program);
161 glGetProgramiv(program, GL_LINK_STATUS, &success);
162 if (success == GL_FALSE) {
163 GLchar error_log[1024] = {0};
164 glGetProgramInfoLog(program, 1024, nullptr, error_log);
165 fprintf(stderr, "Error linking program: %s\n", error_log);
171 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
174 glCreateBuffers(1, &vbo);
175 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
176 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
180 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
182 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
187 GLuint vbo = generate_vbo(size, data_size, data);
189 glBindBuffer(GL_ARRAY_BUFFER, vbo);
190 glEnableVertexArrayAttrib(vao, attrib);
191 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
192 glBindBuffer(GL_ARRAY_BUFFER, 0);
197 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
199 if (location == -1) {
203 glBindTextureUnit(texture_unit, tex);
204 glBindSampler(texture_unit, sampler);
205 glProgramUniform1i(program, location, texture_unit);
208 // Compute gradients in every point, used for the motion search.
209 // The DIS paper doesn't actually mention how these are computed,
210 // but seemingly, a 3x3 Sobel operator is used here (at least in
211 // later versions of the code), while a [1 -8 0 8 -1] kernel is
212 // used for all the derivatives in the variational refinement part
213 // (which borrows code from DeepFlow). This is inconsistent,
214 // but I guess we're better off with staying with the original
215 // decisions until we actually know having different ones would be better.
219 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
224 GLuint sobel_program;
227 GLuint uniform_tex, uniform_image_size;
232 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
233 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
234 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
236 // Set up the VAO containing all the required position/texcoord data.
237 glCreateVertexArrays(1, &sobel_vao);
238 glBindVertexArray(sobel_vao);
240 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
241 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
242 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
244 uniform_tex = glGetUniformLocation(sobel_program, "tex");
247 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
249 glUseProgram(sobel_program);
250 glBindTextureUnit(0, tex0_view);
251 glBindSampler(0, nearest_sampler);
252 glProgramUniform1i(sobel_program, uniform_tex, 0);
254 GLuint grad0_fbo; // TODO: cleanup
255 glCreateFramebuffers(1, &grad0_fbo);
256 glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
258 glViewport(0, 0, level_width, level_height);
259 glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
260 glBindVertexArray(sobel_vao);
261 glUseProgram(sobel_program);
263 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
266 // Motion search to find the initial flow. See motion_search.frag for documentation.
270 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 width_patches, int height_patches);
273 GLuint motion_vs_obj;
274 GLuint motion_fs_obj;
275 GLuint motion_search_program;
276 GLuint motion_search_vao;
278 GLuint uniform_image_size, uniform_inv_image_size;
279 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
282 MotionSearch::MotionSearch()
284 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
285 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
286 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
288 // Set up the VAO containing all the required position/texcoord data.
289 glCreateVertexArrays(1, &motion_search_vao);
290 glBindVertexArray(motion_search_vao);
291 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
293 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
294 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
295 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
297 uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
298 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
299 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
300 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
301 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
302 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
305 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 width_patches, int height_patches)
307 glUseProgram(motion_search_program);
309 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
310 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
311 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
312 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
314 glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
315 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
317 GLuint flow_fbo; // TODO: cleanup
318 glCreateFramebuffers(1, &flow_fbo);
319 glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
321 glViewport(0, 0, width_patches, height_patches);
322 glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
323 glBindVertexArray(motion_search_vao);
324 glUseProgram(motion_search_program);
325 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
328 // Do “densification”, ie., upsampling of the flow patches to the flow field
329 // (the same size as the image at this level). We draw one quad per patch
330 // over its entire covered area (using instancing in the vertex shader),
331 // and then weight the contributions in the pixel shader by post-warp difference.
332 // This is equation (3) in the paper.
334 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
335 // weight in the B channel. Dividing R and G by B gives the normalized values.
339 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);
342 GLuint densify_vs_obj;
343 GLuint densify_fs_obj;
344 GLuint densify_program;
347 GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
348 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
353 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
354 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
355 densify_program = link_program(densify_vs_obj, densify_fs_obj);
357 // Set up the VAO containing all the required position/texcoord data.
358 glCreateVertexArrays(1, &densify_vao);
359 glBindVertexArray(densify_vao);
360 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
362 GLint position_attrib = glGetAttribLocation(densify_program, "position");
363 glEnableVertexArrayAttrib(densify_vao, position_attrib);
364 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
366 uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
367 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
368 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
369 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
370 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
371 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
374 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)
376 glUseProgram(densify_program);
378 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
379 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
380 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
382 glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
383 glProgramUniform2f(densify_program, uniform_patch_size,
384 float(patch_size_pixels) / level_width,
385 float(patch_size_pixels) / level_height);
387 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
388 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
389 if (width_patches == 1) patch_spacing_x = 0.0f; // Avoid infinities.
390 if (height_patches == 1) patch_spacing_y = 0.0f;
391 glProgramUniform2f(densify_program, uniform_patch_spacing,
392 patch_spacing_x / level_width,
393 patch_spacing_y / level_height);
395 GLuint dense_flow_fbo; // TODO: cleanup
396 glCreateFramebuffers(1, &dense_flow_fbo);
397 glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
399 glViewport(0, 0, level_width, level_height);
401 glBlendFunc(GL_ONE, GL_ONE);
402 glBindVertexArray(densify_vao);
403 glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
404 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
407 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
408 // I_0 and I_w. The prewarping is what enables us to solve the variational
409 // flow for du,dv instead of u,v.
411 // See variational_refinement.txt for more information.
415 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
418 GLuint prewarp_vs_obj;
419 GLuint prewarp_fs_obj;
420 GLuint prewarp_program;
423 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
428 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
429 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
430 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
432 // Set up the VAO containing all the required position/texcoord data.
433 glCreateVertexArrays(1, &prewarp_vao);
434 glBindVertexArray(prewarp_vao);
435 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
437 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
438 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
439 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
441 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
442 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
443 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
446 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height)
448 glUseProgram(prewarp_program);
450 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
451 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
452 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
454 GLuint prewarp_fbo; // TODO: cleanup
455 glCreateFramebuffers(1, &prewarp_fbo);
456 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
457 glNamedFramebufferDrawBuffers(prewarp_fbo, 2, bufs);
458 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
459 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
461 glViewport(0, 0, level_width, level_height);
463 glBindVertexArray(prewarp_vao);
464 glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
465 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
468 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
469 // central difference filter, since apparently, that's tradition (I haven't
470 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
471 // The coefficients come from
473 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
475 // Also computes β_0, since it depends only on I_x and I_y.
479 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
482 GLuint derivatives_vs_obj;
483 GLuint derivatives_fs_obj;
484 GLuint derivatives_program;
485 GLuint derivatives_vao;
490 Derivatives::Derivatives()
492 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
493 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
494 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
496 // Set up the VAO containing all the required position/texcoord data.
497 glCreateVertexArrays(1, &derivatives_vao);
498 glBindVertexArray(derivatives_vao);
499 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
501 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
502 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
503 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
505 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
508 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
510 glUseProgram(derivatives_program);
512 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
514 GLuint derivatives_fbo; // TODO: cleanup
515 glCreateFramebuffers(1, &derivatives_fbo);
516 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
517 glNamedFramebufferDrawBuffers(derivatives_fbo, 2, bufs);
518 glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT0, I_x_y_tex, 0);
519 glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT1, beta_0_tex, 0);
521 glViewport(0, 0, level_width, level_height);
523 glBindVertexArray(derivatives_vao);
524 glBindFramebuffer(GL_FRAMEBUFFER, derivatives_fbo);
525 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
528 // Calculate the smoothness constraints between neighboring pixels;
529 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
530 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
531 // border color (0,0) later, so that there's zero diffusion out of
534 // See variational_refinement.txt for more information.
535 class ComputeSmoothness {
538 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
541 GLuint smoothness_vs_obj;
542 GLuint smoothness_fs_obj;
543 GLuint smoothness_program;
544 GLuint smoothness_vao;
546 GLuint uniform_flow_tex, uniform_diff_flow_tex;
549 ComputeSmoothness::ComputeSmoothness()
551 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
552 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
553 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
555 // Set up the VAO containing all the required position/texcoord data.
556 glCreateVertexArrays(1, &smoothness_vao);
557 glBindVertexArray(smoothness_vao);
558 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
560 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
561 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
562 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
564 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
565 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
568 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
570 glUseProgram(smoothness_program);
572 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
573 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
575 GLuint smoothness_fbo; // TODO: cleanup
576 glCreateFramebuffers(1, &smoothness_fbo);
577 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
578 glNamedFramebufferDrawBuffers(smoothness_fbo, 2, bufs);
579 glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT0, smoothness_x_tex, 0);
580 glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT1, smoothness_y_tex, 0);
582 glViewport(0, 0, level_width, level_height);
584 // Make sure the smoothness on the right and upper borders is zero.
585 // We could have done this by making a (W-1)x(H-1) texture instead
586 // (we're sampling smoothness with all-zero border color), but we'd
587 // have to adjust the sampling coordinates, which is annoying.
588 glScissor(0, 0, level_width - 1, level_height - 1);
589 glEnable(GL_SCISSOR_TEST);
592 glBindVertexArray(smoothness_vao);
593 glBindFramebuffer(GL_FRAMEBUFFER, smoothness_fbo);
594 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
596 glDisable(GL_SCISSOR_TEST);
599 // Set up the equations set (two equations in two unknowns, per pixel).
600 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
601 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
602 // floats. (Actually, we store the inverse of the diagonal elements, because
603 // we only ever need to divide by them.) This fits into four u32 values;
604 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
605 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
606 // terms that depend on other pixels, are calculated in one pass.
608 // See variational_refinement.txt for more information.
609 class SetupEquations {
612 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);
615 GLuint equations_vs_obj;
616 GLuint equations_fs_obj;
617 GLuint equations_program;
618 GLuint equations_vao;
620 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
621 GLuint uniform_diff_flow_tex, uniform_flow_tex;
622 GLuint uniform_beta_0_tex;
623 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
627 SetupEquations::SetupEquations()
629 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
630 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
631 equations_program = link_program(equations_vs_obj, equations_fs_obj);
633 // Set up the VAO containing all the required position/texcoord data.
634 glCreateVertexArrays(1, &equations_vao);
635 glBindVertexArray(equations_vao);
636 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
638 GLint position_attrib = glGetAttribLocation(equations_program, "position");
639 glEnableVertexArrayAttrib(equations_vao, position_attrib);
640 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
642 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
643 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
644 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
645 uniform_flow_tex = glGetUniformLocation(equations_program, "flow_tex");
646 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
647 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
648 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
651 void SetupEquations::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)
653 glUseProgram(equations_program);
655 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
656 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
657 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
658 bind_sampler(equations_program, uniform_flow_tex, 3, flow_tex, nearest_sampler);
659 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
660 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
661 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
663 GLuint equations_fbo; // TODO: cleanup
664 glCreateFramebuffers(1, &equations_fbo);
665 glNamedFramebufferTexture(equations_fbo, GL_COLOR_ATTACHMENT0, equation_tex, 0);
667 glViewport(0, 0, level_width, level_height);
669 glBindVertexArray(equations_vao);
670 glBindFramebuffer(GL_FRAMEBUFFER, equations_fbo);
671 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
674 // Calculate the smoothness constraints between neighboring pixels;
675 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
676 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
677 // border color (0,0) later, so that there's zero diffusion out of
680 // See variational_refinement.txt for more information.
684 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);
692 GLuint uniform_diff_flow_tex;
693 GLuint uniform_equation_tex;
694 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
699 sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
700 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
701 sor_program = link_program(sor_vs_obj, sor_fs_obj);
703 // Set up the VAO containing all the required position/texcoord data.
704 glCreateVertexArrays(1, &sor_vao);
705 glBindVertexArray(sor_vao);
706 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
708 GLint position_attrib = glGetAttribLocation(sor_program, "position");
709 glEnableVertexArrayAttrib(sor_vao, position_attrib);
710 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
712 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
713 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
714 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
715 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
718 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)
720 glUseProgram(sor_program);
722 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
723 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
724 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
725 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
727 GLuint sor_fbo; // TODO: cleanup
728 glCreateFramebuffers(1, &sor_fbo);
729 glNamedFramebufferTexture(sor_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0); // NOTE: Bind to same as we render from!
731 glViewport(0, 0, level_width, level_height);
733 glBindVertexArray(sor_vao);
734 glBindFramebuffer(GL_FRAMEBUFFER, sor_fbo);
736 for (int i = 0; i < num_iterations; ++i) {
737 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
738 if (i != num_iterations - 1) {
744 // Simply add the differential flow found by the variational refinement to the base flow.
745 // The output is in diff_flow_tex; we don't need to make a new texture.
749 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
752 GLuint add_flow_vs_obj;
753 GLuint add_flow_fs_obj;
754 GLuint add_flow_program;
757 GLuint uniform_base_flow_tex;
760 AddBaseFlow::AddBaseFlow()
762 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
763 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
764 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
766 // Set up the VAO containing all the required position/texcoord data.
767 glCreateVertexArrays(1, &add_flow_vao);
768 glBindVertexArray(add_flow_vao);
769 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
771 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
772 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
773 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
775 uniform_base_flow_tex = glGetUniformLocation(add_flow_program, "base_flow_tex");
778 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
780 glUseProgram(add_flow_program);
782 bind_sampler(add_flow_program, uniform_base_flow_tex, 0, base_flow_tex, nearest_sampler);
784 GLuint add_flow_fbo; // TODO: cleanup
785 glCreateFramebuffers(1, &add_flow_fbo);
786 glNamedFramebufferTexture(add_flow_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0);
788 glViewport(0, 0, level_width, level_height);
790 glBlendFunc(GL_ONE, GL_ONE);
791 glBindVertexArray(add_flow_vao);
792 glBindFramebuffer(GL_FRAMEBUFFER, add_flow_fbo);
794 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
799 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
800 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
803 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
804 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
805 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
806 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
808 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
809 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
810 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
811 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
812 SDL_Window *window = SDL_CreateWindow("OpenGL window",
813 SDL_WINDOWPOS_UNDEFINED,
814 SDL_WINDOWPOS_UNDEFINED,
817 SDL_GLContext context = SDL_GL_CreateContext(window);
818 assert(context != nullptr);
821 GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
822 GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
824 // Make some samplers.
825 glCreateSamplers(1, &nearest_sampler);
826 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
827 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
828 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
829 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
831 glCreateSamplers(1, &linear_sampler);
832 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
833 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
834 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
835 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
837 // The smoothness is sampled so that once we get to a smoothness involving
838 // a value outside the border, the diffusivity between the two becomes zero.
839 glCreateSamplers(1, &smoothness_sampler);
840 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
841 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
842 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
843 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
844 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
845 glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
853 glCreateBuffers(1, &vertex_vbo);
854 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
855 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
857 // Initial flow is zero, 1x1.
858 GLuint initial_flow_tex;
859 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
860 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
862 GLuint prev_level_flow_tex = initial_flow_tex;
865 MotionSearch motion_search;
868 Derivatives derivatives;
869 ComputeSmoothness compute_smoothness;
870 SetupEquations setup_equations;
872 AddBaseFlow add_base_flow;
875 glGenQueries(1, &query);
876 glBeginQuery(GL_TIME_ELAPSED, query);
878 for (int level = coarsest_level; level >= int(finest_level); --level) {
879 int level_width = WIDTH >> level;
880 int level_height = HEIGHT >> level;
881 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
882 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
883 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
885 // Make sure we always read from the correct level; the chosen
886 // mipmapping could otherwise be rather unpredictable, especially
887 // during motion search.
888 // TODO: create these beforehand, and stop leaking them.
889 GLuint tex0_view, tex1_view;
890 glGenTextures(1, &tex0_view);
891 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
892 glGenTextures(1, &tex1_view);
893 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
895 // Create a new texture; we could be fancy and render use a multi-level
898 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
899 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
901 // Find the derivative.
902 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
904 // Motion search to find the initial flow. We use the flow from the previous
905 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
907 // Create an output flow texture.
909 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
910 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
913 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, width_patches, height_patches);
917 // Set up an output texture (initially zero).
918 GLuint dense_flow_tex;
919 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
920 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
923 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
925 // Everything below here in the loop belongs to variational refinement.
926 // It is not done yet.
928 // Prewarping; create I and I_t.
929 GLuint I_tex, I_t_tex;
930 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
931 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
932 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
933 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
934 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, level_width, level_height);
936 // Calculate I_x and I_y. We're only calculating first derivatives;
937 // the others will be taken on-the-fly in order to sample from fewer
938 // textures overall, since sampling from the L1 cache is cheap.
939 // (TODO: Verify that this is indeed faster than making separate
940 // double-derivative textures.)
941 GLuint I_x_y_tex, beta_0_tex;
942 glCreateTextures(GL_TEXTURE_2D, 1, &I_x_y_tex);
943 glCreateTextures(GL_TEXTURE_2D, 1, &beta_0_tex);
944 glTextureStorage2D(I_x_y_tex, 1, GL_RG16F, level_width, level_height);
945 glTextureStorage2D(beta_0_tex, 1, GL_R16F, level_width, level_height);
946 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
948 // We need somewhere to store du and dv (the flow increment, relative
949 // to the non-refined base flow u0 and v0). It starts at zero.
951 glCreateTextures(GL_TEXTURE_2D, 1, &du_dv_tex);
952 glTextureStorage2D(du_dv_tex, 1, GL_RG16F, level_width, level_height);
954 // And for smoothness.
955 GLuint smoothness_x_tex, smoothness_y_tex;
956 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_x_tex);
957 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_y_tex);
958 glTextureStorage2D(smoothness_x_tex, 1, GL_R16F, level_width, level_height);
959 glTextureStorage2D(smoothness_y_tex, 1, GL_R16F, level_width, level_height);
961 // And finally for the equation set. See SetupEquations for
962 // the storage format.
964 glCreateTextures(GL_TEXTURE_2D, 1, &equation_tex);
965 glTextureStorage2D(equation_tex, 1, GL_RGBA32UI, level_width, level_height);
967 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
968 // Calculate the smoothness terms between the neighboring pixels,
969 // both in x and y direction.
970 compute_smoothness.exec(dense_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
972 // Set up the 2x2 equation system for each pixel.
973 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, dense_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
975 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
976 // Note that these are to/from the same texture.
977 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
980 // Add the differential flow found by the variational refinement to the base flow,
981 // giving the final flow estimate for this level.
982 // The output is in diff_flow_tex; we don't need to make a new texture.
983 add_base_flow.exec(dense_flow_tex, du_dv_tex, level_width, level_height);
985 prev_level_flow_tex = du_dv_tex;
987 glEndQuery(GL_TIME_ELAPSED);
991 glGetQueryObjectiv(query, GL_QUERY_RESULT_AVAILABLE, &available);
993 } while (!available);
994 GLuint64 time_elapsed;
995 glGetQueryObjectui64v(query, GL_QUERY_RESULT, &time_elapsed);
996 fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
998 int level_width = WIDTH >> finest_level;
999 int level_height = HEIGHT >> finest_level;
1000 unique_ptr<float[]> dense_flow(new float[level_width * level_height * 3]);
1001 glGetTextureImage(prev_level_flow_tex, 0, GL_RGB, GL_FLOAT, level_width * level_height * 3 * sizeof(float), dense_flow.get());
1003 FILE *fp = fopen("flow.ppm", "wb");
1004 FILE *flowfp = fopen("flow.flo", "wb");
1005 fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
1006 fprintf(flowfp, "FEIH");
1007 fwrite(&level_width, 4, 1, flowfp);
1008 fwrite(&level_height, 4, 1, flowfp);
1009 for (unsigned y = 0; y < unsigned(level_height); ++y) {
1010 int yy = level_height - y - 1;
1011 for (unsigned x = 0; x < unsigned(level_width); ++x) {
1012 float du = dense_flow[(yy * level_width + x) * 3 + 0];
1013 float dv = dense_flow[(yy * level_width + x) * 3 + 1];
1014 float w = dense_flow[(yy * level_width + x) * 3 + 2];
1016 du = (du / w) * level_width;
1017 dv = (-dv / w) * level_height;
1019 fwrite(&du, 4, 1, flowfp);
1020 fwrite(&dv, 4, 1, flowfp);
1023 flow2rgb(du, dv, &r, &g, &b);
1032 fprintf(stderr, "err = %d\n", glGetError());