本文代码基于Vue-cli4和使用WebGL的地图引擎Cesium,主要内容为三维场景下不同对象的动态材质构建。
参考了很多文章,链接附在文末。
为不同的几何对象添加动态材质
不知道这一小节的名称概况是否准确,在我的理解中Cesium中的集合实体分成两类:Primitive和Entity,一般翻译成图元和实体,图元更接近底层,实体是封装后的高级对象,使用更加简便,这里不对使用场景进行分析,但会介绍如果为这两种集合对象添加材质。
使用Primitive生成泛光墙
一般来说,Primitive的使用相对繁琐,相比Entity需要使用者自己初始化更多对象,包括外观、地理信息等,但正因为如此,为Primitive添加材质要方便很多,因为可以直接操作几何体的外观部分。首先我们初始化一个墙几何体:
var wallInstance = new Cesium.GeometryInstance({
geometry: Cesium.WallGeometry.fromConstantHeights({
positions: Cesium.Cartesian3.fromDegreesArray([
97.0,
43.0,
107.0,
43.0,
107.0,
40.0,
97.0,
40.0,
97.0,
43.0,
]),
maximumHeight: 100000.0,
vertexFormat: Cesium.MaterialAppearance.VERTEX_FORMAT,
}),
})
viewer.scene.primitives.add(
new Cesium.Primitive({
geometryInstances: [wallInstance],
appearance: new Cesium.MaterialAppearance(),
})
)
上文代码所创建的是一个只有基础外观的“墙”, 实例化 Cesium.MaterialAppearance()
这个类不传参数所得到的的就是下图的样子:
官方文档中我们可以查到有如下参数:
这里我们关注的是 material
,也就是所谓的“材质”,接下来补充上材质的代码:
let image = '/static/images/colors1.png', //选择自己的动态材质图片
color = new Cesium.Color.fromCssColorString('rgba(0, 255, 255, 1)'),
speed = 0,
source =
'czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
vec2 st = materialInput.st;\n\
vec4 colorImage = texture2D(image, vec2(fract((st.t - speed*czm_frameNumber*0.005)), st.t));\n\
vec4 fragColor;\n\
fragColor.rgb = color.rgb / 1.0;\n\
fragColor = czm_gammaCorrect(fragColor);\n\
material.alpha = colorImage.a * color.a;\n\
material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
material.emission = fragColor.rgb;\n\
return material;\n\
}'
let material = new Cesium.Material({
fabric: {
type: 'PolylinePulseLink',
uniforms: {
color: color,
image: image,
speed: speed,
},
source: source,
},
translucent: function () {
return true
},
})
viewer.scene.primitives.add(
new Cesium.Primitive({
geometryInstances: [greenWallInstance],
appearance: new Cesium.MaterialAppearance({
material: material,
}),
})
)
应用材质的效果图:
材质文件colros1.png:
通过上面的代码和截图可以看出材质文件和最后表现出的结果还是有很大差异的,而且变量source中的代码看起来似乎很难理解,这些内容会在下文进行说明,本节还是针对材质如何应用进行说明。
使用Entity生成流动线
参考Primitive的流程,我们先创建一个实体对象,这次我们换一个场景,改为创建流动线,参考的文章 流动线纹理