]> git.sesse.net Git - movit/blob - util.cpp
675b25b4940c3d9a9048d3d4488220340b31817b
[movit] / util.cpp
1 #include <epoxy/gl.h>
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <locale>
8 #include <sstream>
9 #include <string>
10 #include <Eigen/Core>
11
12 #include "fp16.h"
13 #include "init.h"
14 #include "util.h"
15
16 #if defined(__APPLE__)
17 #include <OpenGL/OpenGL.h>
18 #elif defined(WIN32)
19 #include <epoxy/wgl.h>
20 #else
21 #include <epoxy/glx.h>
22 #include <epoxy/egl.h>
23 #endif
24
25 using namespace std;
26
27 namespace movit {
28
29 extern string *movit_data_directory;
30
31 void hsv2rgb(float h, float s, float v, float *r, float *g, float *b)
32 {
33         if (h < 0.0f) {
34                 h += 2.0f * M_PI;
35         }
36         float c = v * s;
37         float hp = (h * 180.0 / M_PI) / 60.0;
38         float x = c * (1 - fabs(fmod(hp, 2.0f) - 1.0f));
39
40         if (hp >= 0 && hp < 1) {
41                 *r = c;
42                 *g = x;
43                 *b = 0.0f;
44         } else if (hp >= 1 && hp < 2) {
45                 *r = x;
46                 *g = c;
47                 *b = 0.0f;
48         } else if (hp >= 2 && hp < 3) {
49                 *r = 0.0f;
50                 *g = c;
51                 *b = x;
52         } else if (hp >= 3 && hp < 4) {
53                 *r = 0.0f;
54                 *g = x;
55                 *b = c;
56         } else if (hp >= 4 && hp < 5) {
57                 *r = x;
58                 *g = 0.0f;
59                 *b = c;
60         } else {
61                 *r = c;
62                 *g = 0.0f;
63                 *b = x;
64         }
65
66         float m = v - c;
67         *r += m;
68         *g += m;
69         *b += m;
70 }
71
72 void hsv2rgb_normalized(float h, float s, float v, float *r, float *g, float *b)
73 {
74         float ref_r, ref_g, ref_b;
75         hsv2rgb(h, s, v, r, g, b);
76         hsv2rgb(h, 0.0f, v, &ref_r, &ref_g, &ref_b);
77         float lum = 0.2126 * *r + 0.7152 * *g + 0.0722 * *b;
78         float ref_lum = 0.2126 * ref_r + 0.7152 * ref_g + 0.0722 * ref_b;
79         if (lum > 1e-3) {
80                 float fac = ref_lum / lum;
81                 *r *= fac;
82                 *g *= fac;
83                 *b *= fac;
84         }
85 }
86
87 string read_file(const string &filename)
88 {
89         const string full_pathname = *movit_data_directory + "/" + filename;
90
91         FILE *fp = fopen(full_pathname.c_str(), "r");
92         if (fp == NULL) {
93                 perror(full_pathname.c_str());
94                 exit(1);
95         }
96
97         int ret = fseek(fp, 0, SEEK_END);
98         if (ret == -1) {
99                 perror("fseek(SEEK_END)");
100                 exit(1);
101         }
102
103         int size = ftell(fp);
104
105         ret = fseek(fp, 0, SEEK_SET);
106         if (ret == -1) {
107                 perror("fseek(SEEK_SET)");
108                 exit(1);
109         }
110
111         string str;
112         str.resize(size);
113         ret = fread(&str[0], size, 1, fp);
114         if (ret == -1) {
115                 perror("fread");
116                 exit(1);
117         }
118         if (ret == 0) {
119                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
120                         size, full_pathname.c_str());
121                 exit(1);
122         }
123         fclose(fp);
124
125         return str;
126 }
127
128 string read_version_dependent_file(const string &base, const string &extension)
129 {
130         if (movit_shader_model == MOVIT_GLSL_130_AS_110) {
131                 string contents = read_file(base + ".130." + extension);
132                 assert(contents.find("#version 130") == 0);
133                 contents[10] = '1';  // Change from 130 to 110.
134                 return contents;
135         } else if (movit_shader_model == MOVIT_GLSL_130) {
136                 return read_file(base + ".130." + extension);
137         } else if (movit_shader_model == MOVIT_GLSL_150) {
138                 return read_file(base + ".150." + extension);
139         } else if (movit_shader_model == MOVIT_ESSL_300) {
140                 return read_file(base + ".300es." + extension);
141         } else {
142                 assert(false);
143         }
144 }
145
146 GLuint compile_shader(const string &shader_src, GLenum type)
147 {
148         GLuint obj = glCreateShader(type);
149         const GLchar* source[] = { shader_src.data() };
150         const GLint length[] = { (GLint)shader_src.size() };
151         glShaderSource(obj, 1, source, length);
152         glCompileShader(obj);
153
154         GLchar info_log[4096];
155         GLsizei log_length = sizeof(info_log) - 1;
156         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
157         info_log[log_length] = 0; 
158         if (strlen(info_log) > 0) {
159                 fprintf(stderr, "Shader compile log: %s\n", info_log);
160         }
161
162         GLint status;
163         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
164         if (status == GL_FALSE) {
165                 fprintf(stderr, "Failed to compile shader: %s\n", shader_src.c_str());
166                 exit(1);
167         }
168
169         return obj;
170 }
171
172 void print_3x3_matrix(const Eigen::Matrix3d& m)
173 {
174         printf("%6.4f %6.4f %6.4f\n", m(0,0), m(0,1), m(0,2));
175         printf("%6.4f %6.4f %6.4f\n", m(1,0), m(1,1), m(1,2));
176         printf("%6.4f %6.4f %6.4f\n", m(2,0), m(2,1), m(2,2));
177         printf("\n");
178 }
179
180 string output_glsl_mat3(const string &name, const Eigen::Matrix3d &m)
181 {
182         // Use stringstream to be independent of the current locale in a thread-safe manner.
183         stringstream ss;
184         ss.imbue(locale("C"));
185         ss.precision(8);
186         ss << scientific;
187         ss << "const mat3 " << name << " = mat3(\n";
188         ss << "    " << m(0,0) << ", " << m(1,0) << ", " << m(2,0) << ",\n";
189         ss << "    " << m(0,1) << ", " << m(1,1) << ", " << m(2,1) << ",\n";
190         ss << "    " << m(0,2) << ", " << m(1,2) << ", " << m(2,2) << ");\n\n";
191         return ss.str();
192 }
193
194 string output_glsl_float(const string &name, float x)
195 {
196         // Use stringstream to be independent of the current locale in a thread-safe manner.
197         stringstream ss;
198         ss.imbue(locale("C"));
199         ss.precision(8);
200         ss << scientific;
201         ss << "const float " << name << " = " << x << ";\n";
202         return ss.str();
203 }
204
205 string output_glsl_vec2(const string &name, float x, float y)
206 {
207         // Use stringstream to be independent of the current locale in a thread-safe manner.
208         stringstream ss;
209         ss.imbue(locale("C"));
210         ss.precision(8);
211         ss << scientific;
212         ss << "const vec2 " << name << " = vec2(" << x << ", " << y << ");\n";
213         return ss.str();
214 }
215
216 string output_glsl_vec3(const string &name, float x, float y, float z)
217 {
218         // Use stringstream to be independent of the current locale in a thread-safe manner.
219         stringstream ss;
220         ss.imbue(locale("C"));
221         ss.precision(8);
222         ss << scientific;
223         ss << "const vec3 " << name << " = vec3(" << x << ", " << y << ", " << z << ");\n";
224         return ss.str();
225 }
226
227 template<class DestFloat>
228 void combine_two_samples(float w1, float w2, float pos1, float pos2, float num_subtexels, float inv_num_subtexels,
229                          DestFloat *offset, DestFloat *total_weight, float *sum_sq_error)
230 {
231         assert(movit_initialized);
232         assert(w1 * w2 >= 0.0f);  // Should not have differing signs.
233         float z;  // Normalized 0..1 between pos1 and pos2.
234         if (fabs(w1 + w2) < 1e-6) {
235                 z = 0.5f;
236         } else {
237                 z = w2 / (w1 + w2);
238         }
239
240         // Round to the desired precision. Note that this might take z outside the 0..1 range.
241         *offset = from_fp64<DestFloat>(pos1 + z * (pos2 - pos1));
242         z = (to_fp64(*offset) - pos1) / (pos2 - pos1);
243
244         // Round to the minimum number of bits we have measured earlier.
245         // The card will do this for us anyway, but if we know what the real z
246         // is, we can pick a better total_weight below.
247         z = lrintf(z * num_subtexels) * inv_num_subtexels;
248         
249         // Choose total weight w so that we minimize total squared error
250         // for the effective weights:
251         //
252         //   e = (w(1-z) - a)² + (wz - b)²
253         //
254         // Differentiating by w and setting equal to zero:
255         //
256         //   2(w(1-z) - a)(1-z) + 2(wz - b)z = 0
257         //   w(1-z)² - a(1-z) + wz² - bz = 0
258         //   w((1-z)² + z²) = a(1-z) + bz
259         //   w = (a(1-z) + bz) / ((1-z)² + z²)
260         //
261         // If z had infinite precision, this would simply reduce to w = w1 + w2.
262         *total_weight = from_fp64<DestFloat>((w1 + z * (w2 - w1)) / (z * z + (1 - z) * (1 - z)));
263
264         if (sum_sq_error != NULL) {
265                 float err1 = to_fp64(*total_weight) * (1 - z) - w1;
266                 float err2 = to_fp64(*total_weight) * z - w2;
267                 *sum_sq_error = err1 * err1 + err2 * err2;
268         }
269 }
270
271 // Explicit instantiations.
272 template
273 void combine_two_samples<float>(float w1, float w2, float pos1, float pos2, float num_subtexels, float inv_num_subtexels,
274                                 float *offset, float *total_weight, float *sum_sq_error);
275
276 template
277 void combine_two_samples<fp16_int_t>(float w1, float w2, float pos1, float pos2, float num_subtexels, float inv_num_subtexels,
278                                      fp16_int_t *offset, fp16_int_t *total_weight, float *sum_sq_error);
279
280 GLuint fill_vertex_attribute(GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
281 {
282         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
283         if (attrib == -1) {
284                 return -1;
285         }
286
287         GLuint vbo;
288         glGenBuffers(1, &vbo);
289         check_error();
290         glBindBuffer(GL_ARRAY_BUFFER, vbo);
291         check_error();
292         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
293         check_error();
294         glEnableVertexAttribArray(attrib);
295         check_error();
296         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
297         check_error();
298         glBindBuffer(GL_ARRAY_BUFFER, 0);
299         check_error();
300
301         return vbo;
302 }
303
304 void cleanup_vertex_attribute(GLuint glsl_program_num, const string &attribute_name, GLuint vbo)
305 {
306         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
307         if (attrib == -1) {
308                 return;
309         }
310
311         glDisableVertexAttribArray(attrib);
312         check_error();
313         glDeleteBuffers(1, &vbo);
314         check_error();
315 }
316
317 unsigned div_round_up(unsigned a, unsigned b)
318 {
319         return (a + b - 1) / b;
320 }
321
322 // Algorithm from http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2.
323 unsigned next_power_of_two(unsigned v)
324 {
325         v--;
326         v |= v >> 1;
327         v |= v >> 2;
328         v |= v >> 4;
329         v |= v >> 8;
330         v |= v >> 16;
331         v++;
332         return v;
333 }
334
335 void *get_gl_context_identifier()
336 {
337 #if defined(__APPLE__)
338         return (void *)CGLGetCurrentContext();
339 #elif defined(WIN32)
340         return (void *)wglGetCurrentContext();
341 #else
342         void *ret = (void *)eglGetCurrentContext();
343         if (ret != NULL) {
344                 return ret;
345         }
346         return (void *)glXGetCurrentContext();
347 #endif
348 }
349
350 }  // namespace movit