Monday, 9 January 2017

The Future Of Processing.

The Future Of Processing.

Technical Blog 4.

https://processing.org/exhibition/
So far in my series of posts on Processing we have looked at the basics of the language to make simple drawings and animations. Then we looked at some more advanced concepts including translations, 3D graphics and manipulating the camera in order to create visualisations of various objects from the world of mathematics.

Last time, we looked at p5.js (Processing's JavaScript sister-language) and how we can use p5 to make web games. Of course, everything we looked at previously in Processing carries over to p5.js, allowing us to make interactive animations and visualisation which are easily shareable.

For my final post on Processing, we are going to take a quick look into the future of Processing. What lies ahead for Processing, p5.js, Processing.py and Andriod Mode for Processing? But first, let's discuss the two versions of Processing which we have yet to see: Processing.py and Android Mode.


What Is Processing.py?

In my very first post on Processing, I mentioned that you can write Processing code using Python syntax. Without going into great detail, if you know Processing (which you now do having read this blog!) and you know Python - then you can pretty much guess what the syntax is for just about anything you want to do.

I will add, however, that in Processing.py you also have access to the Python core library as well as almost everything in the Processing language. [1]

To get started with Processing.py, click the drop-down menu (the button with "Java" on it) in the top right of the Processing IDE and then choose "add mode" and choose Python Mode.

For more information on Python mode, head over to the the Processing.py website.

What Is Android Mode For Processing?

The Android operating system is written in Java. Processing code compiles to Java. So what is stopping us from making Android apps in Processing? Answer: NOTHING!

Android Mode can been installed from the same place in the Processing IDE as Python Mode.

Code written in Android Mode is written in the usual Java syntax, but this time when you run the sketch you get an emulator of an Android device instead of the normal sketch. It is also possible to connect an Android device (via USB) to you machine and run the sketch on the device itself. [2]

Android Mode comes which a library of features to manipulate sketches using the standard Android controls. Have a look at the documentation and try making a circle move around the screen based on user tilting their device... if you have an Android device to test it on...

What Are All These Different Modes Used For?

Let's be honest: Processing is not a language which is used to make complication production applications. As we have seen, it is possible to make complication applications, but there are better libraries and frameworks out there (for Java, JavaScript and Python) to build whatever it is you are trying to build.

Well, unless you are trying to make interactive artwork.

Processing was originally made for artists and graphic designers, and although there are far better tools for making graphics - there are few tools which are anywhere near as good at making interactive graphics programatically as Processing.

The other area where Processing stands out above other languages is in education.

There are articles and blog posts for, seemingly, every language in existence trying to make an argument for why that language is the best first programming language to learn.

Most of those articles speak a lot of truth, if your reason for learning to program is to become a Java developer, or a .NET developer, etc. but for teaching high-school age children how to program? Just look at Java's "hello world!" program and think whether or not you would show that to a 12 year old and excitedly say "hey, want to learn how to program!?". They will not be impressed.

Even trying to teach a 12 year old to write Python code is bad enough when (at least to begin with) all they are going to be able to do is use Python as a glorified calculator.

Compare that with writing a "hello world!" program in Processing.py. The Syntax is simple, the output not only makes sense but is quite exciting to know that you made your computer draw a circle (far more exciting than making it print out a string which you just wrote, or add two numbers together). And then in mere minutes your small child can made the circle follow the mouse or move around how they wish.

Furthermore, as we have seen, a lot can be done with Processing and by the time our high-school age child has finished studying Processing for 5 years, they could well have a better understanding of OOP than many professional developers (the concept of a "class" makes so much more sense when your objects are tangible things which you are drawing on the screen, such as a spaceship class and an asteroid class).

Daniel Shiffman has written several books and produced hundreds of hours of video on Processing and p5.js (as well as literally being employed to teach creative coding full time). [3]

Processing is used a lot in education by many people around the world, and the Processing Foundation does a lot of work to promote the use of Processing as an educational tool. [4]

Processing's Android Mode and p5.js are great ways of sharing your work without requiring users to install Processing, or have to download .exe files after you export your work as an application.

p5.js And The Future Of The Web

A new p5.js web-editor has been in development for some time (to allow users to write p5 code directly in the browser). The contributors to p5.js have also made special effort to make this new web-editor more accessible (particularly to blind users). For more information see this video.

In this sense, p5 is paving the way for a future in front-end development for blind developers (which is turn would create a better future for blind internet users).

Contributing To Processing

If you have been inspired by the power and beauty of Processing by reading this, and the previous, posts then I highly recommend continuing your Processing journey and maybe even considering contributing to the project.

If you look at the p5.js or Processing.py reference pages you will notice that they have comparably far fewer examples than the Processing examples page. The main reason for this is that the main developers of p5 and Python Mode have far bigger and more important things to be spending their time on.

Fortunately, however, there are plenty of talented Processing coders out there who could write examples for them! In fact, you don't even need to be that good at Processing because all you have to do, most of the time, is to just rewrite existing Processing examples in either JavaScript or Python.

In most cases, this only takes minutes to do and is greatly appreciated by the developers.

To get started, head over to the respective GitHub pages for p5.js or Processing.py, pick an example that isn't being worked on and get coding!

I hope you have enjoyed reading my blog. This is probably the last post I will ever do, so thank you for reading and I hope to see you at a coding meetup somewhere in the world one day!

References 

[1] http://py.processing.org/
[2] http://android.processing.org/
[3] http://shiffman.net/
[4] https://processingfoundation.org/

Friday, 23 December 2016

Last Week Before Christmas

Last Week Before Christmas.

Weeks 7 & 8 of QA Training.

Manchester Christmas Markets - https://flic.kr/p/brVbFP

Team Foundation Server

At the start of Week 7 we were introduced to Microsoft's Team Foundation Server - Microsoft's answer to all the nonsense we learned about during our DevOps week. TFS is a fantastic tool, mostly because it is one technology rather than 5 or 6 bolted together (like Git, Jira, Jenkins, etc. if you were building Java applications). Also, the integration with Visual Studio is great as a developer; everything you need to know about the project your working on can be viewed from the same place that you are writing your code. On top of all this, TFS's version control system is the best I have ever seen and makes Git look a bit primitive.

The trainer teaching us about TFS was Adrian (who is actually a QA Learning guy rather than a QA Consultants guy). Adrian was an excellent trainer, filling in all the odd quiet moments (while we were waiting for visual studio to load for example) with a wide variety of interesting facts and tales from over the years.


More C# And Lots Of Windows Forms

The rest of Week 7 was spent making a plethora of Windows Form Applications to practice our C# programming logic.

We made a numeric number to number in English words converter, a binary to decimal and decimal to binary converter, added find and replace functionality to the text editor we had already made (writing our own find and replace function rather than using the in-built replace function). The biggest project we worked on was a student results viewer which allowed the user to cycle through a list of students displaying all of their exam results and whether they failed or passed, as well a searchable table of students.

More TFS And Even More C#

Week 8 (last week before Christmas!) and we started by learning about TFS administration (which is actually quite straightforward) before getting our hands dirty by building a simple application in teams using a central TFS server.

Well, after the whole of Monday afternfused on occasions when the same user was trying to do so many different things from different machines. We were assured that those problems don't exists in the "real world" outside of training...  


An Introduction To JavaScript

During the final one and a half days of our working year we are learning how to use noon was spent trying to get the network working...

It was eventually fixed at 7pm that evening (we were told) and Tuesday and Wednesday were spent getting used to building a project in teams, which can be a bit tricky at times. Fortunately, TFS's version control system is exceptional so fixing merge conflicts is normally extremely straightforward.... However, we were all logged onto the server as the same user (for strange networking reasons) so TFS did get extremely coJavaScript to manipulate the DOM. I had never given much thought to how JavaScript interacts with the DOM up until now - I just used JQuery and got on with it - so it is interesting to learn how JavaScript it working at a low level.

Next year we will be moving on to Angular.JS, but we will have a deeper understanding of how JavaScript is working behind the scenes before we get on to building applications in Angular.

Some More Board Games

In the last two weeks we have been playing Tiny Epic Kingdoms (and getting quite good at it!) TEK is a brilliant little game with practically no luck and so many different combinations of characters to play that it has yet to get boring. After Christmas we may have some new games to play (potentially including the Imploding Kittens expansion!).

Friday, 16 December 2016

Building Web Games Using p5.js

Building Web Games Using p5.js

Technical Blog 3.

p5.js - Processing but with JavaScript
Last time, we looked at how we can use Processing to visualise mathematics. The other thing I use Processing for is making web games. However, instead of the standard edition of Processing we've been using up until now, to make web games we need to write our code in a more web-friendly language. In particular we need to use JavaScript. Fortunately there is a JavaScript framework which works just like Processing. It is called p5.js.

But first of all: what is p5.js? [1]

What Is p5.js?

Now that Java web-applets are no longer used, Processing's original Java-based design is somewhat redundant if sharing our sketches online is important to us (although using Processing in Java mode still provides the best performance if we are happy to work offline - in an art installation for example).

This is were p5.js comes in.

p5.js was first created by Lauren McCarthy (with the help of the Processing Foundation) with exactly the aim of bringing Processing back to the web. p5.js is a standalone project - not a port or emulation - but is extremely similar to Processing. [2]

How To Setup p5.js

There are several options for writing p5.js code. You can download the p5.js IDE, you can write the code in a text editor and run the code in a web-browser (if you know what you're doing). Or; you can write your code in CodePen, or host it on a GitHub page, or many other methods.

Even though the p5.js editor is still in development, it works for our purposes so download the p5.js editor from here: http://p5js.org/download/ and when you open it, it should look something like this:

p5.js editor
It even gives us the setup and draw functions (notice the JavaScript function syntax)!

When you hit the play button this time, a web-browser will open up with your sketch running in it.

"Hello World!" In p5.js

As we did before, let's draw a black rectangle to the screen. Try typing the following code into the p5.js editor and click the play button to run the sketch:
function setup() {
createCanvas(400, 400);
background(255);
stroke(0);
fill(0);
rect(100, 100, 200, 200);
}
You should see a black square on a white background:
"Hello World" programming in p5.js
As expected, we see a black rectangle on a white background.

As well as the JavaScript syntax for defining functions, we also have to use createCanvas(...) rather than size(...). For the other main differences see this GitHub page.

Taking User Input In p5.js

Let's make a simple button which changes the colour of the background. We can check to see where the mouse is on the screen using the mouseX and mouseY inbuilt variables. We can check if the mouse is pressed using the mouseIsPressed inbuilt variable.

The following code demonstrates how we can use this to make a simple button:
var b = true; 
function setup() {
  createCanvas(800, 600);
}
 
function draw() {
  if (b)
    background(0, 0, 255);
  else
    background(255, 0, 0);
  noStroke();
  fill(0, 255, 0);
  rectMode(CENTER);
  rect(width/2, height/2, 200, 100);

  if (mouseX > width/2 - 100 && mouseX < width/2 + 100 && mouseY < height/2 + 50 && mouseY > height/2 - 50 && mouseIsPressed){
    b = !b;
  }
}
You will notice, if you run this code, that the button doesn't work quite the way we would expect a button to work. The background keeps changing colour every frame as long as the mouse is pressed.

We can fix this by declaring a variable var clicked = false; we can add a check clicked == false to our if statement and as well as changing the color of the background (b = !b) we will set clicked = true;. We can then add another if statement below to changed clicked back to false once the mouse is released (i.e. mouseIsPressed == false). The changes are below:
if (mouseX > width / 2 - 100 && mouseX < width / 2 + 100 && mouseY < height / 2 + 50 && mouseY > height / 2 - 50 && mouseIsPressed && change == true) {
    b = !b;
    change = false;
  }
  if (mouseIsPressed == false) {
    change = true;
  }
This will make the button work as we would expect.

We can also take keyboard input in a similar way. Let's make a rectangle move around the screen using the arrow keys. Again there is an inbuilt variable called keyIsPressed which we will use, but we will also need to check the keyCode variable to make each key do what we want it to do.
var x = 0;
var y = 0;

function setup() {
  createCanvas(800, 600);
}

function draw() {
  background(0)
  noStroke();
  fill(255);
  rect(width/2 + x, height / 2 + y, 100, 100);
  
  if (keyIsPressed){
  if (keyCode == UP_ARROW)
    y--;
  if (keyCode == DOWN_ARROW)
    y++;
  if (keyCode == RIGHT_ARROW)
    x++;
  if (keyCode == LEFT_ARROW)
    x--;
  }
}
When you run the above code you will see a white square on a black background and the arrow keys will move the square around as expected. However, the square moves quite slowly, and is not constrained to the screen. p5.js does have an inbuilt constrain function and of course we can increment x and y by more than 1 to make the square move faster. As an exercise, I recommend implementing these changes in your sketch.


Making Web Games

Before we look at some real-life web games that I have made using p5, we should just note a few aspects of making games beyond simply taking user input.

After playing around with the square moving program for a minute or so you will realise that you cannot move the square in two different directions at the same time. This is because p5 only keeps track of the most recently pressed key in the keyCode variable. This makes for an interesting feature when making action games, but does restrict your design space a little.

It is also worth remember that p5.js is simply a JavaScript framework, so you can make your p5 sketch as part of a normal website. This means you have access to the DOM, HTML, CSS and any other web technologies you wish to use in your website. p5 even has a special library to interact with the DOM.


Some Examples Of Web Games Made Using p5.js

It is time to look at some real-life web games. I have made all of the games I will show here myself and I encourage you to look into the source code to see how each was made.

Let's start with a simple game of Nought's and Crosses: https://codepen.io/LukeBurgess94/full/NRWqgE/


Naughts and Crosses game.
You can view the source-code by going to the "change view" tab in the top-right of the web-page.

This game is an example of implementing lots of buttons, but the AI (who plays randomly) does have to pick an empty space, so there is some data-structure manipulation going on in the background.

Again on CodePen I also made a version of Simon: https://codepen.io/LukeBurgess94/full/bwGwKo/

Simon game.
This game required some subtle timing trickery with p5. The trick being to loop through draw() a certain number of times before executing the next action. This stops the game from moving too quickly and being unplayable.

I have also made an action game in p5: https://callmeluke94.github.io/defend-planet-game/

Defend The Planet game.
The source-code can be seen here: https://github.com/CallMeLuke94/defend-planet-game
This game again utilises the timing trickery from before, but to control the rate of fire of the cannon. You will see the same issue described earlier with only being able to press one button at a time. The game would be much easier if we could move and shoot simultaneously.

Detecting collisions is done by checking that the distance between two objects is less than the sum of their radii, although for the non-circular tank, the radius is slightly larger than the body of the tank.


Conclusion And Next Time

That concludes this week's post, I hope you enjoyed learning about Processing's JavaScript based sister language p5.js. I should note that very similar techniques can be applied to make games in Processing. In fact, I have made a version of the retro Asteroids game in Processing, the source code for which can be found here: https://github.com/CallMeLuke94/AsteroidsGame

Unfortunately you will have to download the files and run them in Processing rather than being able to play in the browser, but it is an entertaining version of Asteroids which you can easily tinker with and adapt.

Of course, Processing is not the best language (and p5.js is not the best JavaScript framework) for making games, but given how intuitive Processing is; it is certainly very enjoyable to build games using Processing and p5.

Next time we will look at the future of Processing, p5.js and Processing's other modes and projects. There is a lot going on in the Processing community with regards to the development of Processing and it is an exciting time to be writing Processing code.

References 

[1] http://p5js.org/
[2] https://www.processing.org/overview/

Friday, 9 December 2016

Specialisations Begin.

Specialisations Begin.

Weeks 5 & 6 of QA Training.

Lowry, Salford Quays: https://flic.kr/p/dDuCw6

Full Stack Microsoft Development

Week 5, and we have finally started our specialisation track. I, along with 10 others, have been put on the Microsoft development course where we will learn how to build software in C#, .NET and Angular.JS whilst using Oracle for database management and Team Foundation Server to help with continuous integration, project tracking, build and deployment.

I did not expect to be trained in full stack development when I signed up but it is an area I am interested in and learning new languages and technologies is always fun. It would be nice, however, if we were given an actual timetable telling us what we are going to be covering in each week rather than various members of staff telling us verbally what we are going to be covering in general but without saying which weeks and what will be involved.

There are also rumors that we will be (potentially) deployed to a big-name software company in London which uses the .NET framework for development after our training is finished...

Databases With Oracle

Beyond the basic SQL course on CodeAcademy I had never done any work with databases. I had no need to. But we have just been through an intensive week long training course on Oracle for database management with the newest trainer at QA, Shafeeq.

Shafeeq was excellent. He has a deep understanding of SQL and made sure we had an understanding of the underlying processes beyond just writing the queries and getting the correct results.

It was hard work though. There was an awful lot to learn and not much time to practice before we had to move on to the next topic.

C# And Finally Learning Real OOP

Having finished our intense SQL bootcamp, we are now in week 6 and learning the basics of Object Orientated Programming in C#. We have already done OOP in Java but as I mentioned last time - we didn't actually learn anything.

This time, Shafeeq is walking us through how and why we do all of the things in OOP. Rather than just being told what inheritance, polymorphism, encapsulation and abstraction are (and what the syntax is for each) we have been going through the fine details of why we do each of these things - and exactly how they implemented in C# (including what happens in the memory and how the garbage collector works).

This is the kind of professional programming training I was expecting to get. I can look up the concepts and syntax in any programming textbook I want, but I was never going to worry about the finer details while I was self-studying.

To write our C# code we have been using Visual Studio which has been one of the best IDE's I've used. Generally I much prefer a text editor (in particular Atom - as it's the best all-purpose text editor around at the moment) to any over-engineered and overly-complicated IDE, but Visual Studio has been pretty good, although I would like to be able to customize it a little more to remove all the unnecessary windows and toolbars that Visual Studio insists you have. At least it's better than the joke that is Eclipse.

We've been making some GUI applications (which is something I never got round to learning in Java) which has been very interesting. So far we have made a calculator and a text editor using Visual Studio's windows form application template.

Some More Board Games

In the last two weeks we have been playing Coup, Zombie Flux and Hanabi. As well as more Exploding Kittens of course.

Friday, 2 December 2016

Visualising Mathematics With Processing.

Visualising Mathematics In Processing.

Technical Blog 2.

https://processing.org/exhibition/
In my previous technical post I introduced the programming language Processing and highlighted some basic features. This time, we will be looking at some more advanced Processing concepts and techniques before using these ideas to do the very thing which got me interested in Processing (and programming in general).

That thing is: visualising mathematics. 


2D Random Walk

A 2D Random Walk
The very first Processing sketch I ever saw was a model of a random process. Here we are also going to model a simple random process using Processing's random() function. We have already seen this function in action in the very last example in my previous post where random() was used to generate a randomly sized circle with a random colour.

This time we are going to use random() to simulate the flipping of a coin and increment a variable by +1 or -1 based on the result. To do this in Processing we will first select a random number between 0 and 2, then if the number if less then 1 we will decrement our variable, if the number is greater than 1 we will increment our variable.

We will do this twice, once for our x values and once for our y values, and draw a square at the coordinates (x,y). Doing this each frame will give us a random walk.

However, it would be nice to see the path that our square is tracing out - so here we can implement a cheap Processing trick and instead of drawing the background again every frame, we can instead draw a rectangle which is the size of the whole canvas but slightly transparent!

This will give the effect of our square tracing out a path which get's fainter over time. The full code is below:
int x = 0;
int y = 0;
int step = 5;
int side = 10;
 
void setup() {
  size(400, 400);
  background(255);
  frameRate(20);
}
 
void draw() {
  //draw a transparent background
  noStroke();
  fill(255, 5);
  rect(0, 0, width, height);

  //draw our randomly moving square
  noStroke();
  fill(0);
  rect(width/2 + x, height / 2 + y, side, side);

  //flip two coins
  float xinc = random(0, 2);
  float yinc = random(0, 2);

  //increment or decrement x and y
  if (xinc < 1) {
    x -= step;
  } else {
    x += step;
  }
  if (yinc < 1) {
    y -= step;
  } else {
    y += step;
  }
 
  //these two functions stop our square
  //from going off the screen.
  x = constrain(x, - width / 2, width / 2);
  y = constrain(y, - height / 2, height / 2);
}
Experiment with the step size and the size of the square, you could even try changing the square to an ellipse. You could also try colouring the square as it moves around the canvas either by linking the colour to the position or to the number of frames that have passed (using the HSB colour mode and the in built frameCount variable for example).

We will see later on a more elegant way of tracing a path without drawing a transparent rectangle over our whole sketch.

2D Fractal

For the fractal geometry course I took during my degree I had to write a program to display the fractal you can see below:
A fractal I had to draw during my degree.
So here I am going to walk you through the code which created that image.

Firstly we need to understand how the fractal is created. The fractal is defined by an iterated function system (IFS), in particular using four contraction mappings to define each of the four stems protruding from the centre of the fractal. [1]

The fractal is built up in a number of stages. Firstly a cross is drawn, then in the centre of each branch another cross is drawn, but scaled down. Then in the middle of each of those new branches another cross is drawn, and so on.

To do this in Processing we can use recursion.

First we need to write a function to draw a cross. We can define functions in Processing just like we would write methods in Java - but we don't need to worry about access modifiers or any other wrappers just type void myFunction(...)and write your function (exchanging void for whatever your return type is of course. Although in Processing we often write functions to draw things - so they have a return type of void). Drawing the cross itself is very easy using Processing's line(...) function. It will be helpful to use a single parameter to define how big the cross is.

With the cross, we need to write another function to recursively draw a smaller cross at the middle of each branch of the large cross. To do this we will make use of Processing's translate(..) function.


The Functions pushMatrix(), popMatrix() and translate(...)

Remember from the last post where we learned that the point (0,0) in a Processing sketch is the top left corner of the window. Isn't that kind of annoying? Wouldn't you rather have (0,0) be in the middle of the screen? Fortunately you can! Try the following code:
void setup() {
  size(400, 400);
  background(255);
  noStroke();
  fill(255, 0, 0); //red
  ellipse(0, 0, 150, 150);
  translate(width/2, height/2);
  fill(0, 0, 255); //blue
  ellipse(0, 0, 150, 150);
}
Notice that both circles were drawn at (0,0) but the blue circle is in the middle of the screen! This is because we translated to (width/2, height/2) before drawing the circle.

Any transformation of the canvas overwrites the previous state unless you use the pushMatrix() function to save the current state. This function pushes the current transformation matrix onto the stack. To revert to the previous state we can use popMatrix() to pop the current transformation off the top of the stack and revert to the previous state.

We will use the translate function to draw our crosses at different locations on the screen and pushMatrix() and popMatrix() to control the translations.


Back To The Fractal...

Now that we can translate our crosses round the canvas at will, we need to write a recursive function that will draw the crosses where we need them to be.

Our function will need a parameter to control the size of the crosses it draws. Inside our function we will need to scale the cross down to the appropriate size and translate it to the middle of one of the branches before calling the function again to repeat the process on the smaller cross. We will need to do this four times - once for each branch.

The full code is below:
float s = pow(2, 10); //initial size of the cross 
void setup(){
  size(1080, 600);
  background(255);
  noLoop(); //stops draw() from looping
}

void draw(){
  translate(width/2, height/2);
  fractal(s);
                        //uncomment the below line to save a picture!
  //save("Cross_Fractal.png");
}

//recursive function to draw the fractal
void fractal(float sc){   
  sc = sc/2;
          //stop when too small
  if (sc>4){         
    
        //draws the left horizontal line
    pushMatrix(); 
    cross(sc);
    translate(-sc/2, 0);
    fractal(sc);
    popMatrix();
    
        //draws the right horizontal line
    pushMatrix();       
    cross(sc);
    translate(sc/2, 0);
    fractal(sc);
    popMatrix();
    
        //draws the bottom vertical line
    pushMatrix();       
    rotate(-PI/2);
    translate(-sc/4, 0);
    cross(sc/4);
    fractal(sc/2);
    popMatrix();
    
        //draws the top vertical line
    pushMatrix();       
    rotate(-PI/2);
    translate(sc/4, 0);
    cross(sc/4);
    fractal(sc/2);
    popMatrix();
  }
}

//draws our cross
void cross(float len){    
  stroke(0);
  line(-len, 0, len, 0);
  line(0, -len/2, 0, len/2);
}
Notice how the fractal(...) function makes use of pushMatrix(), translate(...) and popMatrix() to draw the cross at the required location on the canvas.

We stop draw() from looping by calling noLoop() in setup() because we just want a still image, so we don't need to redraw it 60 times a second. There is also an option to save a png image by uncommenting the line with the save(...) function.

Now it is time to move on to the world of 3D graphics in Processing.

Interactive 3D Lorenz Attractor

We are going to create a simulation of the Lorenz Attractor in Processing.
Lorenz Attractor
The Lorenz Attractor is a very famous fractal coming from the world of chaos theory. In the 1960's Edward Lorenz was trying to model atmospheric convection and developed the following system of differential equations: [2]


{\begin{aligned}{\frac {\mathrm {d} x}{\mathrm {d} t}}&=\sigma (y-x),\\{\frac {\mathrm {d} y}{\mathrm {d} t}}&=x(\rho -z)-y,\\{\frac {\mathrm {d} z}{\mathrm {d} t}}&=xy-\beta z.\end{aligned}}
Lorenz System. /wiki/Lorenz_System

The solution of this system turns out to be a strange attractor [3].

The code itself is adapted from Daniel Shiffman's video tutorial on the Lorenz Attractor, where he walks through the algorithm itself. However, there are some concepts we need to discuss before we can fully understand the code. [4]


3D Graphics and the PeasyCam Library

Processing makes 3D graphics very easy. Simply include "P3D" as a third parameter when declaring the size of your window, e.g. size(800, 600, P3D). We can then create 3D shapes, such as spheres and boxes using Processing's in build shape functions. However, 3D shapes are always drawn at (0, 0, 0) so we need to translate to the point in 3D space where we want to draw the shape, rather than declaring where we want the shape to be in the shape's constructor.

The following code serves as a demonstration of 3D graphics in Processing:
float r = 0;
void setup(){
  size(400, 400, P3D);
  background(0);
} 
void draw(){
  lights();
  background(0);
  translate(width/2, height/2, 50);
  rotateX(radians(r));
  rotateY(radians(r));
  noStroke();
  fill(255);
  box(100);
  r+=0.5;
}
This code also makes use of the rotate functions, which rotate the sketch about whichever axis you choose. The lights() function adds some basic lighting to make 3D objects look a little nicer. Without the rotate or lights, you will just see a white square on the screen.

As nice as the above sketch is, it would be much better if we could interact with our 3D world, rather than just watching it rotate. For that, we need to use the PeasyCam library. [5]

To install PeasyCam, go to Sketch > Import Library... > Add Libary... and search for PeasyCam. Select PeasyCam and click install and then you are ready to make interactive 3D sketches.

To use PeasyCam simply type import peasy.*; at the top of your sketch. Then we need to declare a new PeasyCam object, so on the next line type PeasyCam camera; finally inside setup we create the camera by typing camera = new PeasyCam(this, 0, 0, 0, 500);. The parameters define which sketch to add the camera to, where the camera should be focused (PeasyCam automatically translates everything to (width/2, height/2, 0) so (0, 0, 0) in the PeasyCam constructor is actually the centre of our sketch) and the final parameter is how far away from our focal point the camera lens should be.

Try using PeasyCam in the above example by deleting the translate and rotate lines and declaring a PeasyCam object (notice how the camera movement does not affect the lighting!).


Using ArrayLists and PVector Objects to Create Custom Shapes

In the first example in this post we simulated a random walk and drew the trial by using a transparent background. As I mentioned, that is a cheap Processing trick and will not work for more complex examples (such as the Lorenz Attractor to come, or any other 3D sketch). So we are going to have to be a bit more intelligent and make use of some more Processing features.

 A better way of achieving the desired effect from before (and allowing more flexibility) is to store the positions of our shapes in PVector objects, and store those objects in an ArrayList which we can loop through every frame to draw the entire shape.

A PVector in Processing is nothing more than a 2- or 3-tuple of floats which can be thought of as a point in 2D or 3D space (or as a direction in 2D or 3D space). We can create a PVector by writing PVector p = new PVector(100, 150, 50); the values stored in our PVector can be accessed using the attributes p.x, p.y and p.z so we can translate to the point our PVector is storing by using translate(p.x, p.y, p.z);.

So instead of simply drawing a square at the random point be created each frame in our first sketch earlier, we can store the values in PVector form and then push the PVector to an ArrayList of PVectors.

We are then able to loop through the whole ArrayList each frame, and draw every point.

But wouldn't it be nice if we could join up all of our points into a continuous line? Well Processing makes that very easy by allowing us to define custom shapes. The below code is an example of defining a custom shape:
beginShape();
vertex(100, 100);
vertex(200, 100);
vertex(200, 200);
vertex(100, 100);
endShape();
This will draw three sides of a square. We connect the first and last vertices by specifying CLOSE as a parameter in endShape. Instead of listing out each vertex, we can use the ArrayList method just mentioned and loop through our ArrayList of PVectors defining a vertex for each PVector.

The following code is a development of out 2D random walk sketch to a 3D random walk using PeasyCam and the PVector ArrayList technique just described.
import peasy.*;
PeasyCam camera;

int x = 0;
int y = 0;
int z = 0;
int step = 5;
int side = 5;
ArrayList<PVector> points = new ArrayList<PVector>();

void setup() {
  size(400, 400, P3D);
  background(255);
  frameRate(20);
  camera = new PeasyCam(this, 0, 0, 0, 200);

void draw() {
  background(255);
  
  //draw whole path
  stroke(0);
  noFill();
  beginShape();
  for (PVector p : points){
    vertex(p.x, p.y, p.z);
  }
  endShape();
  
  //draw box at end of path
  pushMatrix();
  translate(x, y, z);
  noStroke();
  fill(0);
  box(side);
  popMatrix();

  //flip three coins
  float xinc = random(0, 2);
  float yinc = random(0, 2);
  float zinc = random(0, 2);

  //increment or decrement x and y
  if (xinc < 1) {
    x -= step;
  } else {
    x += step;
  }
  if (yinc < 1) {
    y -= step;
  } else {
    y += step;
  }
  if (zinc < 1) {
    z -= step;
  } else {
    z += step;
  }

  //add new point to list
  points.add(new PVector(x, y, z));
}
Leave this code running for a while and you'll get a rather intricate fractal like pattern in 3D space. As we have access to every vertex, we can also animate our shape and colour the shape more precisely (as we will do with the Lorenz Attractor code). I highly recommend experimenting with these techniques. 
Example 3D Random Walk

The Lorenz Attractor Itself

We are not ready to create our interactive Lorenz Attractor. As I mentioned before, you can watch Daniel Shiffman's video tutorial to see how the below code is constructed, although the code here includes the PeasyCam library to better explore the sketch.
import peasy.*; 
float xmag, ymag = 0;
float newXmag, newYmag = 0;
PeasyCam camera;
float x, y, z, dx, dy, dz;
float t, dt;
float sigma, beta, rho;
 
//this will store the whole attractor
//as a list of vertices
ArrayList<PVector> points = new ArrayList<PVector>();
 
void setup() {
  size(800, 600, P3D);
  smooth();
  camera = new PeasyCam(this, 0, 0, 0, 500);

  //set initial values
  dt = 0.01;
  x = 1;
  y = 1;
  z = 1;
  //set parameters
  rho = 28;
  sigma = 10;
  beta = 8/3;
}
 
void draw() {
  colorMode(RGB);
  background(0);
  scale(3);
  noFill();
  stroke(255);
 
  //calculate next step
  dx = sigma*(y-x)*dt;
  dy = (x*(rho-z)-y)*dt;
  dz = (x*y-beta*z)*dt;
 
  //add to current position
  x = x + dx;
  y = y + dy;
  z = z + dz;

  //update vertex list
  points.add(new PVector(x, y, z));
 
  //draw the whole attractor
  float hu = 0;
  beginShape();
  for (PVector v : points) {
    colorMode(HSB);
    //rainbow colouring
    stroke(hu%360, 255, 255);
    vertex(v.x, v.y, v.z);
    hu += 0.1;
  }
  endShape();

  //mark the new position
  pushMatrix();
  translate(x, y, z);
  colorMode(RGB);
  stroke(255);
  fill(255);
  sphere(0.5);
  popMatrix();
}

If You Want More...

For more examples of this sort of thing, check out Daniel Shiffman's YouTube channel.

Next time we will be looking at making games in Processing, in particular using p5.js for making web-games.

References 

[1] https://en.wikipedia.org/wiki/Iterated_function_system
[2] https://en.wikipedia.org/wiki/Lorenz_system
[3] https://en.wikipedia.org/wiki/Attractor
[4] https://www.youtube.com/watch?v=f0lkz2gSsIk
[5] http://mrfeinberg.com/peasycam/