: music, art, code
August 17, 2013

One Sketch to Rule Them All (Part 1)

In my last post about VJ’ing, I mentioned I was able to render graphics to an offline buffer in Processing.  Recently, some Boston Creative Coder friends were talking about how great it’d be to switch between different Processing sketches without reloading the application.  It turns out that these 2 topics are related, but first let me start with a simple way to load multiple sketches from 1 super-sketch.


What this .gif shows is a single Processing sketch (the first grey box) spawning 2 other Processing sketches.  To prove that the first grey box is REALLY dumb and is loading external Processing sketches, here is the code:

package mtn.test;
import processing.core.PApplet;
public class UberLoader extends PApplet{
	public PApplet constructedApplet;
	public static void main(String[] args) {
		PApplet.main("mtn.test.UberLoader", args);
	public void draw()
	public void keyPressed()
		if(key == '1')
		} else if(key == '2')
	private void load(String sketch)
		 this.runSketch(new String[]{sketch}, constructedApplet);

First, you’ll notice that this code isn’t running from the default Processing IDE.  You’ll need to run this from a Java IDE like Eclipse.  Regardless, you can see that there isn’t much going on there.  I’m capturing the keyboard input and telling the runSketch() function which sketch I want to run.  This technique, however, has one fatal flaw: we’re not destroying the old sketch when we open the new sketch!  This means that if you want to cycle through memory intensive sketches, they’ll all compete for your resources.

If we want to close our old sketch before opening a new sketch, we need a reference to the old sketch so we can call .dispose() which will free up memory and resources.  Unfortunately, to do this we need to grab the source code for runSketch() and modify it to return the constructed Sketch so that we can close it.  This ends up looking like this:


Final source code is here.  As I alluded to earlier, there’s another way to do this that’s a little cleaner in that you won’t have multiple windows open at once.  That’s covered in the next post.

Leave a Reply