Processing in Scala REPL

This page keeps an updated version of the code I originally wrote about here.

Assuming you’ve got processing in your classpath, you can now interactively draw and compose sketches through the REPL using this piece of code.

2D version as of [08/09/2011] (for 2D):

object Scheduler { val tasks = collection.mutable.Buffer[() => Any]();  def addTask[A](t: => A):() => A = { lazy val task = {() => t}; tasks += task; task }; def removeTask[A](t: () => A) {tasks -= t} }
import processing.core._; import PApplet._; import PConstants._; import Scheduler._;
object Test extends PApplet {
	override def setup() { size(500, 500); }
	override def draw() {Scheduler.tasks.foreach(_())}
}
PApplet.runSketch(Array("Test"), Test)
import Test._

3D version as of [08/10/2011] (using PeasyCam):

object Scheduler { val tasks = collection.mutable.Buffer[() => Any]();  def addTask[A](t: => A):() => A = { lazy val task = {() => t}; tasks += task; task }; def removeTask[A](t: () => A) {tasks -= t} }
import processing.core._; import PApplet._; import PConstants._; import Scheduler._;
object Test extends PApplet {
	override def setup() { size(500, 500, P3D); new peasy.PeasyCam(this, 600); }
	override def draw() {Scheduler.tasks.foreach(_())}
}
PApplet.runSketch(Array("Test"), Test)
import Test._

Changelog:

[08/10/2011] – Typo in 3D version fixed.

[08/09/2011] – Added a Scheduler. You may add and remove arbitrary code blocks to be executed during draw(); e.g.

scala> addTask{ ellipse(random(width), random(height), 25, 25); } //this effectively puts the ellipse call inside draw
res1: () => Unit = <function0>

scala> removeTask(res1) //stop drawing random ellipses
scala> tasks //tasks is just a Buffer that you can change at will
res4: scala.collection.mutable.Buffer[() => Any] = ArrayBuffer()
scala> (0 until 100).foreach(i => addTask{line(0, 0, (i/3f*frameCount)%width, i*5)})

scala> addTask{background(255)}
res7: () => Unit = <function0>

scala> tasks.clear //Be careful, newer tasks will always over-draw old ones!

scala> addTask{background(255)}
res9: () => Unit = <function0>

scala> (0 until 100).foreach(i => addTask{line(0, 0, (i/3f*frameCount)%width, i*5)})


One Comment on “Processing in Scala REPL”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s