001// Copyright (c) Choreo contributors 002 003package choreo.commands3; 004 005import static org.wpilib.units.Units.Seconds; 006import static org.wpilib.util.ErrorMessages.requireNonNullParam; 007 008import choreo.Choreo.TrajectoryCache; 009import choreo.Choreo.TrajectoryLogger; 010import choreo.trajectory.SwerveSample; 011import choreo.trajectory.Trajectory; 012import choreo.trajectory.TrajectorySample; 013import choreo.util.ChoreoAllianceFlipUtil; 014import java.util.HashMap; 015import java.util.List; 016import java.util.Optional; 017import java.util.function.Consumer; 018import java.util.function.Function; 019import java.util.function.Supplier; 020import org.wpilib.command3.Command; 021import org.wpilib.command3.Mechanism; 022import org.wpilib.driverstation.Alliance; 023import org.wpilib.driverstation.MatchState; 024import org.wpilib.framework.OpModeRobot; 025import org.wpilib.framework.RobotBase; 026import org.wpilib.hardware.hal.HAL; 027import org.wpilib.hardware.hal.RobotMode; 028import org.wpilib.math.geometry.Pose2d; 029 030/** 031 * A factory used to create {@link AutoRoutine}s and {@link AutoTrajectory}s for Commands v3. 032 * 033 * @see <a href="https://choreo.autos/choreolib/auto-routines">Auto Routine Docs</a> 034 */ 035public class AutoFactory { 036 static record AllianceContext( 037 boolean useAllianceFlipping, Supplier<Optional<Alliance>> allianceGetter) { 038 boolean allianceKnownOrIgnored() { 039 return allianceGetter.get().isPresent() || !useAllianceFlipping; 040 } 041 042 boolean doFlip() { 043 return useAllianceFlipping 044 && allianceGetter 045 .get() 046 .orElseThrow( 047 () -> new RuntimeException("Flip check was called with an unknown alliance")) 048 .equals(Alliance.RED); 049 } 050 051 Optional<Alliance> alliance() { 052 return allianceGetter.get(); 053 } 054 055 Supplier<Optional<Pose2d>> getFlippedPose(Optional<Pose2d> bluePose) { 056 return ChoreoAllianceFlipUtil.optionalFlippedPose2d( 057 bluePose, this::alliance, useAllianceFlipping); 058 } 059 } 060 061 /** A class used to bind commands to events in all trajectories created by this factory. */ 062 static class AutoBindings { 063 private HashMap<String, Command> bindings = new HashMap<>(); 064 065 /** Default constructor. */ 066 public AutoBindings() {} 067 068 /** 069 * Binds a command to an event in all trajectories created by the factory using this bindings. 070 * 071 * @param name The name of the event to bind the command to. 072 * @param cmd The command to bind to the event. 073 * @return The bindings object for chaining. 074 */ 075 public AutoBindings bind(String name, Command cmd) { 076 bindings.put(name, cmd); 077 return this; 078 } 079 080 /** 081 * Gets the bindings map. 082 * 083 * @return The bindings map. 084 */ 085 HashMap<String, Command> getBindings() { 086 return bindings; 087 } 088 } 089 090 private final TrajectoryCache trajectoryCache = new TrajectoryCache(); 091 private final Supplier<Pose2d> poseSupplier; 092 private final Consumer<Pose2d> resetOdometry; 093 private final Consumer<? extends TrajectorySample<?>> controller; 094 final AllianceContext allianceCtx; 095 private final Mechanism driveMechanism; 096 private final AutoBindings bindings = new AutoBindings(); 097 private final TrajectoryLogger<? extends TrajectorySample<?>> trajectoryLogger; 098 private final AutoRoutine voidRoutine; 099 100 /** 101 * Create a factory that can be used to create {@link AutoRoutine} and {@link AutoTrajectory}. 102 * 103 * @param <SampleType> The type of samples in the trajectory. 104 * @param poseSupplier A function that returns the current field-relative {@link Pose2d} of the 105 * robot. 106 * @param resetOdometry A function that receives a field-relative {@link Pose2d} to reset the 107 * robot's odometry to. 108 * @param controller A function that receives the current {@link SampleType} and controls the 109 * robot. 110 * @param useAllianceFlipping If this is true, when on the red alliance, the path will be mirrored 111 * to the opposite side, while keeping the same coordinate system origin. 112 * @param driveMechanism The drive {@link Mechanism} to require for {@link AutoTrajectory} {@link 113 * Command}s. 114 * @param trajectoryLogger A {@link TrajectoryLogger} to log {@link Trajectory} as they start and 115 * finish. 116 */ 117 public <SampleType extends TrajectorySample<SampleType>> AutoFactory( 118 Supplier<Pose2d> poseSupplier, 119 Consumer<Pose2d> resetOdometry, 120 Consumer<SampleType> controller, 121 boolean useAllianceFlipping, 122 Mechanism driveMechanism, 123 TrajectoryLogger<SampleType> trajectoryLogger) { 124 requireNonNullParam(poseSupplier, "poseSupplier", "AutoFactory"); 125 requireNonNullParam(resetOdometry, "resetOdometry", "AutoFactory"); 126 requireNonNullParam(controller, "controller", "AutoFactory"); 127 requireNonNullParam(driveMechanism, "driveMechanism", "AutoFactory"); 128 requireNonNullParam(useAllianceFlipping, "useAllianceFlipping", "AutoFactory"); 129 130 this.poseSupplier = poseSupplier; 131 this.resetOdometry = resetOdometry; 132 this.controller = controller; 133 this.driveMechanism = driveMechanism; 134 this.allianceCtx = new AllianceContext(useAllianceFlipping, MatchState::getAlliance); 135 this.trajectoryLogger = trajectoryLogger; 136 HAL.reportUsage("ChoreoTrigger", 1, "AutoFactory"); 137 138 voidRoutine = 139 new AutoRoutine(this, "VOID-ROUTINE") { 140 @Override 141 boolean isActive() { 142 return true; 143 } 144 145 @Override 146 void register(AutoTrajectory trajectory) { 147 // Never started or reset, and shared by every trajectoryCmd, so don't hold on to them. 148 } 149 }; 150 } 151 152 /** 153 * Create a factory that can be used to create {@link AutoRoutine} and {@link AutoTrajectory}. 154 * 155 * @param <ST> {@link choreo.trajectory.DifferentialSample} or {@link 156 * choreo.trajectory.SwerveSample} 157 * @param poseSupplier A function that returns the current field-relative {@link Pose2d} of the 158 * robot. 159 * @param resetOdometry A function that receives a field-relative {@link Pose2d} to reset the 160 * robot's odometry to. 161 * @param controller A function that receives the current {@link ST} and controls the robot. 162 * @param useAllianceFlipping If this returns true, when on the red alliance, the path will be 163 * mirrored to the opposite side, while keeping the same coordinate system origin. 164 * @param driveMechanism The drive {@link Mechanism} to require for {@link AutoTrajectory} {@link 165 * Command}s. 166 */ 167 public <ST extends TrajectorySample<ST>> AutoFactory( 168 Supplier<Pose2d> poseSupplier, 169 Consumer<Pose2d> resetOdometry, 170 Consumer<ST> controller, 171 boolean useAllianceFlipping, 172 Mechanism driveMechanism) { 173 this( 174 poseSupplier, 175 resetOdometry, 176 controller, 177 useAllianceFlipping, 178 driveMechanism, 179 (sample, isStart) -> {}); 180 } 181 182 /** 183 * Registers an autonomous routine as an opmode named {@code name}, shown on the Driver Station. 184 * 185 * <p>{@code body} does not run now. It runs each time the opmode is selected on the Driver 186 * Station, on a fresh {@link AutoRoutine}, which is what scopes the triggers and commands it 187 * creates to that opmode. The routine object is deliberately not returned, so it can't be built 188 * ahead of time (such as in the robot constructor) where it would not be scoped. 189 * 190 * <p>This does not publish the opmode to the Driver Station. Call {@link 191 * OpModeRobot#publishOpModes()} after registering all of your opmodes, such as at the end of the 192 * robot constructor, or the routine will not appear in the Driver Station's opmode list. 193 * 194 * <pre><code> 195 * factory.addRoutine(this, "Two Piece", routine -> { 196 * var first = routine.trajectory("first"); 197 * var second = routine.trajectory("second"); 198 * routine.active().onTrue(first.resetOdometry().andThen(first.cmd()).withAutomaticName()); 199 * first.chain(second); 200 * }); 201 * </code></pre> 202 * 203 * @param robot The robot to register the opmode with. 204 * @param name The name of the opmode, as shown on the Driver Station. Must be unique among 205 * autonomous opmodes. 206 * @param body A function that receives the new routine and sets up its triggers. 207 */ 208 public void addRoutine(OpModeRobot robot, String name, Consumer<AutoRoutine> body) { 209 addRoutine(robot, name, "", body); 210 } 211 212 /** 213 * Registers an autonomous routine as an opmode named {@code name} in the given group, shown on 214 * the Driver Station. 215 * 216 * @param robot The robot to register the opmode with. 217 * @param name The name of the opmode, as shown on the Driver Station. Must be unique among 218 * autonomous opmodes. 219 * @param group The group the opmode is listed under on the Driver Station. 220 * @param body A function that receives the new routine and sets up its triggers. 221 * @see #addRoutine(OpModeRobot, String, Consumer) 222 */ 223 public void addRoutine(OpModeRobot robot, String name, String group, Consumer<AutoRoutine> body) { 224 requireNonNullParam(robot, "robot", "addRoutine"); 225 requireNonNullParam(name, "name", "addRoutine"); 226 requireNonNullParam(group, "group", "addRoutine"); 227 requireNonNullParam(body, "body", "addRoutine"); 228 robot.addOpMode(RobotMode.AUTONOMOUS, name, group, () -> buildRoutine(name, body)); 229 } 230 231 /** Builds a routine. Runs when its opmode is selected, so the routine's triggers are scoped. */ 232 private AutoRoutine buildRoutine(String name, Consumer<AutoRoutine> body) { 233 // Clear cache in simulation to allow a form of "hot-reloading" trajectories 234 if (RobotBase.isSimulation()) { 235 trajectoryCache.clear(); 236 } 237 238 var routine = new AutoRoutine(this, name); 239 body.accept(routine); 240 return routine; 241 } 242 243 /** 244 * A package protected method to create a new {@link AutoTrajectory} to be used in an {@link 245 * AutoRoutine}. 246 * 247 * @see AutoRoutine#trajectory(String) 248 */ 249 AutoTrajectory trajectory(String trajectoryName, AutoRoutine routine, boolean useBindings) { 250 Optional<? extends Trajectory<?>> optTrajectory = 251 trajectoryCache.loadTrajectory(trajectoryName); 252 Trajectory<?> trajectory; 253 if (optTrajectory.isPresent()) { 254 trajectory = optTrajectory.get(); 255 } else { 256 trajectory = new Trajectory<SwerveSample>(trajectoryName, List.of(), List.of(), List.of()); 257 } 258 return trajectory(trajectory, routine, useBindings); 259 } 260 261 /** 262 * A package protected method to create a new {@link AutoTrajectory} to be used in an {@link 263 * AutoRoutine}. 264 * 265 * @see AutoRoutine#trajectory(String, int) 266 */ 267 AutoTrajectory trajectory( 268 String trajectoryName, final int splitIndex, AutoRoutine routine, boolean useBindings) { 269 Optional<? extends Trajectory<?>> optTrajectory = 270 trajectoryCache.loadTrajectory(trajectoryName, splitIndex); 271 Trajectory<?> trajectory; 272 if (optTrajectory.isPresent()) { 273 trajectory = optTrajectory.get(); 274 } else { 275 trajectory = new Trajectory<SwerveSample>(trajectoryName, List.of(), List.of(), List.of()); 276 } 277 return trajectory(trajectory, routine, useBindings); 278 } 279 280 /** 281 * A package protected method to create a new {@link AutoTrajectory} to be used in an {@link 282 * AutoRoutine}. 283 * 284 * @see AutoRoutine#trajectory(Trajectory) 285 */ 286 <ST extends TrajectorySample<ST>> AutoTrajectory trajectory( 287 Trajectory<ST> trajectory, AutoRoutine routine, boolean useBindings) { 288 return trajectory(trajectory, routine, useBindings, Function.identity()); 289 } 290 291 /** 292 * A package protected method to create a new {@link AutoTrajectory} to be used in an {@link 293 * AutoRoutine}. 294 * 295 * @see AutoRoutine#trajectory(Trajectory) 296 */ 297 @SuppressWarnings("unchecked") 298 <ST extends TrajectorySample<ST>> AutoTrajectory trajectory( 299 Trajectory<ST> trajectory, 300 AutoRoutine routine, 301 boolean useBindings, 302 Function<Trajectory<ST>, Trajectory<ST>> trajectoryTransform) { 303 // type solidify everything 304 final Trajectory<ST> solidTrajectory = trajectoryTransform.apply(trajectory); 305 final Consumer<ST> solidController = (Consumer<ST>) this.controller; 306 return new AutoTrajectory( 307 trajectory.name(), 308 solidTrajectory, 309 poseSupplier, 310 resetOdometry, 311 solidController, 312 allianceCtx, 313 (TrajectoryLogger<ST>) trajectoryLogger, 314 driveMechanism, 315 routine, 316 useBindings ? bindings : new AutoBindings()); 317 } 318 319 /** 320 * Warms up Choreo so there is no delay at the start of auto. Schedule this command in your Robot 321 * constructor: 322 * 323 * <pre><code> 324 * Scheduler.getDefault().schedule(autoFactory.warmupCmd()); 325 * </code></pre> 326 * 327 * <p>The command requires no mechanisms, so it can run while the robot is disabled. 328 * 329 * @return A command that warms up Choreo's autonomous functionality. 330 */ 331 public Command warmupCmd() { 332 var autoTraj = trajectory("", voidRoutine, false); 333 autoTraj.suppressWarnings(); 334 return autoTraj.warmupCmd().withTimeout(Seconds.of(0.5)); 335 } 336 337 /** 338 * Creates a new {@link AutoTrajectory} command to be used in an auto routine. 339 * 340 * <p>Don't mix {@link #trajectoryCmd} and {@link AutoRoutine#trajectory} in the same auto 341 * routine. {@link #trajectoryCmd} is an escape hatch for teams that don't need the trigger API, 342 * and it does not run bindings added with {@link #bind}. 343 * 344 * @param trajectoryName The name of the trajectory to use. 345 * @return A new {@link AutoTrajectory}. 346 */ 347 public Command trajectoryCmd(String trajectoryName) { 348 return trajectory(trajectoryName, voidRoutine, false).cmd(); 349 } 350 351 /** 352 * Creates a new {@link AutoTrajectory} command to be used in an auto routine. 353 * 354 * <p>See {@link #trajectoryCmd(String)} for caveats. 355 * 356 * @param trajectoryName The name of the trajectory to use. 357 * @param splitIndex The index of the split trajectory to use. 358 * @param transform A function that takes in the loaded trajectory and applies a transformation to 359 * it, such as left-to-right mirroring. 360 * @return A new {@link AutoTrajectory}. 361 */ 362 public Command trajectoryCmd( 363 String trajectoryName, 364 final int splitIndex, 365 Function<AutoTrajectory, AutoTrajectory> transform) { 366 return transform.apply(trajectory(trajectoryName, splitIndex, voidRoutine, false)).cmd(); 367 } 368 369 /** 370 * Creates a new {@link AutoTrajectory} command to be used in an auto routine. 371 * 372 * <p>See {@link #trajectoryCmd(String)} for caveats. 373 * 374 * @param trajectoryName The name of the trajectory to use. 375 * @param transform A function that takes in the loaded trajectory and applies a transformation to 376 * it, such as left-to-right mirroring. 377 * @return A new {@link AutoTrajectory}. 378 */ 379 public Command trajectoryCmd( 380 String trajectoryName, Function<AutoTrajectory, AutoTrajectory> transform) { 381 return transform.apply(trajectory(trajectoryName, voidRoutine, false)).cmd(); 382 } 383 384 /** 385 * Creates a new {@link AutoTrajectory} command to be used in an auto routine. 386 * 387 * <p>See {@link #trajectoryCmd(String)} for caveats. 388 * 389 * @param trajectoryName The name of the trajectory to use. 390 * @param splitIndex The index of the split trajectory to use. 391 * @return A new {@link AutoTrajectory}. 392 */ 393 public Command trajectoryCmd(String trajectoryName, final int splitIndex) { 394 return trajectory(trajectoryName, splitIndex, voidRoutine, false).cmd(); 395 } 396 397 /** 398 * Creates a new {@link AutoTrajectory} command to be used in an auto routine. 399 * 400 * <p>See {@link #trajectoryCmd(String)} for caveats. 401 * 402 * @param <ST> {@link choreo.trajectory.DifferentialSample} or {@link 403 * choreo.trajectory.SwerveSample} 404 * @param trajectory The trajectory to use. 405 * @return A new {@link AutoTrajectory}. 406 */ 407 public <ST extends TrajectorySample<ST>> Command trajectoryCmd(Trajectory<ST> trajectory) { 408 return trajectory(trajectory, voidRoutine, false).cmd(); 409 } 410 411 /** 412 * Creates a command that resets the robot's odometry to the start of a trajectory. 413 * 414 * @param trajectoryName The name of the trajectory to use. 415 * @return A command that resets the robot's odometry. 416 */ 417 public Command resetOdometry(String trajectoryName) { 418 return trajectory(trajectoryName, voidRoutine, false).resetOdometry(); 419 } 420 421 /** 422 * Creates a command that resets the robot's odometry to the start of a trajectory. 423 * 424 * @param trajectoryName The name of the trajectory to use. 425 * @param splitIndex The index of the split trajectory to use. 426 * @return A command that resets the robot's odometry. 427 */ 428 public Command resetOdometry(String trajectoryName, final int splitIndex) { 429 return trajectory(trajectoryName, splitIndex, voidRoutine, false).resetOdometry(); 430 } 431 432 /** 433 * Creates a command that resets the robot's odometry to the start of a trajectory. 434 * 435 * @param <ST> {@link choreo.trajectory.DifferentialSample} or {@link 436 * choreo.trajectory.SwerveSample} 437 * @param trajectory The trajectory to use. 438 * @return A command that resets the robot's odometry. 439 */ 440 public <ST extends TrajectorySample<ST>> Command resetOdometry(Trajectory<ST> trajectory) { 441 return trajectory(trajectory, voidRoutine, false).resetOdometry(); 442 } 443 444 /** 445 * Creates a command that resets the robot's odometry to the supplied pose 446 * 447 * @param pose A function that is called when the command is run. It returns an <code> 448 * Optional<Pose2d></code> of the robot's desired odometry position. 449 * @return A command that resets the robot's odometry to the supplied pose, or does nothing if the 450 * supplied Optional is empty. 451 */ 452 public Command resetOdometry(Supplier<Optional<Pose2d>> pose) { 453 return Command.requiring(driveMechanism) 454 .executing(coroutine -> pose.get().ifPresent(resetOdometry)) 455 .named("Choreo_ResetOdometry"); 456 } 457 458 /** 459 * Creates a command that resets the robot's odometry to the given pose 460 * 461 * @param pose An <code>Optional<Pose2d></code> of the robot's desired odometry position. 462 * @param doFlipForAlliance True if the given pose still needs to be flipped according to the 463 * alliance (usually true). False if it is an absolute field position. 464 * @return A command that resets the robot's odometry to the given pose (flipped as directed), or 465 * does nothing if the supplied Optional is empty. 466 */ 467 public Command resetOdometry(Optional<Pose2d> pose, boolean doFlipForAlliance) { 468 if (pose.isEmpty()) { 469 // equivalent to a no-op that still requires the drive mechanism. 470 return Command.requiring(driveMechanism) 471 .executing(coroutine -> {}) 472 .named("Choreo_ResetOdometry"); 473 } 474 Supplier<Optional<Pose2d>> supplier = 475 doFlipForAlliance ? allianceCtx.getFlippedPose(pose) : (() -> pose); 476 return resetOdometry(supplier); 477 } 478 479 /** 480 * Binds a command to an event in all trajectories created after this point. 481 * 482 * @param name The name of the trajectory to bind the command to. 483 * @param cmd The command to bind to the trajectory. 484 * @return The AutoFactory the method was called from. 485 */ 486 public AutoFactory bind(String name, Command cmd) { 487 bindings.bind(name, cmd); 488 return this; 489 } 490 491 /** 492 * The {@link AutoFactory} caches trajectories with a {@link TrajectoryCache} to avoid reloading 493 * the same trajectory multiple times. 494 * 495 * @return The trajectory cache. 496 */ 497 public TrajectoryCache cache() { 498 return trajectoryCache; 499 } 500}