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