Search code examples
c++openglshadernormalsassimp

Use normals as colors in OpenGL using assimp


I exported the suzanne model from blender(Monkey head) as a .obj file and I can only see it when I use the RGB values in the fragment shader. e.g. frag_color = vec4( 1.0, 0.0, 0.0, 1.0 ); to make the model red. But it just looks like a deformed texture unless I rotate it

Front view

I want to use the normals as colors so that I can see specific details in the face, etc. I bound the normals to vertex position 1.

    if ( mesh -> HasNormals() )
    {

        normals = ( GLfloat * ) malloc( * pointCount * 3 * sizeof( GLfloat ) );

        for ( int i = 0; i < * pointCount; i++ )
        {

            const aiVector3D * vn = &( mesh -> mNormals[ i ] );

            normals[ i * 3 ] = ( GLfloat ) vn -> x;
            normals[ i * 3 + 1 ] = ( GLfloat ) vn -> y;
            normals[ i * 3 + 2 ] = ( GLfloat ) vn -> z;

        }

        GLuint vbo;

        glGenBuffers( 1, &vbo );
        glBindBuffer( GL_ARRAY_BUFFER, vbo );
        glBufferData( GL_ARRAY_BUFFER, 3 * * pointCount * sizeof( GLfloat ), normals, GL_STATIC_DRAW );
        glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, NULL );
        glEnableVertexAttribArray( 1 );

        free( normals );

    }

And I bound 1 to vertex_normal right after attaching the shaders but right before linking.

glAttachShader( program, vertShader );
glAttachShader( program, fragShader );

glBindAttribLocation( program, 0, "vertex_position" );
glBindAttribLocation( program, 1, "vertex_normal" );

glLinkProgram( program );

These are my shaders

vertshader.shader

#version 330

in vec3 vertex_position;
in vec3 vertex_normal;

uniform mat4 proj, view, model;

out vec3 normals;

void main()
{

    normals = vertex_normal;

    gl_Position = proj * vec4( vec3( view * model * vec4( vertex_position, 1.0 ) ), 1.0 );

}

fragshader.shader

#version 330

in vec3 normals;

out vec4 fragment_color;

void main()
{       

    fragment_color = vec4( normals, 1.0 );

}

But this only outputs a black screen. I know the model is loading because I can color it red like above. I tried importing vertex_normal directly into the frag shader, that didn't work, I also tried normalizing normals and that didn't change the effect neither.

So how can I use the models normals as colors in the fragment shader?


Solution

  • Ok, I found a fix. Apparently it was blenders fault. There is a side panel on what I want to export with my mesh, and Write normals wasn't checked. Thanks to Reto Koradi, I didn't think it was possible for a mesh to be written without normals.

    enter image description here