Flow Fields, Part II

tutorial

In Flow Fields, Part I, we covered what a flow field is and looked at a few different formulas to create them. And we rendered flow fields in a various ways. We even animated particles being influenced by fields. In this article we’ll cover a couple more ways to generate flow fields and some new ways to render them. As I said in the first part, the possibilities are endless. I’m just pointing you in a few directions to get started.

Perlin Noise

Using simple math and minimal trigonometry gave us some pretty interesting patterns, but they wound up being very regular and repeating. The more complex function we used (the strange attractor) made for a fairly uninteresting field by itself, but was beautiful with particles tracing lines across it.

What would be nice is something complex but non-repeating. Perlin noise fits the bill, which is why it is used so often to create flow fields. Perlin noise was invented by Ken Perlin and was initially used to generate natural looking textures for computer generated special effects in movies and video games. It gives you random values across a two- or three-dimensional field, and ensures that there is a nice, smooth gradient between the various values. With different settings, scaling and colors applied, you can get textures that look like smoke, fire, liquid, wood grain, rusty metal, etc.

We can tap into Perlin noise to create a flow field that varies all over the place and never repeats. And we can animate it as well by creating a 3D Perlin noise field and moving through slices of it on the z-axis. More on that soon.

If you’re using Processing or some other platform, you may have a Perlin noise function built in. If you’re just using plain vanilla JavaScript like me, however, you’ll need a Perlin noise library to generate the values. There are a few out there. I’m going to use one by Seph Gentle (josephg on github) at https://github.com/josephg/noisejs. I’ve downloaded that into my project folder.

I’m going to start with the same basic HTML file as last time, and add the perlin.js library in the script tag.

And here’s the first script file:

The first block is the same as before. Then we seed the Perlin noise library with a random number so we’ll get a new image each time, and call render.

The render function loops through the canvas in a grid-like fashion as before, getting a value and drawing a line there. All pretty much the same as last time.

It’s the getValue function that changes. Now we’re going to get the value directly from the Perlin noise function. This noise library has a few different functions. We’ll use the 2d Perlin noise function, perlin2, for now. This just takes an x and a y. We’ll scale it down somewhat to make a more interesting pattern. The result of this is a number from -1 to +1. So we can multiply that by 2 PI to get a direction in radians. That’s all, folks. And here’s what it gives us:

Pretty cool, eh? Let’s change the res variable to 2. This makes a much tighter grid:

And now we can see what happens if we change the scale, to maybe 0.004.

It’s like zooming in.

Now, consider 3d Perlin noise as a stack of these 2d Perlin flow fields layered on top of each other, each one varying just a bit. If we could flip through them, one by one, we could see them animating. That’s exactly what our next file does, using the noise.perlin3 function:

Here, we add a z variable set to zero. Then we clear the canvas at the start of render so we can redraw each time. Finally, we increase z by a very small amount and call requestAnimationFrame(render) to set up the next frame of the animation.

The getValue function calls noise.perlin3, passing in the current z. No other changes. A still image would look about the same as the first image in this article, but if you actually run this one, you’ll see a lovely, flowing animation, reminiscent of seaweed, or amber waves of grain.

OK, what’s next? Well, last time we moved on to having the flow field influence the movement of some particles. We’ll do the same thing here, using the Perlin-based flow field.

Again, we create a column of particles on the left edge of the screen, and on each frame, update each particle’s position and draw a line from its last position to where it currently is. This gives us a trail of its movement. The major change here is, again, that we’re using Perlin noise to calculate the flow field. Here’s what we get:

And of course, this looks even cooler as you watch it animate and build up.

One last Perlin example. We’ll use 3d Perlin noise again. This time, on each frame, we’ll create a column of particles down the center of the canvas and iterate each one’s path 500 times. That will create a bunch of flowing lines. Then we’ll update z and draw the next frame. Now, the path of each particle is altered a bit differently on each frame, so you get an eerie, undulating flow going on. The further out from their source each particle gets, the more its path differs from the last frame. Sometimes it jumps off in a totally different direction, giving it a weird, glitchy feeling. The code:

And a single frame of the animation, which you’ll want to see in motion:

What else?

Well, we’ve created flow fields with simple and complex formulas and used third party libraries to create them. You might want to play with the simplex noise contained in that noise library we were using. It’s similar to Perlin noise, also created by Ken Perlin, but has a bit of a different feel to it.

But really we can use anything we want to create a flow field. All we need is something that maps an x, y coordinate to a value. So where could we get a source of values that are mapped to x, y coordinates? Like a map of different… bits of information… like a bit… map. OK, I guess you see where I’m going here. So yeah, any image is simply a 2d map of values. If we can take an image and pass in x and y to some function to get the value at that location, we are golden. And in HTML canvas, we can. And it’s likely you can do the same thing if you are using some other system.

I’ve created a Bitmap module. I’m not going to show it or go into it much here, but you can check out the source at the repo I’ll post at the end of the article. The module takes a url and an onComplete callback that gets called when it’s ready. It then has a getValue method that takes x, y parameters and returns a value between 0 and 255. This is an average of the red, green and blue values of that pixel and basically equates the brightness of the image at that point.

Here’s how we use it:

We create the initial canvas, but we don’t size it full screen like we did before. Then we create the bitmap and wait for it to complete. When it does, we set the canvas to be the same size as the bitmap, create 1000 random points, and call render.

Most of render should look pretty familiar. Get the value at the current location and use that to influence the particle’s velocity. Note that I extracted a couple of values, force and friction. Playing with these can give you very different behaviors. Try out different values. The other main difference here is that if a particle goes off the canvas, we set it back to a random location again.

Finally, the getValue function calls bitmap.getValue. Remember, that will return a value from 0 to 255. So we convert that to be in the range of 2 PI. And that’s it.

All you have to do is supply it an image. Note that for security reasons, you’re not going to just be able to link to any image from anywhere on the web, and you’re probably not going to be able to run this example from the file system. I just set up a simple node.js based server using the http-server package and serve the app and image from there as localhost:8080.

Supplying a random cat image (because this is the Internet, after all), we get the following:

You might even be able to see a hint of the cat there. But if you uncomment line 12 in the code, it will draw the original image before starting to animate the particles. With that, you see the following:

So, there’s a few more ideas. Different images, different settings, different ways of rendering or animating, all make for infinite possibilities. Now you can go explore some of them. Have fun.

The code for all of this can be found at: https://github.com/bit101/tutorials . Note that the code here is not necessarily super clean or ruggedly tested. I’m just having fun here and pretty much just stopped when things looked good.

Useful, or at least fun?

I plan to use the money I make from these posts to finance my presidential campaign. Or at least pay my Netflix bill for a month or two. If you’re down for helping me with either of those two things…

Flow Fields, Part I

tutorial

Maybe you’ve heard the term “flow field” and maybe you’ve seen some neat pictures or animations with the term attached. In this article, I’ll cover what a flow field is, show how to create one, and give a few examples of experimenting with them. Flow fields are also known as vector fields.

The Pre-Game Show

I’ll be using HTML5, JavaScript and Canvas for this article, but the concepts will apply to Processing, p5js, WebGL, or just about any other graphics programming platform. That being the case, I’m going to try to focus less on the canvas specific stuff and more on the core concepts.

But, to just lay the foundations, I’m going to go over the files we’re using. It’s all going to be super basic. An HTML file and a JavaScript file. Here’s the HTML:

A bit of CSS, my QuickSettings Panel, which might come in handy eventually, a canvas element and a link to the main script. The script is going to start out like this:

All we’re doing here is getting a reference to the canvas and its context, then resizing the canvas so it fills the browser window, saving the width and height values for later use. Some of the CSS in the HTML file aids in all this being fully possible.

The Main Event: Flow Fields

So, what is a flow field? Well, you can think of a field as just a two-dimensional area. Of course, you could have a 3D flow field, but let’s save that for another day. You can also think of a magnetic field.

In this image of iron filings revealing a magnetic field, you see various lines and loops. The strength and orientation of the magnetic force is different in different areas of the field. You can imagine that an object moving through this field would be influenced by it and tend to move along those visible lines.

Basically, that’s what we want to do – create a two-dimensional area where each point has a different value. But these aren’t just random values. A particular point has a particular value and as you move out from that point to neighboring points, you get similar, but gradually changing values. In flow fields, these values are usually interpreted as directions. So if you map your values so they are between 0 and 360, they can be directly used as degrees of direction. Of course, we’ll probably map them between 0 and 2PI radians because the computer likes that better.

Once we have values for each point, we can graphically render each one based on it value. For example, we can draw a line pointing in the direction associated with that value.

So that brings us to two different tasks – how to come up with the different values for the field, and how to render the different values on the field. The great thing is, there are no correct answers for either one of those questions. In fact, there are nearly infinite ways of doing either one, so you can explore this technique for quite a while.

Let’s start out really simple, to get the idea of what’s going on. I’m just going to loop through from left to right and top to bottom, every 10 pixels. The value for that point on the grid will simply be (x + y) * 0.01 % Math.PI * 2. Just adding x and y together, scaling it down and modding it by 360 degrees (Math.PI * 2 radians). Then we render that value by translating to that point, rotating by the value and drawing a short line at the point.

Simple as that all is, we already have the start of something interesting going on.

You might now see why this is starting to be something you’d call a “flow field”. As you follow the directions of the lines, you start to see some very directional motion going on.

We can start cleaning this up a bit by extracting the two things that we’ve already determined are going to change a lot – the calculation of the value and how each value point is rendered. We’ll put each one of those into its own function and call them where appropriate.

No change in behavior, but we’ve isolated the things that we now want to change. Furthermore, we don’t necessarily always want this to be in a strict grid. Instead we can grab any number of random points on the grid and render those.

I’ve arbitrarily defined a value of 20,000 for number of points to render. Just looping through that many times, getting a random point and finding its value and rendering it. I’ve changed a few other values as well, such as the length of the line and the scale value that (x + y) is multiplied by. Now we’re getting something a bit more natural looking.

At this point, we can just start messing with the formula we use to get the value. Generally, you’re going to want to use the x and y inputs somehow, but really, just do whatever you want here. Here’s a somewhat interesting one I came up with.

Just taking the sine of x and y and adding them together. Some rendering changes too: reduced the line width and varied the line length at each point. But with just those few small changes, we’re onto something really hairy looking.

Now I could spend all day iterating on this – different formulas, different parameters for the lines it’s drawing etc. I know I could spend all day on it because I have spent whole days doing just that in the past. But let’s move on to something else.

Earlier I mentioned the idea that you could possibly imagine an object moving through a flow field and being influenced by those flows. Let’s simulate that. I’ll start with a single random point. Call it a particle. This particle will actually be an object with not only position, but velocity on the x and y axes. Initially these will be set to zero. On each iteration, wherever the particle is, we’ll get the value at that location – which is a direction, remember – and use that value to influence the particle’s velocity. Then we’ll add that velocity to the position to get a new position. And repeat.

Hopefully the comments explain a bit more what’s going on here. This gives us the following:

What’s interesting in this case is that we no longer actually see the field. We only see the result that the field has on the motion of the particle.

Do run this one on your own. It’s pretty neat to watch the drawing build up over time. You can see that the flow field is influencing the way the particle moves. You can change some of those hard-coded values to see what they do to the motion. Even in just our fifth iteration here, we have a ton of things to experiment with.

Let’s do one more for this article. Where one particle was fun, more particles is… more fun.

Here, I just made an array of particles and arranged them down the left side of the screen. For the algorithm, I used a strange attractor called the “Clifford Attractor”, published by Paul Bourke and attributed to Clifford Pickover. You can see the code for that here: http://paulbourke.net/fractals/clifford/ This gives you a very complex field. The parameters, a-d, are randomized at the top of the file, so you’ll get a different pattern every time.

Again, this is one you want to run on your own and play around with. It’s really quite beautiful to see in action. If you’re curious what the flow field actually looks like for one of these attractors, it’s something like this:

OK, that’s enough for one article. In part two, we’ll look at some other ways to create fields and other ways to render them. If you want to play around with the code itself, you can either grab the gists I’ve embedded here, or just check out the full tutorial repo itself at https://github.com/bit101/tutorials.

Pay(pal) it Forward?

If you’ve found this post useful or at least entertaining and want to contribute in some way, I will gladly accept your kindness.

It’s not my plan to make any kind of premium, subscriber-only content. And the Patreon model doesn’t really cut it for me. I just want to write tutorials for a while. If I make a few bucks here and there, I will probably want to write tutorials even more.

REBOOT!

misc

History

I’ve been coding – as a hobbyist – since the 1980’s. But I’d say my programming career actually started around 1998, when I first accepted money for writing code. Make no mistake – the money I received at that time was worth a hell of a lot more than the code I was writing. But I like to think I’ve improved over the years and that my value as a coder is a considerably more commensurate with my current compensation.

I continued coding as a part time second job for a year or two until that late 90’s bubble finally burst. But I was hooked and had learned a lot. I knew coding was in my future in spite of the state of technology jobs at the time. So I continued to study and eventually learned enough that I was writing my own tutorials. This was back in the early days of Flash. My first tutorial was on coding physics and motion graphics. I called it the “Gravity Tutorial” but it covered stuff like velocity, acceleration, gravity, bouncing, friction and mouse interaction (dragging, throwing, catching). I promoted the tutorial on sites like Flashkit and before long it had thousands of views and had been translated into a half dozen different languages. That tutorial was followed up with several others, which led to book deals and speaking engagements and a full time employment as a programmer with a series of increasingly better jobs.

Throughout my career as a programmer, I’ve always taken a two-pronged approach. One is whatever job I happen to have a the time – writing code for a pay check. And the other is education – sharing whatever I’ve learned with other aspiring programmers. It’s been a successful combination and I’ve explored a number of different ways of doing the education part: tutorials, blog posts, open source experiments, books, conference talks, seminars and workshops, and in the last few years, videos.

Actually, over the last six months or so, I’ve really been slacking on the education stuff. I started a new job working with several technologies that I was really not up to snuff on. So I’ve been focusing far more on catching up on that stuff. But by now I’ve gotten to a pretty stable place and I’m feeling the urge to get back into teaching some stuff again.

Videos

While I’ve had a lot of fun making videos, they are a ton of work. First you come up with a subject and write a script. Then you record the audio, record the screencast, edit the audio, edit the video, sync everything up along with any other graphics you might want to add in, prepare the transcript, the title, upload it, prepare all the links and everything else that go on and around the videos, and promote it here and there. A single 15 minute video takes many hours of work. I guess other people can just sit down, hit record, start talking and typing away, finish up and publish. For me, though, a lot more goes into it than that.

Writing

So, in my next phase, I’m going to try going back to plain old writing, making some tutorial-type blog posts right here. I’m still working out some of the technical details, such as code embedding. I was initially thinking of using either codepen or jsbin for embedding interactive examples, but I think I’ve decided to stick with github gists for code only, and screenshots for results. I think my tutorials will wind up with multiple iterations of a single file and having an interactive example for each iteration is going to be heavy and overkill.

$$$?

I’m also trying to come up with some kind of idea of monetization. I don’t want to force people to pay in order to get the content, but in my experience, if you deliver regular doses of quality material, a lot of people are more than happy to voluntarily give something back. And who am I to deny them that opportunity? I’m not really happy with the Patreon model that I used for my Coding Math video series. I got paid once each time I published a video. All of those videos are still getting tons of views on YouTube, and likely will for years to come. But I won’t see another penny from Patreon on any of those views. Advertising is meh. I guess I can just throw up a “tip jar” link and make it really obvious. So that part will just most likely evolve over time. In the end, it’s not about the money, but it’s not NOT about the money, either.

Another idea I’m thinking of is cross publishing on other platforms. Medium is the one that comes to mind initially. I’ve never put anything on Medium. I kind of have mixed feelings about the platform, but it could wind up being a good thing. More eyes on the content, more clicks on the tip jar. One more idea I’ve kicked around is eventually compiling a bunch of articles into a self-published book. My Playing With Chaos book still gets a few sales per month. Enough to keep my Paypal account from bottoming out. 🙂 In fact, I have been planning a follow up book to PWC for quite a while now, but never seem to get around to it. So a lot of the articles I’m thinking of publishing here come from that project’s table of contents.

In closing…

Anyway, I’ve decided to just wipe out the old blog and start fresh here. I may put an archived version of the old blog up eventually. It’s quite old and really needed some severe maintenance anyway. But look forward to seeing some new content around here soon. Hopefully at the pace of an article a week? Maybe more, maybe less. And if you have any ideas or requests, feel fee to comment or otherwise shout at me via some random social network.