Object center in fragment shader [Solved]

here is the code for my fragment shader:

vec4 point = g_WorldViewProjectionMatrix * vec4(0.0, 0.0, 0.0, 1.0);
float dist = sqrt(pow(gl_FragCoord.x - point.x, 2) + pow(gl_FragCoord.y - point.y, 2));
if(dist < 100){
    gl_FragColor = vec4(1.0, 0.0, 0.0, 0.0);  
} else {
    gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);  
}

what i expected: a red circle with 100xp radius on the center of the object
what i got: a quarter of a circle on the lower left edge of the screen (0,0 coordinates)

so what am i misunderstanding or is the desired effect even possible to achieve?

gl_FragCoord is in window coordinates, e.g. [0, width], [0, height]. You gotta convert to normalized device coordinates [-1,1] which is what the projection matrix uses, here’s how to do it:
http://www.txutxi.com/?p=182

1 Like

Is there a reason you aren’t just rendering a red circle around the object? Is this shader full screen or?

float normalizedX = (gl_FragCoord.x/m_screenWidth) * 2 -1;
float normalizedY = (gl_FragCoord.y/m_screenHeight) * 2 -1;
vec4 point = g_WorldViewProjectionMatrix * vec4(0.0, 0.0, 0.0, 1.0);
float dist = sqrt(pow(normalizedX - point.x, 2) + pow(normalizedY - point.y, 2));
if(dist < 0.1){
    gl_FragColor = vec4(1.0, 0.0, 0.0, 0.0);  
} else {
    gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);  
}

it’s now in the enter of the screen (only if the object is also roughly somewhere around the center, otherwise not visible) … :frowning:

does WorldViewProjectionMatrix really transforms object space to projection space in fragment shader?

What are you trying to do? Show a circle in the middle of the screen? I don’t understand the purpose.

I’m trying to write a fragment shader that is influenced by line going through my object. Since it didn’t work and I need two points to construct a line, I made this example to verify if I could at least get the center coordinate of my mesh. As it turns out - I can’t.

UPDATE:
I managed to find the reason why it didn’t work. Apparently after normalized device transformation, normalized perspective division was needed ( * point.w):

result:

vec4 point = g_WorldViewProjectionMatrix * vec4(0.0, 0.0, 0.0, 1.0);
float normalizedX = ((gl_FragCoord.x/m_screenWidth) * 2 -1) * point.w;
float normalizedY = ((gl_FragCoord.y/m_screenHeight) * 2 -1) * point.w;
float dist = sqrt(pow(normalizedX - point.x, 2) + pow(normalizedY - point.y, 2));
if(dist < 0.1){
    gl_FragColor = vec4(1.0, 0.0, 0.0, 0.0);  
} else {
    gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);  
}

in case someone else needs this obscure shit:

some good material:
http://www.glprogramming.com/red/chapter03.html#name1