Cannot pass color value to shader vertex attribute

Hi,

I find that I cannot pass the color attribute to the shader vertex.

For example, if I use "vColor = vec4(1.0, 1.0, 1.0, 1.0);", it will show the sphere in white. However, if I pass the color attribute "red" to the buffer, it cannot show me the correct color.

Can anyone help me to find out the mistake in my coding?

<script id="shader-fs" type="x-shader/x-fragment"> 
  #ifdef GL_ES
  precision highp float;
  #endif
 
  varying vec4 vColor;
  
  void main(void) {
    gl_FragColor = vColor;
  }
</script>

 <script id="shader-vs" type="x-shader/x-vertex"> 
  attribute vec3 aVertexPosition;
  attribute vec3 aVertexNormal;
  attribute vec4 aVertexColor;

  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;
 
  varying vec4 vColor;
 
  void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  vColor = aVertexColor;
  }
</script>

<script type="text/javascript">

    var gl;
    function initGL(canvas) {
        try {
            gl = canvas.getContext("experimental-webgl");
            gl.viewportWidth = canvas.width;
            gl.viewportHeight = canvas.height;
        } catch (e) {
        }
        if (!gl) {
            alert("Could not initialise WebGL, sorry :-(");
        }
    }

    function getShader(gl, id) {
        var shaderScript = document.getElementById(id);
        if (!shaderScript) {
            return null;
        }

        var str = "";
        var k = shaderScript.firstChild;
        while (k) {
            if (k.nodeType == 3) {
                str += k.textContent;
            }
            k = k.nextSibling;
        }

        var shader;
        if (shaderScript.type == "x-shader/x-fragment") {
            shader = gl.createShader(gl.FRAGMENT_SHADER);
        } else if (shaderScript.type == "x-shader/x-vertex") {
            shader = gl.createShader(gl.VERTEX_SHADER);
        } else {
            return null;
        }

        gl.shaderSource(shader, str);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            alert(gl.getShaderInfoLog(shader));
            return null;
        }

        return shader;
    }

    var shaderProgram;
    function initShaders() {
        var fragmentShader = getShader(gl, "shader-fs");
        var vertexShader = getShader(gl, "shader-vs");

        shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert("Could not initialise shaders");
        }

        gl.useProgram(shaderProgram);

        shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
        gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

        shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
        gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

        shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
        shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
    }

    var mvMatrix;
    var mvMatrixStack = [];

    function mvPushMatrix(m) {
        if (m) {
            mvMatrixStack.push(m.dup());
            mvMatrix = m.dup();
        } else {
            mvMatrixStack.push(mvMatrix.dup());
        }
    }

    function mvPopMatrix() {
        if (mvMatrixStack.length == 0) {
            throw "Invalid popMatrix!";
        }
        mvMatrix = mvMatrixStack.pop();
        return mvMatrix;
    }

    function loadIdentity() {
        mvMatrix = Matrix.I(4);
    }

    function multMatrix(m) {
        mvMatrix = mvMatrix.x(m);
    }

    function mvTranslate(v) {
        var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4();
        multMatrix(m);
    }

    function createRotationMatrix(angle, v) {
        var arad = angle * Math.PI / 180.0;
        return Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
    }

    function mvRotate(ang, v) {
        var arad = ang * Math.PI / 180.0;
        var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
        multMatrix(m);
    }

    var pMatrix;
    function perspective(fovy, aspect, znear, zfar) {
        pMatrix = makePerspective(fovy, aspect, znear, zfar);
    }

    function setMatrixUniforms() {
        gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten()));
        gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten()));
    }

    var z = -7.0;

    var vertexPositionBuffer;
    var vertexNormalBuffer;
    var vertexColorBuffer;
    var vertexIndexBuffer;

    function initBuffers() {
        var latitudeBands = 30;
        var longitudeBands = 30;
        var radius = 2;

        var vertexPositionData = [];
        var normalData = [];
        var vertexColorData = [];
        for (var latNumber = 0; latNumber <= latitudeBands; latNumber++) {
            var theta = latNumber * Math.PI / latitudeBands;
            var sinTheta = Math.sin(theta);
            var cosTheta = Math.cos(theta);

            for (var longNumber = 0; longNumber <= longitudeBands; longNumber++) {
                var phi = longNumber * 2 * Math.PI / longitudeBands;
                var sinPhi = Math.sin(phi);
                var cosPhi = Math.cos(phi);

                var x = cosPhi * sinTheta;
                var y = cosTheta;
                var z = sinPhi * sinTheta;
                var u = 1 - (longNumber / longitudeBands);
                var v = 1 - (latNumber / latitudeBands);

                normalData.push(x);
                normalData.push(y);
                normalData.push(z);
                vertexColorData = vertexColorData.concat("[1.0, 0.0, 0.0, 1.0]");
                vertexPositionData.push(radius * x);
                vertexPositionData.push(radius * y);
                vertexPositionData.push(radius * z);
            }
        }        
        var indexData = [];
        for (var latNumber = 0; latNumber < latitudeBands; latNumber++) {
            for (var longNumber = 0; longNumber < longitudeBands; longNumber++) {
                var first = (latNumber * (longitudeBands + 1)) + longNumber;
                var second = first + longitudeBands + 1;
                indexData.push(first);
                indexData.push(second);
                indexData.push(first + 1);

                indexData.push(second);
                indexData.push(second + 1);
                indexData.push(first + 1);
            }
        }

        vertexNormalBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normalData), gl.STATIC_DRAW);
        vertexNormalBuffer.itemSize = 3;
        vertexNormalBuffer.numItems = normalData.length / 3;
        
        vertexColorBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexColorData), gl.STATIC_DRAW);
        vertexColorBuffer.itemSize = 4;
        vertexColorBuffer.numItems = vertexColorData.length / 4;

        vertexPositionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexPositionData), gl.STATIC_DRAW);
        vertexPositionBuffer.itemSize = 3;
        vertexPositionBuffer.numItems = vertexPositionData.length / 3;

        vertexIndexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexIndexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), gl.STREAM_DRAW);
        vertexIndexBuffer.itemSize = 1;
        vertexIndexBuffer.numItems = indexData.length;
    }


    function drawScene() {
        gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
        loadIdentity();

        mvTranslate([0, 0.0, z]);
        multMatrix(rotationMatrix);
        
        mvPushMatrix();
        mvTranslate([0, 0, 0]);

        gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
        gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
        gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer);
        gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, vertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);

        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexIndexBuffer);
        setMatrixUniforms();
        gl.drawElements(gl.TRIANGLES, vertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);

        mvPopMatrix();
    }

    var mouseDown = false;
    var lastMouseX = null;
    var lastMouseY = null;
    var rotationMatrix = Matrix.I(4);
    
    function handleMouseDown(event) {
        mouseDown = true;
        lastMouseX = event.clientX;
        lastMouseY = event.clientY;
    }

    function handleMouseUp(event) {
        mouseDown = false;
    }

    function handleMouseMove(event) {
        if (!mouseDown) {
            return;
        }
        
        var newX = event.clientX;
        var newY = event.clientY;
        var deltaX = (newX - lastMouseX) / 2;
        var deltaY = (newY - lastMouseY) / 2;
        
        var newRotationMatrix = createRotationMatrix(deltaX, [0, 1, 0]);
        newRotationMatrix = newRotationMatrix.x(createRotationMatrix(deltaY, [1, 0, 0]));
        rotationMatrix = newRotationMatrix.x(rotationMatrix);

        lastMouseX = newX
        lastMouseY = newY;
    }

    function tick() {
        drawScene();
    }

    function webGLStart() {
        var canvas = document.getElementById("lesson11-canvas");
        initGL(canvas);
        initShaders();
        initBuffers();

        gl.clearColor(0.0, 0.0, 0.0, 1.0);

        gl.clearDepth(1.0);

        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);

        canvas.onmousedown = handleMouseDown;
        document.onmouseup = handleMouseUp;
        document.onmousemove = handleMouseMove;

        setInterval(tick, 15);
    }
 
</script> 

Probably due to the fact that you are concatenating strings rather than floating point numbers in


vertexColorData = vertexColorData.concat("[1.0, 0.0, 0.0, 1.0]");

get rid of the quotes as


vertexColorData = vertexColorData.concat([1.0, 0.0, 0.0, 1.0]);

I have tried but the result is the same as before.

What I wonder is that when I comment the following:

 
//        gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
//        gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

it still can generate a sphere in multi-color.

If I directly set the vertex color to white as the following in “shader-vs”, the sphere can be drawn in white.

vColor = vec4(1.0, 1.0, 1.0, 1.0);

No matter what, passing a string is incorrect and will give bogus results. Do not pass a string in.

Don’t know what to say – if I remove the two quotes a red colored sphere shows up on my computer. Only one line is changed as follows


                ...
                normalData.push(z);
                vertexColorData = vertexColorData.concat([1.0, 0.0, 0.0, 1.0]);
                vertexPositionData.push(radius * x);
                ...


Yes. A sphere with multi-color is shown in google chrome. (attached Untitled.png).

I have tried to test it in Firefox, it shows the red sphere but fails to show other objects such as the object in Untitled2.png.

May I know your web browser version(Firefox or google chrome, with download link if any?)? I think I can install your version and have a try.

I think you asked this before and you had a newer version but anyhow I have Chrome 6.0.472.63.

One longshot, what if you replace the single concat with 4 separate push calls ie


vertexColorData = vertexColorData.push(1.0);
vertexColorData = vertexColorData.push(0.0);
vertexColorData = vertexColorData.push(0.0);
vertexColorData = vertexColorData.push(1.0);

I don’t really have a good reason to suggest.

I install your chrome version. However, it shows the message that the WebGL does not initialise. How can I enable the WebGL in chrome?

Add --enable-webgl to your run command.

Yes. I added it. But it still fails to initialise webgl.
I will check it later.

You may have to completely exit crhome, then restart it with the
command


<insert_your_path_to_here>chrome.exe --enable-webgl