% Demo to create a movie file from a Gaussian and then optionally save it to disk as a gray scale MP4 video file.

%==============================================================================================
% Initialization code
clear all;
clc;
workspace;
numberOfFrames = 61;
x1d = linspace(-3, 3, numberOfFrames);
y1d = x1d;
t = linspace(0, 5, numberOfFrames);
hFigure = figure;

% Set up the movie structure.
vidHeight = 344;
vidWidth = 446;
% Need to change from the default renderer to zbuffer to get it to work right.
% openGL doesn't work and Painters is way too slow.
set(gcf, 'renderer', 'zbuffer');

%==============================================================================================
% Create the movie.
fullFileName = fullfile(pwd, 'Deleteme.mp4');
% Create a video writer object with that file name.
% The VideoWriter object must have a profile input argument, otherwise you get jpg.
% Determine the format the user specified:
[folder, baseFileName, ext] = fileparts(fullFileName);
switch lower(ext)
	case '.jp2'
		profile = 'Archival';
	case '.mp4'
		profile = 'MPEG-4';
	otherwise
		% Either avi or some other invalid extension.
		profile = 'Uncompressed AVI';
end
writerObj = VideoWriter(fullFileName, profile);
open(writerObj);
% Get a list of x and y coordinates for every pixel in the x-y plane.
[x, y] = meshgrid(x1d, y1d);
% After this loop starts, BE SURE NOT TO RESIZE THE WINDOW AS IT'S SHOWING THE FRAMES, or else you won't be able to save it.
for frameIndex = 1 : numberOfFrames
	z = exp(-(x-t(frameIndex)).^2-(y-t(frameIndex)).^2);
	cla reset;
	% Enlarge figure to full screen.
	% 	set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0, 1, 1]);
	surf(x,y,z);
	axis('tight')
	zlim([0, 1]);
	caption = sprintf('Frame #%d of %d, t = %.1f', frameIndex, numberOfFrames, t(frameIndex));
	title(caption, 'FontSize', 15);
	drawnow;
	thisFrame = getframe(gca);
	% Write this frame out to a new video file.
	grayImage = rgb2gray(thisFrame.cdata);
	writeVideo(writerObj, grayImage);
	% 	myMovie(frameIndex) = thisFrame;
end
close(writerObj);
% Display the current folder panel so they can see their newly created file.
cd(folder);
filebrowser;
if contains(computer, 'WIN')
	% If using Windows, play the movie in the default video player.
	winopen(fullFileName);
end
message = sprintf('Finished creating movie file\n      %s.\n\nDone with demo!', fullFileName);
uiwait(helpdlg(message));

