在GLSL中外部定义预处理器宏

时间:2010-03-04 10:27:29

标签: opengl preprocessor glsl

GLSL有一个完整的C风格预处理器。唯一不起作用的是#include。其中一个很棒的功能是,您可以使用#ifdef注释掉函数,从而创建一个着色器,如果不使用某些特征,可以将其稀疏。

我的问题是:

有没有办法从C代码定义宏?

使用openGL接口似乎无法做到这一点。快速入侵是在代码加载表单文件之前使用#define FOO添加几行。但它似乎有点倒退。

2 个答案:

答案 0 :(得分:25)

您实际上不需要将其添加到您加载的代码中。这就是glShaderSourceARB API中有多个字符串的原因。

以下内容可以满足您的需求:

char *sources[2] = { "#define FOO\n", sourceFromFile };
glShaderSourceARB(shader, 2, sources, NULL);

答案 1 :(得分:8)

以下是我用来避免#version问题的方法。它是Java,并没有针对perfo进行优化,但它运行良好:

// extract shader sourcecode from file
StringBuilder shaderSource = Tools.readTextRessource(shaderSrcFile.url);

// apply defined values
int versionIndex = shaderSource.indexOf("#version");
if(versionIndex == -1) err("missing #version xxx in shader "+shaderSrcFile.name());
int defineInsertPoint = shaderSource.indexOf("\n", versionIndex)+1;

for (int i = defined.size() - 1; i >= 0; --i)
    shaderSource.insert(defineInsertPoint, "#define " + defined.get(i) + "\n");