% Movie of transformation from dipole to synchrotron radiation as a
% function of beta (v/c)
clear; close all;
vid = VideoWriter('dipoleToSynchrotron2.mp4','MPEG-4');
vid.Quality = 100;
vid.FrameRate = 30;
open(vid);
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
set(0,'defaultfigurecolor',[1 1 1]);
set(gca,'linewidth',7);

phi = 0:pi/500:2*pi; % phi azimuthal
theta = 0:pi/500:2*pi; % theta polar
[phi,theta]=meshgrid(phi,theta);
N = 199; % Number of time frames

lp1 = [-0.4 -0.4 0.4]; % light position for illuminating surface
lp2 = [0.4 -0.2 0.4]; % light position for illuminating surface
ec = [0.25 0.28 0.55]; % Phil blue color
fc = [1.0 0.83 0]; % Gold color


for i = 0:0.5:N
    hold off;
    beta = 0.0025+i/(N+1); % v/c
    gamma = 1/(1 - beta^2)^0.5; % E/mec^2
    scaleFac = 1/(1 - beta)^3;
    boxSize = scaleFac*(N+1-i)^0.125;
    pt1 = (1 - beta*cos(theta)).^2;
    pt2 = ((sin(theta).*cos(phi)).^2)/gamma^2;
    pt3 = (1 - beta*cos(theta)).^5;
    rho = (pt1-pt2)./pt3;
    x = rho.*sin(theta).*cos(phi);
    y = rho.*sin(theta).*sin(phi);
    z = rho.*cos(theta);
    
    fa = 0.56;
    ea = 0.0;
    surf(x,-z,y,'FaceAlpha',fa,'FaceColor',fc,'EdgeAlpha',ea,'EdgeColor', ...
        ec,'LineStyle','none','FaceLighting','gouraud','DiffuseStrength',0.8);
    light('Position',lp1,'Style','infinite');
    light('Position',lp2,'Style','infinite');
    
    if (i <= N/4)
        view(-90,16);
    elseif (i > N/4) && (i < N/2)
        view(-90,16+(74*((i-N/4)/(N/4)))); % Fast tilt from 23 deg above plane to vertically above plane
    else
        view(-90,90);
    end
    str1 = '{\beta} = ';
    str2 = num2str(beta,'% 4.4f');
    strTot = [str1,str2];
    hText = text(0.55*boxSize, -0.64*boxSize, strTot, 'FontSize',14);
    hold on;
    
    th = 0:pi/50:2*pi;
    xunit = 2*boxSize*cos(th) + 0;
    yunit = 2*boxSize*sin(th) + 2*boxSize;
    zunit = 0 * sin(th);
    plot3(-yunit,xunit,zunit,'color','blue', 'LineWidth', 2.0);
    
    [x y] = meshgrid(-boxSize:boxSize/4:boxSize); % Generate x and y data
    z = zeros(size(x, 1)); % Generate z data
    surf(x/2, y, z,'FaceAlpha',0.1,'FaceColor',ec,'EdgeAlpha',ea,'EdgeColor',ec,'LineStyle','none') % Plot the surface
    
    axis square % Keep scaling 1:1:1 for x,y,z
    axis off
    
    set(gca, 'Projection','perspective');
    
    % Dimensions of 3D box
    xlim([-boxSize boxSize]);
    ylim([-boxSize boxSize]);
    zlim([-boxSize boxSize]);
    % Store the frame
    frame = getframe(gcf);
    writeVideo(vid,frame);
    
end
hold off;
% Output the movie as an mpg file
close(vid);
