#include <windows.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include "usersurf.h"

/*
Written by Kenneth E. Moore
August 25, 2003
*/

int __declspec(dllexport) APIENTRY UserDefinedSurface(USER_DATA *UD, FIXED_DATA *FD);

/* a generic Snells law refraction routine */
int Refract(double thisn, double nextn, double *l, double *m, double *n, double ln, double mn, double nn);

BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved)
	{
   return TRUE;
   }

/*

This DLL models a biconic asphere surface:

The sag is given by:

Z = N/(1 + sqrt(D) ) + A + B

where

N = cx * x^2 + cy * y^2
D = 1 - (1+kx)*(cx*x)^2 - (1+ky)*(cy*y)^2
A = sum(i = 1 to 16) Ai * x ^ i
B = sum(i = 1 to 16) Bi * y ^ i

The MaxTerms parameter maybe set to less than 16 to speed up the ray trace.

*/

int __declspec(dllexport) APIENTRY UserDefinedSurface(USER_DATA *UD, FIXED_DATA *FD)
	{
   int i, loop, maxq;
   double A, B, N, D, xpower, ypower, t, tp, x, y, z, dz, sag, cx, cy, kx, ky;
	double dNdx, dNdy, dDdx, dDdy, dAdx, dBdy, alpha, mx, my;

   switch(FD->type)
   	{
      case 0:
      	/* ZEMAX is requesting general information about the surface */
         switch(FD->numb)
         	{
            case 0:
            	/* ZEMAX wants to know the name of the surface */
		         /* do not exceed 12 characters */
		         strcpy(UD->string,"BiConAsphere");
               break;
            case 1:
            	/* ZEMAX wants to know if this surface is rotationally symmetric */
               /* it is not, so return a null string */
            	UD->string[0] = '\0';
               break;
            case 2:
            	/* ZEMAX wants to know if this surface is a gradient index media */
               /* it is not, so return a null string */
            	UD->string[0] = '\0';
            	break;
            }
         break;
      case 1:
      	/* ZEMAX is requesting the names of the parameter columns */
         /* the value FD->numb will indicate which value ZEMAX wants. */
         /* Only "q" in parameter 1 is used for this surface type */
         /* returning a null string indicates that the parameter is unused. */
         switch(FD->numb)
         	{
            case 0:
            	strcpy(UD->string, "Max Terms");
               break;
            case 1:
            	strcpy(UD->string, "Cx");
               break;
            case 2:
            	strcpy(UD->string, "Cy");
               break;
            case 3:
            	strcpy(UD->string, "Kx");
               break;
            case 4:
            	strcpy(UD->string, "Ky");
               break;
            default:
            	UD->string[0] = '\0';
            	break;
            }
      	break;
      case 2:
      	/* ZEMAX is requesting the names of the extra data columns */
         /* the value FD->numb will indicate which value ZEMAX wants. */
         /* returning a null string indicates that the extradata value is unused. */
			UD->string[0] = '\0';
         if (FD->numb >=  1 && FD->numb <= 16)
            {
            sprintf(UD->string, "X ^ %i", FD->numb);
            }
         if (FD->numb >= 17 && FD->numb <= 32)
            {
            sprintf(UD->string, "Y ^ %i", FD->numb - 16);
            }
      	break;
      case 3:
      	/* ZEMAX wants to know the sag of the surface */

         UD->sag1 = 0.0;
         UD->sag2 = 0.0;
         maxq = (int) FD->param[0];
			maxq = min(16, max(0, maxq));

			cx = FD->param[1];
			cy = FD->param[2];
			kx = FD->param[3];
			ky = FD->param[4];

			N = cx*UD->x*UD->x + cy*UD->y*UD->y;
			D = 1.0 - (1.0 + kx)*cx*cx*UD->x*UD->x - (1.0 + ky)*cy*cy*UD->y*UD->y;
         if (D < 0) return(-1);

			A = 0.0;
			B = 0.0;
			for (i = maxq; i >= 1; i--)
				{
				A = FD->xdata[i   ] + UD->x*A;
				B = FD->xdata[i+16] + UD->y*B;
				}
			A *= UD->x;
			B *= UD->y;

         UD->sag1 = N/(1.0+sqrt(D)) + A + B;
         UD->sag2 = UD->sag1;

      	break;
      case 4:
      	/* ZEMAX wants a paraxial ray trace to this surface */
         /* x, y, z, and the optical path are unaffected, at least for this surface type */
         /* for paraxial ray tracing, the return z coordinate should always be zero. */
         /* paraxial surfaces are always planes with the following normals */
         /* we will ignore the aspheric terms, even the quadratic one, since it has a */
         /* meaning that is hard to interpret if q != 0.0 */

         UD->ln =  0.0;
         UD->mn =  0.0;
         UD->nn = -1.0;
			if (FD->param[0] > 2)
				{
				/* account for quadratic asphere term in power */
				xpower = (FD->n2 - FD->n1)*(FD->param[1] + 2.0*FD->xdata[2   ]);
				ypower = (FD->n2 - FD->n1)*(FD->param[2] + 2.0*FD->xdata[2+16]);
				}
			else
				{
				xpower = (FD->n2 - FD->n1)*(FD->param[1]);
				ypower = (FD->n2 - FD->n1)*(FD->param[2]);
				}
         if ((UD->n) != 0.0)
         	{
            (UD->l) = (UD->l)/(UD->n);
            (UD->m) = (UD->m)/(UD->n);

            (UD->l) = (FD->n1*(UD->l) - (UD->x)*xpower)/(FD->n2);
            (UD->m) = (FD->n1*(UD->m) - (UD->y)*ypower)/(FD->n2);

            /* normalize */
            (UD->n) = sqrt(1/(1 + (UD->l)*(UD->l) + (UD->m)*(UD->m) ) );
            /* de-paraxialize */
            (UD->l) = (UD->l)*(UD->n);
            (UD->m) = (UD->m)*(UD->n);
            }
         break;
      case 5:
      	/* ZEMAX wants a real ray trace to this surface */
         /* okay, not a plane. */
         /* do not allow n == 0 */
         if (UD->n == 0.0) return -1;

         /* Now, we illustrate an iterative method of finding
            the intercept for a general surface. */

			/* make sure we do at least 1 loop */

			t = 100.0;
         tp = 0.0;
         x = UD->x;
         y = UD->y;
         z = UD->z;
         loop = 0;

         maxq = (int) FD->param[0];
			maxq = min(16, max(0, maxq));

			cx = FD->param[1];
			cy = FD->param[2];
			kx = FD->param[3];
			ky = FD->param[4];
		
         while (fabs(t) > 1e-10)
         	{
				/*
            First, compute the sag using whatever the surface sag expression is.
            This is given the x and y starting points. The following block of code
            will change depending upon the surface shape, the rest of this iteration
            is typically common to all surface shapes.
            */

				N = cx*x*x + cy*y*y;
				D = 1.0 - (1.0 + kx)*cx*cx*x*x - (1.0 + ky)*cy*cy*y*y;
				if (D < 0) return(-1);
				A = 0.0;
				B = 0.0;
				for (i = maxq; i >= 1; i--)
					{
					A = FD->xdata[i   ] + x*A;
					B = FD->xdata[i+16] + y*B;
					}
				A *= x;
				B *= y;

				sag = N/(1.0+sqrt(D)) + A + B;

            /* okay, now with sag in hand, how far are we away in z? */
            dz = sag - z;

            /* now compute how far along the z axis this is */
            /* note this will crash if n == 0!! */
            t = dz / (UD->n);

            /* propagate the additional "t" distance */
            x += UD->l*t;
            y += UD->m*t;
            z += UD->n*t;

            /* add in the optical path */
				tp += t;

            /* prevent infinte loop if no convergence */
            loop++;
            if (loop > 1000) return(-1);
            }

         /* okay, we should be a the intercept coordinates now */
         UD->x = x;
         UD->y = y;
         UD->z = z;

      	/* don't forget the path! */
			UD->path = tp;

			/* now do the normals */
         if (x == 0.0 && y == 0.0)
         	{
            UD->ln =  0;
            UD->mn =  0;
            UD->nn = -1;
            }
         else
         	{
				N = cx*x*x + cy*y*y;
				D = 1.0 - (1.0 + kx)*cx*cx*x*x - (1.0 + ky)*cy*cy*y*y;
				if (D <= 0) return(-1);
				A = 0.0;
				dAdx = 0.0;
				B = 0.0;
				dBdy = 0.0;
				for (i = maxq; i >= 1; i--)
					{
					A = FD->xdata[i   ] + x*A;
					dAdx = (double) i * FD->xdata[i   ] + x * dAdx; 

					B = FD->xdata[i+16] + y*B;
					dBdy = (double) i * FD->xdata[i+16] + y * dBdy; 
					}
				A *= x;
				B *= y;

				dNdx = 2.0*cx*x;
				dNdy = 2.0*cy*y;
				dDdx = -2.0*(1.0+kx)*cx*cx*x;
				dDdy = -2.0*(1.0+ky)*cy*cy*y;

				alpha = 1+sqrt(D);
				mx = dNdx/(alpha) - N*(1.0/(alpha*alpha))*(0.5/sqrt(D))*dDdx + dAdx;
				my = dNdy/(alpha) - N*(1.0/(alpha*alpha))*(0.5/sqrt(D))*dDdy + dBdy;

				UD->nn = -sqrt(1/(1 + (mx*mx) + (my*my)));
				UD->ln = -mx*UD->nn;
				UD->mn = -my*UD->nn;
            }
         if (Refract(FD->n1, FD->n2, &UD->l, &UD->m, &UD->n, UD->ln, UD->mn, UD->nn)) return(-FD->surf);
         break;
      case 6:
      	/* ZEMAX wants the index, dn/dx, dn/dy, and dn/dz at the given x, y, z. */

         /* This is only required for gradient index surfaces, so return dummy values */
         UD->index = FD->n2;
         UD->dndx = 0.0;
         UD->dndy = 0.0;
         UD->dndz = 0.0;
      	break;
      case 7:
      	/* ZEMAX wants the "safe" data. */
         /* this is used by ZEMAX to set the initial values for all parameters and extra data */
         /* when the user first changes to this surface type. */
         /* this is the only time the DLL should modify the data in the FIXED_DATA FD structure */
         for (i = 0; i <= 8; i++) FD->param[i] = 0.0;
         for (i = 0; i <= 200; i++) FD->xdata[i] = 0.0;
         break;
      }
   return 0;
   }

int Refract(double thisn, double nextn, double *l, double *m, double *n, double ln, double mn, double nn)
{
double nr, cosi, cosi2, rad, cosr, gamma;
if (thisn != nextn)
	{
	nr = thisn / nextn;
	cosi = fabs((*l) * ln + (*m) * mn + (*n) * nn);
	cosi2 = cosi * cosi;
	if (cosi2 > 1) cosi2 = 1;
	rad = 1 - ((1 - cosi2) * (nr * nr));
	if (rad < 0) return(-1);
	cosr = sqrt(rad);
	gamma = nr * cosi - cosr;
	(*l) = (nr * (*l)) + (gamma * ln);
	(*m) = (nr * (*m)) + (gamma * mn);
	(*n) = (nr * (*n)) + (gamma * nn);
	}
return 0;
}

