]> git.sesse.net Git - nageru/blob - flow.cpp
Fix an issue where we would lose >1 ms for computing flow on NVIDIA, due to lack...
[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 "gpu_timers.h"
19 #include "util.h"
20
21 #include <algorithm>
22 #include <deque>
23 #include <memory>
24 #include <map>
25 #include <stack>
26 #include <vector>
27
28 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
29
30 using namespace std;
31
32 SDL_Window *window;
33
34 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
35 constexpr float patch_overlap_ratio = 0.75f;
36 constexpr unsigned coarsest_level = 5;
37 constexpr unsigned finest_level = 1;
38 constexpr unsigned patch_size_pixels = 12;
39
40 // Weighting constants for the different parts of the variational refinement.
41 // These don't correspond 1:1 to the values given in the DIS paper,
42 // since we have different normalizations and ranges in some cases.
43 // These are found through a simple grid search on some MPI-Sintel data,
44 // although the error (EPE) seems to be fairly insensitive to the precise values.
45 // Only the relative values matter, so we fix alpha (the smoothness constant)
46 // at unity and tweak the others.
47 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
48
49 bool enable_timing = true;
50 bool detailed_timing = false;
51 bool enable_variational_refinement = true;  // Just for debugging.
52 bool enable_interpolation = false;
53
54 // Some global OpenGL objects.
55 // TODO: These should really be part of DISComputeFlow.
56 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
57 GLuint vertex_vbo;
58
59 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
60 struct ReadInProgress {
61         GLuint pbo;
62         string filename0, filename1;
63         string flow_filename, ppm_filename;  // Either may be empty for no write.
64 };
65 stack<GLuint> spare_pbos;
66 deque<ReadInProgress> reads_in_progress;
67
68 int find_num_levels(int width, int height)
69 {
70         int levels = 1;
71         for (int w = width, h = height; w > 1 || h > 1; ) {
72                 w >>= 1;
73                 h >>= 1;
74                 ++levels;
75         }
76         return levels;
77 }
78
79 string read_file(const string &filename)
80 {
81         FILE *fp = fopen(filename.c_str(), "r");
82         if (fp == nullptr) {
83                 perror(filename.c_str());
84                 exit(1);
85         }
86
87         int ret = fseek(fp, 0, SEEK_END);
88         if (ret == -1) {
89                 perror("fseek(SEEK_END)");
90                 exit(1);
91         }
92
93         int size = ftell(fp);
94
95         ret = fseek(fp, 0, SEEK_SET);
96         if (ret == -1) {
97                 perror("fseek(SEEK_SET)");
98                 exit(1);
99         }
100
101         string str;
102         str.resize(size);
103         ret = fread(&str[0], size, 1, fp);
104         if (ret == -1) {
105                 perror("fread");
106                 exit(1);
107         }
108         if (ret == 0) {
109                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
110                                 size, filename.c_str());
111                 exit(1);
112         }
113         fclose(fp);
114
115         return str;
116 }
117
118
119 GLuint compile_shader(const string &shader_src, GLenum type)
120 {
121         GLuint obj = glCreateShader(type);
122         const GLchar* source[] = { shader_src.data() };
123         const GLint length[] = { (GLint)shader_src.size() };
124         glShaderSource(obj, 1, source, length);
125         glCompileShader(obj);
126
127         GLchar info_log[4096];
128         GLsizei log_length = sizeof(info_log) - 1;
129         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
130         info_log[log_length] = 0;
131         if (strlen(info_log) > 0) {
132                 fprintf(stderr, "Shader compile log: %s\n", info_log);
133         }
134
135         GLint status;
136         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
137         if (status == GL_FALSE) {
138                 // Add some line numbers to easier identify compile errors.
139                 string src_with_lines = "/*   1 */ ";
140                 size_t lineno = 1;
141                 for (char ch : shader_src) {
142                         src_with_lines.push_back(ch);
143                         if (ch == '\n') {
144                                 char buf[32];
145                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
146                                 src_with_lines += buf;
147                         }
148                 }
149
150                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
151                 exit(1);
152         }
153
154         return obj;
155 }
156
157 enum MipmapPolicy {
158         WITHOUT_MIPMAPS,
159         WITH_MIPMAPS
160 };
161
162 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
163 {
164         SDL_Surface *surf = IMG_Load(filename);
165         if (surf == nullptr) {
166                 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
167                 exit(1);
168         }
169
170         // For whatever reason, SDL doesn't support converting to YUV surfaces
171         // nor grayscale, so we'll do it ourselves.
172         SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
173         if (rgb_surf == nullptr) {
174                 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
175                 exit(1);
176         }
177
178         SDL_FreeSurface(surf);
179
180         unsigned width = rgb_surf->w, height = rgb_surf->h;
181         const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
182         unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
183
184         // Extract the Y component, and convert to bottom-left origin.
185         for (unsigned y = 0; y < height; ++y) {
186                 unsigned y2 = height - 1 - y;
187                 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
188         }
189         SDL_FreeSurface(rgb_surf);
190
191         int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
192
193         GLuint tex;
194         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
195         glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
196         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
197
198         if (mipmaps == WITH_MIPMAPS) {
199                 glGenerateTextureMipmap(tex);
200         }
201
202         *width_ret = width;
203         *height_ret = height;
204
205         return tex;
206 }
207
208 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
209 {
210         GLuint program = glCreateProgram();
211         glAttachShader(program, vs_obj);
212         glAttachShader(program, fs_obj);
213         glLinkProgram(program);
214         GLint success;
215         glGetProgramiv(program, GL_LINK_STATUS, &success);
216         if (success == GL_FALSE) {
217                 GLchar error_log[1024] = {0};
218                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
219                 fprintf(stderr, "Error linking program: %s\n", error_log);
220                 exit(1);
221         }
222         return program;
223 }
224
225 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
226 {
227         GLuint vbo;
228         glCreateBuffers(1, &vbo);
229         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
230         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
231         return vbo;
232 }
233
234 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
235 {
236         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
237         if (attrib == -1) {
238                 return -1;
239         }
240
241         GLuint vbo = generate_vbo(size, data_size, data);
242
243         glBindBuffer(GL_ARRAY_BUFFER, vbo);
244         glEnableVertexArrayAttrib(vao, attrib);
245         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
246         glBindBuffer(GL_ARRAY_BUFFER, 0);
247
248         return vbo;
249 }
250
251 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
252 {
253         if (location == -1) {
254                 return;
255         }
256
257         glBindTextureUnit(texture_unit, tex);
258         glBindSampler(texture_unit, sampler);
259         glProgramUniform1i(program, location, texture_unit);
260 }
261
262 // A class that caches FBOs that render to a given set of textures.
263 // It never frees anything, so it is only suitable for rendering to
264 // the same (small) set of textures over and over again.
265 template<size_t num_elements>
266 class PersistentFBOSet {
267 public:
268         void render_to(const array<GLuint, num_elements> &textures);
269
270         // Convenience wrappers.
271         void render_to(GLuint texture0) {
272                 render_to({{texture0}});
273         }
274
275         void render_to(GLuint texture0, GLuint texture1) {
276                 render_to({{texture0, texture1}});
277         }
278
279         void render_to(GLuint texture0, GLuint texture1, GLuint texture2) {
280                 render_to({{texture0, texture1, texture2}});
281         }
282
283         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
284                 render_to({{texture0, texture1, texture2, texture3}});
285         }
286
287 private:
288         // TODO: Delete these on destruction.
289         map<array<GLuint, num_elements>, GLuint> fbos;
290 };
291
292 template<size_t num_elements>
293 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
294 {
295         auto it = fbos.find(textures);
296         if (it != fbos.end()) {
297                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
298                 return;
299         }
300
301         GLuint fbo;
302         glCreateFramebuffers(1, &fbo);
303         GLenum bufs[num_elements];
304         for (size_t i = 0; i < num_elements; ++i) {
305                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
306                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
307         }
308         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
309
310         fbos[textures] = fbo;
311         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
312 }
313
314 // Same, but with a depth texture.
315 template<size_t num_elements>
316 class PersistentFBOSetWithDepth {
317 public:
318         void render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures);
319
320         // Convenience wrappers.
321         void render_to(GLuint depth_tex, GLuint texture0) {
322                 render_to(depth_tex, {{texture0}});
323         }
324
325         void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1) {
326                 render_to(depth_tex, {{texture0, texture1}});
327         }
328
329         void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2) {
330                 render_to(depth_tex, {{texture0, texture1, texture2}});
331         }
332
333         void render_to(GLuint depth_tex, GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3) {
334                 render_to(depth_tex, {{texture0, texture1, texture2, texture3}});
335         }
336
337 private:
338         // TODO: Delete these on destruction.
339         map<pair<GLuint, array<GLuint, num_elements>>, GLuint> fbos;
340 };
341
342 template<size_t num_elements>
343 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_tex, const array<GLuint, num_elements> &textures)
344 {
345         auto key = make_pair(depth_tex, textures);
346
347         auto it = fbos.find(key);
348         if (it != fbos.end()) {
349                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
350                 return;
351         }
352
353         GLuint fbo;
354         glCreateFramebuffers(1, &fbo);
355         GLenum bufs[num_elements];
356         glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
357         for (size_t i = 0; i < num_elements; ++i) {
358                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
359                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
360         }
361         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
362
363         fbos[key] = fbo;
364         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
365 }
366
367 // Convert RGB to grayscale, using Rec. 709 coefficients.
368 class GrayscaleConversion {
369 public:
370         GrayscaleConversion();
371         void exec(GLint tex, GLint gray_tex, int width, int height);
372
373 private:
374         PersistentFBOSet<1> fbos;
375         GLuint gray_vs_obj;
376         GLuint gray_fs_obj;
377         GLuint gray_program;
378         GLuint gray_vao;
379
380         GLuint uniform_tex;
381 };
382
383 GrayscaleConversion::GrayscaleConversion()
384 {
385         gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
386         gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
387         gray_program = link_program(gray_vs_obj, gray_fs_obj);
388
389         // Set up the VAO containing all the required position/texcoord data.
390         glCreateVertexArrays(1, &gray_vao);
391         glBindVertexArray(gray_vao);
392
393         GLint position_attrib = glGetAttribLocation(gray_program, "position");
394         glEnableVertexArrayAttrib(gray_vao, position_attrib);
395         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
396
397         uniform_tex = glGetUniformLocation(gray_program, "tex");
398 }
399
400 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height)
401 {
402         glUseProgram(gray_program);
403         bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
404
405         glViewport(0, 0, width, height);
406         fbos.render_to(gray_tex);
407         glBindVertexArray(gray_vao);
408         glUseProgram(gray_program);
409         glDisable(GL_BLEND);
410         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
411 }
412
413 // Compute gradients in every point, used for the motion search.
414 // The DIS paper doesn't actually mention how these are computed,
415 // but seemingly, a 3x3 Sobel operator is used here (at least in
416 // later versions of the code), while a [1 -8 0 8 -1] kernel is
417 // used for all the derivatives in the variational refinement part
418 // (which borrows code from DeepFlow). This is inconsistent,
419 // but I guess we're better off with staying with the original
420 // decisions until we actually know having different ones would be better.
421 class Sobel {
422 public:
423         Sobel();
424         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
425
426 private:
427         PersistentFBOSet<1> fbos;
428         GLuint sobel_vs_obj;
429         GLuint sobel_fs_obj;
430         GLuint sobel_program;
431         GLuint sobel_vao;
432
433         GLuint uniform_tex;
434 };
435
436 Sobel::Sobel()
437 {
438         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
439         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
440         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
441
442         // Set up the VAO containing all the required position/texcoord data.
443         glCreateVertexArrays(1, &sobel_vao);
444         glBindVertexArray(sobel_vao);
445
446         GLint position_attrib = glGetAttribLocation(sobel_program, "position");
447         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
448         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
449
450         uniform_tex = glGetUniformLocation(sobel_program, "tex");
451 }
452
453 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
454 {
455         glUseProgram(sobel_program);
456         bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
457
458         glViewport(0, 0, level_width, level_height);
459         fbos.render_to(grad0_tex);
460         glBindVertexArray(sobel_vao);
461         glUseProgram(sobel_program);
462         glDisable(GL_BLEND);
463         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
464 }
465
466 // Motion search to find the initial flow. See motion_search.frag for documentation.
467 class MotionSearch {
468 public:
469         MotionSearch();
470         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);
471
472 private:
473         PersistentFBOSet<1> fbos;
474
475         GLuint motion_vs_obj;
476         GLuint motion_fs_obj;
477         GLuint motion_search_program;
478         GLuint motion_search_vao;
479
480         GLuint uniform_inv_image_size, uniform_inv_prev_level_size;
481         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
482 };
483
484 MotionSearch::MotionSearch()
485 {
486         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
487         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
488         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
489
490         // Set up the VAO containing all the required position/texcoord data.
491         glCreateVertexArrays(1, &motion_search_vao);
492         glBindVertexArray(motion_search_vao);
493         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
494
495         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
496         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
497         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
498
499         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
500         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
501         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
502         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
503         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
504         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
505 }
506
507 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)
508 {
509         glUseProgram(motion_search_program);
510
511         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
512         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
513         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
514         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
515
516         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
517         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
518
519         glViewport(0, 0, width_patches, height_patches);
520         fbos.render_to(flow_out_tex);
521         glBindVertexArray(motion_search_vao);
522         glUseProgram(motion_search_program);
523         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
524 }
525
526 // Do “densification”, ie., upsampling of the flow patches to the flow field
527 // (the same size as the image at this level). We draw one quad per patch
528 // over its entire covered area (using instancing in the vertex shader),
529 // and then weight the contributions in the pixel shader by post-warp difference.
530 // This is equation (3) in the paper.
531 //
532 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
533 // weight in the B channel. Dividing R and G by B gives the normalized values.
534 class Densify {
535 public:
536         Densify();
537         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);
538
539 private:
540         PersistentFBOSet<1> fbos;
541
542         GLuint densify_vs_obj;
543         GLuint densify_fs_obj;
544         GLuint densify_program;
545         GLuint densify_vao;
546
547         GLuint uniform_patch_size;
548         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
549 };
550
551 Densify::Densify()
552 {
553         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
554         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
555         densify_program = link_program(densify_vs_obj, densify_fs_obj);
556
557         // Set up the VAO containing all the required position/texcoord data.
558         glCreateVertexArrays(1, &densify_vao);
559         glBindVertexArray(densify_vao);
560         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
561
562         GLint position_attrib = glGetAttribLocation(densify_program, "position");
563         glEnableVertexArrayAttrib(densify_vao, position_attrib);
564         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
565
566         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
567         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
568         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
569         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
570 }
571
572 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)
573 {
574         glUseProgram(densify_program);
575
576         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
577         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
578         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
579
580         glProgramUniform2f(densify_program, uniform_patch_size,
581                 float(patch_size_pixels) / level_width,
582                 float(patch_size_pixels) / level_height);
583
584         glViewport(0, 0, level_width, level_height);
585         glEnable(GL_BLEND);
586         glBlendFunc(GL_ONE, GL_ONE);
587         glBindVertexArray(densify_vao);
588         fbos.render_to(dense_flow_tex);
589         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
590         glClear(GL_COLOR_BUFFER_BIT);
591         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
592 }
593
594 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
595 // I_0 and I_w. The prewarping is what enables us to solve the variational
596 // flow for du,dv instead of u,v.
597 //
598 // Also calculates the normalized flow, ie. divides by z (this is needed because
599 // Densify works by additive blending) and multiplies by the image size.
600 //
601 // See variational_refinement.txt for more information.
602 class Prewarp {
603 public:
604         Prewarp();
605         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);
606
607 private:
608         PersistentFBOSet<3> fbos;
609
610         GLuint prewarp_vs_obj;
611         GLuint prewarp_fs_obj;
612         GLuint prewarp_program;
613         GLuint prewarp_vao;
614
615         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
616 };
617
618 Prewarp::Prewarp()
619 {
620         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
621         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
622         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
623
624         // Set up the VAO containing all the required position/texcoord data.
625         glCreateVertexArrays(1, &prewarp_vao);
626         glBindVertexArray(prewarp_vao);
627         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
628
629         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
630         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
631         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
632
633         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
634         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
635         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
636 }
637
638 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)
639 {
640         glUseProgram(prewarp_program);
641
642         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
643         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
644         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
645
646         glViewport(0, 0, level_width, level_height);
647         glDisable(GL_BLEND);
648         glBindVertexArray(prewarp_vao);
649         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
650         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
651 }
652
653 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
654 // central difference filter, since apparently, that's tradition (I haven't
655 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
656 // The coefficients come from
657 //
658 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
659 //
660 // Also computes β_0, since it depends only on I_x and I_y.
661 class Derivatives {
662 public:
663         Derivatives();
664         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
665
666 private:
667         PersistentFBOSet<2> fbos;
668
669         GLuint derivatives_vs_obj;
670         GLuint derivatives_fs_obj;
671         GLuint derivatives_program;
672         GLuint derivatives_vao;
673
674         GLuint uniform_tex;
675 };
676
677 Derivatives::Derivatives()
678 {
679         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
680         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
681         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
682
683         // Set up the VAO containing all the required position/texcoord data.
684         glCreateVertexArrays(1, &derivatives_vao);
685         glBindVertexArray(derivatives_vao);
686         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
687
688         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
689         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
690         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
691
692         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
693 }
694
695 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
696 {
697         glUseProgram(derivatives_program);
698
699         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
700
701         glViewport(0, 0, level_width, level_height);
702         glDisable(GL_BLEND);
703         glBindVertexArray(derivatives_vao);
704         fbos.render_to(I_x_y_tex, beta_0_tex);
705         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
706 }
707
708 // Calculate the smoothness constraints between neighboring pixels;
709 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
710 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
711 // border color (0,0) later, so that there's zero diffusion out of
712 // the border.
713 //
714 // See variational_refinement.txt for more information.
715 class ComputeSmoothness {
716 public:
717         ComputeSmoothness();
718         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, bool zero_diff_flow);
719
720 private:
721         PersistentFBOSet<2> fbos;
722
723         GLuint smoothness_vs_obj;
724         GLuint smoothness_fs_obj;
725         GLuint smoothness_program;
726         GLuint smoothness_vao;
727
728         GLuint uniform_flow_tex, uniform_diff_flow_tex;
729         GLuint uniform_alpha, uniform_zero_diff_flow;
730 };
731
732 ComputeSmoothness::ComputeSmoothness()
733 {
734         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
735         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
736         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
737
738         // Set up the VAO containing all the required position/texcoord data.
739         glCreateVertexArrays(1, &smoothness_vao);
740         glBindVertexArray(smoothness_vao);
741         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
742
743         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
744         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
745         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
746
747         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
748         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
749         uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
750         uniform_zero_diff_flow = glGetUniformLocation(smoothness_program, "zero_diff_flow");
751 }
752
753 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, bool zero_diff_flow)
754 {
755         glUseProgram(smoothness_program);
756
757         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
758         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
759         glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
760         glProgramUniform1i(smoothness_program, uniform_zero_diff_flow, zero_diff_flow);
761
762         glViewport(0, 0, level_width, level_height);
763
764         glDisable(GL_BLEND);
765         glBindVertexArray(smoothness_vao);
766         fbos.render_to(smoothness_x_tex, smoothness_y_tex);
767         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
768
769         // Make sure the smoothness on the right and upper borders is zero.
770         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
771         // (we're sampling smoothness with all-zero border color), but we'd
772         // have to adjust the sampling coordinates, which is annoying.
773         glClearTexSubImage(smoothness_x_tex, 0,  level_width - 1, 0, 0,   1, level_height, 1,  GL_RED, GL_FLOAT, nullptr);
774         glClearTexSubImage(smoothness_y_tex, 0,  0, level_height - 1, 0,  level_width, 1, 1,   GL_RED, GL_FLOAT, nullptr);
775 }
776
777 // Set up the equations set (two equations in two unknowns, per pixel).
778 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
779 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
780 // floats. (Actually, we store the inverse of the diagonal elements, because
781 // we only ever need to divide by them.) This fits into four u32 values;
782 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
783 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
784 // terms that depend on other pixels, are calculated in one pass.
785 //
786 // See variational_refinement.txt for more information.
787 class SetupEquations {
788 public:
789         SetupEquations();
790         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, bool zero_diff_flow);
791
792 private:
793         PersistentFBOSet<1> fbos;
794
795         GLuint equations_vs_obj;
796         GLuint equations_fs_obj;
797         GLuint equations_program;
798         GLuint equations_vao;
799
800         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
801         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
802         GLuint uniform_beta_0_tex;
803         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
804         GLuint uniform_gamma, uniform_delta, uniform_zero_diff_flow;
805 };
806
807 SetupEquations::SetupEquations()
808 {
809         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
810         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
811         equations_program = link_program(equations_vs_obj, equations_fs_obj);
812
813         // Set up the VAO containing all the required position/texcoord data.
814         glCreateVertexArrays(1, &equations_vao);
815         glBindVertexArray(equations_vao);
816         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
817
818         GLint position_attrib = glGetAttribLocation(equations_program, "position");
819         glEnableVertexArrayAttrib(equations_vao, position_attrib);
820         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
821
822         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
823         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
824         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
825         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
826         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
827         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
828         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
829         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
830         uniform_delta = glGetUniformLocation(equations_program, "delta");
831         uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
832 }
833
834 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, bool zero_diff_flow)
835 {
836         glUseProgram(equations_program);
837
838         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
839         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
840         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
841         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
842         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
843         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
844         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
845         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
846         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
847         glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
848
849         glViewport(0, 0, level_width, level_height);
850         glDisable(GL_BLEND);
851         glBindVertexArray(equations_vao);
852         fbos.render_to(equation_tex);
853         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
854 }
855
856 // Actually solve the equation sets made by SetupEquations, by means of
857 // successive over-relaxation (SOR).
858 //
859 // See variational_refinement.txt for more information.
860 class SOR {
861 public:
862         SOR();
863         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, bool zero_diff_flow, ScopedTimer *sor_timer);
864
865 private:
866         PersistentFBOSet<1> fbos;
867
868         GLuint sor_vs_obj;
869         GLuint sor_fs_obj;
870         GLuint sor_program;
871         GLuint sor_vao;
872
873         GLuint uniform_diff_flow_tex;
874         GLuint uniform_equation_tex;
875         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
876         GLuint uniform_phase, uniform_zero_diff_flow;
877 };
878
879 SOR::SOR()
880 {
881         sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
882         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
883         sor_program = link_program(sor_vs_obj, sor_fs_obj);
884
885         // Set up the VAO containing all the required position/texcoord data.
886         glCreateVertexArrays(1, &sor_vao);
887         glBindVertexArray(sor_vao);
888         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
889
890         GLint position_attrib = glGetAttribLocation(sor_program, "position");
891         glEnableVertexArrayAttrib(sor_vao, position_attrib);
892         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
893
894         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
895         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
896         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
897         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
898         uniform_phase = glGetUniformLocation(sor_program, "phase");
899         uniform_zero_diff_flow = glGetUniformLocation(sor_program, "zero_diff_flow");
900 }
901
902 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, bool zero_diff_flow, ScopedTimer *sor_timer)
903 {
904         glUseProgram(sor_program);
905
906         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
907         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
908         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
909         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
910
911         glProgramUniform1i(sor_program, uniform_zero_diff_flow, zero_diff_flow);
912
913         // NOTE: We bind to the texture we are rendering from, but we never write any value
914         // that we read in the same shader pass (we call discard for red values when we compute
915         // black, and vice versa), and we have barriers between the passes, so we're fine
916         // as per the spec.
917         glViewport(0, 0, level_width, level_height);
918         glDisable(GL_BLEND);
919         glBindVertexArray(sor_vao);
920         fbos.render_to(diff_flow_tex);
921
922         for (int i = 0; i < num_iterations; ++i) {
923                 {
924                         ScopedTimer timer("Red pass", sor_timer);
925                         glProgramUniform1i(sor_program, uniform_phase, 0);
926                         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
927                         glTextureBarrier();
928                 }
929                 {
930                         ScopedTimer timer("Black pass", sor_timer);
931                         if (zero_diff_flow && i == 0) {
932                                 // Not zero anymore.
933                                 glProgramUniform1i(sor_program, uniform_zero_diff_flow, 0);
934                         }
935                         glProgramUniform1i(sor_program, uniform_phase, 1);
936                         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
937                         if (i != num_iterations - 1) {
938                                 glTextureBarrier();
939                         }
940                 }
941         }
942 }
943
944 // Simply add the differential flow found by the variational refinement to the base flow.
945 // The output is in base_flow_tex; we don't need to make a new texture.
946 class AddBaseFlow {
947 public:
948         AddBaseFlow();
949         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
950
951 private:
952         PersistentFBOSet<1> fbos;
953
954         GLuint add_flow_vs_obj;
955         GLuint add_flow_fs_obj;
956         GLuint add_flow_program;
957         GLuint add_flow_vao;
958
959         GLuint uniform_diff_flow_tex;
960 };
961
962 AddBaseFlow::AddBaseFlow()
963 {
964         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
965         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
966         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
967
968         // Set up the VAO containing all the required position/texcoord data.
969         glCreateVertexArrays(1, &add_flow_vao);
970         glBindVertexArray(add_flow_vao);
971         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
972
973         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
974         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
975         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
976
977         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
978 }
979
980 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
981 {
982         glUseProgram(add_flow_program);
983
984         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
985
986         glViewport(0, 0, level_width, level_height);
987         glEnable(GL_BLEND);
988         glBlendFunc(GL_ONE, GL_ONE);
989         glBindVertexArray(add_flow_vao);
990         fbos.render_to(base_flow_tex);
991
992         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
993 }
994
995 // Take a copy of the flow, bilinearly interpolated and scaled up.
996 class ResizeFlow {
997 public:
998         ResizeFlow();
999         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
1000
1001 private:
1002         PersistentFBOSet<1> fbos;
1003
1004         GLuint resize_flow_vs_obj;
1005         GLuint resize_flow_fs_obj;
1006         GLuint resize_flow_program;
1007         GLuint resize_flow_vao;
1008
1009         GLuint uniform_flow_tex;
1010         GLuint uniform_scale_factor;
1011 };
1012
1013 ResizeFlow::ResizeFlow()
1014 {
1015         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1016         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
1017         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
1018
1019         // Set up the VAO containing all the required position/texcoord data.
1020         glCreateVertexArrays(1, &resize_flow_vao);
1021         glBindVertexArray(resize_flow_vao);
1022         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1023
1024         GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
1025         glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
1026         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1027
1028         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
1029         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
1030 }
1031
1032 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
1033 {
1034         glUseProgram(resize_flow_program);
1035
1036         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
1037
1038         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
1039
1040         glViewport(0, 0, output_width, output_height);
1041         glDisable(GL_BLEND);
1042         glBindVertexArray(resize_flow_vao);
1043         fbos.render_to(out_tex);
1044
1045         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1046 }
1047
1048 class TexturePool {
1049 public:
1050         GLuint get_texture(GLenum format, GLuint width, GLuint height);
1051         void release_texture(GLuint tex_num);
1052
1053 private:
1054         struct Texture {
1055                 GLuint tex_num;
1056                 GLenum format;
1057                 GLuint width, height;
1058                 bool in_use = false;
1059         };
1060         vector<Texture> textures;
1061 };
1062
1063 class DISComputeFlow {
1064 public:
1065         DISComputeFlow(int width, int height);
1066
1067         enum ResizeStrategy {
1068                 DO_NOT_RESIZE_FLOW,
1069                 RESIZE_FLOW_TO_FULL_SIZE
1070         };
1071
1072         // Returns a texture that must be released with release_texture()
1073         // after use.
1074         GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
1075
1076         void release_texture(GLuint tex) {
1077                 pool.release_texture(tex);
1078         }
1079
1080 private:
1081         int width, height;
1082         GLuint initial_flow_tex;
1083         TexturePool pool;
1084
1085         // The various passes.
1086         Sobel sobel;
1087         MotionSearch motion_search;
1088         Densify densify;
1089         Prewarp prewarp;
1090         Derivatives derivatives;
1091         ComputeSmoothness compute_smoothness;
1092         SetupEquations setup_equations;
1093         SOR sor;
1094         AddBaseFlow add_base_flow;
1095         ResizeFlow resize_flow;
1096 };
1097
1098 DISComputeFlow::DISComputeFlow(int width, int height)
1099         : width(width), height(height)
1100 {
1101         // Make some samplers.
1102         glCreateSamplers(1, &nearest_sampler);
1103         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1104         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1105         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1106         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1107
1108         glCreateSamplers(1, &linear_sampler);
1109         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1110         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1111         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1112         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1113
1114         // The smoothness is sampled so that once we get to a smoothness involving
1115         // a value outside the border, the diffusivity between the two becomes zero.
1116         // Similarly, gradients are zero outside the border, since the edge is taken
1117         // to be constant.
1118         glCreateSamplers(1, &zero_border_sampler);
1119         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1120         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1121         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1122         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1123         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1124         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1125
1126         // Initial flow is zero, 1x1.
1127         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1128         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1129         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1130 }
1131
1132 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1133 {
1134         int prev_level_width = 1, prev_level_height = 1;
1135         GLuint prev_level_flow_tex = initial_flow_tex;
1136
1137         GPUTimers timers;
1138
1139         ScopedTimer total_timer("Total", &timers);
1140         for (int level = coarsest_level; level >= int(finest_level); --level) {
1141                 char timer_name[256];
1142                 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
1143                 ScopedTimer level_timer(timer_name, &total_timer);
1144
1145                 int level_width = width >> level;
1146                 int level_height = height >> level;
1147                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1148
1149                 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1150                 // and patch_spacing=3 (the default), we put out patch centers in
1151                 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1152                 // lock all the centers to integer coordinates if needed.
1153                 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1154                 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1155
1156                 // Make sure we always read from the correct level; the chosen
1157                 // mipmapping could otherwise be rather unpredictable, especially
1158                 // during motion search.
1159                 GLuint tex0_view, tex1_view;
1160                 glGenTextures(1, &tex0_view);
1161                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1162                 glGenTextures(1, &tex1_view);
1163                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1164
1165                 // Create a new texture; we could be fancy and render use a multi-level
1166                 // texture, but meh.
1167                 GLuint grad0_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1168
1169                 // Find the derivative.
1170                 {
1171                         ScopedTimer timer("Sobel", &level_timer);
1172                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1173                 }
1174
1175                 // Motion search to find the initial flow. We use the flow from the previous
1176                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1177
1178                 // Create an output flow texture.
1179                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1180
1181                 // And draw.
1182                 {
1183                         ScopedTimer timer("Motion search", &level_timer);
1184                         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);
1185                 }
1186                 pool.release_texture(grad0_tex);
1187
1188                 // Densification.
1189
1190                 // Set up an output texture (cleared in Densify).
1191                 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1192
1193                 // And draw.
1194                 {
1195                         ScopedTimer timer("Densification", &level_timer);
1196                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1197                 }
1198                 pool.release_texture(flow_out_tex);
1199
1200                 // Everything below here in the loop belongs to variational refinement.
1201                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1202
1203                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1204                 // have to normalize it over and over again, and also save some bandwidth).
1205                 //
1206                 // During the entire rest of the variational refinement, flow will be measured
1207                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1208                 // This is because variational refinement depends so heavily on derivatives,
1209                 // which are measured in intensity levels per pixel.
1210                 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1211                 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1212                 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1213                 {
1214                         ScopedTimer timer("Prewarping", &varref_timer);
1215                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1216                 }
1217                 pool.release_texture(dense_flow_tex);
1218                 glDeleteTextures(1, &tex0_view);
1219                 glDeleteTextures(1, &tex1_view);
1220
1221                 // Calculate I_x and I_y. We're only calculating first derivatives;
1222                 // the others will be taken on-the-fly in order to sample from fewer
1223                 // textures overall, since sampling from the L1 cache is cheap.
1224                 // (TODO: Verify that this is indeed faster than making separate
1225                 // double-derivative textures.)
1226                 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1227                 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1228                 {
1229                         ScopedTimer timer("First derivatives", &varref_timer);
1230                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1231                 }
1232                 pool.release_texture(I_tex);
1233
1234                 // We need somewhere to store du and dv (the flow increment, relative
1235                 // to the non-refined base flow u0 and v0). It's initially garbage,
1236                 // but not read until we've written something sane to it.
1237                 GLuint du_dv_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1238
1239                 // And for smoothness.
1240                 GLuint smoothness_x_tex = pool.get_texture(GL_R16F, level_width, level_height);
1241                 GLuint smoothness_y_tex = pool.get_texture(GL_R16F, level_width, level_height);
1242
1243                 // And finally for the equation set. See SetupEquations for
1244                 // the storage format.
1245                 GLuint equation_tex = pool.get_texture(GL_RGBA32UI, level_width, level_height);
1246
1247                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1248                         // Calculate the smoothness terms between the neighboring pixels,
1249                         // both in x and y direction.
1250                         {
1251                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1252                                 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, outer_idx == 0);
1253                         }
1254
1255                         // Set up the 2x2 equation system for each pixel.
1256                         {
1257                                 ScopedTimer timer("Set up equations", &varref_timer);
1258                                 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, outer_idx == 0);
1259                         }
1260
1261                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1262                         // Note that these are to/from the same texture.
1263                         {
1264                                 ScopedTimer timer("SOR", &varref_timer);
1265                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5, outer_idx == 0, &timer);
1266                         }
1267                 }
1268
1269                 pool.release_texture(I_t_tex);
1270                 pool.release_texture(I_x_y_tex);
1271                 pool.release_texture(beta_0_tex);
1272                 pool.release_texture(smoothness_x_tex);
1273                 pool.release_texture(smoothness_y_tex);
1274                 pool.release_texture(equation_tex);
1275
1276                 // Add the differential flow found by the variational refinement to the base flow,
1277                 // giving the final flow estimate for this level.
1278                 // The output is in diff_flow_tex; we don't need to make a new texture.
1279                 //
1280                 // Disabling this doesn't save any time (although we could easily make it so that
1281                 // it is more efficient), but it helps debug the motion search.
1282                 if (enable_variational_refinement) {
1283                         ScopedTimer timer("Add differential flow", &varref_timer);
1284                         add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1285                 }
1286                 pool.release_texture(du_dv_tex);
1287
1288                 if (prev_level_flow_tex != initial_flow_tex) {
1289                         pool.release_texture(prev_level_flow_tex);
1290                 }
1291                 prev_level_flow_tex = base_flow_tex;
1292                 prev_level_width = level_width;
1293                 prev_level_height = level_height;
1294         }
1295         total_timer.end();
1296
1297         timers.print();
1298
1299         // Scale up the flow to the final size (if needed).
1300         if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1301                 return prev_level_flow_tex;
1302         } else {
1303                 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1304                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1305                 pool.release_texture(prev_level_flow_tex);
1306                 return final_tex;
1307         }
1308 }
1309
1310 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1311 // radius fills most of the holes.
1312 class Splat {
1313 public:
1314         Splat();
1315
1316         // alpha is the time of the interpolated frame (0..1).
1317         void exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha);
1318
1319 private:
1320         PersistentFBOSetWithDepth<1> fbos;
1321
1322         GLuint splat_vs_obj;
1323         GLuint splat_fs_obj;
1324         GLuint splat_program;
1325         GLuint splat_vao;
1326
1327         GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1328         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1329         GLuint uniform_inv_flow_size;
1330 };
1331
1332 Splat::Splat()
1333 {
1334         splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1335         splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1336         splat_program = link_program(splat_vs_obj, splat_fs_obj);
1337
1338         // Set up the VAO containing all the required position/texcoord data.
1339         glCreateVertexArrays(1, &splat_vao);
1340         glBindVertexArray(splat_vao);
1341         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1342
1343         GLint position_attrib = glGetAttribLocation(splat_program, "position");
1344         glEnableVertexArrayAttrib(splat_vao, position_attrib);
1345         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1346
1347         uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1348         uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1349         uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1350         uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1351         uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1352         uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1353         uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1354 }
1355
1356 void Splat::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha)
1357 {
1358         glUseProgram(splat_program);
1359
1360         bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1361         bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1362
1363         // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1364         // Move to 2.0 later, or even 4.0.
1365         // (Since we have hole filling, it's not critical, but larger values seem to do
1366         // better than hole filling for large motion, blurs etc.)
1367         float splat_size = 1.0f;  // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1368         glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1369         glProgramUniform1f(splat_program, uniform_alpha, alpha);
1370         glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1371
1372         glViewport(0, 0, width, height);
1373         glDisable(GL_BLEND);
1374         glEnable(GL_DEPTH_TEST);
1375         glDepthFunc(GL_LESS);  // We store the difference between I_0 and I_1, where less difference is good. (Default 1.0 is effectively +inf, which always loses.)
1376         glBindVertexArray(splat_vao);
1377
1378         fbos.render_to(depth_tex, flow_tex);
1379
1380         // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
1381         // we've got it bound.
1382         glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f);  // Invalid flow.
1383         glClearDepth(1.0f);  // Effectively infinity.
1384         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
1385
1386         // Do forward splatting.
1387         bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1388         glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1389         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1390
1391         // Do backward splatting.
1392         bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1393         glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1394         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1395
1396         glDisable(GL_DEPTH_TEST);
1397 }
1398
1399 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
1400 // that's fairly simple (given that most holes are really small) and also hopefully
1401 // cheap should the holes not be so small. Conceptually, we look for the first
1402 // non-hole to the left of us (ie., shoot a ray until we hit something), then
1403 // the first non-hole to the right of us, then up and down, and then average them
1404 // all together. It's going to create “stars” if the holes are big, but OK, that's
1405 // a tradeoff.
1406 //
1407 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
1408 // on even for shaders that do discard (this typically kills early Z, but hopefully
1409 // not hierarchical Z); we set up Z so that only holes are written to, which means
1410 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
1411 // fullscreen quads should just be discarded outright, really.
1412 class HoleFill {
1413 public:
1414         HoleFill();
1415
1416         // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
1417         // from the down, left, right and up, respectively. Use HoleBlend to merge
1418         // them into one.
1419         void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1420
1421 private:
1422         PersistentFBOSetWithDepth<1> fbos;
1423
1424         GLuint fill_vs_obj;
1425         GLuint fill_fs_obj;
1426         GLuint fill_program;
1427         GLuint fill_vao;
1428
1429         GLuint uniform_tex;
1430         GLuint uniform_z, uniform_sample_offset;
1431 };
1432
1433 HoleFill::HoleFill()
1434 {
1435         fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
1436         fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
1437         fill_program = link_program(fill_vs_obj, fill_fs_obj);
1438
1439         // Set up the VAO containing all the required position/texcoord data.
1440         glCreateVertexArrays(1, &fill_vao);
1441         glBindVertexArray(fill_vao);
1442         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1443
1444         GLint position_attrib = glGetAttribLocation(fill_program, "position");
1445         glEnableVertexArrayAttrib(fill_vao, position_attrib);
1446         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1447
1448         uniform_tex = glGetUniformLocation(fill_program, "tex");
1449         uniform_z = glGetUniformLocation(fill_program, "z");
1450         uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
1451 }
1452
1453 void HoleFill::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1454 {
1455         glUseProgram(fill_program);
1456
1457         bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
1458
1459         glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
1460
1461         glViewport(0, 0, width, height);
1462         glDisable(GL_BLEND);
1463         glEnable(GL_DEPTH_TEST);
1464         glDepthFunc(GL_LESS);  // Only update the values > 0.999f (ie., only invalid pixels).
1465         glBindVertexArray(fill_vao);
1466
1467         fbos.render_to(depth_tex, flow_tex);  // NOTE: Reading and writing to the same texture.
1468
1469         // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
1470         for (int offs = 1; offs < width; offs *= 2) {
1471                 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
1472                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1473                 glTextureBarrier();
1474         }
1475         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1476
1477         // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
1478         // were overwritten in the last algorithm.
1479         glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
1480         for (int offs = 1; offs < width; offs *= 2) {
1481                 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
1482                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1483                 glTextureBarrier();
1484         }
1485         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1486
1487         // Up.
1488         glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
1489         for (int offs = 1; offs < height; offs *= 2) {
1490                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
1491                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1492                 glTextureBarrier();
1493         }
1494         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1495
1496         // Down.
1497         glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1498         for (int offs = 1; offs < height; offs *= 2) {
1499                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
1500                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1501                 glTextureBarrier();
1502         }
1503
1504         glDisable(GL_DEPTH_TEST);
1505 }
1506
1507 // Blend the four directions from HoleFill into one pixel, so that single-pixel
1508 // holes become the average of their four neighbors.
1509 class HoleBlend {
1510 public:
1511         HoleBlend();
1512
1513         void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1514
1515 private:
1516         PersistentFBOSetWithDepth<1> fbos;
1517
1518         GLuint blend_vs_obj;
1519         GLuint blend_fs_obj;
1520         GLuint blend_program;
1521         GLuint blend_vao;
1522
1523         GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
1524         GLuint uniform_z, uniform_sample_offset;
1525 };
1526
1527 HoleBlend::HoleBlend()
1528 {
1529         blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);  // Reuse the vertex shader from the fill.
1530         blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
1531         blend_program = link_program(blend_vs_obj, blend_fs_obj);
1532
1533         // Set up the VAO containing all the required position/texcoord data.
1534         glCreateVertexArrays(1, &blend_vao);
1535         glBindVertexArray(blend_vao);
1536         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1537
1538         GLint position_attrib = glGetAttribLocation(blend_program, "position");
1539         glEnableVertexArrayAttrib(blend_vao, position_attrib);
1540         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1541
1542         uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
1543         uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
1544         uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
1545         uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
1546         uniform_z = glGetUniformLocation(blend_program, "z");
1547         uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
1548 }
1549
1550 void HoleBlend::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1551 {
1552         glUseProgram(blend_program);
1553
1554         bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
1555         bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
1556         bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
1557         bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
1558
1559         glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1560         glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
1561
1562         glViewport(0, 0, width, height);
1563         glDisable(GL_BLEND);
1564         glEnable(GL_DEPTH_TEST);
1565         glDepthFunc(GL_LEQUAL);  // Skip over all of the pixels that were never holes to begin with.
1566         glBindVertexArray(blend_vao);
1567
1568         fbos.render_to(depth_tex, flow_tex);  // NOTE: Reading and writing to the same texture.
1569
1570         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1571
1572         glDisable(GL_DEPTH_TEST);
1573 }
1574
1575 class Blend {
1576 public:
1577         Blend();
1578         void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1579
1580 private:
1581         PersistentFBOSet<1> fbos;
1582         GLuint blend_vs_obj;
1583         GLuint blend_fs_obj;
1584         GLuint blend_program;
1585         GLuint blend_vao;
1586
1587         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1588         GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1589 };
1590
1591 Blend::Blend()
1592 {
1593         blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1594         blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1595         blend_program = link_program(blend_vs_obj, blend_fs_obj);
1596
1597         // Set up the VAO containing all the required position/texcoord data.
1598         glCreateVertexArrays(1, &blend_vao);
1599         glBindVertexArray(blend_vao);
1600
1601         GLint position_attrib = glGetAttribLocation(blend_program, "position");
1602         glEnableVertexArrayAttrib(blend_vao, position_attrib);
1603         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1604
1605         uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1606         uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1607         uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1608         uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1609         uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1610 }
1611
1612 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1613 {
1614         glUseProgram(blend_program);
1615         bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1616         bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1617         bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler);  // May be upsampled.
1618         glProgramUniform1f(blend_program, uniform_alpha, alpha);
1619         //glProgramUniform1f(blend_program, uniform_flow_consistency_tolerance, 1.0f / 
1620
1621         glViewport(0, 0, level_width, level_height);
1622         fbos.render_to(output_tex);
1623         glBindVertexArray(blend_vao);
1624         glUseProgram(blend_program);
1625         glDisable(GL_BLEND);  // A bit ironic, perhaps.
1626         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1627 }
1628
1629 class Interpolate {
1630 public:
1631         Interpolate(int width, int height, int flow_level);
1632
1633         // Returns a texture that must be released with release_texture()
1634         // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1635         // (unless flow_level == 0).
1636         GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1637
1638         void release_texture(GLuint tex) {
1639                 pool.release_texture(tex);
1640         }
1641
1642 private:
1643         int width, height, flow_level;
1644         TexturePool pool;
1645         Splat splat;
1646         HoleFill hole_fill;
1647         HoleBlend hole_blend;
1648         Blend blend;
1649 };
1650
1651 Interpolate::Interpolate(int width, int height, int flow_level)
1652         : width(width), height(height), flow_level(flow_level) {}
1653
1654 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1655 {
1656         GPUTimers timers;
1657
1658         ScopedTimer total_timer("Total", &timers);
1659
1660         // Pick out the right level to test splatting results on.
1661         GLuint tex0_view, tex1_view;
1662         glGenTextures(1, &tex0_view);
1663         glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1664         glGenTextures(1, &tex1_view);
1665         glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1666
1667         int flow_width = width >> flow_level;
1668         int flow_height = height >> flow_level;
1669
1670         GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1671         GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height);  // Used for ranking flows.
1672
1673         {
1674                 ScopedTimer timer("Splat", &total_timer);
1675                 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1676         }
1677         glDeleteTextures(1, &tex0_view);
1678         glDeleteTextures(1, &tex1_view);
1679
1680         GLuint temp_tex[3];
1681         temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1682         temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1683         temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1684
1685         {
1686                 ScopedTimer timer("Fill holes", &total_timer);
1687                 hole_fill.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1688                 hole_blend.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1689         }
1690
1691         pool.release_texture(temp_tex[0]);
1692         pool.release_texture(temp_tex[1]);
1693         pool.release_texture(temp_tex[2]);
1694         pool.release_texture(depth_tex);
1695
1696         GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1697         {
1698                 ScopedTimer timer("Blend", &total_timer);
1699                 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1700         }
1701         total_timer.end();
1702         timers.print();
1703
1704         return output_tex;
1705 }
1706
1707 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1708 {
1709         for (Texture &tex : textures) {
1710                 if (!tex.in_use && tex.format == format &&
1711                     tex.width == width && tex.height == height) {
1712                         tex.in_use = true;
1713                         return tex.tex_num;
1714                 }
1715         }
1716
1717         Texture tex;
1718         glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1719         glTextureStorage2D(tex.tex_num, 1, format, width, height);
1720         tex.format = format;
1721         tex.width = width;
1722         tex.height = height;
1723         tex.in_use = true;
1724         textures.push_back(tex);
1725         return tex.tex_num;
1726 }
1727
1728 void TexturePool::release_texture(GLuint tex_num)
1729 {
1730         for (Texture &tex : textures) {
1731                 if (tex.tex_num == tex_num) {
1732                         assert(tex.in_use);
1733                         tex.in_use = false;
1734                         return;
1735                 }
1736         }
1737         assert(false);
1738 }
1739
1740 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1741 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1742 {
1743         for (unsigned i = 0; i < width * height; ++i) {
1744                 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1745         }
1746 }
1747
1748 // Not relevant for RGB.
1749 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1750 {
1751 }
1752
1753 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1754 {
1755         FILE *flowfp = fopen(filename, "wb");
1756         fprintf(flowfp, "FEIH");
1757         fwrite(&width, 4, 1, flowfp);
1758         fwrite(&height, 4, 1, flowfp);
1759         for (unsigned y = 0; y < height; ++y) {
1760                 int yy = height - y - 1;
1761                 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1762         }
1763         fclose(flowfp);
1764 }
1765
1766 // Not relevant for RGB.
1767 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1768 {
1769         assert(false);
1770 }
1771
1772 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1773 {
1774         FILE *fp = fopen(filename, "wb");
1775         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1776         for (unsigned y = 0; y < unsigned(height); ++y) {
1777                 int yy = height - y - 1;
1778                 for (unsigned x = 0; x < unsigned(width); ++x) {
1779                         float du = dense_flow[(yy * width + x) * 2 + 0];
1780                         float dv = dense_flow[(yy * width + x) * 2 + 1];
1781
1782                         uint8_t r, g, b;
1783                         flow2rgb(du, dv, &r, &g, &b);
1784                         putc(r, fp);
1785                         putc(g, fp);
1786                         putc(b, fp);
1787                 }
1788         }
1789         fclose(fp);
1790 }
1791
1792 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1793 {
1794         unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1795
1796         FILE *fp = fopen(filename, "wb");
1797         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1798         for (unsigned y = 0; y < height; ++y) {
1799                 unsigned y2 = height - 1 - y;
1800                 for (size_t x = 0; x < width; ++x) {
1801                         memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1802                 }
1803                 fwrite(rgb_line.get(), width * 3, 1, fp);
1804         }
1805         fclose(fp);
1806 }
1807
1808 struct FlowType {
1809         using type = float;
1810         static constexpr GLenum gl_format = GL_RG;
1811         static constexpr GLenum gl_type = GL_FLOAT;
1812         static constexpr int num_channels = 2;
1813 };
1814
1815 struct RGBAType {
1816         using type = uint8_t;
1817         static constexpr GLenum gl_format = GL_RGBA;
1818         static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1819         static constexpr int num_channels = 4;
1820 };
1821
1822 template <class Type>
1823 void finish_one_read(GLuint width, GLuint height)
1824 {
1825         using T = typename Type::type;
1826         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1827
1828         assert(!reads_in_progress.empty());
1829         ReadInProgress read = reads_in_progress.front();
1830         reads_in_progress.pop_front();
1831
1832         unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1833         void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT);  // Blocks if the read isn't done yet.
1834         memcpy(flow.get(), buf, width * height * bytes_per_pixel);  // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1835         glUnmapNamedBuffer(read.pbo);
1836         spare_pbos.push(read.pbo);
1837
1838         flip_coordinate_system(flow.get(), width, height);
1839         if (!read.flow_filename.empty()) {
1840                 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1841                 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1842         }
1843         if (!read.ppm_filename.empty()) {
1844                 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1845         }
1846 }
1847
1848 template <class Type>
1849 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1850 {
1851         using T = typename Type::type;
1852         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1853
1854         if (spare_pbos.empty()) {
1855                 finish_one_read<Type>(width, height);
1856         }
1857         assert(!spare_pbos.empty());
1858         reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1859         glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1860         spare_pbos.pop();
1861         glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1862         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1863 }
1864
1865 void compute_flow_only(int argc, char **argv, int optind)
1866 {
1867         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1868         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1869         const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1870
1871         // Load pictures.
1872         unsigned width1, height1, width2, height2;
1873         GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1874         GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1875
1876         if (width1 != width2 || height1 != height2) {
1877                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1878                         width1, height1, width2, height2);
1879                 exit(1);
1880         }
1881
1882         // Set up some PBOs to do asynchronous readback.
1883         GLuint pbos[5];
1884         glCreateBuffers(5, pbos);
1885         for (int i = 0; i < 5; ++i) {
1886                 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1887                 spare_pbos.push(pbos[i]);
1888         }
1889
1890         int levels = find_num_levels(width1, height1);
1891         GLuint tex0_gray, tex1_gray;
1892         glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1893         glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1894         glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1895         glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1896
1897         GrayscaleConversion gray;
1898         gray.exec(tex0, tex0_gray, width1, height1);
1899         glDeleteTextures(1, &tex0);
1900         glGenerateTextureMipmap(tex0_gray);
1901
1902         gray.exec(tex1, tex1_gray, width1, height1);
1903         glDeleteTextures(1, &tex1);
1904         glGenerateTextureMipmap(tex1_gray);
1905
1906         DISComputeFlow compute_flow(width1, height1);
1907         GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1908
1909         schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1910         compute_flow.release_texture(final_tex);
1911
1912         // See if there are more flows on the command line (ie., more than three arguments),
1913         // and if so, process them.
1914         int num_flows = (argc - optind) / 3;
1915         for (int i = 1; i < num_flows; ++i) {
1916                 const char *filename0 = argv[optind + i * 3 + 0];
1917                 const char *filename1 = argv[optind + i * 3 + 1];
1918                 const char *flow_filename = argv[optind + i * 3 + 2];
1919                 GLuint width, height;
1920                 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1921                 if (width != width1 || height != height1) {
1922                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1923                                 filename0, width, height, width1, height1);
1924                         exit(1);
1925                 }
1926                 gray.exec(tex0, tex0_gray, width, height);
1927                 glGenerateTextureMipmap(tex0_gray);
1928                 glDeleteTextures(1, &tex0);
1929
1930                 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1931                 if (width != width1 || height != height1) {
1932                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1933                                 filename1, width, height, width1, height1);
1934                         exit(1);
1935                 }
1936                 gray.exec(tex1, tex1_gray, width, height);
1937                 glGenerateTextureMipmap(tex1_gray);
1938                 glDeleteTextures(1, &tex1);
1939
1940                 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1941
1942                 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1943                 compute_flow.release_texture(final_tex);
1944         }
1945         glDeleteTextures(1, &tex0_gray);
1946         glDeleteTextures(1, &tex1_gray);
1947
1948         while (!reads_in_progress.empty()) {
1949                 finish_one_read<FlowType>(width1, height1);
1950         }
1951 }
1952
1953 // Interpolate images based on
1954 //
1955 //   Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1956 //   Using Optical Flow”
1957 //
1958 // or at least a reasonable subset thereof. Unfinished.
1959 void interpolate_image(int argc, char **argv, int optind)
1960 {
1961         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1962         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1963         //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1964
1965         // Load pictures.
1966         unsigned width1, height1, width2, height2;
1967         GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1968         GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1969
1970         if (width1 != width2 || height1 != height2) {
1971                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1972                         width1, height1, width2, height2);
1973                 exit(1);
1974         }
1975
1976         // Set up some PBOs to do asynchronous readback.
1977         GLuint pbos[5];
1978         glCreateBuffers(5, pbos);
1979         for (int i = 0; i < 5; ++i) {
1980                 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
1981                 spare_pbos.push(pbos[i]);
1982         }
1983
1984         DISComputeFlow compute_flow(width1, height1);
1985         GrayscaleConversion gray;
1986         Interpolate interpolate(width1, height1, finest_level);
1987
1988         int levels = find_num_levels(width1, height1);
1989         GLuint tex0_gray, tex1_gray;
1990         glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1991         glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1992         glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1993         glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1994
1995         gray.exec(tex0, tex0_gray, width1, height1);
1996         glGenerateTextureMipmap(tex0_gray);
1997
1998         gray.exec(tex1, tex1_gray, width1, height1);
1999         glGenerateTextureMipmap(tex1_gray);
2000
2001         GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
2002         GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
2003
2004         for (int frameno = 1; frameno < 60; ++frameno) {
2005                 char ppm_filename[256];
2006                 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
2007
2008                 float alpha = frameno / 60.0f;
2009                 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
2010
2011                 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
2012                 interpolate.release_texture(interpolated_tex);
2013         }
2014
2015         while (!reads_in_progress.empty()) {
2016                 finish_one_read<RGBAType>(width1, height1);
2017         }
2018 }
2019
2020 int main(int argc, char **argv)
2021 {
2022         static const option long_options[] = {
2023                 { "smoothness-relative-weight", required_argument, 0, 's' },  // alpha.
2024                 { "intensity-relative-weight", required_argument, 0, 'i' },  // delta.
2025                 { "gradient-relative-weight", required_argument, 0, 'g' },  // gamma.
2026                 { "disable-timing", no_argument, 0, 1000 },
2027                 { "detailed-timing", no_argument, 0, 1003 },
2028                 { "ignore-variational-refinement", no_argument, 0, 1001 },  // Still calculates it, just doesn't apply it.
2029                 { "interpolate", no_argument, 0, 1002 }
2030         };
2031
2032         for ( ;; ) {
2033                 int option_index = 0;
2034                 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
2035
2036                 if (c == -1) {
2037                         break;
2038                 }
2039                 switch (c) {
2040                 case 's':
2041                         vr_alpha = atof(optarg);
2042                         break;
2043                 case 'i':
2044                         vr_delta = atof(optarg);
2045                         break;
2046                 case 'g':
2047                         vr_gamma = atof(optarg);
2048                         break;
2049                 case 1000:
2050                         enable_timing = false;
2051                         break;
2052                 case 1001:
2053                         enable_variational_refinement = false;
2054                         break;
2055                 case 1002:
2056                         enable_interpolation = true;
2057                         break;
2058                 case 1003:
2059                         detailed_timing = true;
2060                         break;
2061                 default:
2062                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
2063                         exit(1);
2064                 };
2065         }
2066
2067         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
2068                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
2069                 exit(1);
2070         }
2071         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
2072         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
2073         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
2074         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
2075
2076         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
2077         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
2078         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
2079         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
2080         window = SDL_CreateWindow("OpenGL window",
2081                 SDL_WINDOWPOS_UNDEFINED,
2082                 SDL_WINDOWPOS_UNDEFINED,
2083                 64, 64,
2084                 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
2085         SDL_GLContext context = SDL_GL_CreateContext(window);
2086         assert(context != nullptr);
2087
2088         glDisable(GL_DITHER);
2089
2090         // FIXME: Should be part of DISComputeFlow (but needs to be initialized
2091         // before all the render passes).
2092         float vertices[] = {
2093                 0.0f, 1.0f,
2094                 0.0f, 0.0f,
2095                 1.0f, 1.0f,
2096                 1.0f, 0.0f,
2097         };
2098         glCreateBuffers(1, &vertex_vbo);
2099         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
2100         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
2101
2102         if (enable_interpolation) {
2103                 interpolate_image(argc, argv, optind);
2104         } else {
2105                 compute_flow_only(argc, argv, optind);
2106         }
2107 }