Demonstrating the thread convenience function
in
Share your Work
•
3 months ago
There is neat sketch on
openprocessing by Chinchbug that demonstrates the use of threads in processing. Here I've adapted it to use the convenience method
thread to run a function in processing (uses reflection under the hood). Since I was using processing-2.0 no point in me trying to publish it on open processing.
- float ang;
- int curr;
- PImage frames[];
- boolean bLoadDone;
-
- void setup() {
- size(305, 395);
- background(0);
- smooth();
- noStroke();
- textAlign(CENTER, CENTER);
- frames = new PImage[116];
- bLoadDone = false;
- thread("loadFrames"); // processing convenience method for starting new Thread with a function
- ang = 0.0;
- }
-
-
- void draw() {
- if (bLoadDone) {
- background(0);
- image(frames[curr++], 0, 0);
- if (curr > 115) {
- curr = 0;
- }
- }
- else {
- float x, y;
- ang += 0.1;
- x = cos(ang) * 8;
- y = sin(ang) * 8;
- fill(0, 8);
- rect(50, 150, 100, 100);
- fill(32, 32, 255);
- ellipse(x + 100, y + 200, 8, 8);
- fill(0);
- rect(120, 150, 170, 100);
- fill(128);
- text(String.format("loading frames (%s of 115)", curr), 200, 200);
- }
- }
-
- void loadFrames() {
- for (curr = 0; curr < 116; curr++) {
- frames[curr] = loadImage(dataPath(String.format("a%s copy.jpg", nf(curr, 3))));
- delay(75); //just slows down this thread - the main draw() cycle is unaffected...
- }
- curr = 0;
- frameRate(30);
- bLoadDone = true;
- }
Part of my motivation was to find an example for my new
thread convenience function in ruby-processing, where instead of using reflection to call a function the user need only supply a block (which is more idiomatically correct in ruby anyway). Here is the equivalent sketch in ruby-processing:-
- FRAMES = 116
- attr_reader :ang, :curr, :frames, :done_loading
- def setup
- size(305, 395)
- background(0)
- no_stroke
- text_align(CENTER, CENTER)
- @frames = []
- @done_loading = false
- @curr = 0
- thread do # supply a block in ruby-processing rather than use reflection
- FRAMES.times do |i|
- frames << load_image(data_path("a#{nf(i, 3)} copy.jpg"))
- @curr = i
- delay(75) #just slows down this thread - the main draw cycle is unaffected...
- end
- @curr = 0
- frame_rate(30)
- @done_loading = true
- end
- @ang = 0.0
- end
- def draw
- if (done_loading)
- background(0)
- image(frames[curr], 0, 0)
- @curr += 1
- if (curr > 115)
- @curr = 0
- end
- else
- @ang += 0.1
- x = cos(ang) * 8
- y = sin(ang) * 8
- fill(0, 8)
- rect(50, 150, 100, 100)
- fill(32, 32, 255)
- ellipse(x + 100, y + 200, 8, 8)
- fill(0)
- rect(120, 150, 170, 100)
- fill(128)
- text("loading frames (#{curr} of 115)", 200, 200)
- end
- end