11 #include "gpu_timers.h"
21 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
25 // Weighting constants for the different parts of the variational refinement.
26 // These don't correspond 1:1 to the values given in the DIS paper,
27 // since we have different normalizations and ranges in some cases.
28 // These are found through a simple grid search on some MPI-Sintel data,
29 // although the error (EPE) seems to be fairly insensitive to the precise values.
30 // Only the relative values matter, so we fix alpha (the smoothness constant)
31 // at unity and tweak the others.
33 // TODO: Maybe this should not be global.
34 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
36 // Some global OpenGL objects.
37 // TODO: These should really be part of DISComputeFlow.
38 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
41 int find_num_levels(int width, int height)
44 for (int w = width, h = height; w > 1 || h > 1; ) {
52 string read_file(const string &filename)
54 FILE *fp = fopen(filename.c_str(), "r");
56 perror(filename.c_str());
60 int ret = fseek(fp, 0, SEEK_END);
62 perror("fseek(SEEK_END)");
68 ret = fseek(fp, 0, SEEK_SET);
70 perror("fseek(SEEK_SET)");
76 ret = fread(&str[0], size, 1, fp);
82 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
83 size, filename.c_str());
92 GLuint compile_shader(const string &shader_src, GLenum type)
94 GLuint obj = glCreateShader(type);
95 const GLchar* source[] = { shader_src.data() };
96 const GLint length[] = { (GLint)shader_src.size() };
97 glShaderSource(obj, 1, source, length);
100 GLchar info_log[4096];
101 GLsizei log_length = sizeof(info_log) - 1;
102 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
103 info_log[log_length] = 0;
104 if (strlen(info_log) > 0) {
105 fprintf(stderr, "Shader compile log: %s\n", info_log);
109 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
110 if (status == GL_FALSE) {
111 // Add some line numbers to easier identify compile errors.
112 string src_with_lines = "/* 1 */ ";
114 for (char ch : shader_src) {
115 src_with_lines.push_back(ch);
118 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
119 src_with_lines += buf;
123 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
130 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
132 GLuint program = glCreateProgram();
133 glAttachShader(program, vs_obj);
134 glAttachShader(program, fs_obj);
135 glLinkProgram(program);
137 glGetProgramiv(program, GL_LINK_STATUS, &success);
138 if (success == GL_FALSE) {
139 GLchar error_log[1024] = {0};
140 glGetProgramInfoLog(program, 1024, nullptr, error_log);
141 fprintf(stderr, "Error linking program: %s\n", error_log);
147 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
149 if (location == -1) {
153 glBindTextureUnit(texture_unit, tex);
154 glBindSampler(texture_unit, sampler);
155 glProgramUniform1i(program, location, texture_unit);
158 template<size_t num_elements>
159 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
161 auto it = fbos.find(textures);
162 if (it != fbos.end()) {
163 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
168 glCreateFramebuffers(1, &fbo);
169 GLenum bufs[num_elements];
170 for (size_t i = 0; i < num_elements; ++i) {
171 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
172 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
174 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
176 fbos[textures] = fbo;
177 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
180 template<size_t num_elements>
181 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_rb, const array<GLuint, num_elements> &textures)
183 auto key = make_pair(depth_rb, textures);
185 auto it = fbos.find(key);
186 if (it != fbos.end()) {
187 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
192 glCreateFramebuffers(1, &fbo);
193 GLenum bufs[num_elements];
194 glNamedFramebufferRenderbuffer(fbo, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb);
195 for (size_t i = 0; i < num_elements; ++i) {
196 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
197 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
199 glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
202 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
205 GrayscaleConversion::GrayscaleConversion()
207 gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
208 gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
209 gray_program = link_program(gray_vs_obj, gray_fs_obj);
211 // Set up the VAO containing all the required position/texcoord data.
212 glCreateVertexArrays(1, &gray_vao);
213 glBindVertexArray(gray_vao);
215 GLint position_attrib = glGetAttribLocation(gray_program, "position");
216 glEnableVertexArrayAttrib(gray_vao, position_attrib);
217 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
219 uniform_tex = glGetUniformLocation(gray_program, "tex");
222 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height, int num_layers)
224 glUseProgram(gray_program);
225 bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
227 glViewport(0, 0, width, height);
228 fbos.render_to(gray_tex);
229 glBindVertexArray(gray_vao);
231 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
236 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
237 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
238 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
240 uniform_tex = glGetUniformLocation(sobel_program, "tex");
243 void Sobel::exec(GLint tex_view, GLint grad_tex, int level_width, int level_height, int num_layers)
245 glUseProgram(sobel_program);
246 bind_sampler(sobel_program, uniform_tex, 0, tex_view, nearest_sampler);
248 glViewport(0, 0, level_width, level_height);
249 fbos.render_to(grad_tex);
251 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
254 MotionSearch::MotionSearch(const OperatingPoint &op)
257 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
258 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
259 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
261 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
262 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
263 uniform_out_flow_size = glGetUniformLocation(motion_search_program, "out_flow_size");
264 uniform_image_tex = glGetUniformLocation(motion_search_program, "image_tex");
265 uniform_grad_tex = glGetUniformLocation(motion_search_program, "grad_tex");
266 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
267 uniform_patch_size = glGetUniformLocation(motion_search_program, "patch_size");
268 uniform_num_iterations = glGetUniformLocation(motion_search_program, "num_iterations");
271 void MotionSearch::exec(GLuint tex_view, GLuint grad_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, int num_layers)
273 glUseProgram(motion_search_program);
275 bind_sampler(motion_search_program, uniform_image_tex, 0, tex_view, linear_sampler);
276 bind_sampler(motion_search_program, uniform_grad_tex, 1, grad_tex, nearest_sampler);
277 bind_sampler(motion_search_program, uniform_flow_tex, 2, flow_tex, linear_sampler);
279 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
280 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
281 glProgramUniform2f(motion_search_program, uniform_out_flow_size, width_patches, height_patches);
282 glProgramUniform1ui(motion_search_program, uniform_patch_size, op.patch_size_pixels);
283 glProgramUniform1ui(motion_search_program, uniform_num_iterations, op.search_iterations);
285 glViewport(0, 0, width_patches, height_patches);
286 fbos.render_to(flow_out_tex);
287 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
290 Densify::Densify(const OperatingPoint &op)
293 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
294 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
295 densify_program = link_program(densify_vs_obj, densify_fs_obj);
297 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
298 uniform_image_tex = glGetUniformLocation(densify_program, "image_tex");
299 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
302 void Densify::exec(GLuint tex_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches, int num_layers)
304 glUseProgram(densify_program);
306 bind_sampler(densify_program, uniform_image_tex, 0, tex_view, linear_sampler);
307 bind_sampler(densify_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
309 glProgramUniform2f(densify_program, uniform_patch_size,
310 float(op.patch_size_pixels) / level_width,
311 float(op.patch_size_pixels) / level_height);
313 glViewport(0, 0, level_width, level_height);
315 glBlendFunc(GL_ONE, GL_ONE);
316 fbos.render_to(dense_flow_tex);
317 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
318 glClear(GL_COLOR_BUFFER_BIT);
319 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches * num_layers);
324 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
325 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
326 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
328 uniform_image_tex = glGetUniformLocation(prewarp_program, "image_tex");
329 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
332 void Prewarp::exec(GLuint tex_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height, int num_layers)
334 glUseProgram(prewarp_program);
336 bind_sampler(prewarp_program, uniform_image_tex, 0, tex_view, linear_sampler);
337 bind_sampler(prewarp_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
339 glViewport(0, 0, level_width, level_height);
341 fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
342 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
345 Derivatives::Derivatives()
347 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
348 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
349 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
351 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
354 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height, int num_layers)
356 glUseProgram(derivatives_program);
358 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
360 glViewport(0, 0, level_width, level_height);
362 fbos.render_to(I_x_y_tex, beta_0_tex);
363 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
366 ComputeDiffusivity::ComputeDiffusivity()
368 diffusivity_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
369 diffusivity_fs_obj = compile_shader(read_file("diffusivity.frag"), GL_FRAGMENT_SHADER);
370 diffusivity_program = link_program(diffusivity_vs_obj, diffusivity_fs_obj);
372 uniform_flow_tex = glGetUniformLocation(diffusivity_program, "flow_tex");
373 uniform_diff_flow_tex = glGetUniformLocation(diffusivity_program, "diff_flow_tex");
374 uniform_alpha = glGetUniformLocation(diffusivity_program, "alpha");
375 uniform_zero_diff_flow = glGetUniformLocation(diffusivity_program, "zero_diff_flow");
378 void ComputeDiffusivity::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers)
380 glUseProgram(diffusivity_program);
382 bind_sampler(diffusivity_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
383 bind_sampler(diffusivity_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
384 glProgramUniform1f(diffusivity_program, uniform_alpha, vr_alpha);
385 glProgramUniform1i(diffusivity_program, uniform_zero_diff_flow, zero_diff_flow);
387 glViewport(0, 0, level_width, level_height);
390 fbos.render_to(diffusivity_tex);
391 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
394 SetupEquations::SetupEquations()
396 equations_vs_obj = compile_shader(read_file("equations.vert"), GL_VERTEX_SHADER);
397 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
398 equations_program = link_program(equations_vs_obj, equations_fs_obj);
400 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
401 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
402 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
403 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
404 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
405 uniform_diffusivity_tex = glGetUniformLocation(equations_program, "diffusivity_tex");
406 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
407 uniform_delta = glGetUniformLocation(equations_program, "delta");
408 uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
411 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 diffusivity_tex, GLuint equation_red_tex, GLuint equation_black_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers)
413 glUseProgram(equations_program);
415 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
416 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
417 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
418 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
419 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
420 bind_sampler(equations_program, uniform_diffusivity_tex, 5, diffusivity_tex, zero_border_sampler);
421 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
422 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
423 glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
425 glViewport(0, 0, (level_width + 1) / 2, level_height);
427 fbos.render_to(equation_red_tex, equation_black_tex);
428 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
433 sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
434 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
435 sor_program = link_program(sor_vs_obj, sor_fs_obj);
437 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
438 uniform_equation_red_tex = glGetUniformLocation(sor_program, "equation_red_tex");
439 uniform_equation_black_tex = glGetUniformLocation(sor_program, "equation_black_tex");
440 uniform_diffusivity_tex = glGetUniformLocation(sor_program, "diffusivity_tex");
441 uniform_phase = glGetUniformLocation(sor_program, "phase");
442 uniform_num_nonzero_phases = glGetUniformLocation(sor_program, "num_nonzero_phases");
445 void SOR::exec(GLuint diff_flow_tex, GLuint equation_red_tex, GLuint equation_black_tex, GLuint diffusivity_tex, int level_width, int level_height, int num_iterations, bool zero_diff_flow, int num_layers, ScopedTimer *sor_timer)
447 glUseProgram(sor_program);
449 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
450 bind_sampler(sor_program, uniform_diffusivity_tex, 1, diffusivity_tex, zero_border_sampler);
451 bind_sampler(sor_program, uniform_equation_red_tex, 2, equation_red_tex, nearest_sampler);
452 bind_sampler(sor_program, uniform_equation_black_tex, 3, equation_black_tex, nearest_sampler);
454 if (!zero_diff_flow) {
455 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
458 // NOTE: We bind to the texture we are rendering from, but we never write any value
459 // that we read in the same shader pass (we call discard for red values when we compute
460 // black, and vice versa), and we have barriers between the passes, so we're fine
462 glViewport(0, 0, level_width, level_height);
464 fbos.render_to(diff_flow_tex);
466 for (int i = 0; i < num_iterations; ++i) {
468 ScopedTimer timer("Red pass", sor_timer);
469 if (zero_diff_flow && i == 0) {
470 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
472 glProgramUniform1i(sor_program, uniform_phase, 0);
473 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
477 ScopedTimer timer("Black pass", sor_timer);
478 if (zero_diff_flow && i == 0) {
479 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
481 glProgramUniform1i(sor_program, uniform_phase, 1);
482 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
483 if (zero_diff_flow && i == 0) {
484 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
486 if (i != num_iterations - 1) {
493 AddBaseFlow::AddBaseFlow()
495 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
496 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
497 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
499 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
502 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height, int num_layers)
504 glUseProgram(add_flow_program);
506 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
508 glViewport(0, 0, level_width, level_height);
510 glBlendFunc(GL_ONE, GL_ONE);
511 fbos.render_to(base_flow_tex);
513 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
516 ResizeFlow::ResizeFlow()
518 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
519 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
520 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
522 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
523 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
526 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height, int num_layers)
528 glUseProgram(resize_flow_program);
530 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
532 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
534 glViewport(0, 0, output_width, output_height);
536 fbos.render_to(out_tex);
538 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
541 DISComputeFlow::DISComputeFlow(int width, int height, const OperatingPoint &op)
542 : width(width), height(height), op(op), motion_search(op), densify(op)
544 // Make some samplers.
545 glCreateSamplers(1, &nearest_sampler);
546 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
547 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
548 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
549 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
551 glCreateSamplers(1, &linear_sampler);
552 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
553 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
554 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
555 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
557 // The smoothness is sampled so that once we get to a smoothness involving
558 // a value outside the border, the diffusivity between the two becomes zero.
559 // Similarly, gradients are zero outside the border, since the edge is taken
561 glCreateSamplers(1, &zero_border_sampler);
562 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
563 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
564 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
565 glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
566 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f }; // Note that zero alpha means we can also see whether we sampled outside the border or not.
567 glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
569 // Initial flow is zero, 1x1.
570 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &initial_flow_tex);
571 glTextureStorage3D(initial_flow_tex, 1, GL_RG16F, 1, 1, 1);
572 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
574 // Set up the vertex data that will be shared between all passes.
581 glCreateBuffers(1, &vertex_vbo);
582 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
584 glCreateVertexArrays(1, &vao);
585 glBindVertexArray(vao);
586 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
588 GLint position_attrib = 0; // Hard-coded in every vertex shader.
589 glEnableVertexArrayAttrib(vao, position_attrib);
590 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
593 GLuint DISComputeFlow::exec(GLuint tex, FlowDirection flow_direction, ResizeStrategy resize_strategy)
595 int num_layers = (flow_direction == FORWARD_AND_BACKWARD) ? 2 : 1;
596 int prev_level_width = 1, prev_level_height = 1;
597 GLuint prev_level_flow_tex = initial_flow_tex;
601 glBindVertexArray(vao);
602 glDisable(GL_DITHER);
604 ScopedTimer total_timer("Compute flow", &timers);
605 for (int level = op.coarsest_level; level >= int(op.finest_level); --level) {
606 char timer_name[256];
607 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
608 ScopedTimer level_timer(timer_name, &total_timer);
610 int level_width = width >> level;
611 int level_height = height >> level;
612 float patch_spacing_pixels = op.patch_size_pixels * (1.0f - op.patch_overlap_ratio);
614 // Make sure we have patches at least every Nth pixel, e.g. for width=9
615 // and patch_spacing=3 (the default), we put out patch centers in
616 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
617 // lock all the centers to integer coordinates if needed.
618 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
619 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
621 // Make sure we always read from the correct level; the chosen
622 // mipmapping could otherwise be rather unpredictable, especially
623 // during motion search.
625 glGenTextures(1, &tex_view);
626 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, tex, GL_R8, level, 1, 0, 2);
628 // Create a new texture to hold the gradients.
629 GLuint grad_tex = pool.get_texture(GL_R32UI, level_width, level_height, num_layers);
631 // Find the derivative.
633 ScopedTimer timer("Sobel", &level_timer);
634 sobel.exec(tex_view, grad_tex, level_width, level_height, num_layers);
637 // Motion search to find the initial flow. We use the flow from the previous
638 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
640 // Create an output flow texture.
641 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches, num_layers);
645 ScopedTimer timer("Motion search", &level_timer);
646 motion_search.exec(tex_view, grad_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches, num_layers);
648 pool.release_texture(grad_tex);
652 // Set up an output texture (cleared in Densify).
653 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height, num_layers);
657 ScopedTimer timer("Densification", &level_timer);
658 densify.exec(tex_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches, num_layers);
660 pool.release_texture(flow_out_tex);
662 // Everything below here in the loop belongs to variational refinement.
663 ScopedTimer varref_timer("Variational refinement", &level_timer);
665 // Prewarping; create I and I_t, and a normalized base flow (so we don't
666 // have to normalize it over and over again, and also save some bandwidth).
668 // During the entire rest of the variational refinement, flow will be measured
669 // in pixels, not 0..1 normalized OpenGL texture coordinates.
670 // This is because variational refinement depends so heavily on derivatives,
671 // which are measured in intensity levels per pixel.
672 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
673 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
674 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
676 ScopedTimer timer("Prewarping", &varref_timer);
677 prewarp.exec(tex_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height, num_layers);
679 pool.release_texture(dense_flow_tex);
680 glDeleteTextures(1, &tex_view);
682 // TODO: If we don't have variational refinement, we don't need I and I_t,
683 // so computing them is a waste.
684 if (op.variational_refinement) {
685 // Calculate I_x and I_y. We're only calculating first derivatives;
686 // the others will be taken on-the-fly in order to sample from fewer
687 // textures overall, since sampling from the L1 cache is cheap.
688 // (TODO: Verify that this is indeed faster than making separate
689 // double-derivative textures.)
690 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
691 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
693 ScopedTimer timer("First derivatives", &varref_timer);
694 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height, num_layers);
696 pool.release_texture(I_tex);
698 // We need somewhere to store du and dv (the flow increment, relative
699 // to the non-refined base flow u0 and v0). It's initially garbage,
700 // but not read until we've written something sane to it.
701 GLuint diff_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
703 // And for diffusivity.
704 GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
706 // And finally for the equation set. See SetupEquations for
707 // the storage format.
708 GLuint equation_red_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
709 GLuint equation_black_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
711 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
712 // Calculate the diffusivity term for each pixel.
714 ScopedTimer timer("Compute diffusivity", &varref_timer);
715 compute_diffusivity.exec(base_flow_tex, diff_flow_tex, diffusivity_tex, level_width, level_height, outer_idx == 0, num_layers);
718 // Set up the 2x2 equation system for each pixel.
720 ScopedTimer timer("Set up equations", &varref_timer);
721 setup_equations.exec(I_x_y_tex, I_t_tex, diff_flow_tex, base_flow_tex, beta_0_tex, diffusivity_tex, equation_red_tex, equation_black_tex, level_width, level_height, outer_idx == 0, num_layers);
724 // Run a few SOR iterations. Note that these are to/from the same texture.
726 ScopedTimer timer("SOR", &varref_timer);
727 sor.exec(diff_flow_tex, equation_red_tex, equation_black_tex, diffusivity_tex, level_width, level_height, 5, outer_idx == 0, num_layers, &timer);
731 pool.release_texture(I_t_tex);
732 pool.release_texture(I_x_y_tex);
733 pool.release_texture(beta_0_tex);
734 pool.release_texture(diffusivity_tex);
735 pool.release_texture(equation_red_tex);
736 pool.release_texture(equation_black_tex);
738 // Add the differential flow found by the variational refinement to the base flow,
739 // giving the final flow estimate for this level.
740 // The output is in base_flow_tex; we don't need to make a new texture.
742 ScopedTimer timer("Add differential flow", &varref_timer);
743 add_base_flow.exec(base_flow_tex, diff_flow_tex, level_width, level_height, num_layers);
745 pool.release_texture(diff_flow_tex);
748 if (prev_level_flow_tex != initial_flow_tex) {
749 pool.release_texture(prev_level_flow_tex);
751 prev_level_flow_tex = base_flow_tex;
752 prev_level_width = level_width;
753 prev_level_height = level_height;
761 // Scale up the flow to the final size (if needed).
762 if (op.finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
763 return prev_level_flow_tex;
765 GLuint final_tex = pool.get_texture(GL_RG16F, width, height, num_layers);
766 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height, num_layers);
767 pool.release_texture(prev_level_flow_tex);
772 Splat::Splat(const OperatingPoint &op)
775 splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
776 splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
777 splat_program = link_program(splat_vs_obj, splat_fs_obj);
779 uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
780 uniform_alpha = glGetUniformLocation(splat_program, "alpha");
781 uniform_image_tex = glGetUniformLocation(splat_program, "image_tex");
782 uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
783 uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
786 void Splat::exec(GLuint image_tex, GLuint bidirectional_flow_tex, GLuint flow_tex, GLuint depth_rb, int width, int height, float alpha)
788 glUseProgram(splat_program);
790 bind_sampler(splat_program, uniform_image_tex, 0, image_tex, linear_sampler);
791 bind_sampler(splat_program, uniform_flow_tex, 1, bidirectional_flow_tex, nearest_sampler);
793 glProgramUniform2f(splat_program, uniform_splat_size, op.splat_size / width, op.splat_size / height);
794 glProgramUniform1f(splat_program, uniform_alpha, alpha);
795 glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
797 glViewport(0, 0, width, height);
799 glEnable(GL_DEPTH_TEST);
800 glDepthMask(GL_TRUE);
801 glDepthFunc(GL_LESS); // We store the difference between I_0 and I_1, where less difference is good. (Default 1.0 is effectively +inf, which always loses.)
803 fbos.render_to(depth_rb, flow_tex);
805 // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
806 // we've got it bound.
807 glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f); // Invalid flow.
808 glClearDepth(1.0f); // Effectively infinity.
809 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
811 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height * 2);
813 glDisable(GL_DEPTH_TEST);
818 fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
819 fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
820 fill_program = link_program(fill_vs_obj, fill_fs_obj);
822 uniform_tex = glGetUniformLocation(fill_program, "tex");
823 uniform_z = glGetUniformLocation(fill_program, "z");
824 uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
827 void HoleFill::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
829 glUseProgram(fill_program);
831 bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
833 glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
835 glViewport(0, 0, width, height);
837 glEnable(GL_DEPTH_TEST);
838 glDepthFunc(GL_LESS); // Only update the values > 0.999f (ie., only invalid pixels).
840 fbos.render_to(depth_rb, flow_tex); // NOTE: Reading and writing to the same texture.
842 // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
843 for (int offs = 1; offs < width; offs *= 2) {
844 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
845 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
848 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
850 // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
851 // were overwritten in the last algorithm.
852 glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
853 for (int offs = 1; offs < width; offs *= 2) {
854 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
855 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
858 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
861 glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
862 for (int offs = 1; offs < height; offs *= 2) {
863 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
864 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
867 glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
870 glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
871 for (int offs = 1; offs < height; offs *= 2) {
872 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
873 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
877 glDisable(GL_DEPTH_TEST);
880 HoleBlend::HoleBlend()
882 blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER); // Reuse the vertex shader from the fill.
883 blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
884 blend_program = link_program(blend_vs_obj, blend_fs_obj);
886 uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
887 uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
888 uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
889 uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
890 uniform_z = glGetUniformLocation(blend_program, "z");
891 uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
894 void HoleBlend::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
896 glUseProgram(blend_program);
898 bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
899 bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
900 bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
901 bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
903 glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
904 glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
906 glViewport(0, 0, width, height);
908 glEnable(GL_DEPTH_TEST);
909 glDepthFunc(GL_LEQUAL); // Skip over all of the pixels that were never holes to begin with.
911 fbos.render_to(depth_rb, flow_tex); // NOTE: Reading and writing to the same texture.
913 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
915 glDisable(GL_DEPTH_TEST);
920 blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
921 blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
922 blend_program = link_program(blend_vs_obj, blend_fs_obj);
924 uniform_image_tex = glGetUniformLocation(blend_program, "image_tex");
925 uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
926 uniform_alpha = glGetUniformLocation(blend_program, "alpha");
927 uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
930 void Blend::exec(GLuint image_tex, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
932 glUseProgram(blend_program);
933 bind_sampler(blend_program, uniform_image_tex, 0, image_tex, linear_sampler);
934 bind_sampler(blend_program, uniform_flow_tex, 1, flow_tex, linear_sampler); // May be upsampled.
935 glProgramUniform1f(blend_program, uniform_alpha, alpha);
937 glViewport(0, 0, level_width, level_height);
938 fbos.render_to(output_tex);
939 glDisable(GL_BLEND); // A bit ironic, perhaps.
940 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
943 Interpolate::Interpolate(int width, int height, const OperatingPoint &op)
944 : width(width), height(height), flow_level(op.finest_level), op(op), splat(op) {
945 // Set up the vertex data that will be shared between all passes.
952 glCreateBuffers(1, &vertex_vbo);
953 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
955 glCreateVertexArrays(1, &vao);
956 glBindVertexArray(vao);
957 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
959 GLint position_attrib = 0; // Hard-coded in every vertex shader.
960 glEnableVertexArrayAttrib(vao, position_attrib);
961 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
964 GLuint Interpolate::exec(GLuint image_tex, GLuint bidirectional_flow_tex, GLuint width, GLuint height, float alpha)
968 ScopedTimer total_timer("Interpolate", &timers);
970 glBindVertexArray(vao);
971 glDisable(GL_DITHER);
973 // Pick out the right level to test splatting results on.
975 glGenTextures(1, &tex_view);
976 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, image_tex, GL_RGBA8, flow_level, 1, 0, 2);
978 int flow_width = width >> flow_level;
979 int flow_height = height >> flow_level;
981 GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
982 GLuint depth_rb = pool.get_renderbuffer(GL_DEPTH_COMPONENT16, flow_width, flow_height); // Used for ranking flows.
985 ScopedTimer timer("Splat", &total_timer);
986 splat.exec(tex_view, bidirectional_flow_tex, flow_tex, depth_rb, flow_width, flow_height, alpha);
988 glDeleteTextures(1, &tex_view);
991 temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
992 temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
993 temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
996 ScopedTimer timer("Fill holes", &total_timer);
997 hole_fill.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
998 hole_blend.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1001 pool.release_texture(temp_tex[0]);
1002 pool.release_texture(temp_tex[1]);
1003 pool.release_texture(temp_tex[2]);
1004 pool.release_renderbuffer(depth_rb);
1006 GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1008 ScopedTimer timer("Blend", &total_timer);
1009 blend.exec(image_tex, flow_tex, output_tex, width, height, alpha);
1011 pool.release_texture(flow_tex);
1020 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height, GLuint num_layers)
1023 lock_guard<mutex> lock(mu);
1024 for (Texture &tex : textures) {
1025 if (!tex.in_use && !tex.is_renderbuffer && tex.format == format &&
1026 tex.width == width && tex.height == height && tex.num_layers == num_layers) {
1034 if (num_layers == 0) {
1035 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1036 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1038 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex.tex_num);
1039 glTextureStorage3D(tex.tex_num, 1, format, width, height, num_layers);
1041 tex.format = format;
1043 tex.height = height;
1044 tex.num_layers = num_layers;
1046 tex.is_renderbuffer = false;
1048 lock_guard<mutex> lock(mu);
1049 textures.push_back(tex);
1054 GLuint TexturePool::get_renderbuffer(GLenum format, GLuint width, GLuint height)
1057 lock_guard<mutex> lock(mu);
1058 for (Texture &tex : textures) {
1059 if (!tex.in_use && tex.is_renderbuffer && tex.format == format &&
1060 tex.width == width && tex.height == height) {
1068 glCreateRenderbuffers(1, &tex.tex_num);
1069 glNamedRenderbufferStorage(tex.tex_num, format, width, height);
1071 tex.format = format;
1073 tex.height = height;
1075 tex.is_renderbuffer = true;
1077 lock_guard<mutex> lock(mu);
1078 textures.push_back(tex);
1083 void TexturePool::release_texture(GLuint tex_num)
1085 lock_guard<mutex> lock(mu);
1086 for (Texture &tex : textures) {
1087 if (!tex.is_renderbuffer && tex.tex_num == tex_num) {
1096 void TexturePool::release_renderbuffer(GLuint tex_num)
1098 lock_guard<mutex> lock(mu);
1099 for (Texture &tex : textures) {
1100 if (tex.is_renderbuffer && tex.tex_num == tex_num) {