]> git.sesse.net Git - nageru/blob - flow.cpp
In the variational refinement, change the flow unit from normalized coordinates to...
[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 prev_level_width, int prev_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, uniform_inv_prev_level_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_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
301         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
302         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
303         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
304         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
305 }
306
307 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
308 {
309         glUseProgram(motion_search_program);
310
311         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
312         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
313         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
314         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
315
316         glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
317         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
318         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
319
320         GLuint flow_fbo;  // TODO: cleanup
321         glCreateFramebuffers(1, &flow_fbo);
322         glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
323
324         glViewport(0, 0, width_patches, height_patches);
325         glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
326         glBindVertexArray(motion_search_vao);
327         glUseProgram(motion_search_program);
328         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
329 }
330
331 // Do “densification”, ie., upsampling of the flow patches to the flow field
332 // (the same size as the image at this level). We draw one quad per patch
333 // over its entire covered area (using instancing in the vertex shader),
334 // and then weight the contributions in the pixel shader by post-warp difference.
335 // This is equation (3) in the paper.
336 //
337 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
338 // weight in the B channel. Dividing R and G by B gives the normalized values.
339 class Densify {
340 public:
341         Densify();
342         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);
343
344 private:
345         GLuint densify_vs_obj;
346         GLuint densify_fs_obj;
347         GLuint densify_program;
348         GLuint densify_vao;
349
350         GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
351         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
352 };
353
354 Densify::Densify()
355 {
356         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
357         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
358         densify_program = link_program(densify_vs_obj, densify_fs_obj);
359
360         // Set up the VAO containing all the required position/texcoord data.
361         glCreateVertexArrays(1, &densify_vao);
362         glBindVertexArray(densify_vao);
363         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
364
365         GLint position_attrib = glGetAttribLocation(densify_program, "position");
366         glEnableVertexArrayAttrib(densify_vao, position_attrib);
367         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
368
369         uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
370         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
371         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
372         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
373         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
374         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
375 }
376
377 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)
378 {
379         glUseProgram(densify_program);
380
381         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
382         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
383         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
384
385         glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
386         glProgramUniform2f(densify_program, uniform_patch_size,
387                 float(patch_size_pixels) / level_width,
388                 float(patch_size_pixels) / level_height);
389
390         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
391         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
392         if (width_patches == 1) patch_spacing_x = 0.0f;  // Avoid infinities.
393         if (height_patches == 1) patch_spacing_y = 0.0f;
394         glProgramUniform2f(densify_program, uniform_patch_spacing,
395                 patch_spacing_x / level_width,
396                 patch_spacing_y / level_height);
397
398         GLuint dense_flow_fbo;  // TODO: cleanup
399         glCreateFramebuffers(1, &dense_flow_fbo);
400         glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
401
402         glViewport(0, 0, level_width, level_height);
403         glEnable(GL_BLEND);
404         glBlendFunc(GL_ONE, GL_ONE);
405         glBindVertexArray(densify_vao);
406         glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
407         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
408 }
409
410 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
411 // I_0 and I_w. The prewarping is what enables us to solve the variational
412 // flow for du,dv instead of u,v.
413 //
414 // Also calculates the normalized flow, ie. divides by z (this is needed because
415 // Densify works by additive blending) and multiplies by the image size.
416 //
417 // See variational_refinement.txt for more information.
418 class Prewarp {
419 public:
420         Prewarp();
421         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
422
423 private:
424         GLuint prewarp_vs_obj;
425         GLuint prewarp_fs_obj;
426         GLuint prewarp_program;
427         GLuint prewarp_vao;
428
429         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
430         GLuint uniform_image_size;
431 };
432
433 Prewarp::Prewarp()
434 {
435         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
436         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
437         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
438
439         // Set up the VAO containing all the required position/texcoord data.
440         glCreateVertexArrays(1, &prewarp_vao);
441         glBindVertexArray(prewarp_vao);
442         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
443
444         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
445         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
446         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
447
448         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
449         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
450         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
451
452         uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
453 }
454
455 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
456 {
457         glUseProgram(prewarp_program);
458
459         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
460         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
461         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
462
463         glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
464
465         GLuint prewarp_fbo;  // TODO: cleanup
466         glCreateFramebuffers(1, &prewarp_fbo);
467         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
468         glNamedFramebufferDrawBuffers(prewarp_fbo, 3, bufs);
469         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
470         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
471         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT2, normalized_flow_tex, 0);
472
473         glViewport(0, 0, level_width, level_height);
474         glDisable(GL_BLEND);
475         glBindVertexArray(prewarp_vao);
476         glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
477         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
478 }
479
480 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
481 // central difference filter, since apparently, that's tradition (I haven't
482 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
483 // The coefficients come from
484 //
485 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
486 //
487 // Also computes β_0, since it depends only on I_x and I_y.
488 class Derivatives {
489 public:
490         Derivatives();
491         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
492
493 private:
494         GLuint derivatives_vs_obj;
495         GLuint derivatives_fs_obj;
496         GLuint derivatives_program;
497         GLuint derivatives_vao;
498
499         GLuint uniform_tex;
500 };
501
502 Derivatives::Derivatives()
503 {
504         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
505         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
506         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
507
508         // Set up the VAO containing all the required position/texcoord data.
509         glCreateVertexArrays(1, &derivatives_vao);
510         glBindVertexArray(derivatives_vao);
511         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
512
513         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
514         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
515         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
516
517         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
518 }
519
520 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
521 {
522         glUseProgram(derivatives_program);
523
524         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
525
526         GLuint derivatives_fbo;  // TODO: cleanup
527         glCreateFramebuffers(1, &derivatives_fbo);
528         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
529         glNamedFramebufferDrawBuffers(derivatives_fbo, 2, bufs);
530         glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT0, I_x_y_tex, 0);
531         glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT1, beta_0_tex, 0);
532
533         glViewport(0, 0, level_width, level_height);
534         glDisable(GL_BLEND);
535         glBindVertexArray(derivatives_vao);
536         glBindFramebuffer(GL_FRAMEBUFFER, derivatives_fbo);
537         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
538 }
539
540 // Calculate the smoothness constraints between neighboring pixels;
541 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
542 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
543 // border color (0,0) later, so that there's zero diffusion out of
544 // the border.
545 //
546 // See variational_refinement.txt for more information.
547 class ComputeSmoothness {
548 public:
549         ComputeSmoothness();
550         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
551
552 private:
553         GLuint smoothness_vs_obj;
554         GLuint smoothness_fs_obj;
555         GLuint smoothness_program;
556         GLuint smoothness_vao;
557
558         GLuint uniform_flow_tex, uniform_diff_flow_tex;
559 };
560
561 ComputeSmoothness::ComputeSmoothness()
562 {
563         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
564         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
565         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
566
567         // Set up the VAO containing all the required position/texcoord data.
568         glCreateVertexArrays(1, &smoothness_vao);
569         glBindVertexArray(smoothness_vao);
570         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
571
572         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
573         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
574         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
575
576         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
577         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
578 }
579
580 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
581 {
582         glUseProgram(smoothness_program);
583
584         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
585         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
586
587         GLuint smoothness_fbo;  // TODO: cleanup
588         glCreateFramebuffers(1, &smoothness_fbo);
589         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
590         glNamedFramebufferDrawBuffers(smoothness_fbo, 2, bufs);
591         glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT0, smoothness_x_tex, 0);
592         glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT1, smoothness_y_tex, 0);
593
594         glViewport(0, 0, level_width, level_height);
595
596         // Make sure the smoothness on the right and upper borders is zero.
597         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
598         // (we're sampling smoothness with all-zero border color), but we'd
599         // have to adjust the sampling coordinates, which is annoying.
600         //
601         // FIXME: We shouldn't scissor width for horizontal,
602         // and we shouldn't scissor height for vertical
603         glScissor(0, 0, level_width - 1, level_height - 1);
604         glEnable(GL_SCISSOR_TEST);
605
606         glDisable(GL_BLEND);
607         glBindVertexArray(smoothness_vao);
608         glBindFramebuffer(GL_FRAMEBUFFER, smoothness_fbo);
609         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
610
611         glDisable(GL_SCISSOR_TEST);
612 }
613
614 // Set up the equations set (two equations in two unknowns, per pixel).
615 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
616 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
617 // floats. (Actually, we store the inverse of the diagonal elements, because
618 // we only ever need to divide by them.) This fits into four u32 values;
619 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
620 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
621 // terms that depend on other pixels, are calculated in one pass.
622 //
623 // See variational_refinement.txt for more information.
624 class SetupEquations {
625 public:
626         SetupEquations();
627         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);
628
629 private:
630         GLuint equations_vs_obj;
631         GLuint equations_fs_obj;
632         GLuint equations_program;
633         GLuint equations_vao;
634
635         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
636         GLuint uniform_diff_flow_tex, uniform_flow_tex;
637         GLuint uniform_beta_0_tex;
638         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
639 };
640
641 SetupEquations::SetupEquations()
642 {
643         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
644         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
645         equations_program = link_program(equations_vs_obj, equations_fs_obj);
646
647         // Set up the VAO containing all the required position/texcoord data.
648         glCreateVertexArrays(1, &equations_vao);
649         glBindVertexArray(equations_vao);
650         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
651
652         GLint position_attrib = glGetAttribLocation(equations_program, "position");
653         glEnableVertexArrayAttrib(equations_vao, position_attrib);
654         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
655
656         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
657         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
658         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
659         uniform_flow_tex = glGetUniformLocation(equations_program, "flow_tex");
660         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
661         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
662         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
663 }
664
665 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)
666 {
667         glUseProgram(equations_program);
668
669         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
670         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
671         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
672         bind_sampler(equations_program, uniform_flow_tex, 3, flow_tex, nearest_sampler);
673         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
674         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
675         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
676
677         GLuint equations_fbo;  // TODO: cleanup
678         glCreateFramebuffers(1, &equations_fbo);
679         glNamedFramebufferTexture(equations_fbo, GL_COLOR_ATTACHMENT0, equation_tex, 0);
680
681         glViewport(0, 0, level_width, level_height);
682         glDisable(GL_BLEND);
683         glBindVertexArray(equations_vao);
684         glBindFramebuffer(GL_FRAMEBUFFER, equations_fbo);
685         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
686 }
687
688 // Calculate the smoothness constraints between neighboring pixels;
689 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
690 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
691 // border color (0,0) later, so that there's zero diffusion out of
692 // the border.
693 //
694 // See variational_refinement.txt for more information.
695 class SOR {
696 public:
697         SOR();
698         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);
699
700 private:
701         GLuint sor_vs_obj;
702         GLuint sor_fs_obj;
703         GLuint sor_program;
704         GLuint sor_vao;
705
706         GLuint uniform_diff_flow_tex;
707         GLuint uniform_equation_tex;
708         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
709 };
710
711 SOR::SOR()
712 {
713         sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
714         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
715         sor_program = link_program(sor_vs_obj, sor_fs_obj);
716
717         // Set up the VAO containing all the required position/texcoord data.
718         glCreateVertexArrays(1, &sor_vao);
719         glBindVertexArray(sor_vao);
720         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
721
722         GLint position_attrib = glGetAttribLocation(sor_program, "position");
723         glEnableVertexArrayAttrib(sor_vao, position_attrib);
724         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
725
726         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
727         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
728         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
729         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
730 }
731
732 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)
733 {
734         glUseProgram(sor_program);
735
736         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
737         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
738         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
739         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
740
741         GLuint sor_fbo;  // TODO: cleanup
742         glCreateFramebuffers(1, &sor_fbo);
743         glNamedFramebufferTexture(sor_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0);  // NOTE: Bind to same as we render from!
744
745         glViewport(0, 0, level_width, level_height);
746         glDisable(GL_BLEND);
747         glBindVertexArray(sor_vao);
748         glBindFramebuffer(GL_FRAMEBUFFER, sor_fbo);
749
750         for (int i = 0; i < num_iterations; ++i) {
751                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
752                 if (i != num_iterations - 1) {
753                         glTextureBarrier();
754                 }
755         }
756 }
757
758 // Simply add the differential flow found by the variational refinement to the base flow.
759 // The output is in base_flow_tex; we don't need to make a new texture.
760 class AddBaseFlow {
761 public:
762         AddBaseFlow();
763         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
764
765 private:
766         GLuint add_flow_vs_obj;
767         GLuint add_flow_fs_obj;
768         GLuint add_flow_program;
769         GLuint add_flow_vao;
770
771         GLuint uniform_diff_flow_tex;
772 };
773
774 AddBaseFlow::AddBaseFlow()
775 {
776         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
777         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
778         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
779
780         // Set up the VAO containing all the required position/texcoord data.
781         glCreateVertexArrays(1, &add_flow_vao);
782         glBindVertexArray(add_flow_vao);
783         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
784
785         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
786         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
787         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
788
789         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
790 }
791
792 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
793 {
794         glUseProgram(add_flow_program);
795
796         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
797
798         GLuint add_flow_fbo;  // TODO: cleanup
799         glCreateFramebuffers(1, &add_flow_fbo);
800         glNamedFramebufferTexture(add_flow_fbo, GL_COLOR_ATTACHMENT0, base_flow_tex, 0);
801
802         glViewport(0, 0, level_width, level_height);
803         glEnable(GL_BLEND);
804         glBlendFunc(GL_ONE, GL_ONE);
805         glBindVertexArray(add_flow_vao);
806         glBindFramebuffer(GL_FRAMEBUFFER, add_flow_fbo);
807
808         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
809 }
810
811 class GPUTimers {
812 public:
813         void print();
814         pair<GLuint, GLuint> begin_timer(const string &name, int level);
815
816 private:
817         struct Timer {
818                 string name;
819                 int level;
820                 pair<GLuint, GLuint> query;
821         };
822         vector<Timer> timers;
823 };
824
825 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
826 {
827         GLuint queries[2];
828         glGenQueries(2, queries);
829         glQueryCounter(queries[0], GL_TIMESTAMP);
830
831         Timer timer;
832         timer.name = name;
833         timer.level = level;
834         timer.query.first = queries[0];
835         timer.query.second = queries[1];
836         timers.push_back(timer);
837         return timer.query;
838 }
839
840 void GPUTimers::print()
841 {
842         for (const Timer &timer : timers) {
843                 // NOTE: This makes the CPU wait for the GPU.
844                 GLuint64 time_start, time_end;
845                 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
846                 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
847                 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
848                 for (int i = 0; i < timer.level * 2; ++i) {
849                         fprintf(stderr, " ");
850                 }
851                 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), (time_end - time_start) / 1e6);
852         }
853 }
854
855 // A simple RAII class for timing until the end of the scope.
856 class ScopedTimer {
857 public:
858         ScopedTimer(const string &name, GPUTimers *timers)
859                 : timers(timers), level(0)
860         {
861                 query = timers->begin_timer(name, level);
862         }
863
864         ScopedTimer(const string &name, ScopedTimer *parent_timer)
865                 : timers(parent_timer->timers),
866                   level(parent_timer->level + 1)
867         {
868                 query = timers->begin_timer(name, level);
869         }
870
871         ~ScopedTimer()
872         {
873                 end();
874         }
875
876         void end()
877         {
878                 if (!ended) {
879                         glQueryCounter(query.second, GL_TIMESTAMP);
880                         ended = true;
881                 }
882         }
883
884 private:
885         GPUTimers *timers;
886         int level;
887         pair<GLuint, GLuint> query;
888         bool ended = false;
889 };
890
891 int main(void)
892 {
893         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
894                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
895                 exit(1);
896         }
897         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
898         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
899         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
900         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
901
902         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
903         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
904         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
905         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
906         SDL_Window *window = SDL_CreateWindow("OpenGL window",
907                         SDL_WINDOWPOS_UNDEFINED,
908                         SDL_WINDOWPOS_UNDEFINED,
909                         64, 64,
910                         SDL_WINDOW_OPENGL);
911         SDL_GLContext context = SDL_GL_CreateContext(window);
912         assert(context != nullptr);
913
914         // Load pictures.
915         GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
916         GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
917
918         // Make some samplers.
919         glCreateSamplers(1, &nearest_sampler);
920         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
921         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
922         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
923         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
924
925         glCreateSamplers(1, &linear_sampler);
926         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
927         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
928         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
929         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
930
931         // The smoothness is sampled so that once we get to a smoothness involving
932         // a value outside the border, the diffusivity between the two becomes zero.
933         glCreateSamplers(1, &smoothness_sampler);
934         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
935         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
936         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
937         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
938         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
939         glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
940
941         float vertices[] = {
942                 0.0f, 1.0f,
943                 0.0f, 0.0f,
944                 1.0f, 1.0f,
945                 1.0f, 0.0f,
946         };
947         glCreateBuffers(1, &vertex_vbo);
948         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
949         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
950
951         // Initial flow is zero, 1x1.
952         GLuint initial_flow_tex;
953         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
954         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
955         int prev_level_width = 1, prev_level_height = 1;
956
957         GLuint prev_level_flow_tex = initial_flow_tex;
958
959         Sobel sobel;
960         MotionSearch motion_search;
961         Densify densify;
962         Prewarp prewarp;
963         Derivatives derivatives;
964         ComputeSmoothness compute_smoothness;
965         SetupEquations setup_equations;
966         SOR sor;
967         AddBaseFlow add_base_flow;
968
969         GLuint query;
970         glGenQueries(1, &query);
971         glBeginQuery(GL_TIME_ELAPSED, query);
972
973         GPUTimers timers;
974
975         ScopedTimer total_timer("Total", &timers);
976         for (int level = coarsest_level; level >= int(finest_level); --level) {
977                 char timer_name[256];
978                 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
979                 ScopedTimer level_timer(timer_name, &total_timer);
980
981                 int level_width = WIDTH >> level;
982                 int level_height = HEIGHT >> level;
983                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
984                 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
985                 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
986
987                 // Make sure we always read from the correct level; the chosen
988                 // mipmapping could otherwise be rather unpredictable, especially
989                 // during motion search.
990                 // TODO: create these beforehand, and stop leaking them.
991                 GLuint tex0_view, tex1_view;
992                 glGenTextures(1, &tex0_view);
993                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
994                 glGenTextures(1, &tex1_view);
995                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
996
997                 // Create a new texture; we could be fancy and render use a multi-level
998                 // texture, but meh.
999                 GLuint grad0_tex;
1000                 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
1001                 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
1002
1003                 // Find the derivative.
1004                 {
1005                         ScopedTimer timer("Sobel", &level_timer);
1006                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1007                 }
1008
1009                 // Motion search to find the initial flow. We use the flow from the previous
1010                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1011
1012                 // Create an output flow texture.
1013                 GLuint flow_out_tex;
1014                 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
1015                 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
1016
1017                 // And draw.
1018                 {
1019                         ScopedTimer timer("Motion search", &level_timer);
1020                         motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1021                 }
1022
1023                 // Densification.
1024
1025                 // Set up an output texture (initially zero).
1026                 GLuint dense_flow_tex;
1027                 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
1028                 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
1029
1030                 // And draw.
1031                 {
1032                         ScopedTimer timer("Densification", &level_timer);
1033                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1034                 }
1035
1036                 // Everything below here in the loop belongs to variational refinement.
1037                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1038
1039                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1040                 // have to normalize it over and over again, and also save some bandwidth).
1041                 //
1042                 // During the entire rest of the variational refinement, flow will be measured
1043                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1044                 // This is because variational refinement depends so heavily on derivatives,
1045                 // which are measured in intensity levels per pixel.
1046                 GLuint I_tex, I_t_tex, base_flow_tex;
1047                 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
1048                 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
1049                 glCreateTextures(GL_TEXTURE_2D, 1, &base_flow_tex);
1050                 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
1051                 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
1052                 glTextureStorage2D(base_flow_tex, 1, GL_RG16F, level_width, level_height);
1053                 {
1054                         ScopedTimer timer("Prewarping", &varref_timer);
1055                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1056                 }
1057
1058                 // Calculate I_x and I_y. We're only calculating first derivatives;
1059                 // the others will be taken on-the-fly in order to sample from fewer
1060                 // textures overall, since sampling from the L1 cache is cheap.
1061                 // (TODO: Verify that this is indeed faster than making separate
1062                 // double-derivative textures.)
1063                 GLuint I_x_y_tex, beta_0_tex;
1064                 glCreateTextures(GL_TEXTURE_2D, 1, &I_x_y_tex);
1065                 glCreateTextures(GL_TEXTURE_2D, 1, &beta_0_tex);
1066                 glTextureStorage2D(I_x_y_tex, 1, GL_RG16F, level_width, level_height);
1067                 glTextureStorage2D(beta_0_tex, 1, GL_R16F, level_width, level_height);
1068                 {
1069                         ScopedTimer timer("First derivatives", &varref_timer);
1070                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1071                 }
1072
1073                 // We need somewhere to store du and dv (the flow increment, relative
1074                 // to the non-refined base flow u0 and v0). It starts at zero.
1075                 GLuint du_dv_tex;
1076                 glCreateTextures(GL_TEXTURE_2D, 1, &du_dv_tex);
1077                 glTextureStorage2D(du_dv_tex, 1, GL_RG16F, level_width, level_height);
1078
1079                 // And for smoothness.
1080                 GLuint smoothness_x_tex, smoothness_y_tex;
1081                 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_x_tex);
1082                 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_y_tex);
1083                 glTextureStorage2D(smoothness_x_tex, 1, GL_R16F, level_width, level_height);
1084                 glTextureStorage2D(smoothness_y_tex, 1, GL_R16F, level_width, level_height);
1085
1086                 // And finally for the equation set. See SetupEquations for
1087                 // the storage format.
1088                 GLuint equation_tex;
1089                 glCreateTextures(GL_TEXTURE_2D, 1, &equation_tex);
1090                 glTextureStorage2D(equation_tex, 1, GL_RGBA32UI, level_width, level_height);
1091
1092                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1093                         // Calculate the smoothness terms between the neighboring pixels,
1094                         // both in x and y direction.
1095                         {
1096                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1097                                 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1098                         }
1099
1100                         // Set up the 2x2 equation system for each pixel.
1101                         {
1102                                 ScopedTimer timer("Set up equations", &varref_timer);
1103                                 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1104                         }
1105
1106                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1107                         // Note that these are to/from the same texture.
1108                         {
1109                                 ScopedTimer timer("SOR", &varref_timer);
1110                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1111                         }
1112                 }
1113
1114                 // Add the differential flow found by the variational refinement to the base flow,
1115                 // giving the final flow estimate for this level.
1116                 // The output is in diff_flow_tex; we don't need to make a new texture.
1117                 // You can comment out this prat if you wish to test disabling of the variational refinement.
1118                 {
1119                         ScopedTimer timer("Add differential flow", &varref_timer);
1120                         add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1121                 }
1122
1123                 prev_level_flow_tex = base_flow_tex;
1124                 prev_level_width = level_width;
1125                 prev_level_height = level_height;
1126         }
1127         total_timer.end();
1128
1129         timers.print();
1130
1131         int level_width = WIDTH >> finest_level;
1132         int level_height = HEIGHT >> finest_level;
1133         unique_ptr<float[]> dense_flow(new float[level_width * level_height * 2]);
1134         glGetTextureImage(prev_level_flow_tex, 0, GL_RG, GL_FLOAT, level_width * level_height * 2 * sizeof(float), dense_flow.get());
1135
1136         FILE *fp = fopen("flow.ppm", "wb");
1137         FILE *flowfp = fopen("flow.flo", "wb");
1138         fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
1139         fprintf(flowfp, "FEIH");
1140         fwrite(&level_width, 4, 1, flowfp);
1141         fwrite(&level_height, 4, 1, flowfp);
1142         for (unsigned y = 0; y < unsigned(level_height); ++y) {
1143                 int yy = level_height - y - 1;
1144                 for (unsigned x = 0; x < unsigned(level_width); ++x) {
1145                         float du = dense_flow[(yy * level_width + x) * 2 + 0];
1146                         float dv = dense_flow[(yy * level_width + x) * 2 + 1];
1147
1148                         dv = -dv;
1149
1150                         fwrite(&du, 4, 1, flowfp);
1151                         fwrite(&dv, 4, 1, flowfp);
1152
1153                         uint8_t r, g, b;
1154                         flow2rgb(du, dv, &r, &g, &b);
1155                         putc(r, fp);
1156                         putc(g, fp);
1157                         putc(b, fp);
1158                 }
1159         }
1160         fclose(fp);
1161         fclose(flowfp);
1162
1163         fprintf(stderr, "err = %d\n", glGetError());
1164 }