snow.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. class SnowEffect {
  2. constructor(viewer, options) {
  3. if (!viewer) throw new Error("no viewer object!");
  4. options = options || {};
  5. this.snowSize = Cesium.defaultValue(options.snowSize, 0.02); //最好小于0.02
  6. this.snowSpeed = Cesium.defaultValue(options.snowSpeed, 60.0);
  7. this.viewer = viewer;
  8. this.init();
  9. }
  10. init() {
  11. this.snowStage = new Cesium.PostProcessStage({
  12. name: "czml_snow",
  13. fragmentShader: this.snow(),
  14. uniforms: {
  15. snowSize: () => {
  16. return this.snowSize;
  17. },
  18. snowSpeed: () => {
  19. return this.snowSpeed;
  20. },
  21. },
  22. });
  23. this.viewer.scene.postProcessStages.add(this.snowStage);
  24. }
  25. //销毁对象
  26. destroy() {
  27. if (!this.viewer || !this.snowStage) return;
  28. this.viewer.scene.postProcessStages.remove(this.snowStage);
  29. this.snowStage.destroy();
  30. delete this.snowSize;
  31. delete this.snowSpeed;
  32. }
  33. //控制显示
  34. show(visible) {
  35. this.snowStage.enabled = visible;
  36. }
  37. //CLML对象,方便导出使用
  38. snow() {
  39. return "uniform sampler2D colorTexture;\n\
  40. varying vec2 v_textureCoordinates;\n\
  41. uniform float snowSpeed;\n\
  42. uniform float snowSize;\n\
  43. float snow(vec2 uv,float scale)\n\
  44. {\n\
  45. float time=czm_frameNumber/snowSpeed;\n\
  46. float w=smoothstep(1.,0.,-uv.y*(scale/10.));if(w<.1)return 0.;\n\
  47. uv+=time/scale;uv.y+=time*2./scale;uv.x+=sin(uv.y+time*.5)/scale;\n\
  48. uv*=scale;vec2 s=floor(uv),f=fract(uv),p;float k=3.,d;\n\
  49. p=.5+.35*sin(11.*fract(sin((s+p+scale)*mat2(7,3,6,5))*5.))-f;d=length(p);k=min(d,k);\n\
  50. k=smoothstep(0.,k,sin(f.x+f.y)*snowSize);\n\
  51. return k*w;\n\
  52. }\n\
  53. void main(void){\n\
  54. vec2 resolution=czm_viewport.zw;\n\
  55. vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y);\n\
  56. vec3 finalColor=vec3(0);\n\
  57. //float c=smoothstep(1.,0.3,clamp(uv.y*.3+.8,0.,.75));\n\
  58. float c=0.;\n\
  59. c+=snow(uv,30.)*.0;\n\
  60. c+=snow(uv,20.)*.0;\n\
  61. c+=snow(uv,15.)*.0;\n\
  62. c+=snow(uv,10.);\n\
  63. c+=snow(uv,8.);\n\
  64. c+=snow(uv,6.);\n\
  65. c+=snow(uv,5.);\n\
  66. finalColor=(vec3(c));\n\
  67. gl_FragColor=mix(texture2D(colorTexture,v_textureCoordinates),vec4(finalColor,1),.5);\n\
  68. }\n\
  69. ";
  70. }
  71. }
  72. export default SnowEffect;