classdef ManipulatorApp < matlab.apps.AppBase
% MANIPULATORAPP Interactive MATLAB App Designer GUI for 6-DOF Puma 560
% kinematics, workspace validation, DH parameter inspection, and trajectory animation.

    % Public UI components
    properties (Access = public)
        UIFigure                        matlab.ui.Figure
        ExitButton                      matlab.ui.control.Button
        TextArea                        matlab.ui.control.TextArea
        Animation                       matlab.ui.control.Button
        InverseKinematicsButton         matlab.ui.control.Button
        ForwardKinematicsButton         matlab.ui.control.Button
        TransformationMatrixPOSEButton  matlab.ui.control.Button
        TextArea_2                      matlab.ui.control.TextArea
        UIAxes2                         matlab.ui.control.UIAxes
    end

    % Internal state
    properties (Access = private)
        BackgroundImage
        RobotModel
    end

    methods (Access = private)

        function robot = getRobotModel(app)
            % Lazy-load and cache the Puma 560 RigidBodyTree model.
            if isempty(app.RobotModel)
                app.RobotModel = loadrobot('puma560', 'DataFormat', 'row', 'Gravity', [0 0 -9.81]);
            end
            robot = app.RobotModel;
        end

        function pose = forwardKinematics(~, theta1, theta2, theta3, ~)
            % Planar 2-link + vertical prismatic FK helper (L1 = 1 m, L2 = 1 m).
            L1 = 1;
            L2 = 1;
            x = L1 * cos(theta1) + L2 * cos(theta1 + theta2);
            y = L1 * sin(theta1) + L2 * sin(theta1 + theta2);
            z = theta3;
            pose = [1 0 0 x; 0 1 0 y; 0 0 1 z; 0 0 0 1];
        end

        function singularity = isSingular(app, jointAngles)
            % Probe near-singular configurations using the 6x6 geometric Jacobian.
            robot = app.getRobotModel();
            J = geometricJacobian(robot, jointAngles, 'link6');
            singularity = abs(det(J)) < 1e-6;
        end

        function showResult(app, msg, durationSec)
            % Display formatted output in the overlay TextArea and Command Window.
            disp(msg);
            app.TextArea.Value = splitlines(msg);
            app.TextArea.Visible = 'on';
            drawnow;
            pause(durationSec);
            if isvalid(app.TextArea)
                app.TextArea.Visible = 'off';
            end
        end

        function ok = checkJointLimits(~, robot, jointAngles)
            % Validate each joint against RigidBodyTree PositionLimits (reported in degrees).
            ok = true;
            for i = 1:min(numel(jointAngles), numel(robot.Bodies))
                if isa(robot.Bodies{i}.Joint, 'rigidBodyJoint')
                    lims = robot.Bodies{i}.Joint.PositionLimits;
                    if jointAngles(i) < lims(1) || jointAngles(i) > lims(2)
                        errordlg(sprintf('Joint %d exceeds limits! Valid range: [%.1f deg, %.1f deg]', ...
                            i, rad2deg(lims(1)), rad2deg(lims(2))), 'Joint Limit Error');
                        ok = false;
                        return;
                    end
                end
            end
        end
    end

    % Component callbacks
    methods (Access = private)

        function startupFcn(app)
            app.TextArea.Visible = 'off';
            appDir = fileparts(mfilename('fullpath'));
            imgFile = fullfile(appDir, 'R2.jpg');
            if exist(imgFile, 'file') ~= 2
                imgFile = fullfile(pwd, 'R2.jpg');
            end

            if exist(imgFile, 'file') == 2
                app.BackgroundImage = imread(imgFile);
                app.UIAxes2.Position = [-90 -110 1700 1300];
                imshow(app.BackgroundImage, 'Parent', app.UIAxes2, 'InitialMagnification', 'fit');
                app.UIAxes2.XLim = [0 size(app.BackgroundImage, 2)];
                app.UIAxes2.YLim = [0 size(app.BackgroundImage, 1)];
                app.UIAxes2.Interactions = [];
            else
                app.UIFigure.Color = [0.09 0.12 0.18];
            end
        end

        function TransformationMatrixPOSEButtonPushed(app, ~)
            prompt = {'Enter theta1 (degrees):', 'Enter theta2 (degrees):', ...
                      'Enter theta3 (degrees):', 'Enter theta4 (degrees):'};
            answer = inputdlg(prompt, 'Input Angles', [1 35], {'0', '0', '0', '0'});
            if isempty(answer); return; end

            valsDeg = str2double(answer);
            if any(isnan(valsDeg))
                errordlg('All inputs must be numeric values. Please try again.', 'Input Error');
                return;
            end

            th = deg2rad(valsDeg);
            pose = app.forwardKinematics(th(1), th(2), th(3), th(4));

            formattedPose = sprintf([ ...
                '[%.2f  %.2f  %.2f  %.2f\n' ...
                ' %.2f  %.2f  %.2f  %.2f\n' ...
                ' %.2f  %.2f  %.2f  %.2f\n' ...
                ' %.2f  %.2f  %.2f  %.2f]'], ...
                pose(1,1), pose(1,2), pose(1,3), pose(1,4), ...
                pose(2,1), pose(2,2), pose(2,3), pose(2,4), ...
                pose(3,1), pose(3,2), pose(3,3), pose(3,4), ...
                pose(4,1), pose(4,2), pose(4,3), pose(4,4));

            app.showResult(sprintf('OUTPUT\n\nPOSE =\n%s', formattedPose), 5);

            puma560 = app.getRobotModel();
            theta = [th(1), th(2), th(3), th(4), 0, 0];
            if ~app.checkJointLimits(puma560, theta)
                return;
            end

            figure('Name', 'Puma 560 — Pose View', 'NumberTitle', 'off', 'WindowState', 'maximized');
            show(puma560, theta, 'Frames', 'off');
            title('Puma 560 Configuration');
        end

        function ForwardKinematicsButtonPushed(app, ~)
            p560 = app.getRobotModel();
            prompt = {'Enter theta1 (degrees):', 'Enter theta2 (degrees):', ...
                      'Enter theta3 (degrees):', 'Enter theta4 (degrees):'};
            answer = inputdlg(prompt, 'Input Joint Angles', [1 35], {'0', '0', '0', '0'});
            if isempty(answer); return; end

            valsDeg = str2double(answer);
            if any(isnan(valsDeg))
                errordlg('All inputs must be numeric values. Please try again.', 'Input Error');
                return;
            end

            jointAngles = [deg2rad(valsDeg(:)'), 0, 0];
            if ~app.checkJointLimits(p560, jointAngles)
                return;
            end

            endEffectorPose = getTransform(p560, jointAngles, 'link4');
            position = endEffectorPose(1:3, 4);

            if app.isSingular(jointAngles)
                msg = sprintf('Warning: Near-singular configuration!\n\nEnd Effector Position:\nX = %.3f m\nY = %.3f m\nZ = %.3f m', ...
                    position(1), position(2), position(3));
            else
                msg = sprintf('End Effector Position:\nX = %.3f m\nY = %.3f m\nZ = %.3f m', ...
                    position(1), position(2), position(3));
            end

            app.showResult(msg, 4);

            figure('Name', 'Puma 560 — Forward Kinematics', 'NumberTitle', 'off', 'WindowState', 'maximized');
            show(p560, jointAngles);
            title(sprintf('FK Pose (X=%.2f, Y=%.2f, Z=%.2f)', position(1), position(2), position(3)));
        end

        function InverseKinematicsButtonPushed(app, ~)
            p560 = app.getRobotModel();
            prompt = {'Enter X position (m):', 'Enter Y position (m):', 'Enter Z position (m):'};
            answer = inputdlg(prompt, 'Input End-Effector Position', [1 35], {'0.7', '0.2', '0.3'});
            if isempty(answer); return; end

            xyz = str2double(answer);
            if any(isnan(xyz))
                errordlg('All inputs must be numeric values. Please try again.', 'Input Error');
                return;
            end

            x = xyz(1); y = xyz(2); z = xyz(3);
            r = hypot(x, y);
            theta = atan2d(y, x);

            if r < 0.5 || r > 1.0
                errordlg('Position is outside the radial limits of the workspace (0.5 m <= r <= 1.0 m).', 'Workspace Error');
                return;
            elseif theta < -90 || theta > 90
                errordlg('Position is outside the angular limits of the workspace (-90 deg <= theta <= 90 deg).', 'Workspace Error');
                return;
            elseif z < 0
                errordlg('Z-position must be non-negative (z >= 0).', 'Workspace Error');
                return;
            end

            endEffectorPose = trvec2tform([x, y, z]);
            ik = inverseKinematics('RigidBodyTree', p560);
            weights = [0 0 0 1 1 1];
            [jointAngles, solInfo] = ik('link6', endEffectorPose, weights, zeros(1, 6));

            if isempty(jointAngles) || strcmp(solInfo.Status, 'failed')
                errordlg('No valid joint angles found for the desired position.', 'IK Error');
                return;
            end

            msg = sprintf([ ...
                'Joint Angles (deg):\n' ...
                'Theta1 = %.2f\nTheta2 = %.2f\nTheta3 = %.2f\n' ...
                'Theta4 = %.2f\nTheta5 = %.2f\nTheta6 = %.2f'], ...
                rad2deg(jointAngles(1)), rad2deg(jointAngles(2)), rad2deg(jointAngles(3)), ...
                rad2deg(jointAngles(4)), rad2deg(jointAngles(5)), rad2deg(jointAngles(6)));

            app.showResult(msg, 5);

            figure('Name', 'Puma 560 — Inverse Kinematics', 'NumberTitle', 'off', 'WindowState', 'maximized');
            show(p560, jointAngles);
            title(sprintf('IK Solution for (%.2f, %.2f, %.2f)', x, y, z));
        end

        function ExitButtonPushed(app, ~)
            delete(app.UIFigure);
        end

        function AnimationButtonPushed(~, ~)
            dh_table = {
                '1', '0', '0.2', '0.5', '-90';
                '2', '0', '0',   '0.5', '0';
                '3', '0', '0',   '0.5', '0';
                '4', '0', '0.1', '0',   '-90';
                '5', '0', '0',   '0',   '90';
                '6', '0', '0',   '0',   '0'
            };

            dhFig = uifigure('Name', 'DH Parameter Table', 'NumberTitle', 'off', 'Position', [100 100 760 280]);
            uitable(dhFig, 'Data', dh_table, ...
                'ColumnName', {'Joint', 'Theta (deg)', 'Offset d (m)', 'Link Length a (m)', 'Twist alpha (deg)'}, ...
                'Position', [20 20 720 240]);

            numPoints = 60;
            theta = linspace(0, pi, numPoints);
            S = [cos(theta(:)), sin(theta(:)), zeros(numPoints, 1)];

            fig = figure('Name', 'Workspace Semicircle Reach Animation', 'NumberTitle', 'off');
            ax = axes(fig);
            hold(ax, 'on'); grid(ax, 'on'); axis(ax, 'equal');
            xlim(ax, [-1.3 1.3]); ylim(ax, [-0.3 1.3]); zlim(ax, [-0.5 0.5]);
            xlabel(ax, 'X (m)'); ylabel(ax, 'Y (m)'); zlabel(ax, 'Z (m)');
            title(ax, 'Planar Workspace Semicircle Reach (r = 1.0 m)');
            plot3(ax, S(:,1), S(:,2), S(:,3), '--', 'Color', [0.4 0.5 0.6], 'LineWidth', 1.2);
            marker = plot3(ax, S(1,1), S(1,2), S(1,3), 'ro', 'MarkerSize', 10, 'MarkerFaceColor', 'r');

            for idx = 1:numPoints
                if ~isvalid(fig); break; end
                set(marker, 'XData', S(idx,1), 'YData', S(idx,2), 'ZData', S(idx,3));
                drawnow;
                pause(0.03);
            end
        end
    end

    % Component initialization
    methods (Access = private)

        function createComponents(app)
            app.UIFigure = uifigure('Visible', 'off');
            app.UIFigure.Position = [100 100 1280 720];
            app.UIFigure.Name = 'Robotic Manipulator Kinematics Studio';
            app.UIFigure.WindowState = 'maximized';

            app.UIAxes2 = uiaxes(app.UIFigure);
            app.UIAxes2.Toolbar.Visible = 'off';
            app.UIAxes2.XColor = 'none';
            app.UIAxes2.YColor = 'none';
            app.UIAxes2.ZColor = 'none';
            app.UIAxes2.Visible = 'off';
            app.UIAxes2.Position = [1 1 1280 720];

            app.TextArea_2 = uitextarea(app.UIFigure);
            app.TextArea_2.Editable = 'off';
            app.TextArea_2.HorizontalAlignment = 'center';
            app.TextArea_2.WordWrap = 'off';
            app.TextArea_2.FontName = 'Segoe UI';
            app.TextArea_2.FontSize = 40;
            app.TextArea_2.FontWeight = 'bold';
            app.TextArea_2.FontColor = [0.06 0.95 0.95];
            app.TextArea_2.BackgroundColor = [0.12 0.14 0.18];
            app.TextArea_2.Position = [40 600 1200 84];
            app.TextArea_2.Value = {'Robotic Arm Simulation'};

            app.TransformationMatrixPOSEButton = uibutton(app.UIFigure, 'push');
            app.TransformationMatrixPOSEButton.ButtonPushedFcn = createCallbackFcn(app, @TransformationMatrixPOSEButtonPushed, true);
            app.TransformationMatrixPOSEButton.HorizontalAlignment = 'left';
            app.TransformationMatrixPOSEButton.BackgroundColor = [0.07 0.58 0.62];
            app.TransformationMatrixPOSEButton.FontColor = [1 1 1];
            app.TransformationMatrixPOSEButton.FontName = 'Segoe UI';
            app.TransformationMatrixPOSEButton.FontSize = 18;
            app.TransformationMatrixPOSEButton.FontWeight = 'bold';
            app.TransformationMatrixPOSEButton.Position = [440 420 400 58];
            app.TransformationMatrixPOSEButton.Text = '1)  Transformation Matrix (POSE)';

            app.ForwardKinematicsButton = uibutton(app.UIFigure, 'push');
            app.ForwardKinematicsButton.ButtonPushedFcn = createCallbackFcn(app, @ForwardKinematicsButtonPushed, true);
            app.ForwardKinematicsButton.HorizontalAlignment = 'left';
            app.ForwardKinematicsButton.BackgroundColor = [0.07 0.58 0.62];
            app.ForwardKinematicsButton.FontColor = [1 1 1];
            app.ForwardKinematicsButton.FontName = 'Segoe UI';
            app.ForwardKinematicsButton.FontSize = 18;
            app.ForwardKinematicsButton.FontWeight = 'bold';
            app.ForwardKinematicsButton.Position = [440 340 400 58];
            app.ForwardKinematicsButton.Text = '2)  Forward Kinematics';

            app.InverseKinematicsButton = uibutton(app.UIFigure, 'push');
            app.InverseKinematicsButton.ButtonPushedFcn = createCallbackFcn(app, @InverseKinematicsButtonPushed, true);
            app.InverseKinematicsButton.HorizontalAlignment = 'left';
            app.InverseKinematicsButton.BackgroundColor = [0.07 0.58 0.62];
            app.InverseKinematicsButton.FontColor = [1 1 1];
            app.InverseKinematicsButton.FontName = 'Segoe UI';
            app.InverseKinematicsButton.FontSize = 18;
            app.InverseKinematicsButton.FontWeight = 'bold';
            app.InverseKinematicsButton.Position = [440 260 400 58];
            app.InverseKinematicsButton.Text = '3)  Inverse Kinematics';

            app.Animation = uibutton(app.UIFigure, 'push');
            app.Animation.ButtonPushedFcn = createCallbackFcn(app, @AnimationButtonPushed, true);
            app.Animation.HorizontalAlignment = 'left';
            app.Animation.BackgroundColor = [0.07 0.58 0.62];
            app.Animation.FontColor = [1 1 1];
            app.Animation.FontName = 'Segoe UI';
            app.Animation.FontSize = 18;
            app.Animation.FontWeight = 'bold';
            app.Animation.Position = [440 180 400 58];
            app.Animation.Text = '4)  DH Table & Animation';

            app.ExitButton = uibutton(app.UIFigure, 'push');
            app.ExitButton.ButtonPushedFcn = createCallbackFcn(app, @ExitButtonPushed, true);
            app.ExitButton.HorizontalAlignment = 'left';
            app.ExitButton.BackgroundColor = [0.65 0.18 0.22];
            app.ExitButton.FontColor = [1 1 1];
            app.ExitButton.FontName = 'Segoe UI';
            app.ExitButton.FontSize = 18;
            app.ExitButton.FontWeight = 'bold';
            app.ExitButton.Position = [440 100 400 58];
            app.ExitButton.Text = '5)  Exit';

            app.TextArea = uitextarea(app.UIFigure);
            app.TextArea.Editable = 'off';
            app.TextArea.HorizontalAlignment = 'center';
            app.TextArea.FontSize = 22;
            app.TextArea.FontWeight = 'bold';
            app.TextArea.FontColor = [1 1 1];
            app.TextArea.BackgroundColor = [0.09 0.35 0.38];
            app.TextArea.Position = [240 140 800 420];
            app.TextArea.Value = {'Output'};

            app.UIFigure.Visible = 'on';
        end
    end

    methods (Access = public)

        function app = ManipulatorApp
            createComponents(app);
            registerApp(app, app.UIFigure);
            runStartupFcn(app, @startupFcn);
            if nargout == 0
                clear app
            end
        end

        function delete(app)
            delete(app.UIFigure);
        end
    end
end
