2D displacement mapping for water effect

Hey great stuff! - very happy to find this thread

just a quick fix for the problem with the above code. – the offset variable was returning a negative number. I just removed the modulo length and change to 0 if returning a negative number.

PImage img;

void setup(){
   size(730, 549, P2D); //width and height should be similar to the picture's dimensions
    
    img = loadImage("turner.jpg");
    int len = img.pixels.length;
    //print(len);
    //print(img.width * img.height);
    loadPixels();
    for(int x = 0; x < img.width; x++){ // by row
      for(int y = 0; y < img.height; y++) { // by column
         int i = x + y * img.width; // i = index of grid columns
         float n = warp(x, y, .003, 555); 
         int offset = (i-int(n)); //%len; // with a modulo the offset should wrap around 
         if (offset<0){
          offset = 0; 
         }
         color c = img.pixels[offset]; // --> ArrayIndexOutOfBoundsException
         
         pixels[i] = color(c);
         }
      }
    updatePixels();
}

       
float warp(int _x, int _y, float factor, int n_range) {
    float n1 = noise((_x+0.0) * factor, (_y+0.0) * factor) * n_range;
    float n2 = noise((_x+5.2) * factor, (_y+1.3) * factor) * n_range;
    PVector q = new PVector(n1, n2);
            
    float n3 = noise(((_x + q.x * 4) + 1.7) * factor, ((_y + q.y * 4) + 9.2) * factor) * n_range;
    float n4 = noise(((_x + q.x * 4) + 8.3) * factor, ((_y + q.y * 4) + 2.8) * factor) * n_range;
    PVector r = new PVector(n3, n4);
                
    return noise((_x + r.x * 4) * factor, (_y + r.y * 4) * factor) * n_range;
}
5 Likes