This samples us how to apply Cg vertex shader in OpenGL. Shader is a kind of short c-like code that could run on the GPU. One the one hand, we could get much flexibility while rendering our-own visual effect. This will keep us away from hard understanding OpenGL render states settings. On the other hand, we could move some work form the CPU to GPU, this could be better for us balance the whole workload between CPU and GPU.
The Usage of CG Vertex Shader
The workflow to use cg vertex shader almost the same as GLSL or HLSL. Usually, the general steps as following:
1) Setup the shader context: check the supported version number, check whether video card support shader or not, create some container to hold all shaders and so on;
2) Compile the shader from source code;
3) Get the shader program from the compiled result;
4) Retrieve the shader parameters from shader program;
5) While rendering, bind or set shader program, and set the shader parameters;
6) Release shader program resource while shut down;
Set up Cg & Get the latest Vertex Profile
cgContext = cgCreateContext();
...
cgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
Compile the Cg shader Source code
cgGLSetOptimalOptions(cgVertexProfile); cgVertexProgram = cgCreateProgramFromFile(cgContext, CG_SOURCE, "CG/Wave.cg", cgVertexProfile, "main", 0);
Load the Shader Program & Retrieve the Shader Parameter
cgGLLoadProgram(cgVertexProgram); position = cgGetNamedParameter(cgVertexProgram, "IN.position");
Draw with Shader Program
cgGLEnableProfile(cgVertexProfile); // Bind Our Vertex Program To The Current State cgGLBindProgram(cgVertexProgram); cgGLSetParameter4f(color, 0.5f, 1.0f, 0.5f, 1.0f); // Submit verterx data here ... cgGLDisableProfile(cgVertexProfile);
Release Cg Shader Program
cgDestroyProgram(cgVertexProgram);
cgDestroyContext(cgContext);
The full source code could be found here.
本文详细介绍了如何在OpenGL中使用Cg顶点着色器,包括设置上下文、编译着色器、加载程序、获取参数、绘制及释放资源等步骤,展示了如何将工作负载从CPU转移到GPU,以实现更灵活的视觉效果渲染。

371

被折叠的 条评论
为什么被折叠?



