Calling draw() from a function doesn't update the screen

I'm experimenting with how to process some data in one function while displaying a loading bar on the screen. For an example, I'm adding a bunch of values to an array - a process that takes about 5 seconds on my computer. I have the following code:

ArrayList<String> strs = new ArrayList<String>();
String state;
float counter;

void setup() {
  size(640, 480);
  state = "load";
  noStroke();
}

void draw() {
  if (state.equals("load")) {
    load();
  } else if (state.equals("loading")) {
    background(255);
    fill(255, 0, 0);
    rect(0, height/2-25, map(counter, 0, 10000000, 0, width), 50);
  } else if (state.equals("play")) {
    background(0, 255, 0);
  }
}

void load() {
  state = "loading";
  for (int i = 0; i < 10000000; i++) {
    strs.add(str(pow(i, 2)));

    if (i % 1000 == 0) {
      counter = i;
      draw();
    }
  }
  state = "play";
}

But I just get a grey screen (indicating that background(255) has never been called) for about 5 seconds until I get a green screen. I could, of course, replace the code with something like:

ArrayList<String> strs = new ArrayList<String>();
String state;
int counter;

void setup() {
  size(640, 480);
  state = "load";
  noStroke();
  counter = 0;
}

void draw() {
  if (state.equals("load")) {
    float theMillis = millis();
    while (millis()-theMillis < 1000.0/frameRate && counter < 10000000) {
      strs.add(str(pow(counter, 2)));
      counter++;
    }
    if (counter >= 10000000) {
      state = "play";
    }

    background(255);
    fill(255, 0, 0);
    rect(0, height/2-25, map(counter, 0, 10000000, 0, width), 50);
  } else if (state.equals("play")) {
    background(0, 255, 0);
  }
}

And that would work for this simple example, but I am trying to get draw() to work when called from a function explicitly as depending on the complexity of load() (the one I'm actually trying to get to work in my project is 250+ lines long of opening and uncompressing files, processing JSONArrays and ArrayLists, etc.) splitting the load function into chunks inside draw() could be a nightmare. So is there anyway to update the screen from inside a function?

Thanks in advance for all your help :)

Tagged:

Answers

  • read the tutorial on setup and draw and the forum FAQ.

    in short, draw is called on a timer and trying to subvert that probably won't work.

  • for 5 seconds i wouldn't even bother with a bar showing progress. the mac beachball doesn't show progress...

  • Well, as I said, this is but a sample - my real bar is much longer than 5 seconds. I think I may have been able to answer my question using thread().

  • Answer ✓

    ha, i was just about to post this https://processing.org/reference/thread_.html

    which pretty much does what you want - loads a json file in a thread in the background.

  • Yep. All I had to do was replace load() in line 13 of my first code with thread("load")

Sign In or Register to comment.