]> git.sesse.net Git - nageru/blob - vu_common.cpp
Some refactoring of common VU functions.
[nageru] / vu_common.cpp
1 #include "vu_common.h"
2 #include <math.h>
3 #include <algorithm>
4
5 using namespace std;
6
7 int lufs_to_pos(float level_lu, int height)
8 {       
9         const float min_level = 9.0f;    // y=0 is top of screen, so “min” is the loudest level.
10         const float max_level = -18.0f;
11
12         // Handle -inf.
13         if (level_lu < max_level) {
14                 return height - 1;
15         }
16
17         int y = lrintf(height * (level_lu - min_level) / (max_level - min_level));
18         y = std::max(y, 0);
19         y = std::min(y, height - 1);
20         return y;
21 }
22
23 void draw_vu_meter(QPainter &painter, float level_lu, int width, int height, int margin)
24 {
25         painter.fillRect(margin, 0, width - 2 * margin, height, Qt::black);
26
27         // TODO: QLinearGradient is not gamma-correct; we might want to correct for that.
28         QLinearGradient on(0, 0, 0, height);
29         on.setColorAt(0.0f, QColor(255, 0, 0));
30         on.setColorAt(0.5f, QColor(255, 255, 0));
31         on.setColorAt(1.0f, QColor(0, 255, 0));
32         QColor off(80, 80, 80);
33
34         int y = lufs_to_pos(level_lu, height);
35
36         // Draw bars colored up until the level, then gray from there.
37         for (int level = -18; level < 9; ++level) {
38                 int min_y = lufs_to_pos(level + 1.0f, height) + 1;
39                 int max_y = lufs_to_pos(level, height) - 1;
40
41                 if (y > max_y) {
42                         painter.fillRect(margin, min_y, width - 2 * margin, max_y - min_y, off);
43                 } else if (y < min_y) {
44                         painter.fillRect(margin, min_y, width - 2 * margin, max_y - min_y, on);
45                 } else {
46                         painter.fillRect(margin, min_y, width - 2 * margin, y - min_y, off);
47                         painter.fillRect(margin, y, width - 2 * margin, max_y - y, on);
48                 }
49         }
50 }