webgl gis java_WebGL-实例化绘制

今天来学习webgl一个重要功能:Instanced Drawing

(实例化绘制),内容翻译自webgl学习网站webglfundamentals(由于英语水平尽量按原文翻译):https://webglfundamentals.org/webgl/lessons/webgl-instanced-drawing.html。

WebGL下个版本(WebGL2.0)有一个功能叫实例化绘制。

它的基本思想是:一次绘制多个相同对象的效率要高于多次绘制同一个对象。这个功能在WebGL1.0标准可以通过扩展实现,目前大部分浏览器都支持这个功能。

首先我们来做一个示例:绘制同一个对象的多个实例。

我们以下面这两个shader代码开始:

·

·

·attribute vec4 a_position;

·uniform mat4 matrix;

·voidmain(){

·// Multiply the position by the matrix.

·gl_Position=matrix*a_position;

·}

·

·

·

·precision mediumpfloat;

·uniform vec4 color;

·voidmain(){

·gl_FragColor=color;

·}

·

顶点着色器代码中实现每个顶点都乘以一个变换矩阵实现坐标转换,片元着色器中通过uniform变量传进一个颜色实现每个片元都是一样颜色。最终绘制需要编译和连接shader代码,关联attribute和uniform变量位置:

·constprogram=webglUtils.createProgramFromScripts(

·gl,['3d-vertex-shader','3d-fragment-shader']);

·constpositionLoc=gl.getAttribLocation(program,'a_position');

·constcolorLoc=gl.getUniformLocation(program,'color');

·constmatrixLoc=gl.getUniformLocation(program,'matrix');

通过buffer关联所需顶点数据:

·constpositionBuffer=gl.createBuffer();

·gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);

·gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([

·-0.1,0.4,

·-0.1,-0.4,

·0.1,-0.4,

·0.1,-0.4,

·-0.1,0.4,

·0.1,0.4,

·0.4,-0.1,

·-0.4,-0.1,

·-0.4,0.1,

·-0.4,0.1,

·0.4,-0.1,

·0.4,0.1,

·]),gl.STATIC_DRAW);

·constnumVertices=12;

我们绘制5个相同(这里的相同指每个示例的形状大小一样)实例,那么就需要对应5个矩阵和5个颜色值:

·constnumInstances=5;

·constmatrices=[

·m4.identity(),

·m4.identity(),

·m4.identity(),

·m4.identity(),

·m4.identity(),

·];

·constcolors=[

·[1,0,0,1,],// red

·[0,1,0,1,],// green

·[0,0,1,1,],// blue

·[1,0,1,1,],// magenta

·[0,1,1,1,],// cyan

·];

渲染对象首先设置attribute对应的值,循环5次(这里绘制5个实例),每次设置不同的变换矩阵和颜色。

·functionrender(time){

·time *=0.001;// seconds

·gl.useProgram(program);

·// setup the position attribute

·g

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...