RainEffect.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. class RainEffect {
  2. constructor(viewer, options) {
  3. if (!viewer) throw new Error('no viewer object!');
  4. options = options || {};
  5. //倾斜角度,负数向右,正数向左
  6. this.tiltAngle = Cesium.defaultValue(options.tiltAngle, -.6);
  7. this.rainSize = Cesium.defaultValue(options.rainSize, 0.3);
  8. this.rainSpeed = Cesium.defaultValue(options.rainSpeed, 60.0);
  9. this.viewer = viewer;
  10. this.init();
  11. }
  12. init() {
  13. this.rainStage = new Cesium.PostProcessStage({
  14. name: 'czm_rain',
  15. fragmentShader: this.rain(),
  16. uniforms: {
  17. tiltAngle: () => {
  18. return this.tiltAngle;
  19. },
  20. rainSize: () => {
  21. return this.rainSize;
  22. },
  23. rainSpeed: () => {
  24. return this.rainSpeed;
  25. }
  26. }
  27. });
  28. this.viewer.scene.postProcessStages.add(this.rainStage);
  29. }
  30. destroy() {
  31. if (!this.viewer || !this.rainStage) return;
  32. this.viewer.scene.postProcessStages.remove(this.rainStage);
  33. this.rainStage.destroy();
  34. delete this.tiltAngle;
  35. delete this.rainSize;
  36. delete this.rainSpeed;
  37. }
  38. show(visible) {
  39. this.rainStage.enabled = visible;
  40. }
  41. rain() {
  42. return "uniform sampler2D colorTexture;\n\
  43. varying vec2 v_textureCoordinates;\n\
  44. uniform float tiltAngle;\n\
  45. uniform float rainSize;\n\
  46. uniform float rainSpeed;\n\
  47. float hash(float x) {\n\
  48. return fract(sin(x * 133.3) * 13.13);\n\
  49. }\n\
  50. void main(void) {\n\
  51. float time = czm_frameNumber / rainSpeed;\n\
  52. vec2 resolution = czm_viewport.zw;\n\
  53. vec2 uv = (gl_FragCoord.xy * 2. - resolution.xy) / min(resolution.x, resolution.y);\n\
  54. vec3 c = vec3(.6, .7, .8);\n\
  55. float a = tiltAngle;\n\
  56. float si = sin(a), co = cos(a);\n\
  57. uv *= mat2(co, -si, si, co);\n\
  58. uv *= length(uv + vec2(0, 4.9)) * rainSize + 1.;\n\
  59. float v = 1. - sin(hash(floor(uv.x * 100.)) * 2.);\n\
  60. float b = clamp(abs(sin(20. * time * v + uv.y * (5. / (2. + v)))) - .95, 0., 1.) * 20.;\n\
  61. c *= v * b;\n\
  62. gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(c, 1), .5);\n\
  63. }\n\
  64. ";
  65. }
  66. }
  67. Cesium.RainEffect = RainEffect;