Friday, October 23, 2015

opengl - GLSL to Cg fragment shader


I have found very useful resource on the Swiftless website on OpenGL.



Unfortunately, I cannot manage to adapt a GLSL fragment shader to my project, which uses Cg. Here it is:


uniform sampler2D color_texture;  
uniform sampler2D normal_texture;

void main() {

// Extract the normal from the normal map
vec3 normal = normalize(texture2D(normal_texture, gl_TexCoord[0].st).rgb * 2.0 - 1.0);

// Determine where the light is positioned (this can be set however you like)

vec3 light_pos = normalize(vec3(1.0, 1.0, 1.5));

// Calculate the lighting diffuse value
float diffuse = max(dot(normal, light_pos), 0.0);

vec3 color = diffuse * texture2D(color_texture, gl_TexCoord[0].st).rgb;

// Set the output color of our current pixel
gl_FragColor = vec4(color, 1.0);
}


I have tried something:


struct fsOutput {
vec4 color : COLOR;
};

uniform sampler2D detailTexture : TEXUNIT0;
uniform sampler2D bumpTexture : TEXUNIT1;

fsOutput FS_Main(float2 detailCoords : TEXCOORD0,

float2 bumpCoords: TEXCOORD1)
{

fsOutput fragm;

float4 anorm = tex2D(bumpTexture, bumpCoords);
vec3 normal = normalize(anorm.rgb * 2.0f - 1.0f);
vec3 light_pos = normalize(vec3(1.0f, 1.0f, 1.5f));
float diffuse = max(dot(normal, light_pos), 0.0);
vec3 color = diffuse * texture2D(detailTexture, detailCoords).rgb;

fragm.color = vec4(color, 1.0f);
return fragm;
}

But it doesn't work. To debug, I have a function that catches Cg errors, and my program breaks at this point. I have identified the two texture IDs in the main program. Can you suggest any improvement for this Cg shader?



Answer



I tried compiling it from the command-line as follows:


cgc -profile glslf -entry FS_Main test.cg

This gave the following error output:



test.cg
test.cg(18) : error C1066: invalid type in type constructor
test.cg(18) : error C1010: expression left of ."rgb" is not a struct

This immediately highlights the fact that you used texture2D on line 18 instead of the correct Cg function tex2D. Fixing this error makes it compile correctly.


In the future, you should probably use the cgGetLastListing function when cgGetError returns CG_COMPILER_ERROR. This will allow you to print out the error listing in your application, which makes your shaders easier to debug.


On another note, you use vec3 and vec4 on various occasions. While the Cg compiler seems to accept this, the correct types are float3 and float4, I believe.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...