/*******************************************************************************
*
* McStas, neutron ray-tracing package
*         Copyright 1997-2002, All rights reserved
*         Risoe National Laboratory, Roskilde, Denmark
*         Institut Laue Langevin, Grenoble, France
*
* Component: Mirror
*
* %I
* Written by: Kristian Nielsen
* Date: August 1998
* Version: $Revision: 1.19 $
* Origin: Risoe
* Release: McStas 1.6
*
* Single mirror plate.
*
* %D
* Single mirror plate (used to build guides in compound components).
*
* Example: Mirror(xlength=.1, yheight=.1,R0=0.99,Qc=0.021,alpha=6.1,m=2,W=0.003)
*
* %P
* INPUT PARAMETERS:
*
* xlenght: (m)    length of mirror plate 
* yheight: (m)    height of mirror plate
* R0:      (1)    Low-angle reflectivity 
* Qc:      (AA-1) Critical scattering vector 
* alpha:   (AA)   Slope of reflectivity
* m:       (1)    m-value of material. Zero means completely absorbing.
* W:       (AA-1) Width of supermirror cut-off
*
* %D
* Example values: m=4 Qc=0.02 W=1/300 alpha=6.49 R0=1
*
* %E
*******************************************************************************/

DEFINE COMPONENT Mirror
DEFINITION PARAMETERS ()
SETTING PARAMETERS (xlength, yheight,R0=0.99,Qc=0.021,alpha=6.07,m=2,W=0.003)
STATE PARAMETERS (x,y,z,vx,vy,vz,t,s1,s2,p)

TRACE
%{
  double dt, q;
  
  /* First check if neutron has the right direction. */
  if(vz != 0.0 && (dt = -z/vz) >= 0)
  {
    double old_x = x, old_y = y;
    x += vx*dt;
    y += vy*dt;
    /* Now check if neutron intersects mirror. */
    if(x >= 0 && x <= xlength && y >= 0 && y <= yheight)
    {
      z = 0;
      t += dt;
      q = fabs(2*vz*V2Q);
      vz = -vz;
      /* Reflectivity (see component Guide). */
      if(m == 0)
        ABSORB;
      if(q > Qc)
      {
        double arg = (q-m*Qc)/W;
        if(arg < 10)
          p *= .5*(1-tanh(arg))*(1-alpha*(q-Qc));
        else
          ABSORB;                               /* Cutoff ~ 1E-10 */
      }
      p *= R0;
      SCATTER;
    }
    else
    {
      /* No intersection: restore neutron position. */
      x = old_x;
      y = old_y;
    }
  }
%}

MCDISPLAY
%{
  multiline(5, 0.0, 0.0, 0.0,
               (double)xlength, 0.0, 0.0,
               (double)xlength, (double)yheight, 0.0,
               0.0, (double)yheight, 0.0,
               0.0, 0.0, 0.0);
%}
END
