import ij.*;
import ij.plugin.filter.PlugInFilter;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import java.util.*;
import ij.measure.*;

/** This plugin finds the orientation of facets in a topographical image.
	Bob Dougherty 4/10/2002
	Extended by Gary Chinga 7/26/2002 and 7/29/2002
 */
/*	License:
	Copyright (c) 2002, 2005, OptiNav, Inc.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

		Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
		Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.
		Neither the name of OptiNav, Inc. nor the names of its contributors
	may be used to endorse or promote products derived from this software
	without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
	A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
	CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
	PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class Facet_orientation implements PlugInFilter {

	ImagePlus imp;
	int i,w,h,index;
   	ResultsTable rt = new ResultsTable();
	double dx, ut, whiteAreas,whiteAreaFraction,blackAreas,blackAreaFraction;
    	float ra,min,max,temp;
	boolean azimuthal=false, polar=false;
	boolean canceled = false, pseudo = false, threshold1 = false,results = false;
	static int[] kernelX = new int[]{-1,0,1,-2,0,2,-1,0,1};
	static int[] kernelY = new int[]{1,2,1,0,0,0,-1,-2,-1};

	float[] theta, phi,threshold;


	public int setup(String arg, ImagePlus imp) {
		if (IJ.versionLessThan("1.28"))
			return DONE;
		this.imp = imp;
		return DOES_32;
	}

	public void run(ImageProcessor ip) {
		double pi = Math.PI;
     		temp = 0;

		int numSlices = imp.getStackSize();
		ImageStack stack = imp.getStack();
		w = stack.getWidth();
		h = stack.getHeight();

		//Get the pixel size;
		getDetails();
		if (canceled) return;

		//Create new stacks for the output.
        		ImageStack imsTheta = new ImageStack(w,h);
       		ImageStack imsPhi = new ImageStack(w,h);
		ImageStack imsThreshold = new ImageStack(w,h);

        		//Go through the slices of the input stack.
		for (i = 0; i < numSlices; i++){
			whiteAreas = 0; whiteAreaFraction=0;blackAreas=0;blackAreaFraction=0;
        			min = Float.MAX_VALUE;
        			max = -Float.MAX_VALUE;
       	 		ra = 0;

			IJ.showProgress((double)i/numSlices);
			IJ.showStatus("a: "+i+"/"+numSlices);

			//Get a slice and make copies of the pixel arrays.
 			ImageProcessor ipSlice = stack.getProcessor(i+1);
 			float[] gradX = (float[])ipSlice.getPixelsCopy();
  			float[] gradY = (float[])ipSlice.getPixelsCopy();

 			//Put the pixel arrays into image processors for the convolutions.
 			ImageProcessor ipGradX = new FloatProcessor(w,h);
 			ipGradX.setPixels(gradX);
  			ImageProcessor ipGradY = new FloatProcessor(w,h);
 			ipGradY.setPixels(gradY);

  			//Evaluate the gradients.
  			ipGradX.convolve3x3(kernelX);
  			ipGradY.convolve3x3(kernelY);

			//Make places for the results.
			FloatProcessor ipTheta = new FloatProcessor(w,h);
			FloatProcessor ipPhi = new FloatProcessor(w,h);
			FloatProcessor ipThreshold = new FloatProcessor(w,h);
			theta = (float[])ipTheta.getPixels();
			phi = (float[])ipPhi.getPixels();
			threshold = (float[])ipThreshold.getPixels();

			//Extract the orientation data from the gradients of the distance image.
			//Normal vector components: nx = cos_phi sin_theta, ny = sin_phi sin_theta
			//Range image gradients: gx = -nx/nz, gy = -ny/nz.
			//Solving: phi = atan(gy/gx) = atan2(gy,gx)
			//theta = atan(sqrt(gx^2 + gy^2)

			for (int y = 0; y < h; y++){
				for (int x = 0; x < w; x++){
					index = x + w*y;
					//The derivative requires the factors 1/(2*dx) for the centered
					//finite difference and 1/4 for the coefficients of the kernel.
					double gx = gradX[index]/(8*dx);
					double gy = gradY[index]/(8*dx);
					theta[index] = (float)(Math.atan(Math.sqrt(gx*gx + gy*gy))*(360/(2*pi)));
					phi[index] = (float)((Math.atan2(gy,gx))*(360/(2*pi)));
					temp = ipTheta.getPixelValue(x,y);

					if (results) calculateResults();
					if (threshold1) thresholdImage();

				}
			}

			//Put the results in the destination stacks.
			ipTheta.setMinAndMax(0,0);
			ipPhi.setMinAndMax(0,0);
			ipThreshold.setMinAndMax(0,0);
			imsTheta.addSlice("Polar  image (Theta)",ipTheta);
			imsPhi.addSlice("Azimuthal image (Phi)",ipPhi);
			imsThreshold.addSlice("Thresholded image",ipThreshold);

			if (results)
				writeResults();
		}

		// Create new images using the new stacks.
		ImagePlus impTheta = new ImagePlus("Polar image (Theta)",imsTheta);
		ImagePlus impPhi = new ImagePlus("Azimuthal image (Phi)",imsPhi);

		if (threshold1){
			ImagePlus impThreshold = new ImagePlus("Thresholded image",imsThreshold);
			impThreshold.setStack(null,imsThreshold);
			impThreshold.show();
		}

		impTheta.setStack(null,imsTheta);
        		impPhi.setStack(null,imsPhi);

		IJ.showProgress(1.0);

		// Display the new stacks.
		if (polar){
			impTheta.show();
			if(pseudo) IJ.run("Fire");
		}
		if (azimuthal){
			impPhi.show();
			if(pseudo) IJ.run("Fire");
		}
		IJ.run("Tile");



	}

   	void getDetails() {

		GenericDialog gd = new GenericDialog("Facet orientation...");
		gd.addNumericField("Pixel size: ", 1,0);

		gd.addNumericField("Max  threshold angle(Max 90): ", 10, 0);
		gd.addCheckbox("Display polar image", true);
		gd.addCheckbox("Display azimuthal image", true);
		gd.addCheckbox("Apply threshold and display image", threshold1);
		gd.addCheckbox("Apply pseudocolors ", pseudo);
		gd.addCheckbox("Write results ", results);

		gd.showDialog();
		if (gd.wasCanceled()) {
			canceled = true;
			return;
		}
		dx= (int)gd.getNextNumber();
		ut= (int)gd.getNextNumber();

		if (ut>90) {
			canceled = true;
			IJ.showMessage("Values between 0 and 90 are required");
			return;
		}
		polar = gd.getNextBoolean();
		azimuthal = gd.getNextBoolean();
		threshold1 = gd.getNextBoolean();
		pseudo = gd.getNextBoolean();
		results = gd.getNextBoolean();


	}

	void calculateResults(){
		//CALCULATE FACET ORIENTATION
		ra = ra +  Math.abs(temp);
		if (temp<min) min = temp;
		if (temp>max) max = temp;
		if (theta[index]<ut){whiteAreas++;}
	}

   	 void writeResults() {

	    //Write the results in the result table
       		rt.incrementCounter();

		whiteAreaFraction = 100*whiteAreas/(w*h);
		blackAreaFraction = 100-whiteAreaFraction;
		blackAreas=(w*h)-whiteAreas;

		rt.addValue("Orientation", ra/(w*h));
		rt.addValue("Highest angle",max);
		rt.addValue("Lowest angle", min);
		if (threshold1){
			rt.addValue("# White areas", whiteAreas);
			rt.addValue("# Black areas", blackAreas);
			rt.addValue("White (%)", whiteAreaFraction);
			rt.addValue("Black (%)", blackAreaFraction);
		}

        		if (i==0)
           			IJ.setColumnHeadings(rt.getColumnHeadings());
        			IJ.write(rt.getRowAsString(rt.getCounter()-1));
 	}

 	void thresholdImage(){
		if (theta[index]<ut){threshold[index]=255;}
		else {threshold[index]=0;}
	}

}


