% Program following the evolution of edge fringes past an opaque knife edge
% 

clear all
close all

vid = VideoWriter('edgePropagation.mp4','MPEG-4'); 
vid.FrameRate = 60;    % Default 30
vid.Quality = 100;    % Default 75
open(vid); 
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none'); 
set(0,'defaultfigurecolor',[1 1 1]); % White background 
set(gca,'linewidth',7); 

ydir = -1:0.1:1; % h and ydir define detector surface 
h = -10:0.01:10; 
hpos = 0:0.01:10;
[H,YDir] = meshgrid(h,ydir);
Det = 0*sin(H).^2+cos(YDir).^2; 

d2 = 0.0001:0.025:10.0001; 
lambda = 1; 
nuStep = 0.01; 

xc=0; yc=-5; zc=0;   % coordinates of box center
Lx=0.1;              % box size x
Ly=10;               % box size y
Lz=4;                % box size z
maskAlp=0.5;         % transparency of box (max=1=opaque) 
Cs = [0.625 0.64 0.775];        % Light Phil blue 



X = [0 0 0 0 0 1; 1 0 1 1 1 1; 1 0 1 1 1 1; 0 0 0 0 0 1];
Y = [0 0 0 0 1 0; 0 1 0 0 1 1; 0 1 1 1 1 1; 0 0 1 1 1 0];
Z = [0 0 1 0 0 0; 0 0 1 0 0 0; 1 1 1 0 1 1; 1 1 1 0 1 1];

Xcoords = Lx*(X-0.5) + xc;
Ycoords = Ly*(Y-0.5) + yc;
Zcoords = Lz*(Z-0.5) + zc;

lp = [-2 -2 0];

for m = 1:length(d2) 
    newplot 
    hold on 
    clear F 
    for n=1:length(h)
        nu = h(n)*(2/(lambda*d2(m)))^0.5; 
        nu_vector=nu:nuStep:nu+100; 
        F(n)=((1+1i)/2)*sum(exp((-1i*pi*(nu_vector).^2)/2)); 
        Det(:,n)=(abs(max(F))/10000)*((1+1i)/2)*sum(exp((-1i*pi*(nu_vector).^2)/2));
    end 
    % Curve tracking the position of the first minimum with distance from
    % the screen 
    plot3(hpos,(2*hpos).^0.5,hpos*0,'LineWidth',2,'Color','r');
    % max(F)
    F=abs(F)/abs(max(F));
    
    colormap gray
    cb = colorbar; 
    set(cb,'position',[.125 .31 .01 .25],'TickLength',0.0); % Size and position of colorbar 
    cb.Color = [0 0 0]; 
    
    axis off
    % Semitransparent mask 
    screen = fill3(Xcoords-0.1,Ycoords,Zcoords,Cs,'FaceAlpha',maskAlp,'LineStyle','none');    % draw cube
    hold on 
    if (m > 1)
        aa = pcolor(YDir,-H,abs(Det)); 
        set(aa,'EdgeColor','none','FaceAlpha',0.92); 
        aa.ZData = d2(m) + aa.ZData; 
        rotate(aa,[0 1 0],90,[0,0,0]); 
        line1 = plot3([-0.8 10],[0 0],[0 0],'color','k','LineWidth',2,'LineStyle','-.');
        xlim([-1 10.01]);
        ylim([-1 1]);
        zlim([-2 2]);
        axis equal
        set(gca,'linewidth',2);
        set(gca, 'Projection','perspective');
        set(gca,'View',[-95,16]); 
        
        frame = getframe(gcf);
        writeVideo(vid,frame); 
    end
    

    hold off;
end 
% Output the movie as an mpg file
close(vid); 