clf; close all; clear;

global MIN_X MAX_X MIN_Y MAX_Y MIN_Z MAX_Z;
MIN_X = 0; MAX_X = 50;
MIN_Y = 0; MAX_Y = 50;
MIN_Z = 0; MAX_Z = 50;

f = figure;
hold on

global neutrons uraniums stables 
% create a neutron
neutron = Particle;
neutron.type = Particle.NEUTRON;
neutron.position = [50; 40; 50];
neutron.direction = [0; 1; -1];
neutron.direction = neutron.direction / norm(neutron.direction);
neutron.speed = 1;

neutrons = [neutron];

% create a uranium
% uranium = Particle;
% uranium.type = Particle.URANIUM;
% uranium.position = [50; 60; 50];
% uranium.direction = [0; -1; 0];
% uranium.speed = 1.4;

% uraniums = [uranium];
uraniums = [];
% create many uraniums
for i=1:100
    thing = Particle;
    thing.type = Particle.URANIUM;
    thing.position = [rand*100; rand*100; rand*100];
    thing.direction = [rand*2-1; rand*2-1; rand*2-1];
    thing.direction = thing.direction / norm(thing.direction);
    thing.speed = rand*3+.5;
    uraniums = [uraniums, thing];
end

% stable particles after uranium breaks up
stables = [];

collisions_time = [0];
f=0;
iters = 0;
while true
    iters = iters + 1;
    % drawing
    p_view = setup_grid();
    % draw neutrons
    positions = [neutrons.position];
    scatter3(positions(1,:), ...
            positions(2,:), ...
            positions(3,:), ...
            (50), ...
            'MarkerEdgeColor', 'k',...
            'MarkerFaceColor', [.4 .4 .4])
    
    % draw uraniums
    if ~isempty(uraniums)
        positions = [uraniums.position];
        scatter3(positions(1,:), ...
                positions(2,:), ...
                positions(3,:), ...
                600, ...
                'MarkerEdgeColor', 'k',...
                'MarkerFaceColor', [.8 .3 .3])
    end
    
    % draw stables
    if ~isempty(stables)
        positions = [stables.position];
        scatter3(positions(1,:), ...
                positions(2,:), ...
                positions(3,:), ...
                300, ...
                'MarkerEdgeColor', 'k',...
                'MarkerFaceColor', [.3 .3 .8])
    end
    drawnow
    
    % screenshot
    if mod(iters, 5) == 0
        saveas(gcf, ['final_', num2str(f, '%03d'),'.png'])
        f = f+1;
    end
    
    pause(.001);
    
    % logic, update
    for i=1:length(uraniums)
        update(uraniums(i));
    end
    for i=1:length(neutrons)
        did_collide = check_collisions(i);
        if did_collide
            collisions_time = [collisions_time iters];
        end
        update(neutrons(i));
        did_collide = check_collisions(i);
        if did_collide
            collisions_time = [collisions_time iters];
        end
    end
    for i=1:length(stables)
        update(stables(i));
    end
end

stairs(collisions_time, 0:length(stables)/2);
xlabel('Time (timesteps)');
ylabel('Total number of collisions');
title('Total Number of Collisions vs Time');

