Quantcast
Channel: FlexMonkey
Viewing all articles
Browse latest Browse all 257

Build Your Own Black Hole with Stage3D and ActionScript Workers

$
0
0

Here's a little bit of fun using ActionScript Workers to calculate a system of particles with mutual gravitation all falling into a central gravity well and Stage3D to render them. 

Once the particles have fallen past the event horizon at the centre of the screen, they find themselves miraculously reborn at the edge of the screen to live another day.

This is an ActionScript project rather than a Flex project - I decided on this so I could make use of the new ASC2.0 with Inline support. 

My ParticleWorker class is doing the brunt of the work. It loops over the vector of particles then uses 3 dimensional bin lattice subdivision to find each particle's neighbours (well, that's a slight fib, since I'm rendering with orthographic projection I've cheated and I only look in nine subdivision cells in two dimensions rather that 27 in three).

The common workaround for multidimensional arrays in ActionScript seems to be arrays of arrays or arrays of arrays of arrays for 3 dimensions. I've created a simple CubicArray class which is a one dimensional array of size width * depth * height that I use for the bin lattice subdivision.  

One performance killing function turned out to be Math.sqrt(), so the worker pre-calculates square roots and stores them in an array for use by the code later. Likewise, Vector3D.distance() wasn't helping matters - especially when I was creating instances of Vector3D from the x, y and z properties of my particles to calculate distances.

Once the ParticleWorker has done its stuff, it bundles up the vertices and triangles for the particles (each particle is a triangle with one vertex being its x and y and the other two with a small offset) and sends them as a message back to the main application. These are passed to my ParticleRenderer which contains the world's simplest AGAL.

Easy street! Not going to win any awards, but a nice introduction to one solution for rendering particles as triangles with Stage3D and having a Worker doing the math in the background. 

There's no UI to this piece, just leave it to its own devices.

The application lives here and the source code lives here.


Viewing all articles
Browse latest Browse all 257

Trending Articles