We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I was playing with threads and I wrote this sketch just to test async tasks in processing.
This sketch draws a rect in the center and draws random points with random color called by the thread.
Simply, it glitch a lot :D It changes the color of everything until you click with the leftbutton. And if you right click, the central quad doesn't change color(but the color is wrong) and the background continues.
Am I asking too much?
boolean drawpoints = true;
color c = color(255,0,0);
exampleThread exthr;
void setup() {
size(500,500);
noStroke();
frameRate(15);
exthr = new exampleThread();
exthr.start();
}
void draw() {
background(127);
rect(225,225,50,50);
if (drawpoints) {
pushStyle();
fill(c);
for(int i = 0; i < 50; i++) {
ellipse(random(width),random(height), 5, 5);
}
popStyle();
}
}
void setDrawPoints() {
drawpoints = !drawpoints;
}
void randColor(color r) {
c = r;
}
void mouseClicked() {
if (mouseButton == LEFT)
exthr.leftClick();
else if (mouseButton == RIGHT)
exthr.rightClick();
else if (mouseButton == CENTER) {
exthr.centerClick();
}
}
class exampleThread extends Thread {
int cycles = 0;
exampleThread () {}
void start () {
super.start();
}
void run () {
while(true) { // keep running
while (cycles > 0) { // simulate time consuming task
cycles--;
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
color randC = color(random(255), random(255), random(255));
randColor(randC);
}
}
void leftClick() {
cycles = 50;
}
void rightClick() {
setDrawPoints();
}
void centerClick() {
color randC = color(random(255), random(255), random(255));
randColor(randC);
}
void quit() {
System.out.println("Quitting.");
interrupt();
}
}
Answers
Found the solution, I'm asking too much to Processing and it glitch.
I've solved by putting the thread in sleep for 5 millis.
}
Most of Processing's functions aren't build for concurrent access, in this case it's the color() method that creates the "glitch". Just replace line 64 and 65 with the following code:
randColor(0xff000000 | ((int)random(255) << 16) | ((int)random(255) << 8) | (int)random(255));
Most performance-wise expression to pick a randomly opaque color: $-)
For JavaScript, to force it to be opaque, we need an extra Or bitwise operation: >:)
If performance is a problem (and you still wanna use Processing :D ), I would also pick another pseudo random number generator, Java's build in generator is neither the fastest nor the best. ;)