FogEffect.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. (function () {
  2. function FogEffect(viewer, options) {
  3. if (!viewer) throw new Error("viewer is undefined")
  4. this.viewer = viewer;
  5. this.fogByDistance = Cesium.defaultValue(options.fogByDistance, new Cesium.Cartesian4(10, 0.0, 1000, 0.9))
  6. this.maxHeight = Cesium.defaultValue(options.maxHeight, 9000)
  7. this.color = Cesium.defaultValue(options.color, Cesium.Color.WHITE)
  8. this.init();
  9. }
  10. FogEffect.prototype.init = function () {
  11. this.FogStage = new Cesium.PostProcessStage({
  12. name: 'czm_fog',
  13. fragmentShader: this.FragmentShader_Fog(),
  14. uniforms: {
  15. fogByDistance: () => { return this.fogByDistance; },
  16. fogColor: () => { return this.color; }
  17. }
  18. });
  19. this.FogStage.enabled = this.enabled
  20. this.viewer.scene.postProcessStages.add(this.FogStage)
  21. }
  22. //定义下雨场景 着色器
  23. FogEffect.prototype.FragmentShader_Fog = function () {
  24. return `float getDistance(sampler2D depthTexture, vec2 texCoords)
  25. {
  26. float depth = czm_unpackDepth(texture2D(depthTexture, texCoords));
  27. if (depth == 0.0) {
  28. return czm_infinity;
  29. }
  30. vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, depth);
  31. return -eyeCoordinate.z / eyeCoordinate.w;
  32. }
  33. float interpolateByDistance(vec4 nearFarScalar, float distance)
  34. {
  35. float startDistance = nearFarScalar.x;
  36. float startValue = nearFarScalar.y;
  37. float endDistance = nearFarScalar.z;
  38. float endValue = nearFarScalar.w;
  39. float t = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0);
  40. return mix(startValue, endValue, t);
  41. }
  42. vec4 alphaBlend(vec4 sourceColor, vec4 destinationColor)
  43. {
  44. return sourceColor * vec4(sourceColor.aaa, 1.0) + destinationColor * (1.0 - sourceColor.a);
  45. }
  46. uniform sampler2D colorTexture;
  47. uniform sampler2D depthTexture;
  48. uniform vec4 fogByDistance;
  49. uniform vec4 fogColor;
  50. varying vec2 v_textureCoordinates;
  51. void main(void)
  52. {
  53. float distance = getDistance(depthTexture, v_textureCoordinates);
  54. vec4 sceneColor = texture2D(colorTexture, v_textureCoordinates);
  55. float blendAmount = interpolateByDistance(fogByDistance, distance);
  56. vec4 finalFogColor = vec4(fogColor.rgb, fogColor.a * blendAmount);
  57. gl_FragColor = alphaBlend(finalFogColor, sceneColor);
  58. }
  59. `
  60. }
  61. FogEffect.prototype.show = function (visible) {
  62. this.FogStage.enabled = visible;
  63. }
  64. FogEffect.prototype.destroy = function (visible) {
  65. if (!this.viewer || !this.FogStage) return;
  66. this.viewer.scene.postProcessStages.remove(this.FogStage);
  67. this.FogStage.destroy();
  68. delete this.alpha
  69. }
  70. Cesium.FogEffect = FogEffect
  71. })()