Visualizing SDFs: Flies & Force Fields


I’ve been spending quite a bit of time learning shaders and with that, learning SDFs (Signed Distance Functions). SDFs are very useful for rendering geometric shapes. There’s certainly a beauty to them–composed basically of just a bunch of math. Often void conditionals, they are efficient, but not so readable.

When first learning to read SDFs, it can be daunting. Just take a look at the definition for a cylinder:

float sdCylinder(vec3 p, vec2 sz ){
  vec2 d = abs(vec2(length(p.xz),p.y)) - sz;
  float _out = length(max(vec2(d.x,d.y), 0.));
  float _in = min(max(d.x,d.y), 0.);
  return _in + _out;

Errr, what? A month ago, I would have given up after the second line. Certain visualization tools are necessary to help break apart the logic, which is what this blog is all about.

Anyway, this week I was in process of understanding a cylinder SDF and I had a neat insight. Understanding the logic is much easier if visualized with flies and force fields.

Game Rules

In this world, our object is enveloped in force fields. Each field has a fly trapped inside. Poor dudes. Flies cannot pass between the fields. There’s the “tube” force field that defines the radius of the cylinder and force fields along the XZ-planes controlling the height.

There’s also a fly trapped inside the object itself and another stuck directly on the cylinder. Other than not being able to pass between fields, the flies (our sample points) are free to travel anywhere inside the field. And each case, there is a straight-line distance from the fly/point to the object. The force fields represent the different cases of our logic. Hmmm, a diagram might help:


If you spend a bit of time visualizing each case separately, seeing the flies buzzing in their respective fields, it becomes more clear how the different parts of the logic work.


Fly A: (y – height) => (Cylinder Top)
Fly B: length of vec2(p.xz – radius, p.y – height) => (Cylinder Rim)
Fly C: length of (p.xz – radius) => (Cylinder Body)
Fly D: greater of length of (p.xz – radius) OR (y-height) => (Inside Cylinder)
Fly E: distance = zero, strictly lives on cylinder

Okay, let’s dive in.

float sdCylinder(vec3 p, vec2 sz ){

Easy stuff here. Return a float since which is our distance from the sample point to the surface of the object. The two parameters are a vec3 p and a vec2 sz. The sz variable contains the radius and height of the cylinder as its x and y components respectively.

vec2 d = abs(vec2(length(p.xz),p.y)) - sz;

The vec2 defined contains p.xz distance from the origin and p.y. We use abs since a cylinder is symmetrical and only the “top right front” part needs to be evaluated. Everything else is just a “mirror” case. Subtracting sz yields the differences for both the “top” and “body” distances. Store that in d.

float _out = length(max(vec2(d.x, d.y), 0.));

Using max with zero isolates which case we’re working with. If the point/fly is at the top of the cylinder, then d.x < 0. If it is in the ‘body’ force field, it’s d.y 0 and d.y > 0, the we’re dealing with fly B. The neat part is that either we’ll have one component set to zero in which case length is just using 1-dimensions, or we’ll have 2 components, which case length still works.

float _in = min(max(d.x,d.y), 0.);

Lastly, if the fly is trapped inside, then which surface is it closer to? Top or body? d.y or d.x? Use max to find that out. If one of the values are positive here, min is used to set it to zero. Think of min here as a replacement to a conditional.

Again, here is the final definition:

float sdCylinder(vec3 p, vec2 sz ){
  vec2 d = abs(vec2(length(p.xz),p.y)) - sz;
  float _out = length(max(vec2(d.x,d.y), 0.));
  float _in = min(max(d.x,d.y), 0.);
  return _in + _out;

This visualization tool has helped me to deconstruct the SDF logic. I hope it has been of use to you too! I suggest memorizing the five cases where the fly/point can exist. Then you can derive the code from scratch if necessary–it’s a good way of testing your understanding. It’s also really fun once you grasp it!


SDFs: Rendering a Rectangle

A couple of weeks ago I wrote a post on how to render a square using a SDF. It works….but I later found out it isn’t entirely correct. I made a mistake when calculating the distance from the corners of the square when a point is ‘beyond’ both edges of the square. In that case, what you actually need to do is calculate the Euclidean distance, not whatever the heck I decided to do.

Moving on, I’m going to play around with creating the SDF of a rectangle. I began by looking at what others have already done. A few resource I was looking at:

To fully understand SDFs, you really need to get a notebook and sketch the use-cases of rectangle/point distances. After doing that and breaking down what I had read online, I re-wrote the SDF with some nice variable names:


We start with the signature.

float sdRect(vec2 p, vec2 sz){

The first parameter is the sample point, the second is the size. Note that size here acts more like the “radius” of the rectangle. To prevent having to perform a division within the sdRect function, we expect the user to pass in the halfWidth and halfHeight sizes.

Next we get the difference between the sample point and the size. I use ‘d’ to denote the distance.

float sdRect(vec2 p, vec2 sz){
  vec2 d = abs(p) - sz;

Just like in the square SDF, we’re taking the absolute value since the rectangle is symmetrical on both axis.

Now we’re going to calculate 2 things: the inside distance and outside distance.
let’s start with this section of code:

max(vec2(0,0), vec2(d.x,d.y));

We’re expressing that we want the result of greater of a 2D zero-vector and the distance we calculated one line above. It means that if the sample point is inside the rectangle (negative distance), the expression will evaluate to zero. I like to think if it a bit like a clamp. It makes certain the value stays >= zero.

Now we call length. Wait, why would we use length? Well, if the d vector is positive on both axis, we’re somewhere along the corner ‘edge’ from the rectangle. In that case we want the euclidean distance from the corner to the sample point. But it also works if only one of the components is zero and the other is positive. In that case, we’re just getting the vertical or horizontal length from the edge to the sample point. If the result of max is zero(sample point is exactly on the corner) the call to length will still work, it will just evaluate to zero. Pretty cool, right? I hope to one day write a sketch to visualize this. It honestly works best when you can play with the sample point and move it around..

Anyway, you can express the line succinctly:

float outside = length(max(d, 0.));

It’s less cluttered, but also a bit harder to read if you’re still getting used to max returning a vec2 and having the 0 ‘upgraded’ to a vec2.

Okay, onto the next line:

float inside = min(max(d.x, d.y), 0.);

As the variable suggest, we’re calculating the distance if the point is inside the rectangle either on the x or y axs. Remember that d holds the distance from the point to each edge. This line assumes the point is inside the rectangle for one dimension, so even if both components are negative, we’d want the one less negative (closer to the edge). That’s why we use max here. Now, the call to min does something similar to the max call on the 2nd line in the function. It prevents the potential ‘positive’ component from being used in the final contribution. The point can be ‘outside’ the rectangle in the x dimension but ‘inside’ rectangle on the y dimension.

Lastly, we combine both inside and outside. The beauty here is at least one of these will be zero and then we’d get the contribution from the other. If the sample point is exactly on the edge of the rectangle, the result will be zero. Huzzah, it all works like magic.

Finally, here’s the SDF:

float sdRect(vec2 p, vec2 sz) {  
  vec2 d = abs(p) - sz;
  float outside = length(max(d, 0.));
  float inside = min(max(d.x, d.y), 0.);
  return outside + inside;

I prefer using the temp variable here since it gives a clear picture of what’s happening, but of course you could forgo them entirely.

SDFs: Rendering a Square

Something I found early on when learning shaders is the importance and ubiquity of signed distance functions. I’m currently venturing into 3D SDFs and I wanted to review what I understood with 2D SDFs. I figured I should write about to prove to myself that I actually knew what I was talking about. So this post is a very simple investigation into rendering a square SDF.

Let’s investigate a visual representation. Here’s a picture of what we’re trying to accomplish here. Here are some sample points with their distances from the surface.


If p is exactly on the edge, the distance is zero. If p is outside, return the 1-dimensional difference between the ‘closest’ side of the square and the the point. If p is inside the square, our function will return a negative value. Lastly, if p is a the center of the square, the return value will be -w since we are w distance from any side. Also, take a look at the diagonals…interesting right? We’ll get to those in a minute.

Now that we played around with a theoretical model, let’s start dig into the code.  Let’s create the interface first. We’re dealing with distance fields, so it must return a float. As for parameters, we need to compare it to some sample point and we also need the dimension of the square w.

float sdSquare(vec2 p, float w){
  // return distance from edge of surface to sample point.

Now for some logic. Because the square is symmetrical, our logic will be ‘shared’ between the two dimensions: x and y. If we get the x-dimension working, we should be able to get the y for free.

To get the difference between the p.x and the x edge of the square, we’ll just subtract. And since the distance in the opposite ‘quadrant’ will be the same, we can use abs().

float sdSquare(vec2 p, float w){
  return p.x - w;

Here is the result SDF along with another version where we capped the distance at distance = zero.

sdf_x_1       sdf_x

Now that we have the x figured out, let’s look at y. Remember those diagonal lines in the first diagram? They give us some really important information. They basically defined a region. If the sample point is in the top region, it means we’ll need to use the difference between y and the edge. Same with the bottom.

We get the absolute values of the sample point and then simply get the greater of the two with max(). We can either use a temp variable to store the absolute values or call abs twice.

float sdSquare(vec2 p, float w){
  vec2 _p = abs(p);
  return max(_p.x, _p.y) - w;

Tada! Pretty neat right? …Well, I think so. The code itself it really simple, but there something magical about SDFs. Specifying a surface with math is just really cool.

sdf      sdf_final

Thanks for reading!

Spying on Functions


I’ve been working through a series of insightful coding tutorials. It’s a series of episodes that walk developers through creating Super Mario in JavaScript from scratch. They were created by Pontus Alexander and I highly recommend them.

So while working through the videos, Pontus demonstrated a really interesting JavaScript pattern in episode 5. Essentially we can spy on a given a function or method — and add custom logic every time it is called.

Let’s look at an example. We start with a simple class:

class Person {
  sayHi(name) {
    console.log(`Yo ${name}!`);

A common use case is knowing how many times a function is called. It’s overly simplistic, but it clearly demonstrates what we’re doing. So let’s find out how many times sayHi is called.

Since functions/methods are just values, we can create reference to the original method and overwrite it.

let person = new Person();

// Save a reference to the original function
let sayHiOrig = Person.prototype.sayHi;

// Redefine sayHi. This allows us to add custom logic,
// at the same time leaving sayHi to do whatever it does.
let count = 0;
Person.prototype.sayHi = function(name) {
  console.log(`sayHi called ${++count} times.`);, name);

We then call the function normally. From the perspective of the class, it is unaware of the spy and completely decoupled — which is super great.

// > sayHi called 1 times.
// > Yo Pascal!

Normal Mapping using PShaders in Processing.js

Try my normal mapping PShader Demo:

Last year I made a very simple normal map demo in Processing.js and I posted it on OpenProcessing. It was fun to write, but something that bothered me about it was that the performance was very slow. The reason for this was because it uses a 2D canvas–there’s no hardware acceleration.

Now, I have been working on adding PShader support into Processing.js on my spare time. So here and there i’ll make a few updates. After fixing a bug in my implementation recently, I had enough to port over my normal map demo to use shaders. So, instead of having the lighting calculations in the sketch code, I could have them in GLSL/Shader code. I figured this should increase the performance quite a bit.

Converting the demo from Processing/Java code to GLSL was pretty straightforward–except working out a couple of annoying bugs–I got the demo to resemble what I originally had a year ago, but now the performance is much, much, much better 🙂 I’m no longer limited to a tiny 256×256 canvas and I can use the full client area of the browser. Even with specular lighting, it runs at a solid 60 fps. yay!

If you’re interested in the code, here it is. It’s also posted on github.

#ifdef GL_ES
precision mediump float;

uniform vec2 iResolution;
uniform vec3 iCursor;

uniform sampler2D diffuseMap;
uniform sampler2D normalMap;

void main(){
	vec2 uv = vec2(gl_FragCoord.xy / 512.0);
	uv.y = 1.0 - uv.y;

	vec2 p = vec2(gl_FragCoord);
	float mx = p.x - iCursor.x;
	float my = p.y - (iResolution.y - iCursor.y);
	float mz = 500.0;

	vec3 rayOfLight = normalize(vec3(mx, my, mz));
	vec3 normal = vec3(texture2D(normalMap, uv)) - 0.5;
	normal = normalize(normal);

	float nDotL = max(0.0, dot(rayOfLight, normal));
	vec3 reflection = normal * (2.0 * (nDotL)) - rayOfLight;

	vec3 col = vec3(texture2D(diffuseMap, uv)) * nDotL;

	if(iCursor.z == 1.0){
		float specIntensity = max(0.0, dot(reflection, vec3(.0, .0, 1.)));
		float specRaised = pow(specIntensity, 20.0);
		vec3 specColor = specRaised * vec3(1.0, 0.5, 0.2);
		col += specColor;

	gl_FragColor = vec4(col, 1.0);



I wanted to learn the basics of require.js and pixi.js, so I thought it would be fun to create a small game to experiment with these libraries. I decided to make a clone of a game I used to play: Nibbles. It was a QBASIC game that I played on my 80386.

Getting started with require.js was pretty daunting, there’s a bunch of documentation, but I found more of it confusing. Examples online helped some. Experimenting to see what worked and what didn’t helped me the most. On the other hand, pixi.js was very, very similar to Three.js….So much so, that I found myself guessing the API and I was for the most part right. It’s a fun 2D WebGL rending library that has a canvas fallback. It was overkill for what I was working on, but it was still a good learning experience.

Gomba 0.2


I’ve been busy nursing my cat back to health, so I missed blogging last Saturday 😦 He’s doing a bit better, so I’m trying to stay hopeful.

Today I did manage to find some time to catch up on my blogging, so here are the major changes on Gomba:

  • Fixed a major physics issue (running too quick & jumping was broken)
  • Added coinbox
  • Fixed kicking a sprite from a brick
  • Added render layers

Rendering Layers

The most significant change I added was rendering layers. This allows me to specify a layer for each gameobject. Clouds and background objects must exist on lower layers, then things like coins should be a bit higher, then the goombas, Mario and other sprites even higher. You can think of each layer as a transparent sheet high school teachers use for overhead projectors. Do they have digital projectors yet?? I can also change a gameobject layer at runtime so when a goomba is ‘kicked’, I can move it to the very top layer (closest to the user) so that it appears as if the sprite is being remove from the world. Rendering them under the bricks would look just strange.

I used a binary tree to internally manage the rendering of the layers. This was probably overkill and I could have done away with an array, dynamically resizing it as needed if a layer index was too high. Ah well. I plan to abstract the structure even further so the implementation is unknown to the scene. I also need to fix tunnelling issues and x-collision issues too…Maybe for next month.