Cesium高级教程-百万级图形渲染-自定义实例化渲染基础
构建实例化渲染的图形
我们以实例化渲染一个三角形为例,首先我们需要指定三角形的三个顶点,假定三角形的三个坐标信息如下
// z// | /y// |/// o------xconstpositions=newFloat32Array([-10.,-10,0.,//010.,-10.,0.,//10.,15.,0.,//2]);创建绘制指令并加入渲染
接下来我们根据图形顶点坐标创建绘制指令DrawCommand,该过程我们在前面章节已经详细介绍过,首先就是创建顶点缓冲VBO,然后创建顶点缓冲数组VAO,创建着色器程序,最后创建DrawCommand对象,想要将DrawCommand加入场景渲染队列,我们还需要自定义一个Primitive,这里唯一需要注意的是我们设置了DrawCommand的instanceCount为10,代表我们需要实例化渲染10个三角形。
constvertexBuffer=Cesium.Buffer.createVertexBuffer({context:scene.context,typedArray:positions,usage:Cesium.BufferUsage.STATIC_DRAW});constattributes=[{index:0,enabled:true,vertexBuffer:vertexBuffer,componentsPerAttribute:3,componentDatatype:Cesium.ComponentDatatype.FLOAT,}];constvertexArray=newCesium.VertexArray({context:scene.context,attributes:attributes});constvs=`in vec3 position; void main() { vec3 p=position.xyz; gl_Position = czm_modelViewProjection * vec4(p,1.0); }`letfs=`void main() { out_FragColor = vec4(1.0,1.,0.,0.6); }`...letmodelMatrix=Cesium.Transforms.eastNorthUpToFixedFrame(position);letcommand=newCesium.DrawCommand({modelMatrix:modelMatrix,vertexArray:vertexArray,shaderProgram:shaderProgram,pass:Cesium.Pass.TRANSLUCENT,renderState:Cesium.RenderState.fromCache({depthTest:{enabled:true,},})instanceCount:10,})classMyPrimitive{constructor(){}update(frameState){frameState.commandList.push(command);}isDestroyed(){returnfalse;}}letp=newMyPrimitive();viewer.scene.primitives.add(p);此时运行程序会发现场景中只有一个三角形出现,这是因为虽然已经设置了instanceCount为10,但是还没有设置其它参数,实际上此时场景中确实有10个三角形,只不过这些三角形位置大小都一样,也就是重叠在一起的,所以看上去只有一个三角形。
如何区分每个实例图形
为了区分每一实例图形,首先我们需要用到WebGL着色器中自带的一个变量gl_InstanceID,该变量代表每个实例图形的编号,是一个整数值,从0开始计数,比如设置instanceCount为10,那么gl_InstanceID的取值范围就是[0-9]。现在我们在顶点着色器中通过该变量来设置每个图形的差异,我们将每个图形顶点坐标的z值加上gl_instanceID * 10.,这样每个图形之间就会发生偏移了。
constvs=`in vec3 position; void main() { ... }`示例效果可到 xt3d 官网 运行查看
更多内容见 Cesium高级教程-教程简介