0
$\begingroup$

I recently started using Blender to create 3D models for a game I'm programming with OpenGL and GLFW. However, I'm experiencing a lot of difficulties exporting and using Material Library Files (.mtl) in my project as the color values seem to be messed up in the file. My shading code is per-primitive (I'm using a geometry shader):

layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;

in vec3 passVertex[];
in int passMtlIndex[];

out vec4 color;

struct Material {
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    float shininess;
    float dissolve;
};

struct Light {
    vec3 position;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

uniform mat4 projection;
uniform mat4 view;

uniform Material materials[];
uniform Light light;

void doVertex(int index, vec4 baseColor) {
    gl_Position = projection * view * vec4(passVertex[index], 1.0);
    color = baseColor;
    EmitVertex();
}

mat4 inverseAffine(mat4 matrix) {
    return mat4(
            matrix[0].x, matrix[1].x, matrix[2].x, 0,
            matrix[0].y, matrix[1].y, matrix[2].y, 0,
            matrix[0].z, matrix[1].z, matrix[2].z, 0,
            -dot(matrix[3].xyz, matrix[0].xyz), -dot(matrix[3].xyz, matrix[1].xyz), -dot(matrix[3].xyz, matrix[2].xyz), 1);
}

void main() {
    vec3 toEye = normalize(inverseAffine(view)[3].xyz - passVertex[0]);
    vec3 norm = normalize(cross(passVertex[1] - passVertex[0], passVertex[2] - passVertex[0]));
    vec3 lightDir = normalize(light.position - passVertex[0]);

    Material material = materials[passMtlIndex[0]];

    vec3 ambient = light.ambient * material.ambient;

    float diff = max(dot(norm, lightDir), 0.2);
    vec3 diffuse = light.diffuse * (diff * material.diffuse);

    float spec = pow(max(dot(reflect(-lightDir, norm), toEye), 0.0), material.shininess);
    vec3 specular = light.specular * (spec * material.specular);

    vec4 baseColor = vec4(ambient + diffuse + specular, material.dissolve);

    doVertex(0, baseColor);
    doVertex(1, baseColor);
    doVertex(2, baseColor);

    EndPrimitive();
}

I'm transferring the Ka, Kd, Ks, Ns and d values from the mtl file directly into that Material structure. Is this not the format of the mtl file or have I missed something? The fact that the ambient color in the file is always white would tell me that I'm missing something but I really don't know.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.