9 #include <SDL2/SDL_error.h>
10 #include <SDL2/SDL_events.h>
11 #include <SDL2/SDL_image.h>
12 #include <SDL2/SDL_keyboard.h>
13 #include <SDL2/SDL_mouse.h>
14 #include <SDL2/SDL_video.h>
22 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
26 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
27 constexpr float patch_overlap_ratio = 0.75f;
28 constexpr unsigned coarsest_level = 0;
29 constexpr unsigned finest_level = 0;
30 constexpr unsigned patch_size_pixels = 12;
32 string read_file(const string &filename)
34 FILE *fp = fopen(filename.c_str(), "r");
36 perror(filename.c_str());
40 int ret = fseek(fp, 0, SEEK_END);
42 perror("fseek(SEEK_END)");
48 ret = fseek(fp, 0, SEEK_SET);
50 perror("fseek(SEEK_SET)");
56 ret = fread(&str[0], size, 1, fp);
62 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
63 size, filename.c_str());
72 GLuint compile_shader(const string &shader_src, GLenum type)
74 GLuint obj = glCreateShader(type);
75 const GLchar* source[] = { shader_src.data() };
76 const GLint length[] = { (GLint)shader_src.size() };
77 glShaderSource(obj, 1, source, length);
80 GLchar info_log[4096];
81 GLsizei log_length = sizeof(info_log) - 1;
82 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
83 info_log[log_length] = 0;
84 if (strlen(info_log) > 0) {
85 fprintf(stderr, "Shader compile log: %s\n", info_log);
89 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
90 if (status == GL_FALSE) {
91 // Add some line numbers to easier identify compile errors.
92 string src_with_lines = "/* 1 */ ";
94 for (char ch : shader_src) {
95 src_with_lines.push_back(ch);
98 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
99 src_with_lines += buf;
103 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
111 GLuint load_texture(const char *filename, unsigned width, unsigned height)
113 FILE *fp = fopen(filename, "rb");
118 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
119 if (fread(pix.get(), width * height, 1, fp) != 1) {
120 fprintf(stderr, "Short read from %s\n", filename);
125 // Convert to bottom-left origin.
126 for (unsigned y = 0; y < height / 2; ++y) {
127 unsigned y2 = height - 1 - y;
128 swap_ranges(&pix[y * width], &pix[y * width + width], &pix[y2 * width]);
132 for (int w = width, h = height; w > 1 || h > 1; ) {
139 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
140 glTextureStorage2D(tex, levels, GL_R8, width, height);
141 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
142 glGenerateTextureMipmap(tex);
147 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
149 GLuint program = glCreateProgram();
150 glAttachShader(program, vs_obj);
151 glAttachShader(program, fs_obj);
152 glLinkProgram(program);
154 glGetProgramiv(program, GL_LINK_STATUS, &success);
155 if (success == GL_FALSE) {
156 GLchar error_log[1024] = {0};
157 glGetProgramInfoLog(program, 1024, nullptr, error_log);
158 fprintf(stderr, "Error linking program: %s\n", error_log);
164 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
167 glCreateBuffers(1, &vbo);
168 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
169 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
173 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
175 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
180 GLuint vbo = generate_vbo(size, data_size, data);
182 glBindBuffer(GL_ARRAY_BUFFER, vbo);
183 glEnableVertexArrayAttrib(vao, attrib);
184 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
185 glBindBuffer(GL_ARRAY_BUFFER, 0);
190 void bind_sampler(GLuint program, const char *uniform_name, GLuint texture_unit, GLuint tex, GLuint sampler)
192 GLint location = glGetUniformLocation(program, uniform_name);
193 if (location == -1) {
197 glBindTextureUnit(texture_unit, tex);
198 glBindSampler(texture_unit, sampler);
199 glProgramUniform1i(program, location, texture_unit);
204 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
205 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
208 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
209 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
210 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
211 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
213 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
214 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
215 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
216 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
217 SDL_Window *window = SDL_CreateWindow("OpenGL window",
218 SDL_WINDOWPOS_UNDEFINED,
219 SDL_WINDOWPOS_UNDEFINED,
222 SDL_GLContext context = SDL_GL_CreateContext(window);
223 assert(context != nullptr);
226 GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
227 GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
230 GLuint motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
231 GLuint motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
232 GLuint motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
234 GLuint sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
235 GLuint sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
236 GLuint sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
238 GLuint densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
239 GLuint densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
240 GLuint densify_program = link_program(densify_vs_obj, densify_fs_obj);
242 // Make some samplers.
243 GLuint nearest_sampler;
244 glCreateSamplers(1, &nearest_sampler);
245 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
246 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
247 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
248 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
250 GLuint linear_sampler;
251 glCreateSamplers(1, &linear_sampler);
252 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
253 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
254 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
255 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
257 GLuint mipmap_sampler;
258 glCreateSamplers(1, &mipmap_sampler);
259 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
260 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
261 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
262 glSamplerParameteri(mipmap_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
265 int level = coarsest_level;
266 int level_width = WIDTH >> level;
267 int level_height = HEIGHT >> level;
268 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
269 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
270 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
272 // Make sure we always read from the correct level; the chosen
273 // mipmapping could otherwise be rather unpredictable, especially
274 // during motion search.
275 GLuint tex0_view, tex1_view;
276 glGenTextures(1, &tex0_view);
277 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
278 glGenTextures(1, &tex1_view);
279 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
281 // Compute gradients in every point, used for the motion search.
282 // The DIS paper doesn't actually mention how these are computed,
283 // but seemingly, a 3x3 Sobel operator is used here (at least in
284 // later versions of the code), while a [1 -8 0 8 -1] kernel is
285 // used for all the derivatives in the variational refinement part
286 // (which borrows code from DeepFlow). This is inconsistent,
287 // but I guess we're better off with staying with the original
288 // decisions until we actually know having different ones would be better.
290 // Create a new texture; we could be fancy and render use a multi-level
293 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
294 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
297 glCreateFramebuffers(1, &grad0_fbo);
298 glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
300 glUseProgram(sobel_program);
301 glBindTextureUnit(0, tex0_view);
302 glBindSampler(0, nearest_sampler);
303 glProgramUniform1i(sobel_program, glGetUniformLocation(sobel_program, "tex"), 0);
304 glProgramUniform1f(sobel_program, glGetUniformLocation(sobel_program, "inv_width"), 1.0f / level_width);
305 glProgramUniform1f(sobel_program, glGetUniformLocation(sobel_program, "inv_height"), 1.0f / level_height);
307 // Set up the VAO containing all the required position/texcoord data.
309 glCreateVertexArrays(1, &sobel_vao);
310 glBindVertexArray(sobel_vao);
318 glCreateBuffers(1, &vertex_vbo);
319 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
320 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
322 int position_attrib = glGetAttribLocation(sobel_program, "position");
323 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
324 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
326 int texcoord_attrib = glGetAttribLocation(sobel_program, "texcoord");
327 glEnableVertexArrayAttrib(sobel_vao, texcoord_attrib);
328 glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
330 glBindBuffer(GL_ARRAY_BUFFER, 0);
333 glViewport(0, 0, level_width, level_height);
334 glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
335 glUseProgram(sobel_program);
337 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
339 // Motion search to find the initial flow.
341 // Create a flow texture, initialized to zero.
343 glCreateTextures(GL_TEXTURE_2D, 1, &flow_tex);
344 glTextureStorage2D(flow_tex, 1, GL_RG16F, width_patches, height_patches);
346 // And an output flow texture. (Well, we could have used texture barriers,
347 // but I don't feel lucky today.)
349 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
350 glTextureStorage2D(flow_out_tex, 1, GL_RG16F, width_patches, height_patches);
353 glCreateFramebuffers(1, &flow_fbo);
354 glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
356 glUseProgram(motion_search_program);
358 bind_sampler(motion_search_program, "image0_tex", 0, tex0_view, nearest_sampler);
359 bind_sampler(motion_search_program, "image1_tex", 1, tex1_view, linear_sampler);
360 bind_sampler(motion_search_program, "grad0_tex", 2, grad0_tex, nearest_sampler);
361 bind_sampler(motion_search_program, "flow_tex", 3, flow_tex, nearest_sampler);
363 glProgramUniform1f(motion_search_program, glGetUniformLocation(motion_search_program, "image_width"), level_width);
364 glProgramUniform1f(motion_search_program, glGetUniformLocation(motion_search_program, "image_height"), level_height);
365 glProgramUniform1f(motion_search_program, glGetUniformLocation(motion_search_program, "inv_image_width"), 1.0f / level_width);
366 glProgramUniform1f(motion_search_program, glGetUniformLocation(motion_search_program, "inv_image_height"), 1.0f / level_height);
368 // printf("%d x %d patches on this level\n", width_patches, height_patches);
370 // Set up the VAO containing all the required position/texcoord data.
371 GLuint motion_search_vao;
372 glCreateVertexArrays(1, &motion_search_vao);
373 glBindVertexArray(motion_search_vao);
374 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
376 position_attrib = glGetAttribLocation(motion_search_program, "position");
377 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
378 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
380 texcoord_attrib = glGetAttribLocation(motion_search_program, "texcoord");
381 glEnableVertexArrayAttrib(motion_search_vao, texcoord_attrib);
382 glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
384 glBindBuffer(GL_ARRAY_BUFFER, 0);
387 glViewport(0, 0, width_patches, height_patches);
388 glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
389 glUseProgram(motion_search_program);
390 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
392 // Do “densification”, ie., upsampling of the flow patches to the flow field
393 // (the same size as the image at this level). We draw one quad per patch
394 // over its entire covered area (using instancing in the vertex shader),
395 // and then weight the contributions in the pixel shader by post-warp difference.
396 // This is equation (3) in the paper.
398 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
399 // weight in the B channel. Dividing R and G by B gives the normalized values.
401 // Set up an output texture.
402 GLuint dense_flow_tex;
403 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
404 //glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
405 glTextureStorage2D(dense_flow_tex, 1, GL_RGBA32F, level_width, level_height);
407 GLuint dense_flow_fbo;
408 glCreateFramebuffers(1, &dense_flow_fbo);
409 glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
411 glUseProgram(densify_program);
413 bind_sampler(densify_program, "image0_tex", 0, tex0_view, nearest_sampler);
414 bind_sampler(densify_program, "image1_tex", 1, tex1_view, linear_sampler);
415 bind_sampler(densify_program, "flow_tex", 2, flow_out_tex, nearest_sampler);
417 glProgramUniform1i(densify_program, glGetUniformLocation(densify_program, "width_patches"), width_patches);
418 glProgramUniform2f(densify_program, glGetUniformLocation(densify_program, "patch_size"),
419 float(patch_size_pixels) / level_width,
420 float(patch_size_pixels) / level_height);
422 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
423 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
424 glProgramUniform2f(densify_program, glGetUniformLocation(densify_program, "patch_spacing"),
425 patch_spacing_x / level_width,
426 patch_spacing_y / level_height);
428 // Set up the VAO containing all the required position/texcoord data.
430 glCreateVertexArrays(1, &densify_vao);
431 glBindVertexArray(densify_vao);
432 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
434 position_attrib = glGetAttribLocation(densify_program, "position");
435 glEnableVertexArrayAttrib(densify_vao, position_attrib);
436 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
438 glBindBuffer(GL_ARRAY_BUFFER, 0);
441 glViewport(0, 0, level_width, level_height);
443 glBlendFunc(GL_ONE, GL_ONE);
444 glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
445 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
447 // TODO: Variational refinement.
449 unique_ptr<float[]> dense_flow(new float[level_width * level_height * 3]);
450 glGetTextureImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, level_width * level_height * 3 * sizeof(float), dense_flow.get());
452 FILE *fp = fopen("flow.ppm", "wb");
453 fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
454 for (unsigned y = 0; y < level_height; ++y) {
455 int yy = level_height - y - 1;
456 for (unsigned x = 0; x < level_width; ++x) {
457 float du = dense_flow[(yy * level_width + x) * 3 + 0];
458 float dv = dense_flow[(yy * level_width + x) * 3 + 1];
459 float w = dense_flow[(yy * level_width + x) * 3 + 2];
464 float angle = atan2(dv * level_width, du * level_height);
465 float magnitude = min(hypot(du * level_width, dv * level_height) / 20.0, 1.0);
467 // HSV to RGB (from Wikipedia). Saturation is 1.
469 float h = (angle + M_PI) * 6.0 / (2.0 * M_PI);
470 float X = c * (1.0 - fabs(fmod(h, 2.0) - 1.0));
471 float r = 0.0f, g = 0.0f, b = 0.0f;
474 } else if (h < 2.0f) {
476 } else if (h < 3.0f) {
478 } else if (h < 4.0f) {
480 } else if (h < 5.0f) {
482 } else if (h < 6.0f) {
485 // h is NaN, so black is fine.
487 float m = magnitude - c;
488 r += m; g += m; b += m;
489 r = max(min(r, 1.0f), 0.0f);
490 g = max(min(g, 1.0f), 0.0f);
491 b = max(min(b, 1.0f), 0.0f);
492 putc(lrintf(r * 255.0f), fp);
493 putc(lrintf(g * 255.0f), fp);
494 putc(lrintf(b * 255.0f), fp);
499 fprintf(stderr, "err = %d\n", glGetError());