]> git.sesse.net Git - nageru/blob - flow.cpp
Add a FIXME on the scissor.
[nageru] / flow.cpp
1 #define NO_SDL_GLEXT 1
2
3 #define WIDTH 1280
4 #define HEIGHT 720
5
6 #include <epoxy/gl.h>
7
8 #include <SDL2/SDL.h>
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>
15
16 #include <assert.h>
17 #include <stdio.h>
18 #include <unistd.h>
19
20 #include "util.h"
21
22 #include <algorithm>
23 #include <memory>
24 #include <vector>
25
26 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
27
28 using namespace std;
29
30 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
31 constexpr float patch_overlap_ratio = 0.75f;
32 constexpr unsigned coarsest_level = 5;
33 constexpr unsigned finest_level = 1;
34 constexpr unsigned patch_size_pixels = 12;
35
36 // Some global OpenGL objects.
37 GLuint nearest_sampler, linear_sampler, smoothness_sampler;
38 GLuint vertex_vbo;
39
40 string read_file(const string &filename)
41 {
42         FILE *fp = fopen(filename.c_str(), "r");
43         if (fp == nullptr) {
44                 perror(filename.c_str());
45                 exit(1);
46         }
47
48         int ret = fseek(fp, 0, SEEK_END);
49         if (ret == -1) {
50                 perror("fseek(SEEK_END)");
51                 exit(1);
52         }
53
54         int size = ftell(fp);
55
56         ret = fseek(fp, 0, SEEK_SET);
57         if (ret == -1) {
58                 perror("fseek(SEEK_SET)");
59                 exit(1);
60         }
61
62         string str;
63         str.resize(size);
64         ret = fread(&str[0], size, 1, fp);
65         if (ret == -1) {
66                 perror("fread");
67                 exit(1);
68         }
69         if (ret == 0) {
70                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
71                                 size, filename.c_str());
72                 exit(1);
73         }
74         fclose(fp);
75
76         return str;
77 }
78
79
80 GLuint compile_shader(const string &shader_src, GLenum type)
81 {
82         GLuint obj = glCreateShader(type);
83         const GLchar* source[] = { shader_src.data() };
84         const GLint length[] = { (GLint)shader_src.size() };
85         glShaderSource(obj, 1, source, length);
86         glCompileShader(obj);
87
88         GLchar info_log[4096];
89         GLsizei log_length = sizeof(info_log) - 1;
90         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
91         info_log[log_length] = 0;
92         if (strlen(info_log) > 0) {
93                 fprintf(stderr, "Shader compile log: %s\n", info_log);
94         }
95
96         GLint status;
97         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
98         if (status == GL_FALSE) {
99                 // Add some line numbers to easier identify compile errors.
100                 string src_with_lines = "/*   1 */ ";
101                 size_t lineno = 1;
102                 for (char ch : shader_src) {
103                         src_with_lines.push_back(ch);
104                         if (ch == '\n') {
105                                 char buf[32];
106                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
107                                 src_with_lines += buf;
108                         }
109                 }
110
111                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
112                 exit(1);
113         }
114
115         return obj;
116 }
117
118
119 GLuint load_texture(const char *filename, unsigned width, unsigned height)
120 {
121         FILE *fp = fopen(filename, "rb");
122         if (fp == nullptr) {
123                 perror(filename);
124                 exit(1);
125         }
126         unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
127         if (fread(pix.get(), width * height, 1, fp) != 1) {
128                 fprintf(stderr, "Short read from %s\n", filename);
129                 exit(1);
130         }
131         fclose(fp);
132
133         // Convert to bottom-left origin.
134         for (unsigned y = 0; y < height / 2; ++y) {
135                 unsigned y2 = height - 1 - y;
136                 swap_ranges(&pix[y * width], &pix[y * width + width], &pix[y2 * width]);
137         }
138
139         int levels = 1;
140         for (int w = width, h = height; w > 1 || h > 1; ) {
141                 w >>= 1;
142                 h >>= 1;
143                 ++levels;
144         }
145
146         GLuint tex;
147         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
148         glTextureStorage2D(tex, levels, GL_R8, width, height);
149         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
150         glGenerateTextureMipmap(tex);
151
152         return tex;
153 }
154
155 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
156 {
157         GLuint program = glCreateProgram();
158         glAttachShader(program, vs_obj);
159         glAttachShader(program, fs_obj);
160         glLinkProgram(program);
161         GLint success;
162         glGetProgramiv(program, GL_LINK_STATUS, &success);
163         if (success == GL_FALSE) {
164                 GLchar error_log[1024] = {0};
165                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
166                 fprintf(stderr, "Error linking program: %s\n", error_log);
167                 exit(1);
168         }
169         return program;
170 }
171
172 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
173 {
174         GLuint vbo;
175         glCreateBuffers(1, &vbo);
176         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
177         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
178         return vbo;
179 }
180
181 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 {
183         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
184         if (attrib == -1) {
185                 return -1;
186         }
187
188         GLuint vbo = generate_vbo(size, data_size, data);
189
190         glBindBuffer(GL_ARRAY_BUFFER, vbo);
191         glEnableVertexArrayAttrib(vao, attrib);
192         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
193         glBindBuffer(GL_ARRAY_BUFFER, 0);
194
195         return vbo;
196 }
197
198 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
199 {
200         if (location == -1) {
201                 return;
202         }
203
204         glBindTextureUnit(texture_unit, tex);
205         glBindSampler(texture_unit, sampler);
206         glProgramUniform1i(program, location, texture_unit);
207 }
208
209 // Compute gradients in every point, used for the motion search.
210 // The DIS paper doesn't actually mention how these are computed,
211 // but seemingly, a 3x3 Sobel operator is used here (at least in
212 // later versions of the code), while a [1 -8 0 8 -1] kernel is
213 // used for all the derivatives in the variational refinement part
214 // (which borrows code from DeepFlow). This is inconsistent,
215 // but I guess we're better off with staying with the original
216 // decisions until we actually know having different ones would be better.
217 class Sobel {
218 public:
219         Sobel();
220         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
221
222 private:
223         GLuint sobel_vs_obj;
224         GLuint sobel_fs_obj;
225         GLuint sobel_program;
226         GLuint sobel_vao;
227
228         GLuint uniform_tex, uniform_image_size;
229 };
230
231 Sobel::Sobel()
232 {
233         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
234         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
235         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
236
237         // Set up the VAO containing all the required position/texcoord data.
238         glCreateVertexArrays(1, &sobel_vao);
239         glBindVertexArray(sobel_vao);
240
241         GLint position_attrib = glGetAttribLocation(sobel_program, "position");
242         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
243         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
244
245         uniform_tex = glGetUniformLocation(sobel_program, "tex");
246 }
247
248 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
249 {
250         glUseProgram(sobel_program);
251         glBindTextureUnit(0, tex0_view);
252         glBindSampler(0, nearest_sampler);
253         glProgramUniform1i(sobel_program, uniform_tex, 0);
254
255         GLuint grad0_fbo;  // TODO: cleanup
256         glCreateFramebuffers(1, &grad0_fbo);
257         glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
258
259         glViewport(0, 0, level_width, level_height);
260         glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
261         glBindVertexArray(sobel_vao);
262         glUseProgram(sobel_program);
263         glDisable(GL_BLEND);
264         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
265 }
266
267 // Motion search to find the initial flow. See motion_search.frag for documentation.
268 class MotionSearch {
269 public:
270         MotionSearch();
271         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);
272
273 private:
274         GLuint motion_vs_obj;
275         GLuint motion_fs_obj;
276         GLuint motion_search_program;
277         GLuint motion_search_vao;
278
279         GLuint uniform_image_size, uniform_inv_image_size;
280         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
281 };
282
283 MotionSearch::MotionSearch()
284 {
285         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
286         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
287         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
288
289         // Set up the VAO containing all the required position/texcoord data.
290         glCreateVertexArrays(1, &motion_search_vao);
291         glBindVertexArray(motion_search_vao);
292         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
293
294         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
295         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
296         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
297
298         uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
299         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
300         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
301         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
302         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
303         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
304 }
305
306 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 {
308         glUseProgram(motion_search_program);
309
310         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
311         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
312         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
313         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
314
315         glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
316         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
317
318         GLuint flow_fbo;  // TODO: cleanup
319         glCreateFramebuffers(1, &flow_fbo);
320         glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
321
322         glViewport(0, 0, width_patches, height_patches);
323         glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
324         glBindVertexArray(motion_search_vao);
325         glUseProgram(motion_search_program);
326         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
327 }
328
329 // Do “densification”, ie., upsampling of the flow patches to the flow field
330 // (the same size as the image at this level). We draw one quad per patch
331 // over its entire covered area (using instancing in the vertex shader),
332 // and then weight the contributions in the pixel shader by post-warp difference.
333 // This is equation (3) in the paper.
334 //
335 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
336 // weight in the B channel. Dividing R and G by B gives the normalized values.
337 class Densify {
338 public:
339         Densify();
340         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);
341
342 private:
343         GLuint densify_vs_obj;
344         GLuint densify_fs_obj;
345         GLuint densify_program;
346         GLuint densify_vao;
347
348         GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
349         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
350 };
351
352 Densify::Densify()
353 {
354         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
355         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
356         densify_program = link_program(densify_vs_obj, densify_fs_obj);
357
358         // Set up the VAO containing all the required position/texcoord data.
359         glCreateVertexArrays(1, &densify_vao);
360         glBindVertexArray(densify_vao);
361         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
362
363         GLint position_attrib = glGetAttribLocation(densify_program, "position");
364         glEnableVertexArrayAttrib(densify_vao, position_attrib);
365         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
366
367         uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
368         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
369         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
370         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
371         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
372         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
373 }
374
375 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 {
377         glUseProgram(densify_program);
378
379         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
380         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
381         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
382
383         glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
384         glProgramUniform2f(densify_program, uniform_patch_size,
385                 float(patch_size_pixels) / level_width,
386                 float(patch_size_pixels) / level_height);
387
388         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
389         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
390         if (width_patches == 1) patch_spacing_x = 0.0f;  // Avoid infinities.
391         if (height_patches == 1) patch_spacing_y = 0.0f;
392         glProgramUniform2f(densify_program, uniform_patch_spacing,
393                 patch_spacing_x / level_width,
394                 patch_spacing_y / level_height);
395
396         GLuint dense_flow_fbo;  // TODO: cleanup
397         glCreateFramebuffers(1, &dense_flow_fbo);
398         glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
399
400         glViewport(0, 0, level_width, level_height);
401         glEnable(GL_BLEND);
402         glBlendFunc(GL_ONE, GL_ONE);
403         glBindVertexArray(densify_vao);
404         glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
405         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
406 }
407
408 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
409 // I_0 and I_w. The prewarping is what enables us to solve the variational
410 // flow for du,dv instead of u,v.
411 //
412 // See variational_refinement.txt for more information.
413 class Prewarp {
414 public:
415         Prewarp();
416         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
417
418 private:
419         GLuint prewarp_vs_obj;
420         GLuint prewarp_fs_obj;
421         GLuint prewarp_program;
422         GLuint prewarp_vao;
423
424         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
425 };
426
427 Prewarp::Prewarp()
428 {
429         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
430         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
431         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
432
433         // Set up the VAO containing all the required position/texcoord data.
434         glCreateVertexArrays(1, &prewarp_vao);
435         glBindVertexArray(prewarp_vao);
436         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
437
438         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
439         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
440         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
441
442         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
443         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
444         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
445 }
446
447 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 {
449         glUseProgram(prewarp_program);
450
451         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
452         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
453         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
454
455         GLuint prewarp_fbo;  // TODO: cleanup
456         glCreateFramebuffers(1, &prewarp_fbo);
457         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
458         glNamedFramebufferDrawBuffers(prewarp_fbo, 2, bufs);
459         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
460         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
461
462         glViewport(0, 0, level_width, level_height);
463         glDisable(GL_BLEND);
464         glBindVertexArray(prewarp_vao);
465         glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
466         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
467 }
468
469 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
470 // central difference filter, since apparently, that's tradition (I haven't
471 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
472 // The coefficients come from
473 //
474 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
475 //
476 // Also computes β_0, since it depends only on I_x and I_y.
477 class Derivatives {
478 public:
479         Derivatives();
480         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
481
482 private:
483         GLuint derivatives_vs_obj;
484         GLuint derivatives_fs_obj;
485         GLuint derivatives_program;
486         GLuint derivatives_vao;
487
488         GLuint uniform_tex;
489 };
490
491 Derivatives::Derivatives()
492 {
493         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
494         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
495         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
496
497         // Set up the VAO containing all the required position/texcoord data.
498         glCreateVertexArrays(1, &derivatives_vao);
499         glBindVertexArray(derivatives_vao);
500         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
501
502         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
503         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
504         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
505
506         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
507 }
508
509 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
510 {
511         glUseProgram(derivatives_program);
512
513         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
514
515         GLuint derivatives_fbo;  // TODO: cleanup
516         glCreateFramebuffers(1, &derivatives_fbo);
517         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
518         glNamedFramebufferDrawBuffers(derivatives_fbo, 2, bufs);
519         glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT0, I_x_y_tex, 0);
520         glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT1, beta_0_tex, 0);
521
522         glViewport(0, 0, level_width, level_height);
523         glDisable(GL_BLEND);
524         glBindVertexArray(derivatives_vao);
525         glBindFramebuffer(GL_FRAMEBUFFER, derivatives_fbo);
526         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
527 }
528
529 // Calculate the smoothness constraints between neighboring pixels;
530 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
531 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
532 // border color (0,0) later, so that there's zero diffusion out of
533 // the border.
534 //
535 // See variational_refinement.txt for more information.
536 class ComputeSmoothness {
537 public:
538         ComputeSmoothness();
539         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
540
541 private:
542         GLuint smoothness_vs_obj;
543         GLuint smoothness_fs_obj;
544         GLuint smoothness_program;
545         GLuint smoothness_vao;
546
547         GLuint uniform_flow_tex, uniform_diff_flow_tex;
548 };
549
550 ComputeSmoothness::ComputeSmoothness()
551 {
552         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
553         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
554         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
555
556         // Set up the VAO containing all the required position/texcoord data.
557         glCreateVertexArrays(1, &smoothness_vao);
558         glBindVertexArray(smoothness_vao);
559         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
560
561         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
562         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
563         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
564
565         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
566         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
567 }
568
569 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 {
571         glUseProgram(smoothness_program);
572
573         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
574         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
575
576         GLuint smoothness_fbo;  // TODO: cleanup
577         glCreateFramebuffers(1, &smoothness_fbo);
578         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
579         glNamedFramebufferDrawBuffers(smoothness_fbo, 2, bufs);
580         glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT0, smoothness_x_tex, 0);
581         glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT1, smoothness_y_tex, 0);
582
583         glViewport(0, 0, level_width, level_height);
584
585         // Make sure the smoothness on the right and upper borders is zero.
586         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
587         // (we're sampling smoothness with all-zero border color), but we'd
588         // have to adjust the sampling coordinates, which is annoying.
589         //
590         // FIXME: We shouldn't scissor width for horizontal,
591         // and we shouldn't scissor height for vertical
592         glScissor(0, 0, level_width - 1, level_height - 1);
593         glEnable(GL_SCISSOR_TEST);
594
595         glDisable(GL_BLEND);
596         glBindVertexArray(smoothness_vao);
597         glBindFramebuffer(GL_FRAMEBUFFER, smoothness_fbo);
598         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
599
600         glDisable(GL_SCISSOR_TEST);
601 }
602
603 // Set up the equations set (two equations in two unknowns, per pixel).
604 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
605 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
606 // floats. (Actually, we store the inverse of the diagonal elements, because
607 // we only ever need to divide by them.) This fits into four u32 values;
608 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
609 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
610 // terms that depend on other pixels, are calculated in one pass.
611 //
612 // See variational_refinement.txt for more information.
613 class SetupEquations {
614 public:
615         SetupEquations();
616         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);
617
618 private:
619         GLuint equations_vs_obj;
620         GLuint equations_fs_obj;
621         GLuint equations_program;
622         GLuint equations_vao;
623
624         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
625         GLuint uniform_diff_flow_tex, uniform_flow_tex;
626         GLuint uniform_beta_0_tex;
627         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
628
629 };
630
631 SetupEquations::SetupEquations()
632 {
633         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
634         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
635         equations_program = link_program(equations_vs_obj, equations_fs_obj);
636
637         // Set up the VAO containing all the required position/texcoord data.
638         glCreateVertexArrays(1, &equations_vao);
639         glBindVertexArray(equations_vao);
640         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
641
642         GLint position_attrib = glGetAttribLocation(equations_program, "position");
643         glEnableVertexArrayAttrib(equations_vao, position_attrib);
644         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
645
646         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
647         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
648         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
649         uniform_flow_tex = glGetUniformLocation(equations_program, "flow_tex");
650         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
651         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
652         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
653 }
654
655 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)
656 {
657         glUseProgram(equations_program);
658
659         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
660         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
661         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
662         bind_sampler(equations_program, uniform_flow_tex, 3, flow_tex, nearest_sampler);
663         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
664         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
665         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
666
667         GLuint equations_fbo;  // TODO: cleanup
668         glCreateFramebuffers(1, &equations_fbo);
669         glNamedFramebufferTexture(equations_fbo, GL_COLOR_ATTACHMENT0, equation_tex, 0);
670
671         glViewport(0, 0, level_width, level_height);
672         glDisable(GL_BLEND);
673         glBindVertexArray(equations_vao);
674         glBindFramebuffer(GL_FRAMEBUFFER, equations_fbo);
675         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
676 }
677
678 // Calculate the smoothness constraints between neighboring pixels;
679 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
680 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
681 // border color (0,0) later, so that there's zero diffusion out of
682 // the border.
683 //
684 // See variational_refinement.txt for more information.
685 class SOR {
686 public:
687         SOR();
688         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);
689
690 private:
691         GLuint sor_vs_obj;
692         GLuint sor_fs_obj;
693         GLuint sor_program;
694         GLuint sor_vao;
695
696         GLuint uniform_diff_flow_tex;
697         GLuint uniform_equation_tex;
698         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
699 };
700
701 SOR::SOR()
702 {
703         sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
704         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
705         sor_program = link_program(sor_vs_obj, sor_fs_obj);
706
707         // Set up the VAO containing all the required position/texcoord data.
708         glCreateVertexArrays(1, &sor_vao);
709         glBindVertexArray(sor_vao);
710         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
711
712         GLint position_attrib = glGetAttribLocation(sor_program, "position");
713         glEnableVertexArrayAttrib(sor_vao, position_attrib);
714         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
715
716         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
717         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
718         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
719         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
720 }
721
722 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)
723 {
724         glUseProgram(sor_program);
725
726         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
727         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
728         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
729         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
730
731         GLuint sor_fbo;  // TODO: cleanup
732         glCreateFramebuffers(1, &sor_fbo);
733         glNamedFramebufferTexture(sor_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0);  // NOTE: Bind to same as we render from!
734
735         glViewport(0, 0, level_width, level_height);
736         glDisable(GL_BLEND);
737         glBindVertexArray(sor_vao);
738         glBindFramebuffer(GL_FRAMEBUFFER, sor_fbo);
739
740         for (int i = 0; i < num_iterations; ++i) {
741                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
742                 if (i != num_iterations - 1) {
743                         glTextureBarrier();
744                 }
745         }
746 }
747
748 // Simply add the differential flow found by the variational refinement to the base flow.
749 // The output is in diff_flow_tex; we don't need to make a new texture.
750 class AddBaseFlow {
751 public:
752         AddBaseFlow();
753         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
754
755 private:
756         GLuint add_flow_vs_obj;
757         GLuint add_flow_fs_obj;
758         GLuint add_flow_program;
759         GLuint add_flow_vao;
760
761         GLuint uniform_base_flow_tex;
762 };
763
764 AddBaseFlow::AddBaseFlow()
765 {
766         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
767         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
768         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
769
770         // Set up the VAO containing all the required position/texcoord data.
771         glCreateVertexArrays(1, &add_flow_vao);
772         glBindVertexArray(add_flow_vao);
773         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
774
775         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
776         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
777         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
778
779         uniform_base_flow_tex = glGetUniformLocation(add_flow_program, "base_flow_tex");
780 }
781
782 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
783 {
784         glUseProgram(add_flow_program);
785
786         bind_sampler(add_flow_program, uniform_base_flow_tex, 0, base_flow_tex, nearest_sampler);
787
788         GLuint add_flow_fbo;  // TODO: cleanup
789         glCreateFramebuffers(1, &add_flow_fbo);
790         glNamedFramebufferTexture(add_flow_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0);
791
792         glViewport(0, 0, level_width, level_height);
793         glEnable(GL_BLEND);
794         glBlendFunc(GL_ONE, GL_ONE);
795         glBindVertexArray(add_flow_vao);
796         glBindFramebuffer(GL_FRAMEBUFFER, add_flow_fbo);
797
798         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
799 }
800
801 class GPUTimers {
802 public:
803         void print();
804         pair<GLuint, GLuint> begin_timer(const string &name, int level);
805
806 private:
807         struct Timer {
808                 string name;
809                 int level;
810                 pair<GLuint, GLuint> query;
811         };
812         vector<Timer> timers;
813 };
814
815 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
816 {
817         GLuint queries[2];
818         glGenQueries(2, queries);
819         glQueryCounter(queries[0], GL_TIMESTAMP);
820
821         Timer timer;
822         timer.name = name;
823         timer.level = level;
824         timer.query.first = queries[0];
825         timer.query.second = queries[1];
826         timers.push_back(timer);
827         return timer.query;
828 }
829
830 void GPUTimers::print()
831 {
832         for (const Timer &timer : timers) {
833                 // NOTE: This makes the CPU wait for the GPU.
834                 GLuint64 time_start, time_end;
835                 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
836                 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
837                 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
838                 for (int i = 0; i < timer.level * 2; ++i) {
839                         fprintf(stderr, " ");
840                 }
841                 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), (time_end - time_start) / 1e6);
842         }
843 }
844
845 // A simple RAII class for timing until the end of the scope.
846 class ScopedTimer {
847 public:
848         ScopedTimer(const string &name, GPUTimers *timers)
849                 : timers(timers), level(0)
850         {
851                 query = timers->begin_timer(name, level);
852         }
853
854         ScopedTimer(const string &name, ScopedTimer *parent_timer)
855                 : timers(parent_timer->timers),
856                   level(parent_timer->level + 1)
857         {
858                 query = timers->begin_timer(name, level);
859         }
860
861         ~ScopedTimer()
862         {
863                 end();
864         }
865
866         void end()
867         {
868                 if (!ended) {
869                         glQueryCounter(query.second, GL_TIMESTAMP);
870                         ended = true;
871                 }
872         }
873
874 private:
875         GPUTimers *timers;
876         int level;
877         pair<GLuint, GLuint> query;
878         bool ended = false;
879 };
880
881 int main(void)
882 {
883         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
884                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
885                 exit(1);
886         }
887         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
888         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
889         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
890         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
891
892         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
893         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
894         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
895         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
896         SDL_Window *window = SDL_CreateWindow("OpenGL window",
897                         SDL_WINDOWPOS_UNDEFINED,
898                         SDL_WINDOWPOS_UNDEFINED,
899                         64, 64,
900                         SDL_WINDOW_OPENGL);
901         SDL_GLContext context = SDL_GL_CreateContext(window);
902         assert(context != nullptr);
903
904         // Load pictures.
905         GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
906         GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
907
908         // Make some samplers.
909         glCreateSamplers(1, &nearest_sampler);
910         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
911         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
912         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
913         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
914
915         glCreateSamplers(1, &linear_sampler);
916         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
917         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
918         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
919         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
920
921         // The smoothness is sampled so that once we get to a smoothness involving
922         // a value outside the border, the diffusivity between the two becomes zero.
923         glCreateSamplers(1, &smoothness_sampler);
924         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
925         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
926         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
927         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
928         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
929         glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
930
931         float vertices[] = {
932                 0.0f, 1.0f,
933                 0.0f, 0.0f,
934                 1.0f, 1.0f,
935                 1.0f, 0.0f,
936         };
937         glCreateBuffers(1, &vertex_vbo);
938         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
939         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
940
941         // Initial flow is zero, 1x1.
942         GLuint initial_flow_tex;
943         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
944         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
945
946         GLuint prev_level_flow_tex = initial_flow_tex;
947
948         Sobel sobel;
949         MotionSearch motion_search;
950         Densify densify;
951         Prewarp prewarp;
952         Derivatives derivatives;
953         ComputeSmoothness compute_smoothness;
954         SetupEquations setup_equations;
955         SOR sor;
956         AddBaseFlow add_base_flow;
957
958         GLuint query;
959         glGenQueries(1, &query);
960         glBeginQuery(GL_TIME_ELAPSED, query);
961
962         GPUTimers timers;
963
964         ScopedTimer total_timer("Total", &timers);
965         for (int level = coarsest_level; level >= int(finest_level); --level) {
966                 char timer_name[256];
967                 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
968                 ScopedTimer level_timer(timer_name, &total_timer);
969
970                 int level_width = WIDTH >> level;
971                 int level_height = HEIGHT >> level;
972                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
973                 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
974                 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
975
976                 // Make sure we always read from the correct level; the chosen
977                 // mipmapping could otherwise be rather unpredictable, especially
978                 // during motion search.
979                 // TODO: create these beforehand, and stop leaking them.
980                 GLuint tex0_view, tex1_view;
981                 glGenTextures(1, &tex0_view);
982                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
983                 glGenTextures(1, &tex1_view);
984                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
985
986                 // Create a new texture; we could be fancy and render use a multi-level
987                 // texture, but meh.
988                 GLuint grad0_tex;
989                 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
990                 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
991
992                 // Find the derivative.
993                 {
994                         ScopedTimer timer("Sobel", &level_timer);
995                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
996                 }
997
998                 // Motion search to find the initial flow. We use the flow from the previous
999                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1000
1001                 // Create an output flow texture.
1002                 GLuint flow_out_tex;
1003                 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
1004                 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
1005
1006                 // And draw.
1007                 {
1008                         ScopedTimer timer("Motion search", &level_timer);
1009                         motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, width_patches, height_patches);
1010                 }
1011
1012                 // Densification.
1013
1014                 // Set up an output texture (initially zero).
1015                 GLuint dense_flow_tex;
1016                 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
1017                 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
1018
1019                 // And draw.
1020                 {
1021                         ScopedTimer timer("Densification", &level_timer);
1022                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1023                 }
1024
1025                 // Everything below here in the loop belongs to variational refinement.
1026                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1027
1028                 // Prewarping; create I and I_t.
1029                 GLuint I_tex, I_t_tex;
1030                 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
1031                 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
1032                 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
1033                 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
1034                 {
1035                         ScopedTimer timer("Prewarping", &varref_timer);
1036                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, level_width, level_height);
1037                 }
1038
1039                 // Calculate I_x and I_y. We're only calculating first derivatives;
1040                 // the others will be taken on-the-fly in order to sample from fewer
1041                 // textures overall, since sampling from the L1 cache is cheap.
1042                 // (TODO: Verify that this is indeed faster than making separate
1043                 // double-derivative textures.)
1044                 GLuint I_x_y_tex, beta_0_tex;
1045                 glCreateTextures(GL_TEXTURE_2D, 1, &I_x_y_tex);
1046                 glCreateTextures(GL_TEXTURE_2D, 1, &beta_0_tex);
1047                 glTextureStorage2D(I_x_y_tex, 1, GL_RG16F, level_width, level_height);
1048                 glTextureStorage2D(beta_0_tex, 1, GL_R16F, level_width, level_height);
1049                 {
1050                         ScopedTimer timer("First derivatives", &varref_timer);
1051                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1052                 }
1053
1054                 // We need somewhere to store du and dv (the flow increment, relative
1055                 // to the non-refined base flow u0 and v0). It starts at zero.
1056                 GLuint du_dv_tex;
1057                 glCreateTextures(GL_TEXTURE_2D, 1, &du_dv_tex);
1058                 glTextureStorage2D(du_dv_tex, 1, GL_RG16F, level_width, level_height);
1059
1060                 // And for smoothness.
1061                 GLuint smoothness_x_tex, smoothness_y_tex;
1062                 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_x_tex);
1063                 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_y_tex);
1064                 glTextureStorage2D(smoothness_x_tex, 1, GL_R16F, level_width, level_height);
1065                 glTextureStorage2D(smoothness_y_tex, 1, GL_R16F, level_width, level_height);
1066
1067                 // And finally for the equation set. See SetupEquations for
1068                 // the storage format.
1069                 GLuint equation_tex;
1070                 glCreateTextures(GL_TEXTURE_2D, 1, &equation_tex);
1071                 glTextureStorage2D(equation_tex, 1, GL_RGBA32UI, level_width, level_height);
1072
1073                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1074                         // Calculate the smoothness terms between the neighboring pixels,
1075                         // both in x and y direction.
1076                         {
1077                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1078                                 compute_smoothness.exec(dense_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1079                         }
1080
1081                         // Set up the 2x2 equation system for each pixel.
1082                         {
1083                                 ScopedTimer timer("Set up equations", &varref_timer);
1084                                 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);
1085                         }
1086
1087                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1088                         // Note that these are to/from the same texture.
1089                         {
1090                                 ScopedTimer timer("SOR", &varref_timer);
1091                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1092                         }
1093                 }
1094
1095                 // Add the differential flow found by the variational refinement to the base flow,
1096                 // giving the final flow estimate for this level.
1097                 // The output is in diff_flow_tex; we don't need to make a new texture.
1098                 {
1099                         ScopedTimer timer("Add differential flow", &varref_timer);
1100                         add_base_flow.exec(dense_flow_tex, du_dv_tex, level_width, level_height);
1101                 }
1102
1103                 prev_level_flow_tex = du_dv_tex;
1104         }
1105         total_timer.end();
1106
1107         timers.print();
1108
1109         int level_width = WIDTH >> finest_level;
1110         int level_height = HEIGHT >> finest_level;
1111         unique_ptr<float[]> dense_flow(new float[level_width * level_height * 2]);
1112         glGetTextureImage(prev_level_flow_tex, 0, GL_RG, GL_FLOAT, level_width * level_height * 2 * sizeof(float), dense_flow.get());
1113
1114         FILE *fp = fopen("flow.ppm", "wb");
1115         FILE *flowfp = fopen("flow.flo", "wb");
1116         fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
1117         fprintf(flowfp, "FEIH");
1118         fwrite(&level_width, 4, 1, flowfp);
1119         fwrite(&level_height, 4, 1, flowfp);
1120         for (unsigned y = 0; y < unsigned(level_height); ++y) {
1121                 int yy = level_height - y - 1;
1122                 for (unsigned x = 0; x < unsigned(level_width); ++x) {
1123                         float du = dense_flow[(yy * level_width + x) * 2 + 0];
1124                         float dv = dense_flow[(yy * level_width + x) * 2 + 1];
1125
1126                         du = du * level_width;
1127                         dv = -dv * level_height;
1128
1129                         fwrite(&du, 4, 1, flowfp);
1130                         fwrite(&dv, 4, 1, flowfp);
1131
1132                         uint8_t r, g, b;
1133                         flow2rgb(du, dv, &r, &g, &b);
1134                         putc(r, fp);
1135                         putc(g, fp);
1136                         putc(b, fp);
1137                 }
1138         }
1139         fclose(fp);
1140         fclose(flowfp);
1141
1142         fprintf(stderr, "err = %d\n", glGetError());
1143 }