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