美文网首页
webgl 25.用点光源为正方体添加光照

webgl 25.用点光源为正方体添加光照

作者: lesliefang | 来源:发表于2017-09-11 10:06 被阅读61次

前面两节我们用平行光为正方体添加了光照,这节我们用一个点光源来为正方体添加光照。

point lighted cube.png

平行光只需要一个光线方向和光线颜色就可以描述。而点光源的光线方向是不确定的,取决于点光源的位置和照射到物体上的位置。所以这里的重点是针对每个顶点重新计算光线方向。

我们要把点光源位置和 model matrix 传进去来计算每个顶点的光线方向

uniform vec3 u_LightPosition;
uniform mat4 u_ModelMatrix;

之后就可以计算出每个顶点的光线方向了

// 针对每个顶点计算光线方向
vec4 vertexPosition = u_ModelMatrix * a_Position;
vec3 lightDirection = normalize(u_LightPosition - vec3(vertexPosition));
现在的正方体看起来其实还不是特别的真实,因为只针对每个顶点计算了光线方向,最终的颜色在各个顶点之间进行了插值,而实际上正方体上每一个点上的光线方向都是不同的。要更加逼真的光照效果下节我们来看针对每个 fragment 计算光照。

完整代码

<script id="vertex-shader" type="glsl">
    attribute vec4 a_Position;
    attribute vec4 a_Color;
    attribute vec3 a_Normal;
    uniform vec3 u_LightColor;
    uniform vec3 u_LightPosition;
    uniform vec3 u_AmbientLight;
    uniform mat4 u_mvpMatrix;
    uniform mat4 u_ModelMatrix;
    uniform mat4 u_NormalMatrix;
    varying vec4 v_Color;

    void main() {
        gl_Position = u_mvpMatrix * a_Position;
        // 标准化(把长度变为 1 )
        vec3 normal = normalize(vec3(u_NormalMatrix * vec4(a_Normal,1.0)));

        // 针对每个顶点计算光线方向
        vec4 vertexPosition = u_ModelMatrix * a_Position;
        vec3 lightDirection = normalize(u_LightPosition - vec3(vertexPosition));

        float nDotL = max(dot(lightDirection, normal), 0.0);
        vec3 diffuse = u_LightColor * a_Color.rgb * nDotL;
        vec3 ambient = u_AmbientLight * a_Color.rgb;
        v_Color = vec4(diffuse + ambient, a_Color.a);
    }
</script>

<script id="fragment-shader" type="glsl">
    precision mediump float;
    varying vec4 v_Color;
    void main() {
       gl_FragColor = v_Color;
    }
</script>

<script src="lib/cuon-matrix.js"></script>
<script src="lib/myutils.js"></script>

<script>
    var VERTEX_SHADER_SOURCE = document.getElementById('vertex-shader').text;
    var FRAGMENT_SHADER_SOURCE = document.getElementById('fragment-shader').text;

    var canvas = document.getElementById("canvas");
    var gl = canvas.getContext('webgl');

    if (!initShaders(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE)) {
        alert('Failed to init shaders');
    }

    var n = initVertexBuffers(gl);

    var u_mvpMatrix = gl.getUniformLocation(gl.program, 'u_mvpMatrix');
    var u_LightColor = gl.getUniformLocation(gl.program, 'u_LightColor');
    var u_AmbientLight = gl.getUniformLocation(gl.program, 'u_AmbientLight');
    var u_NormalMatrix = gl.getUniformLocation(gl.program, 'u_NormalMatrix');
    var u_LightPosition = gl.getUniformLocation(gl.program, 'u_LightPosition');
    var u_ModelMatrix = gl.getUniformLocation(gl.program, 'u_ModelMatrix');

    // 设置光源颜色
    gl.uniform3f(u_LightColor, 1.0, 1.0, 1.0);
    // 设置点光源位置
    gl.uniform3f(u_LightPosition, 2.3, 4.0, 3.5);
    // 设置环境光颜色
    gl.uniform3f(u_AmbientLight, 0.2, 0.2, 0.2);

    // <projection matrix> * <view matrix>
    var mvpMatrix = new Matrix4();
    mvpMatrix.setPerspective(30, 1, 1, 100);
    mvpMatrix.lookAt(6, 6, 14, 0, 0, 0, 0, 1, 0);

    var modelMatrix = new Matrix4();
    modelMatrix.rotate(90, 0, 1, 0);
    gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);

    mvpMatrix.multiply(modelMatrix);
    gl.uniformMatrix4fv(u_mvpMatrix, false, mvpMatrix.elements);

    // 计算法向量变换矩阵
    var normalMatrix = new Matrix4();
    normalMatrix.setInverseOf(modelMatrix);
    normalMatrix.transpose();
    gl.uniformMatrix4fv(u_NormalMatrix, false, normalMatrix.elements);

    gl.enable(gl.DEPTH_TEST);
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);

    function initVertexBuffers(gl) {
        // Create a cube
        //    v6----- v5
        //   /|      /|
        //  v1------v0|
        //  | |     | |
        //  | |v7---|-|v4
        //  |/      |/
        //  v2------v3

        var vertices = new Float32Array([
            2.0, 2.0, 2.0, -2.0, 2.0, 2.0, -2.0, -2.0, 2.0, 2.0, -2.0, 2.0, // v0-v1-v2-v3 front
            2.0, 2.0, 2.0, 2.0, -2.0, 2.0, 2.0, -2.0, -2.0, 2.0, 2.0, -2.0, // v0-v3-v4-v5 right
            2.0, 2.0, 2.0, 2.0, 2.0, -2.0, -2.0, 2.0, -2.0, -2.0, 2.0, 2.0, // v0-v5-v6-v1 up
            -2.0, 2.0, 2.0, -2.0, 2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, 2.0, // v1-v6-v7-v2 left
            -2.0, -2.0, -2.0, 2.0, -2.0, -2.0, 2.0, -2.0, 2.0, -2.0, -2.0, 2.0, // v7-v4-v3-v2 down
            2.0, -2.0, -2.0, -2.0, -2.0, -2.0, -2.0, 2.0, -2.0, 2.0, 2.0, -2.0  // v4-v7-v6-v5 back
        ]);

        var colors = new Float32Array([    // Colors
            1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,     // v0-v1-v2-v3 front
            1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,     // v0-v3-v4-v5 right
            1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,     // v0-v5-v6-v1 up
            1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,     // v1-v6-v7-v2 left
            1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,     // v7-v4-v3-v2 down
            1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0     // v4-v7-v6-v5 back
        ]);

        var normals = new Float32Array([    // Normal
            0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,  // v0-v1-v2-v3 front
            1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,  // v0-v3-v4-v5 right
            0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,  // v0-v5-v6-v1 up
            -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,  // v1-v6-v7-v2 left
            0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0,  // v7-v4-v3-v2 down
            0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0   // v4-v7-v6-v5 back
        ]);

        var indices = new Uint8Array([       // Indices of the vertices
            0, 1, 2, 0, 2, 3,    // front
            4, 5, 6, 4, 6, 7,    // right
            8, 9, 10, 8, 10, 11,    // up
            12, 13, 14, 12, 14, 15,    // left
            16, 17, 18, 16, 18, 19,    // down
            20, 21, 22, 20, 22, 23     // back
        ]);

        if (!initArrayBuffer(gl, vertices, 3, gl.FLOAT, 'a_Position')) {
            return -1;
        }
        if (!initArrayBuffer(gl, colors, 3, gl.FLOAT, 'a_Color')) {
            return -1;
        }
        if (!initArrayBuffer(gl, normals, 3, gl.FLOAT, 'a_Normal')) {
            return -1;
        }

        var indexBuffer = gl.createBuffer();
        if (!indexBuffer) {
            console.log('Failed to create index buffer');
            return -1;
        }
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);

        return indices.length;
    }

    function initArrayBuffer(gl, data, numOfComponents, dataType, attributeName) {
        var buffer = gl.createBuffer();
        if (!buffer) {
            console.log('Failed to create buffer object');
            return false;
        }

        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);

        var attribute = gl.getAttribLocation(gl.program, attributeName);
        gl.vertexAttribPointer(attribute, numOfComponents, dataType, false, 0, 0);
        gl.enableVertexAttribArray(attribute);

        return true;
    }
</script>

查看源码

相关文章

  • webgl 25.用点光源为正方体添加光照

    前面两节我们用平行光为正方体添加了光照,这节我们用一个点光源来为正方体添加光照。 平行光只需要一个光线方向和光线颜...

  • webgl 22.为正方体添加光照

    下面来看一下光照先来看一下光源的类型 光源大体可分为 Directional light (平行光),Point ...

  • Unity 渲染教程(五):多个光源

    对每个物体渲染多个光源的光照效果。 支持不同的光源类型。 使用光源cookie。 计算顶点光照。 在光照计算中添加...

  • webgl 24.为旋转平移后的正方体添加光照

    接上节的例子,我们对正方体做一些模型变换(旋转、平移、缩放)后再添加光照。 物体旋转、平移或缩放后法向量会发生变化...

  • Threejs基本概念(七)光

    环境光AmbientLight 为场景提供整体的光照效果,没有明确光源,各处形成亮度一致 点光源PointLigh...

  • webgl 23.为正方体添加环境光

    上一节我们给正方体添加了漫反射,但物体背光的部分几乎完全是黑色的,我们可以再添加环境光让物体显示的更真实。 非常简...

  • Ⅰ标准光照模型

    标准光照模型 基础概念 光源 光源 在实时渲染中我们通常把光源当做一个没有体积的点,用 l 来表示它的方向 辐照度...

  • webgl 光照

    前言 现实世界中被光线照射时,会发射一部分光.只有当反射光线进入你的眼睛时,你才能看到物体,并且分辨出它的颜色. ...

  • WEBGL编程指南之实例

    放一个webgl完整的例子 画了一个正方体,cuon-matrix.js为外部矩阵操作的库。

  • 学习WebGL文章目录

    基础篇 第一个WebGL程序绘制三角形深入了解Shader绘制点线面变换矩阵透视和正交投影摄像机绘制正方体基本光照...

网友评论

      本文标题:webgl 25.用点光源为正方体添加光照

      本文链接:https://www.haomeiwen.com/subject/yymxsxtx.html