dmu
dmu

Reputation: 21

How to access colors in THREE.ShaderMaterial using THREE.OBJMTLLoader

I am trying to write a THREE.ShaderMaterial to render a model loaded using THREE.OBJMTLLoader, but I do not understand how to access the vertex colors in the vertex/fragment shader. The result when using my shader (see code below) is a pure white model (due to the default color value I guess).

The result when not using my shader is ok, i.e. model is rendered with correct colors.

I have set shaderMaterial.vertexColors = THREE.VertexColors; and child.material = shaderMaterial; for all childs in the object.

Vertex shader:

varying vec3 vecColor;
void main()
{
    vecColor = color;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

Fragment shader:

varying vec3 vecColor;
void main()
{
    gl_FragColor = vec4(vecColor, 1.0);
}

Upvotes: 1

Views: 862

Answers (1)

dmu
dmu

Reputation: 21

I finally realized that I was actually replacing materiels generated by OBJMTLLoader with my own material. The solution I found was to extract info from the original child.material and insert it into instances of my shader, organized in in a map:

var materialMap = {};
object.traverse( function ( child ) {
    if ( child instanceof THREE.Mesh ) {
        if (child.material.id in materialMap) {
            console.log("Using predefined material");
            child.material = materialMap[child.material.id];
        }
        else {
            console.log("Creating new material");
            materialMap[child.material.id] =  new THREE.ShaderMaterial({
                uniforms: { 
                    bumpMap: { type: "t", value: texture }, 
                    color: { type: "v3", value: new THREE.Vector3( child.material.color.r, child.material.color.g, child.material.color.b ) } 
                },
                vertexShader:   vShader,
                fragmentShader: fShader
            });
            child.material = materialMap[child.material.id];
        }
    }
});

Upvotes: 1

Related Questions