
// ReadHeightMap.java
// Andrew Davison, ad@coe.psu.ac.th, Nov 2022

/* Reads a grayscale image, and outputs the pixel values as 
   doubles. One row of pixels becomes one row of doubles printed
   to stdout. 

   Since jzy3d puts (0,0) at the bottom left (when the xy plane
   is viewed from above), the data is read in reverse row order,
   last row first, backwards to row 0. This will make the
   heightmap plot in jzy3d match the original PNG height image.

   The text file can be read by PolygonDemo.java, the jzy3d appl.

  Usage:
   > javac ReadHeightMap.java
   > java ReadHeightMap <height map image file>
   e.g.
   > java ReadHeightMap heightmap.png > heights2.txt

   > run PolygonDemo heights2.txt
*/


import java.io.*;
import java.awt.image.*;
import javax.imageio.*;



public class ReadHeightMap 
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: java ReadHeightMap <heightmap image fnm>");
      return;
    }

    try {
      System.out.println("// Reading height map from " + args[0]);
      BufferedImage image = ImageIO.read( new File(args[0]));

      for (int y = image.getHeight()-1; y >= 0; y--) { 
         // read from bottom row to top  
        for (int x = 0; x < image.getWidth(); x++) {
          double height = (image.getRGB(x, y) & 0xFF) / 255.0;
                          /* in a grayscale map, the RGB parts 
                              will all be the same value, 
                              so just take one out of the packed ints */
          System.out.printf("%.2f ", height); 
        }
        System.out.println();
      }
    }
    catch (IOException e) 
    { System.out.println(e); }
  }  // end of main()

}  // end of ReadHeightMap class

