(function (Cesium) { function RainEffect(viewer, options) { if (!viewer) throw new Error("viewer is undefined") this.viewer = viewer; this.speed = Cesium.defaultValue(options.speed, 10) this.size = Cesium.defaultValue(options.size, 20) this.direction = Cesium.Math.toRadians(Cesium.defaultValue(options.direction, -30)); this.enabled = Cesium.defaultValue(options.enabled, true) this.init(); } RainEffect.prototype.init = function () { this.rainStage = new Cesium.PostProcessStage({ name: 'czm_rain', fragmentShader: this.FragmentShader_Rain(), uniforms: { direction: () => { return this.direction }, size: () => { return this.size; }, speed: () => { return this.speed; } } }); this.rainStage.enabled = this.enabled this.viewer.scene.postProcessStages.add(this.rainStage) } //定义下雨场景 着色器 RainEffect.prototype.FragmentShader_Rain = function () { return `uniform sampler2D colorTexture;//下雨前输入的场景渲染照片 varying vec2 v_textureCoordinates; uniform float speed; uniform float size; uniform float direction; float hash(float x){ return fract(sin(x*23.3)*13.13); } void main(void){ float time = czm_frameNumber * speed / 1000.0; vec2 resolution = czm_viewport.zw; vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y); vec3 finalColor=vec3(0.1,0.2,0.3);//粒子的颜色 float si=sin(direction),co=cos(direction); uv*=mat2(co,-si,si,co); uv*=length(uv+vec2(0,4.9))*0.3+1.0; float v=1.-sin(hash(floor(uv.x*100.0))*2.0); float b=clamp(abs(sin(20.0*time*v+uv.y*(5./(2.0+v))))-.95,0.0,1.0)*size; finalColor*=v*b; //屏幕上雨的颜色 gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(finalColor,1.0), 0.5); //将雨和三维场景融合 } ` } RainEffect.prototype.show = function (visible) { this.rainStage.enabled = visible; } RainEffect.prototype.destroy = function () { if (!this.viewer || !this.rainStage) return; this.viewer.scene.postProcessStages.remove(this.rainStage); this.rainStage.destroy(); delete this.direction delete this.size delete this.speed } Cesium.RainEffect = RainEffect })(Cesium)