c - OpenGL 背景颜色渐变器

标签 c opengl

我如何使用 C 和 OpenGL 实现一个例程,使背景颜色从一种颜色很好地过渡到另一种颜色,然后再返回,重复?我调色板中的所有颜色都具有 3 位精度。从 0.000 到 1.000。让颜色分量以统一的时间到达第二种颜色变得很复杂,更不用说调整过渡速度了。我现在可以保持在 0.001。

最佳答案

在 genpfault 的回答中回答你的问题:

glm::mix(以及 GLSL 的)基本上就是做 linear interpolation .在代码中可能意味着类似的东西

struct Color
{
    float r, g, b;
};

Color lerp(Color a, Color b, float t)
{
    Color c;
    c.r = (1-t)*a.r + t*b.r;
    c.g = (1-t)*a.g + t*b.g;
    c.b = (1-t)*a.b + t*b.b;

    return c;
}

现在,用于返回一些来回效果的常用函数是 cosine function .

余弦给你一个介于 -1 和 1 之间的值,所以你可能想在 0 和 1 之间缩放它。这可以使用

float t = cos(x) * 0.5 + 0.5; // *0.5 gets to [-0.5, 0.5], +0.5 gets to [0,1]

然后您使用此 t 来计算您的颜色。 x 可以是当前时间乘以某个有助于控制插值速度的值。

编辑: 使用 gpenfault 的代码作为起点,你可以做这种事情(如果它造成任何问题我将其删除):

// g++ main.cpp -lglut -lGL
#include <GL/glut.h>
#include <cmath>

int dstTime = 0; // milliseconds

struct Color
{
    float r, g, b;
};

Color makeColor(float r, float g, float b)
{
    Color c = { r, g, b };
    return c;
};

Color lerp(Color a, Color b, float t)
{
    Color c;
    c.r = (1-t)*a.r + t*b.r;
    c.g = (1-t)*a.g + t*b.g;
    c.b = (1-t)*a.b + t*b.b;

    return c;
}

void display()
{
    const int curTime = glutGet( GLUT_ELAPSED_TIME );

    // figure out how far along duration we are, between 0.0 and 1.0
    const float t = std::cos(float(curTime) * 0.001) * 0.5 + 0.5;

    // interpolate between two colors
    Color curColor = lerp(makeColor(0.0, 0.0, 0.0), makeColor(1.0, 1.0, 1.0), t);

    glClearColor( curColor.r, curColor.g, curColor.b, 1 );
    glClear( GL_COLOR_BUFFER_BIT );
    glutSwapBuffers();
}

void timer( int value )
{
    glutPostRedisplay();
    glutTimerFunc( 16, timer, 0 );
}

int main( int argc, char** argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
    glutInitWindowSize( 400,400 );
    glutCreateWindow( "GLUT" );
    glutDisplayFunc( display );
    glutTimerFunc( 0, timer, 0 );
    glutMainLoop();
    return 0;
}

关于c - OpenGL 背景颜色渐变器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40316082/

相关文章:

c - 为什么以及在何种意义上 pthread_t 是不透明类型?

ios - 无法从我声明它的 'if' block 之后返回变量

c - 当计算机休眠时让 LaunchAgent 休眠

wpf - DirectX 和 WPF

c - 在64位机器上处理文件但在32位机器上开发

c# - 微 Controller ,哪种语言更可取?高层或 assembly

java - 在同一表面上映射多个纹理

opengl - 在 OpenGL 中,有没有办法获取着色器程序使用的所有制服和属性的列表?

c++ - stb_png_to_mem的参数是什么意思?

c++ - SetPixelFormat 返回 0 错误代码 3221684230 (C0070006)