↓ Skip to main content

Reactive Shield Shader Devlog

·3086 words·15 mins

Project here.

This is a demo of a reactive shield setup that I had build as a combination of a few ideas I saw online and also some really popular shader techniques.  Even if a basic sci-fi shader is simple, I wanted to also make it react to the world in a satisfying way. This article covers a potential set-up, the shader and also some of the performance implications that might not be necessarily mentioned all the time.

The game engine setup
#

Even the fanciest shader will not be able to access any information that is not stored on the GPU. In this case, the game engine will provide proximity information about what geometry is nearby. I think the easier way is to use the engine’s provided collision system to sample the nearby world. For that, I created a script called ShaderController

In regard to how to observe the nearby world, there are a few approaches we can take. The most important criteria is that our shield should not only react to the position of objects, it should react to the entire volume of a very wide wall, otherwise the effect doesn’t work very well.

 

In some situations, creating a huge 3D collider and collecting information about nearby objects is probably the better approach. Or a projectile might look for collisions and notify the right object with it’s position and properties. We can push forward a position and the bounding box of our object. Maybe we can send the positions of objects, the corners of the bounding boxes, or even write a more complex algorithm to sample nearby surfaces.   There is no point in reinventing the wheel, however and for our demo I have chosen a very simple approach. One of the most accessible tools in game engines is the raycast functionality. To define a ray, we need to points, a starting point and a ending point. Then the engine will give us a hit object that might or might not be empty. We subtract the radius of the sphere and clamp to 0, to make activation happen when something is inside the shield. Then we divide by rayLength for a final value between 0 and 1. This setup makes it so the corners of Godot colliders still trigger the shield properly.

var from = GlobalPosition;  
var point = points[i] ;  
var to = ToGlobal(point + point.Normalized() * rayLength);    

var q = PhysicsRayQueryParameters3D.Create(from, to);  
q.Exclude = _ignored;  
var hit = space.IntersectRay(q);

if (hit.Count > 0){  
    float distance = Mathf.Max(from.DistanceTo((Vector3)hit["position"]) - radius, 0f);  
    depths[i] = distance / rayLength;  
}

The starting point is the current object, the centre of the shield. The interesting part is the finish point. We want to cast rays in every direction around the surface of the shield. Because our shield is a sphere, we basically need to distribute points across a sphere. There are many ways to do that and a lot of math involved but for my simple demo I chose the Fibonacci sphere method, which is very common and very well documented online.

{
    points = new Vector3[pointCount];
    
    for (int i = 0; i < pointCount; i++){  
        points[i] = GetPointAtIndex(i) * radius;  
 }
}

Vector3 GetPointAtIndex(int index){  
    float j = index + 0.5f;  
    float phi = Mathf.Acos(1 - 2 * j / pointCount);  
    float theta = 2 * Mathf.Pi * j / goldenRatio;  
  
    float x = Mathf.Cos(theta) * Mathf.Sin(phi);  
    float y = Mathf.Sin(theta) * Mathf.Sin(phi);  
    float z = Mathf.Cos(phi);  
  
    Vector3 newPoint = new Vector3(x, y, z);  
    return newPoint;  
}

We cache those points in local coordinates, and then we can cast rays in every single direction using global coordinates. Most shields in most media is some sort of Spheroid so in theory all you need to do afterwards is scale this and rotate this array of points in various ways.Or create those points manually, or research another way of putting points of your object of choice. In the most desperate case scenario, Blender itself offers as part of Geometry Nodes a lot of ways of placing points on arbitrary surfaces with various distributions. Exporting that as a list of coordinates and using them in your engine of choice is not something that sounds too complicated.

Also, as a downside, small objects will not trigger the ray at all or it might trigger it for a very small amount of time. Increasing the amount of points is an option if this is your hero asset. Distributing the points more efficiently is another option. Or designing an event-based system where objects tell you where they are and you create this information in some other mixed way. I think a lot of solutions can be created based on the specs of your project. For my project, I found that I can make the depth array persistent and slowly decay it inside Update and the effect looks good enough even for smaller objects.

for (int i = 0; i < depths.Length; i++){  
    depths[i] = Mathf.Min(1f, depths[i] + decayRate * (float)delta);  
}

  Finally, it is time to tell the shader about our world. In my case, I have chosen to send to arrays of information as uniform arrays, memory blocks that are associated with our shader program. They are fixed size and many instances of our shader will each read from this single memory block.

{ //64 points, this gets sent once, 
private Vector3[] points; 
shader.SetShaderParameter("points", points);
}

{ //This gets sent every single frame
float[] depths = new float[64]; 
shader.SetShaderParameter("depths", depths);
}

And those end up in the Godot shader as:

const int POINT_COUNT = 64;  
uniform float depths[POINT_COUNT];  
uniform vec3 points[POINT_COUNT];

With this information, we know the position of 64 points and we know a value between 0 and 1 that tells us how close an object is to that point. It might seem a bit convoluted, but it really helps out calculations later while keeping bandwidth at a minimum. Not like bandwidth is a real concern in this case. 64 floats of 32 bits each,  at 60 fps ends up being 122880 bits per second (or 15 kilobytes/s). When we think about modern PCIe GPUs, we think 16GB/s a second so we are fine. Still, it’s good to be aware of this aspect of GPU programming. Game engines also do a lot of very technical work like extracting the data from our C# script, creating the memory buffers, handling buffering, batching, staging and synchronisation. I plan to get into those subjects in future posts.

The vertex shader.
#

First of all, we need to decide what to do with our points and our depths. We are going to sample the 64 points we received from the game engine and calculate a intensity property for each vertex in our model. We might as well simply forward this information directly to the fragment shader and that might result in simpler code and a better-looking result. But also keep in mind that every calculation that ends up in the fragment will be ran for every single pixel that the object is touching. Our shield is transparent so the GPU will draw it on top of existing pixels for the objects that are in the background. Transparency prevents the GPU from rejecting a lot of pixel candidates early and for a 4k screen the number of fragment programs being run is into the millions. As much as modern GPUs are a wonder, you can quickly overwhelm it if you mess too much in the fragment shader.

For the vertex shader, our calculations are done once for each vertex in the shader. Vertex density, the distance between points, their layout- all of this contributes to how the code in the vertex shader ends up being ran.   Because this is a sphere, there are actually 3 popular ways of laying out vertices and triangles in a spherical fashion. Here is the humble quad sphere, the segment sphere and the ico-sphere. They all have strengths and weaknesses. The segment sphere has a single top vertex that will end up breaking a lot of shaders, the quad sphere has very visible seams and the ico sphere has a very difficult-to-handle UV mapping. Luckily, using Blender, it is trivial to just try to all 3 for your own projects. I settled for the segment sphere for it’s simpler projection/ UVs and I simply hide the top of the shader to avoid the weird artefacts.

Depths to vertex sampling
#

What I ended up doing is a combination of sampling nearby ray points and blending them together based on distance in a sort of max blend. The most important variable is influence_range that decides how far each vertex will sample the ray points. Imagine a sphere that exists around each vertex of the model and will contain a various number of our nice Fibonacci sphere points. Depending on how you generate your points and how you decide to do this sampling, I think it can either get really simple or really complicated. For my shader, I opted to simply pick the maximum value I found in the local samples and this works pretty well.

void vertex() {
...
intensity = 0.0;  
for (int i = 0; i < POINT_COUNT; i++) {  
    float distanceScalar = distance(VERTEX, points[i]) / influence_range;  
    if (distanceScalar < 1.0) {  
       float potentialIntensity = (1.0 - depths[i]) * (1.0 - distanceScalar);  
 intensity = max(intensity, potentialIntensity);    }}
...
}

Wobble
#

Finally, I thought a subtle wobble effect would make the shield way cooler. Each point needs to move closer or further away from its origin point so we get a direction that is actually just the vertex position in itself. (Don’t confuse a point with a vector but in this case it just works) The noise texture is just a bit of spice. Noise is structured randomness. We take adjacent points in the noise texture, we map them to 0….2PI and we use them as a phase shift for a sin function. This is the simplest implementation of waves. You can also come up with a 1000 different variations of this. Sometimes just writing down a lot of random math is the path to something good-looking.

vec3 dir = normalize(VERTEX);  
float noise_sample =  texture(cell_tex, UV * noise_tiling).r;  
VERTEX += dir * sin(TIME * wobble_speed + noise_sample * TAU) * wobble_amount;

Finally, keep in mind that even this wobble animation (the same as the depth sampling) happens per vertex. So the position and density of our vertices really matter. Have too few or too many vertices in your model and this kind of animation might start to look weird or be too expensive. The whole shader can definitely look very different depending on how many triangles we work with.

The fragment shader
#

Shader work is where the fun can begin in earnest. I think Godot in particular does a very good job of allowing you to use shaders easily. Simply being able to drag and drop textures and procedural textures into a slot can be a lot of fun. For the fragment shader, I just kept throwing things at the wall. Depending on your own particular needs, a lot of things can be done here.

Let’s remember the information we have right now. We have vertices, each holding a property called intensity. For each pixel, we get an interpolated value of this intensity between the 3 vertices that compose the triangle being rasterised. This is called barycentric interpolation. Those kinds of values that travel between the vertex and fragment shader are called varyings. In Unity’s HLSL, the vertex shader returns a struct of type Varyings that you can modify, but in Godot’s GLSL inspired approach we just a simple declaration. When the GPU starts calling the millions of instances of the fragment shader, it will make sure the values for them are properly interpolated.

varying float intensity;

We also get the actual position of this pixel in local space. We also have the UV position of the pixel. We also get as many arbitrary numbers and textures as our heart desires.

First of all, to get rid of the intensity question, I settled on using intensity for EMISSION and ALPHA. Emission tells Godot and ultimately the GPU that this pixel is self-illuminating and can be a pure blue colour even in a dark room with no light source. ALPHA is basically transparency, when it is 0 the object is transparent and when it is 1 the object’s colours are the only colours on that pixel.

Keep in mind that every property we see is actually just a single number. This fragment shader will run for a pixel, that pixel will position itself in the world and on the textures we load, then it will decide for itself how transparent it is, how shiny it is, etc.

void fragment() {
...
EMISSION = shield_color.rgb * (power  * intensity);
ALPHA = max(intensity, rim) * maskValue 
...
}

Everything we write here basically runs in a giant loop. It is not a loop in the sense that it is not sequential and each run is basically independent of the others, but at the end, each fragment() run will return only a few numbers like colour, transparency, a normal vector, etc. Godot shader code will continue with those numbers until it arrives at a final colour output, that colour is written on the screen buffer by the GPU and then you simply see a pixel change colour.

Here is also an example of the kind of UV mapping that we need to use to assign pixels to a flat surface. Each pixel knows where it is on a 2D texture because we tell it where it is. A good projection does not distort the 2D image and makes the seams invisible. In this example, we can get a UV mapping from the Blender ico-sphere, and we discover how it does a very poor job of hiding seams but with very low distortion.

On the other side, the segment sphere has a much nicer-looking UV projection if you want to take this in Photoshop, and the seams are easy to work around. The problem is mainly that it is a poor projection with a lot of distortion and a lot of concentrated distortion around the top.

Of course, we don’t have to take Blender’s defaults; we can cut a cap around the top, create a single seam, and overall end up with a compromise. Except that now half the surface of the texture ends up unused. Which in practice means objects on screen have half the resolution and take double the VRAM, which I think is a fact that would make a lot of users hostile.

Anyway, with the boring stuff out of the way, here is the moment to be creative. I encourage you to try basically anything. You can try Blender’s workflows, Substance Designer or any procedural texture workflow. For today’s Godot adventure, we will use a free program made in Godot called Material Maker.

We take a beehive, we tone-step it, we assign random grey values, we tone-step again, we make a normal map. The more nodes you know, the more math you want to use, the more liberating it becomes to create all kinds of textures for your shader. They all represent information that you can then draw upon for any use.

Take the alpha calculation. I thought it would be fun to poke some hexagonal holes in our hexagonal shield, so I created a mask and simply did:

float maskValue = texture(mask, UV * hex_tiling).r;  
ALPHA = max(intensity, rim) * maskValue ;

Now, where this texture is dark is where we poke holes in our shield. Because the mask texture is black here, this ends up being a multiplication with 0 and that results in all the pixels that were mapped to this area being simply not drawn.

Another thing that is incredibly easy to do is to rotate your UVs around using the value of time . This animated texture trick is incredibly common, but it does depend on you having UVs that are made with this in mind. Because our segment sphere has an incredibly simple UV map, this effect works wonderfully to rotate the hexagons around the sphere.

UV += vec2(TIME * uv_speed.x, TIME * uv_speed.y);

I also tried a bunch of other effects:

  • Used another texture to modulate the base colour and give the shield a bit more depth.  
  • I tried varying ALPHA using a Fresnel calculation.  This way the middle of the bubble stays transparent while the sides shine. The character remains visible through the shield.
  • I tried the normal map output created by Material Maker. I am not sure it’s 100% compatible but it looks fun so what more can I say.
  • I tried hiding pixels using their height and an arbitrary value in local space. This way, I can just not render the pixel towards the top of the sphere where all the messed-up projection happens. Work smart, not hard.
  • I implemented this rim effect to great results. This is a screen-space and depth buffer effect that would take a lot more time to explain but the most important thing is Godot just gives us everything we need on a platter, so you can begin to learn  those techniques right away without the tedious OpenGL setup. Here is the basic function call you need to follow.
float rim =  getRimValue(SCREEN_UV, INV_PROJECTION_MATRIX, VERTEX) * rim_power;
EMISSION = shield_color.rgb * rim;

And that basically completes our shader. There is a lot of tooling and logic that can be done. Make the shield red on damage. Make it more wobbly, you can calculate a procedural mask to have hexagons disappear with damage. This shield work also needs to be paired up with particle work and sound work before you have a believable projectile that strikes your shield. But I believe a shader like this can really be the centerpiece of your game’s visual language.

Closing
#

Shader programming means getting used to a lot of concepts and tools that are completely outside the shader file. It’s about taking data and combining it in a way the GPU understands. So when I try to learn this stuff, I don’t take game engine knowledge for granted, or Blender knowledge, or graphics API knowledge. It all seems to help a ton. Like a buffet of ideas that I can suddenly assemble together. And any good engineer needs to keep a buffet absolutely full of ideas. Thanks for reading.