001// Copyright (c) Choreo contributors
002
003package choreo.commands3;
004
005import static org.wpilib.util.Alert.Level.MEDIUM;
006
007import choreo.commands3.AutoFactory.AllianceContext;
008import choreo.trajectory.Trajectory;
009import choreo.trajectory.TrajectorySample;
010import choreo.util.ChoreoAlert;
011import java.util.ArrayList;
012import java.util.List;
013import java.util.function.BooleanSupplier;
014import org.wpilib.command3.Trigger;
015import org.wpilib.driverstation.RobotState;
016import org.wpilib.framework.OpModeRobot;
017import org.wpilib.opmode.OpMode;
018
019/**
020 * An autonomous routine, which is an {@link OpMode}.
021 *
022 * <p>Instead of picking a routine from a chooser, register each routine as an autonomous opmode
023 * with {@link AutoFactory#addRoutine(OpModeRobot, String, java.util.function.Consumer)} and select
024 * it on the Driver Station:
025 *
026 * <pre><code>
027 * factory.addRoutine(this, "Two Piece", routine -&gt; {
028 *   var first = routine.trajectory("first");
029 *   var second = routine.trajectory("second");
030 *   routine.active().onTrue(first.resetOdometry().andThen(first.cmd()).withAutomaticName());
031 *   first.chain(second);
032 * });
033 * </code></pre>
034 *
035 * <p>To use the {@code @Autonomous} annotation's description and colors, or to keep a routine in
036 * its own file, subclass instead. {@code OpModeRobot} constructs the class with the robot as its
037 * argument when the opmode is selected:
038 *
039 * <pre><code>
040 * &#64;Autonomous(name = "Two Piece", group = "Choreo")
041 * public class TwoPiece extends AutoRoutine {
042 *   public TwoPiece(Robot robot) {
043 *     super(robot.autoFactory, "Two Piece");
044 *     var first = trajectory("first");
045 *     var second = trajectory("second");
046 *     active().onTrue(first.resetOdometry().andThen(first.cmd()).withAutomaticName());
047 *     first.chain(second);
048 *   }
049 * }
050 * </code></pre>
051 *
052 * <p>The routine is built each time its opmode is selected, never ahead of time. Commands v3 scopes
053 * the triggers and commands created while an opmode is selected to that opmode, so a routine needs
054 * no polling or killing of its own. Everything it bound goes away when the opmode ends. As a
055 * safeguard, the routine's own triggers ({@link #active()}, {@link #idle()}, {@link
056 * #observe(BooleanSupplier)} and everything on {@link AutoTrajectory}) are also gated on the
057 * routine running.
058 *
059 * @see AutoFactory#addRoutine Registering a routine with an AutoFactory
060 */
061public class AutoRoutine implements OpMode {
062  /** The factory that created this routine. Used to create trajectories for this routine. */
063  private final AutoFactory factory;
064
065  /** The name of this routine. */
066  private final String name;
067
068  /** The alliance helper that is used to determine flipping logic. */
069  final AllianceContext allianceCtx;
070
071  /** True from {@link #start()} until {@link #end()}. */
072  private boolean started = false;
073
074  /** The number of trajectories created by this routine that are currently running. */
075  private int runningTrajectories = 0;
076
077  private final Trigger activeTrigger = new Trigger(this::isActive);
078  private final Trigger idleTrigger = activeTrigger.and(() -> runningTrajectories == 0);
079
080  /** The trajectories created by this routine, so their state can be reset when it starts. */
081  private final List<AutoTrajectory> trajectories = new ArrayList<>();
082
083  /**
084   * Creates a new routine with a specific name.
085   *
086   * <p>Subclasses call this to define a routine as its own opmode class. Create the triggers and
087   * bindings in the subclass constructor, and register the class with {@link
088   * org.wpilib.opmode.Autonomous @Autonomous} or {@code OpModeRobot.addOpMode}. The framework then
089   * constructs it when the opmode is selected, which scopes what the constructor creates. Don't
090   * construct a subclass yourself ahead of time, such as in the robot constructor, as it would not
091   * be scoped.
092   *
093   * @param factory The factory used to create this routine's trajectories
094   * @param name The name of the routine
095   * @see AutoFactory#addRoutine Registering a routine without writing a subclass
096   */
097  protected AutoRoutine(AutoFactory factory, String name) {
098    this.factory = factory;
099    this.name = name;
100    this.allianceCtx = factory.allianceCtx;
101  }
102
103  /**
104   * Gets the name of this routine.
105   *
106   * @return The name of this routine.
107   */
108  public String name() {
109    return name;
110  }
111
112  /**
113   * Whether the routine is currently running. Overridable for the factory's internal routine.
114   *
115   * @return True if the opmode has started and the robot is enabled.
116   */
117  boolean isActive() {
118    return started && RobotState.isEnabled();
119  }
120
121  /**
122   * Returns a {@link Trigger} that is true while this routine is running, that is, from when its
123   * opmode starts until it ends or the robot is disabled.
124   *
125   * <p>This is the usual way to start the first command of a routine, such as {@code
126   * routine.active().onTrue(...)}.
127   *
128   * @return A {@link Trigger} that is true while this routine is running.
129   */
130  public Trigger active() {
131    return activeTrigger;
132  }
133
134  /**
135   * Creates a {@link Trigger} from a condition that is only true while this routine is running.
136   *
137   * @param condition The condition represented by the trigger.
138   * @return A {@link Trigger} that mirrors the state of the provided {@code condition} while the
139   *     routine is {@link #active() active}, and is false otherwise.
140   */
141  public Trigger observe(BooleanSupplier condition) {
142    return new Trigger(condition).and(activeTrigger);
143  }
144
145  /**
146   * Creates a trigger that is true when the routine is idle.
147   *
148   * <p>Idle is defined as the routine running with no trajectories made by it running.
149   *
150   * @return A trigger that is true when the routine is idle.
151   */
152  public Trigger idle() {
153    return idleTrigger;
154  }
155
156  /** Registers a trajectory created for this routine. */
157  void register(AutoTrajectory trajectory) {
158    trajectories.add(trajectory);
159  }
160
161  /** Called by this routine's trajectories when they start running. */
162  void trajectoryStarted() {
163    runningTrajectories++;
164  }
165
166  /** Called by this routine's trajectories when they stop running. */
167  void trajectoryEnded() {
168    runningTrajectories = Math.max(0, runningTrajectories - 1);
169  }
170
171  /**
172   * Starts the routine. Called by the framework when the opmode is started.
173   *
174   * <p>If the alliance is required for flipping and is not yet known, the routine does not start.
175   */
176  @Override
177  public void start() {
178    if (!allianceCtx.allianceKnownOrIgnored()) {
179      ChoreoAlert.alert("Alliance not known when starting routine", MEDIUM).set(true);
180      return;
181    }
182    // Clear state left over from a previous run in case this routine object was reused
183    runningTrajectories = 0;
184    trajectories.forEach(AutoTrajectory::reset);
185    started = true;
186  }
187
188  /**
189   * Ends the routine. Called by the framework when the opmode ends.
190   *
191   * <p>Trajectory commands notice the routine is no longer active and finish on their own.
192   */
193  @Override
194  public void end() {
195    started = false;
196  }
197
198  /**
199   * Creates a new {@link AutoTrajectory} to be used in an auto routine.
200   *
201   * @param trajectoryName The name of the trajectory to use.
202   * @return A new {@link AutoTrajectory}.
203   */
204  public AutoTrajectory trajectory(String trajectoryName) {
205    return factory.trajectory(trajectoryName, this, true);
206  }
207
208  /**
209   * Creates a new {@link AutoTrajectory} to be used in an auto routine.
210   *
211   * @param trajectoryName The name of the trajectory to use.
212   * @param splitIndex The index of the split trajectory to use.
213   * @return A new {@link AutoTrajectory}.
214   */
215  public AutoTrajectory trajectory(String trajectoryName, final int splitIndex) {
216    return factory.trajectory(trajectoryName, splitIndex, this, true);
217  }
218
219  /**
220   * Creates a new {@link AutoTrajectory} to be used in an auto routine.
221   *
222   * @param <SampleType> The type of the trajectory samples.
223   * @param trajectory The trajectory to use.
224   * @return A new {@link AutoTrajectory}.
225   */
226  public <SampleType extends TrajectorySample<SampleType>> AutoTrajectory trajectory(
227      Trajectory<SampleType> trajectory) {
228    return factory.trajectory(trajectory, this, true);
229  }
230
231  /**
232   * Creates a trigger that produces a rising edge when any of the trajectories are finished.
233   *
234   * @param trajectory The first trajectory to watch.
235   * @param trajectories The other trajectories to watch
236   * @return a trigger that determines if any of the trajectories are finished
237   * @see #anyDoneDelayed(double, AutoTrajectory, AutoTrajectory...) A version of this method that
238   *     takes a delay in seconds before the trigger is true.
239   */
240  public Trigger anyDone(AutoTrajectory trajectory, AutoTrajectory... trajectories) {
241    return anyDoneDelayed(0, trajectory, trajectories);
242  }
243
244  /**
245   * Creates a trigger that produces a rising edge when any of the trajectories are finished.
246   *
247   * @param secondsToDelay The delay after completion, in seconds.
248   * @param trajectory The first trajectory to watch.
249   * @param trajectories The other trajectories to watch
250   * @return a trigger that goes true for one cycle whenever any of the trajectories finishes,
251   *     delayed by the given number of seconds.
252   * @see AutoTrajectory#doneDelayed(double)
253   */
254  public Trigger anyDoneDelayed(
255      double secondsToDelay, AutoTrajectory trajectory, AutoTrajectory... trajectories) {
256    var trigger = trajectory.doneDelayed(secondsToDelay);
257    for (int i = 0; i < trajectories.length; i++) {
258      trigger = trigger.or(trajectories[i].doneDelayed(secondsToDelay));
259    }
260    return trigger.and(this.active());
261  }
262
263  /**
264   * Creates a trigger that returns true when any of the trajectories given are active.
265   *
266   * @param trajectory The first trajectory to watch.
267   * @param trajectories The other trajectories to watch
268   * @return a trigger that determines if any of the trajectories are active
269   */
270  public Trigger anyActive(AutoTrajectory trajectory, AutoTrajectory... trajectories) {
271    var trigger = trajectory.active();
272    for (int i = 0; i < trajectories.length; i++) {
273      trigger = trigger.or(trajectories[i].active());
274    }
275    return trigger.and(this.active());
276  }
277
278  /**
279   * Creates a trigger that returns true when all of the trajectories given are inactive.
280   *
281   * <p>This trigger will only return true if the routine is active.
282   *
283   * @param trajectory The first trajectory to watch.
284   * @param trajectories The other trajectories to watch
285   * @return a trigger that determines if all of the trajectories are inactive
286   */
287  public Trigger allInactive(AutoTrajectory trajectory, AutoTrajectory... trajectories) {
288    var trigger = trajectory.inactive();
289    for (int i = 0; i < trajectories.length; i++) {
290      trigger = trigger.and(trajectories[i].inactive());
291    }
292    return trigger.and(this.active());
293  }
294}