Weird issue with pgraphics

i’m trying to copy image information from one pgraphic to another (like trying to cache the old one and render it in the background) and it keeping having weird effects like it being linked together permanently when i use an = (i.e. pg1 = pg2;)
and i don’t know of any other variable that acts like this.

here’s some test code that demonstrates my issue

PGraphics pg1;
PGraphics pg2;
float t;

void setup() {
  size(640,480);
  pg1 = createGraphics(width,height);
  pg2 = createGraphics(width,height);
}

void draw() {
  t = t+1;
  pg1.beginDraw();
  pg1.ellipse(random(width),random(height),20,20);
  pg1.endDraw();
  if (t > 200) {
    pg2 = pg1;
    t = 0;
    println("ping");
  }
  image(pg2,0,0);
}

The moment you call pg2 = pg1 then pg1 and pg2 are pointing to the same graphics object and the original pg2 will disappear. This is how object references work in Processing and Java, and is different to primitives like int, float, etc.

What you need to do here is probably copy the contents of pg1 into pg2. eg.

void draw() {
  t = t+1;
  pg1.beginDraw();
  pg1.ellipse(random(width),random(height),20,20);
  pg1.endDraw();
  if (t > 200) {
    pg2.beginDraw();
    pg2.image(pg1, 0, 0);
    pg2.endDraw();
    t = 0;
    println("ping");
  }
  image(pg2,0,0);
}
2 Likes

yay thank you! i think i tried doing that but i don’t think i had it layed out correctly

/**
 * PGraphics arrayCopy() (v1.1)
 * GoToLoop (2018/Jul/25)
 * Discourse.Processing.org/t/weird-issue-with-pgraphics/2063/4
 */

static final String FILENAME = "balls.", EXT = ".jpg";
static final String FC = "Frames: ", SC = "  -  Shots: ";

static final int BALLS = 200, DIAM = 20, RAD = DIAM >> 1;

PGraphics left, right;

void setup() {
  size(640, 480);
  left  = createGraphics(width >> 1, height);
  right = createGraphics(width >> 1, height);

  left.beginDraw();
  left.background((color) random(#000000));
  left.endDraw();

  right.beginDraw();
  right.background((color) random(#000000));
  right.endDraw();
  set(width >> 1, 0, right);
}

void draw() {
  final int shots = frameCount / BALLS;
  final String fc = FC + frameCount, sc = SC + shots;
  getSurface().setTitle(fc + sc);

  left.beginDraw();

  final float x = random(RAD, left.width  - RAD);
  final float y = random(RAD, left.height - RAD);
  left.ellipse(x, y, DIAM, DIAM);

  if (frameCount % BALLS == 0) {
    left.loadPixels();
    arrayCopy(left.pixels, right.pixels);
    right.updatePixels();
    set(width >> 1, 0, right);

    final String filename = FILENAME + nf(shots, 3) + EXT;
    right.save(dataPath(filename));

    left.background((color) random(#000000));
  }

  left.endDraw();
  set(0, 0, left);
}