Client LuaCsForBarotrauma
BlurEffect.cs
1 using Microsoft.Xna.Framework;
2 using Microsoft.Xna.Framework.Graphics;
3 using System;
4 
5 namespace Barotrauma
6 {
7  class BlurEffect
8  {
9  public readonly Effect Effect;
10 
11  public BlurEffect(Effect effect, float dx, float dy)
12  {
13  Effect = effect;
14 
15  SetParameters(dx, dy);
16  }
17 
18 
23  public void SetParameters(float dx, float dy)
24  {
25  EffectParameter weightsParameter = Effect.Parameters["SampleWeights"];
26  EffectParameter offsetsParameter = Effect.Parameters["SampleOffsets"];
27 
28  // Look up how many samples our gaussian blur effect supports.
29  int sampleCount = weightsParameter.Elements.Count;
30 
31  // Create temporary arrays for computing our filter settings.
32  float[] sampleWeights = new float[sampleCount];
33  Vector2[] sampleOffsets = new Vector2[sampleCount];
34 
35  sampleWeights[0] = ComputeGaussian(0);
36  sampleOffsets[0] = new Vector2(0);
37 
38  float totalWeights = sampleWeights[0];
39 
40  // Add pairs of additional sample taps, positioned
41  // along a line in both directions from the center.
42  for (int i = 0; i < sampleCount / 2; i++)
43  {
44  // Store weights for the positive and negative taps.
45  float weight = ComputeGaussian(i + 1);
46 
47  sampleWeights[i * 2 + 1] = weight;
48  sampleWeights[i * 2 + 2] = weight;
49 
50  totalWeights += weight * 2;
51 
52  // To get the maximum amount of blurring from a limited number of
53  // pixel shader samples, we take advantage of the bilinear filtering
54  // hardware inside the texture fetch unit. If we position our texture
55  // coordinates exactly halfway between two texels, the filtering unit
56  // will average them for us, giving two samples for the price of one.
57  // This allows us to step in units of two texels per sample, rather
58  // than just one at a time. The 1.5 offset kicks things off by
59  // positioning us nicely in between two texels.
60  float sampleOffset = i * 2 + 1.5f;
61 
62  Vector2 delta = new Vector2(dx, dy) * sampleOffset;
63 
64  // Store texture coordinate offsets for the positive and negative taps.
65  sampleOffsets[i * 2 + 1] = delta;
66  sampleOffsets[i * 2 + 2] = -delta;
67  }
68 
69  // Normalize the list of sample weightings, so they will always sum to one.
70  for (int i = 0; i < sampleWeights.Length; i++)
71  {
72  sampleWeights[i] /= totalWeights;
73  }
74 
75  weightsParameter.SetValue(sampleWeights);
76  offsetsParameter.SetValue(sampleOffsets);
77  }
78 
79 
84  float ComputeGaussian(float n)
85  {
86  float theta = 2.0f;
87 
88  return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
89  Math.Exp(-(n * n) / (2 * theta * theta)));
90  }
91 
92  }
93 }
void SetParameters(float dx, float dy)
Computes sample weightings and texture coordinate offsets for one pass of a separable gaussian blur f...
Definition: BlurEffect.cs:23
readonly Effect Effect
Definition: BlurEffect.cs:9
BlurEffect(Effect effect, float dx, float dy)
Definition: BlurEffect.cs:11