Multiple shaders

is there a better solution to create a sketch using multiple shaders?

PShader myShader, pixelate;
PImage img;
PGraphics pg, buf;

void settings() {
  size(1000, 1000, P3D);
}

void setup() {
  myShader = loadShader("glitch.glsl");
  pixelate = loadShader("pixelate.glsl");
  myShader.set("iResolution", float(width), float(height));
  pixelate.set("pixels", 200., 200.);
  pg = createGraphics(width, height, P3D);
  buf = createGraphics(width, height, P3D);
}

void draw() {
  pg.beginDraw();
  pg.translate(width/2, height/2);
  pg.background(0);
  pg.fill(255);
  pg.stroke(0);
  pg.rotateY(frameCount*0.02);
  pg.sphere(400);
  pg.endDraw();
  pg.filter(pixelate);
  myShader.set("iTime", millis()/1.);

  //buf.beginDraw();
  buf=pg;
  //buf.endDraw();
  buf.filter(myShader);
  image(buf, 0, 0, width, height);
}

thank you!!

2 Likes

What do you mean by “is there a better solution” exactly?

Some comments -

What is buf for? You seem to immediately set buf=pg.

Do you need to use filter with myShader? Could you use this instead?

shader(myShader);
image(buf, 0, 0, width, height);

Given that you don’t do anything with the output of the first shader before drawing through the second shader, could you merge the two shaders into a single shader?

It all depends on what the shaders are doing really!

1 Like

nope…i can’t use one shader, they are really different.

but i’ve just see that it works fine also like this:

void draw() {
  println(frameRate);
  pg.beginDraw();
  pg.translate(width/2, height/2);
  pg.background(0);
  pg.noFill();
  pg.stroke(255);
  pg.rotateY(frameCount*0.02);
  pg.sphere(400);
  pg.endDraw();
  pg.filter(pixelate);
  pg.filter(myShader);
  myShader.set("iTime", millis()/1.);
  image(pg, 0, 0, width, height);
}

i never use filter before, but it looks work fine!!

btw thank you for the answer @neilcsmith !!

1 Like

Yes, it was a long shot on the single shader! :smile:

You should be able to do …

pg.filter(pixelate);
myShader.set("iTime", millis()/1.);
shader(myShader);
image(pg, 0, 0, width, height);

… though, which will use the second shader in the draw to the screen, which will cut down the workload a bit.

Surely you want to set iTime before you use the shader either way?!

1 Like

oh…in some example i saw i ever see set after shader declaretion!!
it’s uncorrect?

Yes! You’re currently setting the value for the next time though draw().

oh, ok!! thanks :slight_smile: