001/*
002 * Copyright (C) Cross The Road Electronics.  All rights reserved.
003 * License information can be found in CTRE_LICENSE.txt
004 * For support and suggestions contact support@ctr-electronics.com or file
005 * an issue tracker at https://github.com/CrossTheRoadElec/Phoenix-Releases
006 */
007package com.ctre.phoenix6.swerve.utility;
008
009import edu.wpi.first.math.geometry.Pose2d;
010import edu.wpi.first.math.geometry.Rotation2d;
011import edu.wpi.first.math.kinematics.ChassisSpeeds;
012import edu.wpi.first.math.trajectory.TrapezoidProfile;
013
014/**
015 * A linear path for a holonomic drivetrain (i.e. swerve or mechanum).
016 * This generates profiled setpoints for the robot along a straight line
017 * based on trapezoidal velocity constraints (using {@link TrapezoidProfile}).
018 * <p>
019 * Initialization:
020 * <pre><code>
021 * final LinearPath path = new LinearPath(
022 *     new TrapezoidProfile.Constraints(kMaxV, kMaxA),
023 *     new TrapezoidProfile.Constraints(kMaxOmega, kMaxAlpha)
024 * );
025 * LinearPath.State current = new LinearPath.State(
026 *     initialPose, initialFieldSpeeds
027 * );
028 * </code></pre>
029 * <p>
030 * Run on update:
031 * <pre><code>
032 * current = path.calculate(timeSincePreviousUpdate, current, targetPose);
033 * </code></pre>
034 */
035public class LinearPath {
036    /** Path state. */
037    public static class State {
038        /** The pose at this state. */
039        public Pose2d pose;
040        /** The field-centric speeds at this state. */
041        public ChassisSpeeds speeds;
042
043        /** Constructs a new path state with zero'd pose and speeds. */
044        public State() {
045            this(Pose2d.kZero, new ChassisSpeeds());
046        }
047        /**
048         * Constructs a new path state.
049         *
050         * @param pose The pose at this state
051         * @param speeds THe field-centric speeds at this state
052         */
053        public State(Pose2d pose, ChassisSpeeds speeds) {
054            this.pose = pose;
055            this.speeds = speeds;
056        }
057    }
058
059    private final TrapezoidProfile linearProfile;
060    private final TrapezoidProfile angularProfile;
061
062    private Pose2d initialPose = Pose2d.kZero;
063    private Rotation2d heading = Rotation2d.kZero;
064
065    private TrapezoidProfile.State linearGoal = new TrapezoidProfile.State();
066    private TrapezoidProfile.State linearStart = new TrapezoidProfile.State();
067
068    private TrapezoidProfile.State angularGoal = new TrapezoidProfile.State();
069    private TrapezoidProfile.State angularStart = new TrapezoidProfile.State();
070
071    /**
072     * Constructs a linear path.
073     *
074     * @param linear The constraints on the profile linear motion
075     * @param angular The constraints on the profile angular motion
076     */
077    public LinearPath(TrapezoidProfile.Constraints linear, TrapezoidProfile.Constraints angular) {
078        this.linearProfile = new TrapezoidProfile(linear);
079        this.angularProfile = new TrapezoidProfile(angular);
080    }
081
082    /**
083     * Calculates the component of the velocity in the direction of travel.
084     *
085     * @param speeds The field-centric chassis speeds
086     * @param heading The heading of the direction of travel
087     * @return Component of velocity in the direction of the heading
088     */
089    private static double calculateVelocityAtHeading(ChassisSpeeds speeds, Rotation2d heading) {
090        // vel = <vx, vy> ⋅ <cos(heading), sin(heading)>
091        // vel = vx * cos(heading) + vy * sin(heading)
092        return speeds.vxMetersPerSecond * heading.getCos() + speeds.vyMetersPerSecond * heading.getSin();
093    }
094
095    /**
096     * Sets the current and goal states of the linear path.
097     *
098     * @param current The current state
099     * @param goal The desired pose when the path is complete
100     */
101    private void setState(State current, Pose2d goal) {
102        this.initialPose = current.pose;
103
104        {
105            // pull out the translation from our initial pose to the target
106            final var translation = goal.getTranslation().minus(this.initialPose.getTranslation());
107            // pull out distance and heading to the target
108            final var distance = translation.getNorm();
109            if (distance > 1e-6) {
110                this.heading = translation.getAngle();
111            } else {
112                this.heading = Rotation2d.kZero;
113            }
114
115            this.linearGoal = new TrapezoidProfile.State(distance, 0);
116        }
117
118        {
119            // start at current velocity in the direction of travel
120            final var vel = calculateVelocityAtHeading(current.speeds, this.heading);
121            this.linearStart = new TrapezoidProfile.State(0, vel);
122        }
123
124        this.angularStart = new TrapezoidProfile.State(
125            current.pose.getRotation().getRadians(),
126            current.speeds.omegaRadiansPerSecond
127        );
128        // wrap the angular goal so we take the shortest path
129        this.angularGoal = new TrapezoidProfile.State(
130            current.pose.getRotation().getRadians() +
131                goal.getRotation().minus(current.pose.getRotation()).getRadians(),
132            0
133        );
134    }
135
136    /**
137     * Calculates the pose and speeds of the path at a time t where
138     * the current state is at t = 0.
139     *
140     * @param t How long to advance from the current state to the desired state
141     * @return The pose and speeds of the profile at time t
142     */
143    private State calculate(double t) {
144        // calculate our new distance and velocity in the desired direction of travel
145        final var linearState = this.linearProfile.calculate(t, this.linearStart, this.linearGoal);
146        // calculate our new heading and rotational rate
147        final var angularState = this.angularProfile.calculate(t, this.angularStart, this.angularGoal);
148
149        // x is m_state * cos(heading), y is m_state * sin(heading)
150        final var pose = new Pose2d(
151            this.initialPose.getX() + linearState.position * this.heading.getCos(),
152            this.initialPose.getY() + linearState.position * this.heading.getSin(),
153            Rotation2d.fromRadians(angularState.position)
154        );
155        final var speeds = new ChassisSpeeds(
156            linearState.velocity * this.heading.getCos(),
157            linearState.velocity * this.heading.getSin(),
158            angularState.velocity
159        );
160        return new State(pose, speeds);
161    }
162
163    /**
164     * Calculates the pose and speeds of the path at a time t where
165     * the current state is at t = 0.
166     *
167     * @param t How long to advance from the current state to the desired state
168     * @param current The current state
169     * @param goal The desired pose when the path is complete
170     * @return The pose and speeds of the profile at time t
171     */
172    public final State calculate(double t, State current, Pose2d goal) {
173        setState(current, goal);
174        return calculate(t);
175    }
176
177    /**
178     * Returns the total time the profile takes to reach the goal.
179     *
180     * @return The total time the profile takes to reach the goal
181     */
182    public final double totalTime() {
183        return Math.max(
184            this.linearProfile.totalTime(),
185            this.angularProfile.totalTime()
186        );
187    }
188
189    /**
190     * Returns true if the profile has reached the goal.
191     * <p>
192     * The profile has reached the goal if the time since the profile
193     * started has exceeded the profile's total time.
194     *
195     * @param t The time since the beginning of the profile
196     * @return true if the profile has reached the goal
197     */
198    public final boolean isFinished(double t) {
199        return t >= totalTime();
200    }
201}