% ---------------------------------------------------------------------- %
% Fractal Terrain Generation using Splitting Planes                      %
% Jeremy Cowles                                                          %
% EPS 109, Fall 2009                                                     %
% Based on Lab 4                                                         %
% ---------------------------------------------------------------------- %

clear
clf

view([-34.5 14]);

makemovie = 0;
quad_plot = 0;
if makemovie
    set(gca, 'nextplot', 'replacechildren');
    aviobj = avifile('test_movie22','quality',100,'compression','None');
end


NX = 1.5*50;
NY = 1.5*70;

%set initial conditions
Z = zeros(NX,NY);

x = 1:NX;
y = 1:NY;
[X,Y] = meshgrid(y,x); % the y goes first !!!

% Set a fixed random seed for generating movie
RandStream.setDefaultStream(RandStream('mt19937ar', 'seed',2));

% Initial height of terrain is 2
Z = Z + 2;
fc = 1;

shading interp

for k = 1:10000
    if (mod(k, round(1 + 0.005 * k)) == 0)
        drawnow;
        if makemovie
            aviobj = addframe(aviobj,figure(1));
            
            if (k < 5)
               for j = 1:15
                   aviobj = addframe(aviobj,figure(1));
               end
            elseif (k < 10)
               for j = 1:5
                   aviobj = addframe(aviobj,figure(1));
               end
            end
            
            pause(0.01)
        end 
    end
    
    Z = make_land(Z,NX,NY,rand()*NX,rand()*NY,rand()*NX/5,rand());
    
    if (quad_plot)
        subplot(2,2,1);
        pcolor(X,Y,Z);
        surf(X,Y,Z);
        axis([0 NY 0 NX 0 140])

        title('Fractal Terrain Evolution');
        xlabel('x');
        ylabel('y');
        view([-34 14 0]);

        subplot(2,2,2);
        surf(X,Y,Z);
        axis([0 NY 0 NX 0 140])
        title('Fractal Terrain Evolution');
        xlabel('x');
        ylabel('y');
        view([-34 14]);

        subplot(2,2,3);
        surf(X,Y,Z);
        axis([0 NY 0 NX 0 140])
        title('Fractal Terrain Evolution');
        xlabel('x');
        ylabel('y');
        view([0 0 180]);

        subplot(2,2,4);
        contour(X,Y,Z,30,'k');  
    else
        pcolor(X,Y,Z);
        surf(X,Y,Z);
        shading interp
        axis([0 NY 0 NX 0 140])
        title('Fractal Terrain Evolution');
        xlabel('x');
        ylabel('y');
        view([-134 14]);
        pause
    end
end

% Do a 360 degree rotation at the end of the movie
for k = 1:4:360
    view([-134+k 14]);
    drawnow;
    pause(0.01)
    if makemovie
        aviobj = addframe(aviobj,figure(1));%F);
    end
end

% Save the video file
if makemovie
    aviobj = close(aviobj);
    return
end


