欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WebGL的颜色渲染-渲染一张DEM(数字高程模型)

程序员文章站 2023-10-31 22:01:46
通过渲染一张DEM的具体例子,了解在WebGL中颜色渲染的过程。 ......

1. 具体实例

通过webgl,可以渲染生成dem(数字高程模型)。dem(数字高程模型)是网格点组成的模型,每个点都有x,y,z值;x,y根据一定的间距组成网格状,同时根据z值的高低来选定每个点的颜色rgb。通过这个例子可以熟悉webgl颜色渲染的过程。

2. 解决方案

1) dem数据.xyz文件

这里使用的dem文件的数据组织如下,如下图所示。
WebGL的颜色渲染-渲染一张DEM(数字高程模型)
其中每一行表示一个点,前三个数值表示位置xyz,后三个数值表示颜色rgb。

2) showdem.html

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title> 显示地形 </title>
    <script src="lib/webgl-utils.js"></script>
    <script src="lib/webgl-debug.js"></script>
    <script src="lib/cuon-utils.js"></script>
    <script src="lib/cuon-matrix.js"></script>
    <script src="showdem.js"></script>
</head>

<body>
    <div><input type = 'file' id = 'demfile' ></div>
    <!-- <div><textarea id="output" rows="300" cols="200"></textarea></div> -->
    <div>
        <canvas id ="demcanvas" width="600" height="600">
            请使用支持webgl的浏览器
        </canvas>
    </div>
</body>

</html>

3) showdem.js

// vertex shader program
var vshader_source =
    //'precision highp float;\n' +
    'attribute vec4 a_position;\n' +
    'attribute vec4 a_color;\n' +
    'uniform mat4 u_mvpmatrix;\n' +
    'varying vec4 v_color;\n' +
    'void main() {\n' +
    '  gl_position = u_mvpmatrix * a_position;\n' +
    '  v_color = a_color;\n' +
    '}\n';

// fragment shader program
var fshader_source =
    '#ifdef gl_es\n' +
    'precision mediump float;\n' +
    '#endif\n' +
    'varying vec4 v_color;\n' +
    'void main() {\n' +
    '  gl_fragcolor = v_color;\n' +
    '}\n';

//
var col = 89;       //dem宽
var row = 245;      //dem高

// current rotation angle ([x-axis, y-axis] degrees)
var currentangle = [0.0, 0.0];

//当前lookat()函数初始视点的高度
var eyehight = 2000.0;

//setperspective()远截面
var far = 3000;

//
window.onload = function () {
    var demfile = document.getelementbyid('demfile');
    if (!demfile) {
        console.log("error!");
        return;
    }

    //demfile.onchange = openfile(event);
    demfile.addeventlistener("change", function (event) {
        //判断浏览器是否支持filereader接口
        if (typeof filereader == 'undefined') {
            console.log("你的浏览器不支持filereader接口!");
            return;
        }

        //
        var reader = new filereader();
        reader.onload = function () {
            if (reader.result) {        
                //        
                var stringlines = reader.result.split("\n");
                verticescolors = new float32array(stringlines.length * 6);
            
                //
                var pn = 0;
                var ci = 0;
                for (var i = 0; i < stringlines.length; i++) {
                    if (!stringlines[i]) {
                        continue;
                    }
                    var subline = stringlines[i].split(',');
                    if (subline.length != 6) {
                        console.log("错误的文件格式!");
                        return;
                    }
                    for (var j = 0; j < subline.length; j++) {
                        verticescolors[ci] = parsefloat(subline[j]);
                        ci++;
                    }
                    pn++;
                }
            
                if (ci < 3) {
                    console.log("错误的文件格式!");
                }

                //
                var minx = verticescolors[0];
                var maxx = verticescolors[0];
                var miny = verticescolors[1];
                var maxy = verticescolors[1];
                var minz = verticescolors[2];
                var maxz = verticescolors[2];
                for (var i = 0; i < pn; i++) {
                    minx = math.min(minx, verticescolors[i * 6]);
                    maxx = math.max(maxx, verticescolors[i * 6]);
                    miny = math.min(miny, verticescolors[i * 6 + 1]);
                    maxy = math.max(maxy, verticescolors[i * 6 + 1]);
                    minz = math.min(minz, verticescolors[i * 6 + 2]);
                    maxz = math.max(maxz, verticescolors[i * 6 + 2]);
                }
               
                //包围盒中心
                var cx = (minx + maxx) / 2.0;
                var cy = (miny + maxy) / 2.0;
                var cz = (minz + maxz) / 2.0;

                //根据视点高度算出setperspective()函数的合理角度
                var fovy = (maxy - miny) / 2.0 / eyehight;
                fovy = 180.0 / math.pi * math.atan(fovy) * 2;

                startdraw(verticescolors, cx, cy, cz, fovy);
            }
        };

        //
        var input = event.target;
        reader.readastext(input.files[0]);
    });
}

function startdraw(verticescolors, cx, cy, cz, fovy) {
    // retrieve <canvas> element
    var canvas = document.getelementbyid('demcanvas');

    // get the rendering context for webgl
    var gl = getwebglcontext(canvas);
    if (!gl) {
        console.log('failed to get the rendering context for webgl');
        return;
    }

    // initialize shaders
    if (!initshaders(gl, vshader_source, fshader_source)) {
        console.log('failed to intialize shaders.');
        return;
    }

    // set the vertex coordinates and color (the blue triangle is in the front)
    n = initvertexbuffers(gl, verticescolors);          //, verticescolors, n
    if (n < 0) {
        console.log('failed to set the vertex information');
        return;
    }

    // get the storage location of u_mvpmatrix
    var u_mvpmatrix = gl.getuniformlocation(gl.program, 'u_mvpmatrix');
    if (!u_mvpmatrix) {
        console.log('failed to get the storage location of u_mvpmatrix');
        return;
    }

    // register the event handler 
    initeventhandlers(canvas);

    // specify the color for clearing <canvas>
    gl.clearcolor(0, 0, 0, 1);
    gl.enable(gl.depth_test);

    // start drawing
    var tick = function () {

        //setperspective()宽高比
        var aspect = canvas.width / canvas.height;

        //
        draw(gl, n, aspect, cx, cy, cz, fovy, u_mvpmatrix);
        requestanimationframe(tick, canvas);
    };
    tick();
}

//
function initeventhandlers(canvas) {
    var dragging = false;         // dragging or not
    var lastx = -1, lasty = -1;   // last position of the mouse

    // mouse is pressed
    canvas.onmousedown = function (ev) {
        var x = ev.clientx;
        var y = ev.clienty;
        // start dragging if a moue is in <canvas>
        var rect = ev.target.getboundingclientrect();
        if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
            lastx = x;
            lasty = y;
            dragging = true;
        }
    };

    //鼠标离开时
    canvas.onmouseleave = function (ev) {
        dragging = false;
    };

    // mouse is released
    canvas.onmouseup = function (ev) {
        dragging = false;
    };

    // mouse is moved
    canvas.onmousemove = function (ev) {
        var x = ev.clientx;
        var y = ev.clienty;
        if (dragging) {
            var factor = 100 / canvas.height; // the rotation ratio
            var dx = factor * (x - lastx);
            var dy = factor * (y - lasty);
            // limit x-axis rotation angle to -90 to 90 degrees
            //currentangle[0] = math.max(math.min(currentangle[0] + dy, 90.0), -90.0);
            currentangle[0] = currentangle[0] + dy;
            currentangle[1] = currentangle[1] + dx;
        }
        lastx = x, lasty = y;
    };

    //鼠标缩放
    canvas.onmousewheel = function (event) {
        var lastheight = eyehight;
        if (event.wheeldelta > 0) {
            eyehight = math.max(1, eyehight - 80);
        } else {
            eyehight = eyehight + 80;
        }

        far = far + eyehight - lastheight;
    };
}

function draw(gl, n, aspect, cx, cy, cz, fovy, u_mvpmatrix) {
    //模型矩阵
    var modelmatrix = new matrix4();
    modelmatrix.rotate(currentangle[0], 1.0, 0.0, 0.0); // rotation around x-axis 
    modelmatrix.rotate(currentangle[1], 0.0, 1.0, 0.0); // rotation around y-axis    
    modelmatrix.translate(-cx, -cy, -cz);

    //视图矩阵
    var viewmatrix = new matrix4();
    viewmatrix.lookat(0, 0, eyehight, 0, 0, 0, 0, 1, 0);

    //投影矩阵
    var projmatrix = new matrix4();
    projmatrix.setperspective(fovy, aspect, 10, far);

    //模型视图投影矩阵
    var mvpmatrix = new matrix4();
    mvpmatrix.set(projmatrix).multiply(viewmatrix).multiply(modelmatrix);

    // pass the model view projection matrix to u_mvpmatrix
    gl.uniformmatrix4fv(u_mvpmatrix, false, mvpmatrix.elements);

    // clear color and depth buffer
    gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit);

    // draw the cube 
    gl.drawelements(gl.triangles, n, gl.unsigned_short, 0);
}

function initvertexbuffers(gl, verticescolors) {
    //dem的一个网格是由两个三角形组成的
    //      0------1            1
    //      |                   |
    //      |                   |
    //      col       col------col+1    
    var indices = new uint16array((row - 1) * (col - 1) * 6);
    var ci = 0;
    for (var yi = 0; yi < row - 1; yi++) {
        for (var xi = 0; xi < col - 1; xi++) {
            indices[ci * 6] = yi * col + xi;
            indices[ci * 6 + 1] = (yi + 1) * col + xi;
            indices[ci * 6 + 2] = yi * col + xi + 1;
            indices[ci * 6 + 3] = (yi + 1) * col + xi;
            indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
            indices[ci * 6 + 5] = yi * col + xi + 1;
            ci++;
        }
    }

    //创建缓冲区对象
    var vertexcolorbuffer = gl.createbuffer();
    var indexbuffer = gl.createbuffer();
    if (!vertexcolorbuffer || !indexbuffer) {
        return -1;
    }

    // 将缓冲区对象绑定到目标
    gl.bindbuffer(gl.array_buffer, vertexcolorbuffer);
    // 向缓冲区对象中写入数据
    gl.bufferdata(gl.array_buffer, verticescolors, gl.static_draw);

    //
    var fsize = verticescolors.bytes_per_element;
    // 向缓冲区对象分配a_position变量
    var a_position = gl.getattriblocation(gl.program, 'a_position');
    if (a_position < 0) {
        console.log('failed to get the storage location of a_position');
        return -1;
    }
    gl.vertexattribpointer(a_position, 3, gl.float, false, fsize * 6, 0);
    //开启a_position变量
    gl.enablevertexattribarray(a_position);

    // 向缓冲区对象分配a_color变量
    var a_color = gl.getattriblocation(gl.program, 'a_color');
    if (a_color < 0) {
        console.log('failed to get the storage location of a_color');
        return -1;
    }
    gl.vertexattribpointer(a_color, 3, gl.float, false, fsize * 6, fsize * 3);
    //开启a_color变量
    gl.enablevertexattribarray(a_color);

    // 写入并绑定顶点数组的索引值
    gl.bindbuffer(gl.element_array_buffer, indexbuffer);
    gl.bufferdata(gl.element_array_buffer, indices, gl.static_draw);

    return indices.length;
}

4) 运行结果

用chrome打开showdem.html,选择dem文件,界面就会显示dem的渲染效果:
WebGL的颜色渲染-渲染一张DEM(数字高程模型)

3. 详细讲解

1) 读取文件

程序的第一步是通过js的filereader()函数读取dem文件,在其回调函数中读取到数组verticescolors中,它包含了位置和颜色信息。读取完成后调用绘制函数startdraw()。

//
var reader = new filereader();
reader.onload = function () {
    if (reader.result) {        
        //        
        var stringlines = reader.result.split("\n");
        verticescolors = new float32array(stringlines.length * 6);
    
        //
        var pn = 0;
        var ci = 0;
        for (var i = 0; i < stringlines.length; i++) {
            if (!stringlines[i]) {
                continue;
            }
            var subline = stringlines[i].split(',');
            if (subline.length != 6) {
                console.log("错误的文件格式!");
                return;
            }
            for (var j = 0; j < subline.length; j++) {
                verticescolors[ci] = parsefloat(subline[j]);
                ci++;
            }
            pn++;
        }
    
        if (ci < 3) {
            console.log("错误的文件格式!");
        }

        //
        var minx = verticescolors[0];
        var maxx = verticescolors[0];
        var miny = verticescolors[1];
        var maxy = verticescolors[1];
        var minz = verticescolors[2];
        var maxz = verticescolors[2];
        for (var i = 0; i < pn; i++) {
            minx = math.min(minx, verticescolors[i * 6]);
            maxx = math.max(maxx, verticescolors[i * 6]);
            miny = math.min(miny, verticescolors[i * 6 + 1]);
            maxy = math.max(maxy, verticescolors[i * 6 + 1]);
            minz = math.min(minz, verticescolors[i * 6 + 2]);
            maxz = math.max(maxz, verticescolors[i * 6 + 2]);
        }
       
        //包围盒中心
        var cx = (minx + maxx) / 2.0;
        var cy = (miny + maxy) / 2.0;
        var cz = (minz + maxz) / 2.0;

        //根据视点高度算出setperspective()函数的合理角度
        var fovy = (maxy - miny) / 2.0 / eyehight;
        fovy = 180.0 / math.pi * math.atan(fovy) * 2;

        startdraw(verticescolors, cx, cy, cz, fovy);
    }
};

//
var input = event.target;
reader.readastext(input.files[0]);

2) 绘制函数

绘制dem跟绘制一个简单三角形的步骤是差不多的:

  1. 获取webgl环境。
  2. 初始化shaders,构建着色器。
  3. 初始化顶点数组,分配到缓冲对象。
  4. 绑定鼠标键盘事件,设置模型视图投影变换矩阵。
  5. 在重绘函数中调用webgl函数绘制。

其中最关键的步骤是第三步,初始化顶点数组initvertexbuffers()。

function startdraw(verticescolors, cx, cy, cz, fovy) {
    // retrieve <canvas> element
    var canvas = document.getelementbyid('demcanvas');

    // get the rendering context for webgl
    var gl = getwebglcontext(canvas);
    if (!gl) {
        console.log('failed to get the rendering context for webgl');
        return;
    }

    // initialize shaders
    if (!initshaders(gl, vshader_source, fshader_source)) {
        console.log('failed to intialize shaders.');
        return;
    }

    // set the vertex coordinates and color (the blue triangle is in the front)
    n = initvertexbuffers(gl, verticescolors);          //, verticescolors, n
    if (n < 0) {
        console.log('failed to set the vertex information');
        return;
    }

    // get the storage location of u_mvpmatrix
    var u_mvpmatrix = gl.getuniformlocation(gl.program, 'u_mvpmatrix');
    if (!u_mvpmatrix) {
        console.log('failed to get the storage location of u_mvpmatrix');
        return;
    }

    // register the event handler 
    initeventhandlers(canvas);

    // specify the color for clearing <canvas>
    gl.clearcolor(0, 0, 0, 1);
    gl.enable(gl.depth_test);

    // start drawing
    var tick = function () {

        //setperspective()宽高比
        var aspect = canvas.width / canvas.height;

        //
        draw(gl, n, aspect, cx, cy, cz, fovy, u_mvpmatrix);
        requestanimationframe(tick, canvas);
    };
    tick();
}

3) 使用缓冲区对象

在函数initvertexbuffers()中包含了使用缓冲区对象向顶点着色器传入多个顶点数据的过程:

  1. 创建缓冲区对象(gl.createbuffer());
  2. 绑定缓冲区对象(gl.bindbuffer());
  3. 将数据写入缓冲区对象(gl.bufferdata);
  4. 将缓冲区对象分配给一个attribute变量(gl.vertexattribpointer)
  5. 开启attribute变量(gl.enablevertexattribarray);

在本例中,在js中申请的数组verticescolors分成位置和颜色两部分分配给缓冲区对象,并传入顶点着色器;vertexattribpointer()是其关键的函数,需要详细了解其参数的用法。最后,把顶点数据的索引值绑定到缓冲区对象,webgl可以访问索引来间接访问顶点数据进行绘制。

function initvertexbuffers(gl, verticescolors) {
    //dem的一个网格是由两个三角形组成的
    //      0------1            1
    //      |                   |
    //      |                   |
    //      col       col------col+1    
    var indices = new uint16array((row - 1) * (col - 1) * 6);
    var ci = 0;
    for (var yi = 0; yi < row - 1; yi++) {
        for (var xi = 0; xi < col - 1; xi++) {
            indices[ci * 6] = yi * col + xi;
            indices[ci * 6 + 1] = (yi + 1) * col + xi;
            indices[ci * 6 + 2] = yi * col + xi + 1;
            indices[ci * 6 + 3] = (yi + 1) * col + xi;
            indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
            indices[ci * 6 + 5] = yi * col + xi + 1;
            ci++;
        }
    }

    //创建缓冲区对象
    var vertexcolorbuffer = gl.createbuffer();
    var indexbuffer = gl.createbuffer();
    if (!vertexcolorbuffer || !indexbuffer) {
        return -1;
    }

    // 将缓冲区对象绑定到目标
    gl.bindbuffer(gl.array_buffer, vertexcolorbuffer);
    // 向缓冲区对象中写入数据
    gl.bufferdata(gl.array_buffer, verticescolors, gl.static_draw);

    //
    var fsize = verticescolors.bytes_per_element;
    // 向缓冲区对象分配a_position变量
    var a_position = gl.getattriblocation(gl.program, 'a_position');
    if (a_position < 0) {
        console.log('failed to get the storage location of a_position');
        return -1;
    }
    gl.vertexattribpointer(a_position, 3, gl.float, false, fsize * 6, 0);
    //开启a_position变量
    gl.enablevertexattribarray(a_position);

    // 向缓冲区对象分配a_color变量
    var a_color = gl.getattriblocation(gl.program, 'a_color');
    if (a_color < 0) {
        console.log('failed to get the storage location of a_color');
        return -1;
    }
    gl.vertexattribpointer(a_color, 3, gl.float, false, fsize * 6, fsize * 3);
    //开启a_color变量
    gl.enablevertexattribarray(a_color);

    // 写入并绑定顶点数组的索引值
    gl.bindbuffer(gl.element_array_buffer, indexbuffer);
    gl.bufferdata(gl.element_array_buffer, indices, gl.static_draw);

    return indices.length;
}

4. 其他

1.这里用到了几个《webgl编程指南》书中提供的js组件。全部源代码(包含dem数据)地址链接:https://share.weiyun.com/5cvt8pj ,密码:4aqs8e。
2.如果关心如何设置模型视图投影变换矩阵,以及绑定鼠标键盘事件,可参看这篇文章:webgl或opengl关于模型视图投影变换的设置技巧
3.渲染的结果如果加入光照,效果会更好。