% Code to plot simulation results from sdl_vehicle_4wd_testbed
%% Plot Description:
%
% The plot below shows the results of a four-wheel drive vehicle
% accelerating from rest with the left wheels on a low friction surface,
% such as ice, and the right wheels on a high friction surface, such as dry
% tarmac.  The test is run twice with different configurations for the
% front and rear differential.  The Torsen differential automatically locks
% under the split surface condition, resulting in faster acceleration.

% Copyright 2016 The MathWorks, Inc.

% Get simulation results
temp_variant = {'Open','Torsen'};

% Save current variant for center differential
temp_frdiffvnt = get_param('sdl_vehicle_4wd_testbed/Front Differential','ActiveVariant');
temp_rediffvnt = get_param('sdl_vehicle_4wd_testbed/Rear Differential','ActiveVariant');
temp_ctrdiffvnt = get_param('sdl_vehicle_4wd_testbed/Center Differential','ActiveVariant');

% Test with left wheels on low friction surface, rear on high friction
set_param('sdl_vehicle_4wd_testbed/Road','road_condition','Split: Low mu on left');
set_param('sdl_vehicle_4wd_testbed/Center Differential','OverrideUsingVariant','Shaft');

for temp_ivar=1:length(temp_variant)
    set_param('sdl_vehicle_4wd_testbed/Front Differential','OverrideUsingVariant',temp_variant{temp_ivar});
    set_param('sdl_vehicle_4wd_testbed/Rear Differential','OverrideUsingVariant',temp_variant{temp_ivar});
        % Run simulation
    sim('sdl_vehicle_4wd_testbed');
    simlog_t.(temp_variant{temp_ivar}) = simlog_sdl_vehicle_4wd_testbed.Vehicle_Body.Vehicle_Body.V.series.time;
    simlog_vVeh.(temp_variant{temp_ivar}) = simlog_sdl_vehicle_4wd_testbed.Vehicle_Body.Vehicle_Body.V.series.values('m/s');
end

% Reuse figure if it exists, else create new figure
if ~exist('h3_sdl_vehicle_4wd_testbed', 'var') || ...
        ~isgraphics(h3_sdl_vehicle_4wd_testbed, 'figure')
    h3_sdl_vehicle_4wd_testbed = figure('Name', 'sdl_vehicle_4wd_testbed');
end
figure(h3_sdl_vehicle_4wd_testbed)
clf(h3_sdl_vehicle_4wd_testbed)

% Plot results
for temp_ivar=1:length(temp_variant)
    plot(simlog_t.(temp_variant{temp_ivar}), simlog_vVeh.(temp_variant{temp_ivar}), 'LineWidth', 5-temp_ivar);
    hold on
end
hold off
grid on
title('Front and Rear Differential Tests')
ylabel('Vehicle Speed (m/s)')
xlabel('Time (s)')
legend(temp_variant,'Location','Best');

% Return model to original variant for center differential
set_param('sdl_vehicle_4wd_testbed/Front Differential','OverrideUsingVariant',temp_frdiffvnt);
set_param('sdl_vehicle_4wd_testbed/Rear Differential','OverrideUsingVariant',temp_rediffvnt);
set_param('sdl_vehicle_4wd_testbed/Center Differential','OverrideUsingVariant',temp_ctrdiffvnt);

% Remove temporary variables
clear simlog_t simlog_handles
clear clear simlog_vVeh

