zoukankan      html  css  js  c++  java
  • Cesium原理篇:Batch

           通过之前的Material和Entity介绍,不知道你有没有发现,当我们需要添加一个rectangle时,有两种方式可供选择,我们可以直接添加到Scene的PrimitiveCollection,也可以构造一个Entity,添加到Viewer的EntityCollection中,代码如下:

    // 直接构造Primitive,添加
    rectangle = scene.primitives.add(new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.RectangleGeometry({
                rectangle : Cesium.Rectangle.fromDegrees(-120.0, 20.0, -60.0, 40.0),
                vertexFormat : Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
            })
        }),
        appearance : new Cesium.EllipsoidSurfaceAppearance({
            aboveGround : false
        })
    }));
    
    // 间接构造一个Entity,Cesium内部将其转化为Primitive
    viewer.entities.add({
        rectangle : {
            coordinates : Cesium.Rectangle.fromDegrees(-92.0, 20.0, -86.0, 27.0),
            outline : true,
            outlineColor : Cesium.Color.WHITE,
            outlineWidth : 4,
            stRotation : Cesium.Math.toRadians(45),
            material : stripeMaterial
        }
    });

           两者有何不同,为什么还要提供Entity这种方式,绕了一大圈,最后照样是一个primitive。当然,有一个因素是后者调用简单,对用户友好。但还有一个重点是内部在把Entity转为Primitive的这条生产线上,会根据Entity的不同进行打组分类,好比快递的分拣线会将同一个目的地的包裹分到一类,然后用一个大的箱子打包送到该目的地,目的就是优化效率,充分利用显卡的并发能力。

           在Entity转为Primitive的过程中,GeometryInstance是其中的过渡类,以Rectangle为例,我们看看构造GeometryInstance的过程:

    RectangleGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
        if (this._materialProperty instanceof ColorMaterialProperty) {
            var currentColor = Color.WHITE;
            if (defined(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
                currentColor = this._materialProperty.color.getValue(time);
            }
            color = ColorGeometryInstanceAttribute.fromColor(currentColor);
            attributes = {
                show : show,
                color : color
            };
        } else {
            attributes = {
                show : show
            };
        }
    
        return new GeometryInstance({
            id : entity,
            geometry : new RectangleGeometry(this._options),
            attributes : attributes
        });
    }

           首先,该材质_materialProperty就是构建Entity时传入的材质对象,attributes则用来标识该Geometry实例化的attribute属性,Cesium内部判断该材质是否为color类型,进而对应不同的实例化attribute。在其他GeometryUpdater方法中都是此逻辑,因此在材质的处理上,只对color进行了实例化的处理。这里留意一下appearance参数,可以看到主要对应perInstanceColorAppearanceType和materialAppearanceType两种,分别封装ColorMaterialProperty和其他MaterialProperty,这个在之前的Material中已经讲过。

    Batch

           Cesium通过GeometryInstance作为标准,来达到物以类聚鸟以群分的结果,这个标准就是如上的介绍,有了标准还不够,还需要为这个标准搭建一条流水线,将标准转化为行动。这就是Batch的作用。之前在Entity中提到GeometryVisualizer提供了四种Batch,我们以StaticGeometryColorBatch和StaticGeometryPerMaterialBatch为例,对比说明一下这个流水线的流程。

           我们在此来到DataSourceDisplay类,初始化是针对每一个Updater,都封装了一个Visualizer.我们还是以RectangleGeometry为例展开:

    new GeometryVisualizer(WallGeometryUpdater, scene, entities)
    
    function GeometryVisualizer(type, scene, entityCollection) {
        for (var i = 0; i < numberOfShadowModes; ++i) {
            this._outlineBatches[i] = new StaticOutlineGeometryBatch(primitives, scene, i);
            this._closedColorBatches[i] = new StaticGeometryColorBatch(primitives, type.perInstanceColorAppearanceType, true, i);
            this._closedMaterialBatches[i] = new StaticGeometryPerMaterialBatch(primitives, type.materialAppearanceType, true, i);
            this._openColorBatches[i] = new StaticGeometryColorBatch(primitives, type.perInstanceColorAppearanceType, false, i);
            this._openMaterialBatches[i] = new StaticGeometryPerMaterialBatch(primitives, type.materialAppearanceType, false, i);
        }
    }

           而每一次添加的Entity都会以事件的方式通知到每一个Updater绑定的GeometryVisualizer,调用insertUpdaterIntoBatch方法,根据每个Entity材质的不同放到对应的Batch队列中,其实Cesium的batch很简单,就是看是否是color类型的材质,只有这一个逻辑判断:

    function insertUpdaterIntoBatch(that, time, updater) {    
        if (updater.fillMaterialProperty instanceof ColorMaterialProperty) {
            that._openColorBatches[shadows].add(time, updater);
        } else {
            that._openMaterialBatches[shadows].add(time, updater);
        }
    }

           我们先看ColorMaterialProperty材质的处理方式:

    function StaticGeometryColorBatch(primitives, appearanceType, closed, shadows) {
        this._solidBatch = new Batch(primitives, false, appearanceType, closed, shadows);
        this._translucentBatch = new Batch(primitives, true, appearanceType, closed, shadows);
    }
    
    StaticGeometryColorBatch.prototype.add = function(time, updater) {
        var instance = updater.createFillGeometryInstance(time);
        if (instance.attributes.color.value[3] === 255) {
            this._solidBatch.add(updater, instance);
        } else {
            this._translucentBatch.add(updater, instance);
        }
    };

           可见,按照颜色是否透明分为两类,这个不难理解,因为这两类对应的PASS不同,渲染的优先级不一样。同时,在添加到对应batch队列前,会调用Updater.createFillGeometryInstance方法创建该Geometry对应的Instance。因此,这里体现了Cesium的一个规范,每一个GeometryGraphics类型都对应了一个该Geometry的Updater类,该Updater类通过一套create*geometryInstance方法,实现不同的GeometryGraphics到GeometryInstance的标准化封装。下面是RectangleGeometryUpdater提供的三个create方法:

    // 填充面的geoinstance
    RectangleGeometryUpdater.prototype.createFillGeometryInstance
    // 边框线的geoinstance
    RectangleGeometryUpdater.prototype.createOutlineGeometryInstance
    // 针对动态批次
    RectangleGeometryUpdater.prototype.createDynamicUpdater

           前两个不用多说,看注释。后一个一看dynamic,看上去牛逼,其实只是将creategeometryinstance的过程延后进行,不是在add中创建,而是在update的时候创建。接着在Batchupdate中,将batch队列中所有的geometryinstances封装成一个Primitve,这个流水线至此结束。因为我们在之前的Entity中介绍过这个过程,所以不在此展开。下面,我们在看看StaticGeometryPerMaterialBatch,对比一下两者的不一样。

    StaticGeometryPerMaterialBatch.prototype.add = function(time, updater) {
        var items = this._items;
        var length = items.length;
        for (var i = 0; i < length; i++) {
            var item = items[i];
            if (item.isMaterial(updater)) {
                item.add(time, updater);
                return;
            }
        }
        var batch = new Batch(this._primitives, this._appearanceType, updater.fillMaterialProperty, this._closed, this._shadows);
        batch.add(time, updater);
        items.push(batch);
    };

          可以看到,非颜色材质的batch里面还有一个items数组,会判断当前的updater中的材质是否存在于items数组中,如果没有,则根据该材质创建一个新的batch,并添加到items数组中。因为多了这一层,所以之前Updater.createFillGeometryInstance的调用延后到batch.add的过程中,并无其他不同。然后调用batch.update,以材质类型为标准创建对应的primitive。

    BatchTable

           对于这些实例化的属性,Primitive在update中对其进行处理,思路就是将这些值保存到一张RGBA的纹理,并根据实例化属性的长度构建对应的VBO,从而方便Shader中的使用。下面,我们以两个Rectangle为例,来看看详细的过程。

    createBatchTable

    function createBatchTable(primitive, context) {
        // 0 获取instance
        // 获取该Primitive中instance数组
        var geometryInstances = primitive.geometryInstances;
        var instances = (isArray(geometryInstances)) ? geometryInstances : [geometryInstances];
        
        var attributeIndices = {};
        // 获取这些instances中相同的attribute属性字段的名称
        var names = getCommonPerInstanceAttributeNames(instances);
        
        // 1创建attribute
        // 创建这些属性字段的attribute,包括对应的变量名,字段类型等
        // indices是他们的索引
        for (i = 0; i < length; ++i) {
            name = names[i];
            attribute = instanceAttributes[name];
    
            attributeIndices[name] = i;
            attributes[i] = {
                functionName : 'czm_batchTable_' + name,
                componentDatatype : attribute.componentDatatype,
                componentsPerAttribute : attribute.componentsPerAttribute,
                normalize : attribute.normalize
            };
        }
        
        // 2为attributes赋值
        // 遍历所有的instance,取出每一个instance对应的attribute值
        // 将这些值按照其字段类型保存到batchTable中
        for (i = 0; i < numberOfInstances; ++i) {
            var instance = instances[i];
            instanceAttributes = instance.attributes;
    
            for (var j = 0; j < length; ++j) {
                name = names[j];
                attribute = instanceAttributes[name];
                var value = getAttributeValue(attribute.value);
                var attributeIndex = attributeIndices[name];
                batchTable.setBatchedAttribute(i, attributeIndex, value);
            }
        }
    
        // 4 将batch的结果保存在primitive中,方便下面的处理
        primitive._batchTable = batchTable;
        primitive._batchTableAttributeIndices = attributeIndices;
    }

           如上,可以看到BatchTable可以认为是这些instance的一个实例化属性表,属性也是按照VBO的结构来设计的,就是为了后续shader中使用的方便。

    BatchTable.prototype.update

    BatchTable.prototype.update = function(frameState) {
        createTexture(this, context);
        updateTexture(this);
    }

           创建完BatchTable,则调用update,将该Table的属性值以RGBA的方式保存到一张Texture中,这类似于一个float纹理,但通用性更强一些,毕竟有一些浏览器竟然不支持float纹理。比如ColorMaterialProperty,里面有color,show,distanceDisplayCondition三个实例化属性,分别控制颜色,是否可见以及可见范围的控制。实际上,还包括pickColor,boundingSphereRadius,boundingSphereCenter3DHigh,boundingSphereCenter3DLow,boundingSphereCenter2DHigh,boundingSphereCenter2DLow共计9个属性,其中Center占了四个属性,我们后续有机会在详细说一下Cesium的算法细节,目的是为了避免近距离观察物体时因为精度导致的抖动问题,用两个float来表示一个double的思路来解决。这样,假如我们有两个instance对象,则该纹理x维度是9*2 = 18,而大多数情况下,y维度则始终为1(只要x维度的长度不超过显卡最大纹理长度的限制),相当于一个一维纹理,其实就是一个hashtable。

           createTexture后就是updateTexture就是把我们之前set的attribute属性值保存到该纹理中。

    updateBatchTableBoundingSpheres

           这个不多讲了,就是刚才说的,把centre的xyz每一个属性保存为两个float的过程。

    createShaderProgram

    • BatchTable.prototype.getVertexShaderCallback
    • Primitive._appendShowToShader
    • Primitive._appendDistanceDisplayConditionToShader
    • Primitive._updateColorAttribute

           通过如上几个函数,添加处理BatchTable部分的片源着色器代码。

    createCommands

    BatchTable.prototype.getUniformMapCallback = function() {
        var that = this;
        return function(uniformMap) {
            var batchUniformMap = {
                batchTexture : function() {
                    return that._texture;
                },
                batchTextureDimensions : function() {
                    return that._textureDimensions;
                },
                batchTextureStep : function() {
                    return that._textureStep;
                }
            };
    
            return combine(uniformMap, batchUniformMap);
        };
    };

           如上,在创建command时,创建对应的uniformMap,传入uniform变量。

    总结

           如上就是Cesium批次流程的大概流程,着重介绍了BatchTable这种思想,如果我们在实际设计中这也是值得我们学习借鉴的地方。打个比方,如果你对相机不熟悉,就用自动对焦,则基本就是傻瓜操作,而如果你比较熟悉,则可以用单反,自己来设置参数。Batch流程也是如此,只是解决了最常见,最基本的分类,如果你足够熟悉,可以基于Primitive自己来手动完成分组的过程,多快好省,可以不同类型的geometry来做一个批次,always try, never die。

           好了,这里忽略了两个地方,一个是这个面如何做到贴地,二是Geometry在渲染时抖动有是怎么一回事。前者用到了模版缓冲的方法,后者则是float精度问题导致的,我们下一节在说一下第一个问题。

  • 相关阅读:
    现实世界的Windows Azure:采访Gridsum的Sr.业务发展总监Yun Xu
    现在可用——Windows Azure SDK 1.6
    Rock Paper Azure Challenge回来啦
    这几天比较忙,自己的职业生涯规划好了吗?目标又是什么呢?生活在十字路口。。。。。。
    GDI+ 学习记录(24): 输出文本<3>
    GDI+ 学习记录(30): MetaFile 文件操作
    GDI+ 学习记录(29): 区域 Region
    GDI+ 学习记录(26): 显示图像 Image
    GDI+ 学习记录(25): 变换 Transform
    返回整数的四种情况
  • 原文地址:https://www.cnblogs.com/fuckgiser/p/6198522.html
Copyright © 2011-2022 走看看