nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: Three.js

Plotting the Lorenz Attractor using three.js

It’s been a while since I dabbled with three.js. There have been a few API changes, so it’s slightly different from what I remember. That being said it’s still as fun to use, and there are even a few API docs available (not sure if they are fully up to date though)! I happened to be reading an article on Chaos Theory and the “butterfly effect” which mentioned a lovely set of equations; the Lorenz Equations, also known as the Lorenz oscillator. So I decided to investigate further. Here they are in all their glory:

\begin{aligned}\dot{x} & = \sigma(y-x) \\ \dot{y} & = \rho x - y - xz \\ \dot{z} & = -\beta z + xy \end{aligned}

So what exactly is the Lorenz oscillator? Well to quote from Wikipedia “The Lorenz oscillator is a 3-dimensional dynamical system that exhibits chaotic flow, noted for its figure eight shape.”. What this really boils down to is how even very small change in the equations initial conditions (x, y and z) causes large changes over time, in a complex and non-repeating pattern. There’s a famous title of a talk given in 1972 by Philip Merilees:

Does the flap of a butterfly’s wings in Brazil set off a tornado in Texas?

The butterfly flapping its wings introduces slight changes to the initial conditions, creating a chain of events that lead to a tornado in Texas. The Lorenz butterfly is a graphical way of showing these changes over time on a much smaller scale.

I’ve created a demo that allows you to change variables related to the Lorenz butterfly and observe the effect it has on the system.

Example of my Lorenz attractor demo in action

Adjust the demo variables to see how the Lorenz butterfly changes.

There are a few variables you can play to change how the Lorenz attractor is rendered:

  • rhoValue: Called the Rayleigh number. Rho of value 28 shows chaotic behavior. Other values show periodic orbits.
  • showAxis: Allows you to turn the x, y, z (red, green, blue) axis on for reference.
  • randomStart: Picks a random initial conditions, rather than 0, 0, 0.
  • totalTime: The total time (or number of iterations performed) when generating the graph. Higher numbers equals more lines and increases the render time.
  • timeIncriment: The accuracy of the graph depends on the number of points plotted. A lower number creates a smoother graph but increases render time.
  • colorModifier: Simply changes the colo(u)r. Pointless but pretty!

While rendering a larger number of points, I noticed the browser lock-up for a second or so. This was because the points were being calculated on the browsers UI thread. Luckily modern browsers support thread like message passing in the form of the Web Workers API. By offloading the point calculation to its own thread (lorenzPoints.js), I was able to stop the nasty UI freeze. Unfortunately you are fairly limited with what you can pass back and forth between workers. It was possible to generate the three.js geometry in the worker thread thanks to the importScripts() method. I tried passing the three.js geometry back to the browser but all the methods were stripped out, leading to lots of errors (JSON issues). In the end I dropped back to calculating the points in the worker, pushing them into an array and generating the geometry on the main browser thread.

It was good fun dabbling with three.js, Web Workers and dat.gui again. Now on to my next project… View the demo here.

Antimatter 3D Graph Plotter and a little animation

Last year I stumbled upon this blog post by @antimatter15 who added a little three line modification to mr.doobs particle floor demo and created a graph plotter in three.js. Unfortunately as three.js has developed and evolved the API has changed; in doing so it broke the graphing demo. I left a message asking if there was a fix on Antimatters blog but got no response. So I decided to update the code and fix it for the latest version of three.js; once updated for the latest API it ran as expected.

3D graph plotter using three.js

Antimatter15 graph plotter updated for latest version of three.js.

You pass the equation you wish to plot via a URL parameter and out the other pops a pretty 3D graph. Here are a couple of examples taken from the original blog post:

In updating the code I thought I’d have a little play myself and see if I could add a bit of motion to the graphs just for the fun of it. I’ve created a version of my own which you can view here.

Graphing multiple for formula using JavaScript and three.js

Modified version allows you to add more than one formula to plot.

In my version you no longer pass the formula you wish to plot via a URL parameter, you add it via the panel on the right hand side. You can add and remove as many equations as you wish and the demo will cycle between them. To do so update the right hand panel then click the “Plot new formula(e)” button. The equation that is currently being plotted is highlighted in grey and available mathematical functions listed below.

With a little bit of trial end error you can create some interesting effects. There may not be much practical use for the experiment but I enjoyed putting it together with a little help from mr.doob and antimatter15 :)

Debug Axes in three.js

Update: The code I had previously stopped working with the latest three.js API. I’ve updated and improved the code for the latest API.

I’ve been working on a couple of small projects using three.js recently; An issue I always seem to have when working with 3D is knowing the current orientation. To help me out I’ve put together a small snippet of JavaScript.

Creating a set of axis in three.js

{x: red, y: green, z: blue} It's not much to look at but the axes can be very useful.

The point where the lines cross is 0,0,0 as you’d expect, you can adjust the length of the line by changing the axisLength variable. I’ve uploaded a small demo so you can see the code used or copy / paste below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var debugaxis = function(axisLength){
    //Shorten the vertex function
    function v(x,y,z){
            return new THREE.Vertex(new THREE.Vector3(x,y,z));
    }
   
    //Create axis (point1, point2, colour)
    function createAxis(p1, p2, color){
            var line, lineGeometry = new THREE.Geometry(),
            lineMat = new THREE.LineBasicMaterial({color: color, lineWidth: 1});
            lineGeometry.vertices.push(p1, p2);
            line = new THREE.Line(lineGeometry, lineMat);
            scene.add(line);
    }
   
    createAxis(v(-axisLength, 0, 0), v(axisLength, 0, 0), 0xFF0000);
    createAxis(v(0, -axisLength, 0), v(0, axisLength, 0), 0x00FF00);
    createAxis(v(0, 0, -axisLength), v(0, 0, axisLength), 0x0000FF);
};

//To use enter the axis length
debugaxis(100);

It’s not much to look at, but it can certainly help you get your bearing when starting a new project (or when things aren’t working!). Hopefully you find it useful.

Creating 3D trees with some #CreativeJS

Random trees created using three.js and some creative JavaScript

Trees generated at random using some CreateiveJS and Three.js.

Over a month has passed since my last blog post and much has happened. We’ve had a wedding, a funeral at sea (maybe in bad taste!) and I’ve gone full-time freelance (yay!). I’ve had a little more time to work on a couple of personal projects so I’ve finished one that I started way back in January.

I had the pleasure of attending a Creative JavaScript course in Brighton, UK, hosted by Seb Lee-Delisle; a two-day course that covered a wealth of topics from Vanilla JavaScript to Three.js. If you’re looking for some inspiration I highly recommend looking out for one of Seb’s courses. Great fun and you get to meet some really nice people. Quick tip: You may want to brush up on a little Trigonometry before you go as it’s used numerous times. I knew that A-Level Mathematics course would come in useful one day :).

Seb produced a demo in Canvas that created ‘trees’ and it really caught my eye. The trees were in 2D so as I’ve had a bit of experience with Three.js I decided to create a 3D version! I’m quite happy with the result although I’ve had to restrict the number of branches rendered due to the lack of dedicated graphics card in my laptop; I get about 1fps when stopping at a branch length value of 10 (line 211) :(

The demo also allowed me to use the new request animation frame API which vendors have added to aid animations in browsers. The main advantage of using it is if you have the animation running in a tab that isn’t visible, the browser will know to stop the animation! Using the old setTimeout method, the animation still runs in the background and uses up precious CPU, memory and battery power (especially on a laptop). As with most new browser features the API isn’t set in stone (yet) but luckily Paul Irish has created a polyfill that falls back to setTimeout in older browsers.

View the demo here; reload for different trees. JavaScript finally seems to be coming of age!

Update: Original credit goes to Jean-No with his amazing OpenProcessing work! I’ll be bookmarking that link, some stunning work there. Thanks to Seb for pointing out who to credit :)

A three.js community on Reddit

Well 2011 is nearly upon us; which leaves me thinking… where did 2010 go! I hope I’m not the only one who thinks this year has gone quick! One big web application that died in 2010 was digg.com. I used to use it every day for the latest technology and funny videos, but then they changed it. The design became very blue and digg seemed to change from a simple community driven link aggregator to a, well, I’m not sure what it changed to in all honesty. So it was time to find an alternative.

Luckily for me (and all digg users) there’s already a well established alternative: reddit.com. It may not look as flashy as digg, but it makes up for it with ease of use and functionality. Need to set up a community for your web application, current technology, interest or well, just about anything really; then reddit is the place for you.

So that’s exactly what I’ve done for Mr. doobs three.js JavaScript library. I created a Threejs community that anyone can submit links to relating to three.js. Over the past few weeks I’ve been adding a couple of links a day, there really are a great selection of examples out there if you take the time to hunt then down.

So if you’ve created a cool new example using three.js or any other link relating to this excellent JavaScript library submit it here. Digg is dead. Long live reddit.com!

Currently on page 1 of 212