%%********************************************************************************************
%  Author: Tim Chartier
%  Title:  mountain.m
%  Description: This code creates 3D fractal mountains.
%*********************************************************************************************
%
% Exercises:
%
% 1. Run the code to create your own fractal mountain.
% 2. Perform more iterations.  The code is currently set at 6.
% 3. Zoom in on the mountain.  How many zooms can you perform before it no longer appears
%    like a mountain? Can you alter the code to allow you to zoom in more times?
% 4. Increase and decrease the value 2 in the line:
%                 scale = (1/2)^(level);
%    What effect does this have on the resulting mountain?
% 5. Find the line:
%                 zValues = zeros(2);
%    and replace it with:
%                 zValues = zeros(3);
%     Explain the resulting behavior.
%
%*********************************************************************************************

%% Input parameters
iterates = 6;          % set the number of iterations
zValues = zeros(2);    % set up starting "mountain"

%% Plot starting iterate
figure('Color','k')    % set background color of starting figure

h = meshz(zValues);
set(h,'FaceColor','interp','EdgeColor','k')
colormap(jet)
axis tight off
pause

%% Perform iterates to create 3D mountain
for level=1:iterates
    scale = (1/2)^(level);  % adjust 1/2 for effect
    [zRow, zCol] = size(zValues);
    zValuesTmp = [];
    for i=1:zRow
        zRowTmp = zeros(1,2*zRow-1);
        for j=1:zCol-1
            zRowTmp(2*j-1) = zValues(i,j);
            zRand = -scale + 2*scale*rand;
            zRowTmp(2*j) = mean([zValues(i,j),zValues(i,j+1)])+ zRand;
        end
        zRowTmp(2*zCol-1) = zValues(i,zCol); 
        zValuesTmp = [zValuesTmp; zRowTmp];
    end
    zValues = zValuesTmp;
    zValuesTmp = [];

%%
    [zRow, zCol] = size(zValues);
    for i=1:zRow-1
        zValuesTmp = [zValuesTmp; zValues(i,:)];
        zRowTmp = zeros(1,zCol);
        for j=1:2:zCol-1
            zRand = -scale + 2*scale*rand;
            zRowTmp(j) = mean([zValues(i,j),zValues(i+1,j)]) + zRand;
            zRand = -scale + 2*scale*rand;
            zRowTmp(j+1) = mean([zValues(i,j),zValues(i+1,j),zValues(i,j+2),zValues(i+1,j+2)]) + zRand;
        end
        zRand = -scale + 2*scale*rand;
        zRowTmp(zCol) = mean([zValues(i,zCol),zValues(i+1,zCol)]) + zRand;
        zValuesTmp = [zValuesTmp; zRowTmp];
    end
    zValuesTmp = [zValuesTmp; zValues(zRow,:)];
    zValues = zValuesTmp;
    % Plot resulting 3D fractal mountain     
    h = meshz(zValues);
    set(h,'FaceColor','interp','EdgeColor','k')
    colormap(jet)
    axis tight off
    pause
end 


