001// Copyright (c) Choreo contributors 002 003package choreo.commands3; 004 005import static choreo.util.ChoreoAlert.allianceNotReady; 006 007import choreo.Choreo.TrajectoryLogger; 008import choreo.commands3.AutoFactory.AllianceContext; 009import choreo.commands3.AutoFactory.AutoBindings; 010import choreo.trajectory.DifferentialSample; 011import choreo.trajectory.SwerveSample; 012import choreo.trajectory.Trajectory; 013import choreo.trajectory.TrajectorySample; 014import choreo.util.ChoreoAlert; 015import choreo.util.ChoreoAlert.MultiAlert; 016import choreo.util.ChoreoAllianceFlipUtil; 017import java.util.Optional; 018import java.util.function.BooleanSupplier; 019import java.util.function.Consumer; 020import java.util.function.Supplier; 021import org.wpilib.command3.Command; 022import org.wpilib.command3.Coroutine; 023import org.wpilib.command3.Mechanism; 024import org.wpilib.command3.Trigger; 025import org.wpilib.math.geometry.Pose2d; 026import org.wpilib.math.geometry.Rotation2d; 027import org.wpilib.math.geometry.Translation2d; 028import org.wpilib.system.Timer; 029import org.wpilib.util.Alert.Level; 030 031/** 032 * A class that represents a trajectory that can be used in an autonomous routine and have triggers 033 * based off of it. 034 */ 035public class AutoTrajectory { 036 // For any devs looking through this class wondering 037 // about all the type casting and `?` for generics it's intentional. 038 // My goal was to make the sample type minimally leak into user code 039 // so you don't have to retype the sample type everywhere in your auto 040 // code. This also makes the places with generics exposed to users few 041 // and far between. This helps with more novice users 042 043 private static final MultiAlert triggerTimeNegative = 044 ChoreoAlert.multiAlert(causes -> "Trigger time cannot be negative for " + causes, Level.HIGH); 045 private static final MultiAlert triggerTimeAboveMax = 046 ChoreoAlert.multiAlert( 047 causes -> "Trigger time cannot be greater than total trajectory time for " + causes + ".", 048 Level.HIGH); 049 private static final MultiAlert eventNotFound = 050 ChoreoAlert.multiAlert(causes -> "Event Markers " + causes + " not found.", Level.HIGH); 051 private static final MultiAlert noSamples = 052 ChoreoAlert.multiAlert(causes -> "Trajectories " + causes + " have no samples.", Level.HIGH); 053 private static final MultiAlert noInitialPose = 054 ChoreoAlert.multiAlert( 055 causes -> "Unable to get initial pose for trajectories " + causes + ".", Level.HIGH); 056 057 final String name; 058 final Trajectory<? extends TrajectorySample<?>> trajectory; 059 final TrajectoryLogger<? extends TrajectorySample<?>> trajectoryLogger; 060 final Supplier<Pose2d> poseSupplier; 061 final Consumer<Pose2d> resetOdometry; 062 final Consumer<? extends TrajectorySample<?>> controller; 063 final AllianceContext allianceCtx; 064 final Mechanism driveMechanism; 065 final AutoRoutine routine; 066 final AutoBindings bindings; 067 068 private final Timer activeTimer = new Timer(); 069 private final Timer inactiveTimer = new Timer(); 070 071 /** If this trajectory is currently running. */ 072 private boolean isActive = false; 073 074 /** If the trajectory ran to completion. */ 075 private boolean isCompleted = false; 076 077 /** Set by the command body when it finishes without being cancelled. */ 078 private boolean finishedNaturally = false; 079 080 /** Whether to suppress warnings for this trajectory. */ 081 private boolean warnUser = true; 082 083 /** 084 * Constructs an AutoTrajectory. 085 * 086 * @param name The trajectory name. 087 * @param trajectory The trajectory samples. 088 * @param poseSupplier The pose supplier. 089 * @param resetOdometry The odometry reset function. 090 * @param controller The controller function. 091 * @param allianceCtx The alliance context. 092 * @param trajectoryLogger Optional trajectory logger. 093 * @param driveMechanism Drive mechanism. 094 * @param routine The routine this trajectory belongs to. 095 * @param bindings {@link AutoFactory} 096 */ 097 <SampleType extends TrajectorySample<SampleType>> AutoTrajectory( 098 String name, 099 Trajectory<SampleType> trajectory, 100 Supplier<Pose2d> poseSupplier, 101 Consumer<Pose2d> resetOdometry, 102 Consumer<SampleType> controller, 103 AllianceContext allianceCtx, 104 TrajectoryLogger<SampleType> trajectoryLogger, 105 Mechanism driveMechanism, 106 AutoRoutine routine, 107 AutoBindings bindings) { 108 this.name = name; 109 this.trajectory = trajectory; 110 this.poseSupplier = poseSupplier; 111 this.resetOdometry = resetOdometry; 112 this.controller = controller; 113 this.allianceCtx = allianceCtx; 114 this.driveMechanism = driveMechanism; 115 this.routine = routine; 116 this.trajectoryLogger = trajectoryLogger; 117 this.bindings = bindings; 118 routine.register(this); 119 120 bindings.getBindings().forEach((key, value) -> active().and(atTime(key)).onTrue(value)); 121 } 122 123 @SuppressWarnings("unchecked") 124 private void logTrajectory(boolean starting) { 125 var sampleOpt = trajectory.getInitialSample(false); 126 if (sampleOpt.isEmpty()) { 127 return; 128 } 129 var sample = sampleOpt.get(); 130 if (sample instanceof SwerveSample) { 131 TrajectoryLogger<SwerveSample> swerveLogger = 132 (TrajectoryLogger<SwerveSample>) trajectoryLogger; 133 Trajectory<SwerveSample> swerveTrajectory = (Trajectory<SwerveSample>) trajectory; 134 swerveLogger.accept(swerveTrajectory, starting); 135 } else if (sample instanceof DifferentialSample) { 136 TrajectoryLogger<DifferentialSample> differentialLogger = 137 (TrajectoryLogger<DifferentialSample>) trajectoryLogger; 138 Trajectory<DifferentialSample> differentialTrajectory = 139 (Trajectory<DifferentialSample>) trajectory; 140 differentialLogger.accept(differentialTrajectory, starting); 141 } 142 } 143 144 private void cmdInitialize() { 145 activeTimer.reset(); 146 activeTimer.start(); 147 inactiveTimer.stop(); 148 inactiveTimer.reset(); 149 isActive = true; 150 isCompleted = false; 151 finishedNaturally = false; 152 routine.trajectoryStarted(); 153 logTrajectory(true); 154 } 155 156 @SuppressWarnings("unchecked") 157 private void cmdExecute() { 158 if (!allianceCtx.allianceKnownOrIgnored()) { 159 allianceNotReady.set(true); 160 return; 161 } 162 var sampleOpt = trajectory.sampleAt(activeTimer.get(), allianceCtx.doFlip()); 163 if (sampleOpt.isEmpty()) { 164 return; 165 } 166 var sample = sampleOpt.get(); 167 if (sample instanceof SwerveSample swerveSample) { 168 var swerveController = (Consumer<SwerveSample>) this.controller; 169 swerveController.accept(swerveSample); 170 } else if (sample instanceof DifferentialSample differentialSample) { 171 var differentialController = (Consumer<DifferentialSample>) this.controller; 172 differentialController.accept(differentialSample); 173 } 174 } 175 176 @SuppressWarnings("unchecked") 177 private void cmdEnd(boolean interrupted) { 178 activeTimer.stop(); 179 activeTimer.reset(); 180 inactiveTimer.reset(); 181 inactiveTimer.start(); 182 isActive = false; 183 isCompleted = !interrupted; 184 routine.trajectoryEnded(); 185 186 if (!interrupted && allianceCtx.allianceKnownOrIgnored()) { 187 var sampleOpt = trajectory.getFinalSample(allianceCtx.doFlip()); 188 if (sampleOpt.isPresent()) { 189 var sample = sampleOpt.get(); 190 if (sample instanceof SwerveSample swerveSample) { 191 var swerveController = (Consumer<SwerveSample>) this.controller; 192 swerveController.accept(swerveSample); 193 } else if (sample instanceof DifferentialSample differentialSample) { 194 var differentialController = (Consumer<DifferentialSample>) this.controller; 195 differentialController.accept(differentialSample); 196 } 197 } 198 } 199 200 logTrajectory(false); 201 } 202 203 private boolean cmdIsFinished() { 204 return activeTimer.get() > trajectory.getTotalTime() 205 || !routine.active().getAsBoolean() 206 || !allianceCtx.allianceKnownOrIgnored(); 207 } 208 209 /** The body of the trajectory following command. */ 210 private void cmdBody(Coroutine coroutine) { 211 cmdInitialize(); 212 while (!cmdIsFinished()) { 213 cmdExecute(); 214 coroutine.yield(); 215 } 216 finishedNaturally = true; 217 } 218 219 /** Clears the run state of this trajectory. Called when its routine starts. */ 220 void reset() { 221 activeTimer.stop(); 222 activeTimer.reset(); 223 inactiveTimer.stop(); 224 inactiveTimer.reset(); 225 isActive = false; 226 isCompleted = false; 227 finishedNaturally = false; 228 } 229 230 /** Suppresses warnings for this trajectory. */ 231 void suppressWarnings() { 232 warnUser = false; 233 } 234 235 /** 236 * Creates a command that follows the trajectory using the factory's control function, without 237 * requiring the drive mechanism. Used to warm up Choreo, including while disabled. 238 * 239 * @return The command that will follow the trajectory 240 */ 241 Command warmupCmd() { 242 return Command.noRequirements(this::cmdBody) 243 .whenExited(() -> cmdEnd(!finishedNaturally)) 244 .named("Trajectory_" + name); 245 } 246 247 /** 248 * Creates a command that requires the drive mechanism and follows the trajectory using the 249 * factory's control function. 250 * 251 * @return The command that will follow the trajectory 252 */ 253 public Command cmd() { 254 if (trajectory.samples().isEmpty() && warnUser) { 255 return Command.requiring(driveMechanism) 256 .executing(coroutine -> noSamples.addCause(name)) 257 .named("Trajectory_" + name); 258 } 259 return Command.requiring(driveMechanism) 260 .executing(this::cmdBody) 261 .whenExited(() -> cmdEnd(!finishedNaturally)) 262 .named("Trajectory_" + name); 263 } 264 265 /** 266 * Creates a command that schedules the trajectory command separately instead of running it 267 * itself. 268 * 269 * <p>Use this when a sequence needs to start a trajectory that requires a mechanism the sequence 270 * also requires. 271 * 272 * @return The command that will schedule the trajectory following command. 273 */ 274 public Command spawnCmd() { 275 return Command.noRequirements(coroutine -> coroutine.scheduler().schedule(cmd())) 276 .named("Trajectory_" + name + "_Spawner"); 277 } 278 279 /** 280 * Creates a command that resets the robot's odometry to the start of this trajectory. 281 * 282 * @return A command that resets the robot's odometry. 283 */ 284 public Command resetOdometry() { 285 return Command.requiring(driveMechanism) 286 .executing( 287 coroutine -> 288 getInitialPose() 289 .ifPresentOrElse( 290 resetOdometry, 291 () -> { 292 if (warnUser) { 293 noInitialPose.addCause(name); 294 } 295 })) 296 .named("Trajectory_ResetOdometry_" + name); 297 } 298 299 /** 300 * Will get the underlying {@link Trajectory} object. 301 * 302 * <p><b>WARNING:</b> This method is not type safe and should be used with caution. The sample 303 * type of the trajectory should be known before calling this method. 304 * 305 * @param <SampleType> The type of the trajectory samples. 306 * @return The underlying {@link Trajectory} object. 307 */ 308 @SuppressWarnings("unchecked") 309 public <SampleType extends TrajectorySample<SampleType>> 310 Trajectory<SampleType> getRawTrajectory() { 311 return (Trajectory<SampleType>) trajectory; 312 } 313 314 /** 315 * Returns this auto trajectory, mirrored to the other alliance. 316 * 317 * @param <SampleType> The type of the trajectory samples. Due to Java limitations, you have to 318 * specify the sample type again here even if it was already specified when creating the 319 * AutoTrajectory. 320 * @return this auto trajectory, mirrored to the other alliance. 321 */ 322 @SuppressWarnings("unchecked") 323 public <SampleType extends TrajectorySample<SampleType>> AutoTrajectory mirrorX() { 324 return new AutoTrajectory( 325 name, 326 (Trajectory<SampleType>) trajectory.mirrorX(), 327 poseSupplier, 328 resetOdometry, 329 (Consumer<SampleType>) controller, 330 allianceCtx, 331 (TrajectoryLogger<SampleType>) trajectoryLogger, 332 driveMechanism, 333 routine, 334 bindings); 335 } 336 337 /** 338 * Returns this auto trajectory, mirrored left-to-right from the driver's perspective. 339 * 340 * @param <SampleType> The type of the trajectory samples. Due to Java limitations, you have to 341 * specify the sample type again here even if it was already specified when creating the 342 * AutoTrajectory. 343 * @return this auto trajectory, mirrored left-to-right from the driver's perspective. 344 */ 345 @SuppressWarnings("unchecked") 346 public <SampleType extends TrajectorySample<SampleType>> AutoTrajectory mirrorY() { 347 return new AutoTrajectory( 348 name, 349 (Trajectory<SampleType>) trajectory.mirrorY(), 350 poseSupplier, 351 resetOdometry, 352 (Consumer<SampleType>) controller, 353 allianceCtx, 354 (TrajectoryLogger<SampleType>) trajectoryLogger, 355 driveMechanism, 356 routine, 357 bindings); 358 } 359 360 /** 361 * Returns this auto trajectory, rotated 180 degrees around the field center. 362 * 363 * @param <SampleType> The type of the trajectory samples. Due to Java limitations, you have to 364 * specify the sample type again here even if it was already specified when creating the 365 * AutoTrajectory. 366 * @return this auto trajectory, rotated 180 degrees around the field center. 367 */ 368 @SuppressWarnings("unchecked") 369 public <SampleType extends TrajectorySample<SampleType>> AutoTrajectory rotateAround() { 370 return new AutoTrajectory( 371 name, 372 (Trajectory<SampleType>) trajectory.rotateAround(), 373 poseSupplier, 374 resetOdometry, 375 (Consumer<SampleType>) controller, 376 allianceCtx, 377 (TrajectoryLogger<SampleType>) trajectoryLogger, 378 driveMechanism, 379 routine, 380 bindings); 381 } 382 383 /** 384 * Will get the starting pose of the trajectory. 385 * 386 * <p>This position is flipped if alliance flipping is enabled and the alliance supplier returns 387 * Red. 388 * 389 * <p>This method returns an empty Optional if the trajectory is empty. This method returns an 390 * empty Optional if alliance flipping is enabled and the alliance supplier returns an empty 391 * Optional. 392 * 393 * @return The starting pose 394 */ 395 public Optional<Pose2d> getInitialPose() { 396 if (!allianceCtx.allianceKnownOrIgnored()) { 397 allianceNotReady.set(true); 398 return Optional.empty(); 399 } 400 return trajectory.getInitialPose(allianceCtx.doFlip()); 401 } 402 403 /** 404 * Will get the ending pose of the trajectory. 405 * 406 * <p>This position is flipped if alliance flipping is enabled and the alliance supplier returns 407 * Red. 408 * 409 * <p>This method returns an empty Optional if the trajectory is empty. This method returns an 410 * empty Optional if alliance flipping is enabled and the alliance supplier returns an empty 411 * Optional. 412 * 413 * @return The starting pose 414 */ 415 public Optional<Pose2d> getFinalPose() { 416 if (!allianceCtx.allianceKnownOrIgnored()) { 417 allianceNotReady.set(true); 418 return Optional.empty(); 419 } 420 return trajectory.getFinalPose(allianceCtx.doFlip()); 421 } 422 423 /** 424 * Returns a trigger that is true while the trajectory is scheduled. 425 * 426 * @return A trigger that is true while the trajectory is scheduled. 427 */ 428 public Trigger active() { 429 return routine.active().and(() -> this.isActive); 430 } 431 432 /** 433 * Returns a trigger that is true while the command is not scheduled. 434 * 435 * <p>The same as calling <code>active().negate()</code>. 436 * 437 * @return A trigger that is true while the command is not scheduled. 438 */ 439 public Trigger inactive() { 440 return active().negate(); 441 } 442 443 private Trigger enterExitTrigger(Trigger enter, Trigger exit) { 444 return new Trigger( 445 new BooleanSupplier() { 446 private boolean output = false; 447 448 @Override 449 public boolean getAsBoolean() { 450 if (enter.getAsBoolean()) { 451 output = true; 452 } 453 if (exit.getAsBoolean()) { 454 output = false; 455 } 456 return output; 457 } 458 }); 459 } 460 461 /** 462 * Returns a trigger that is true after the trajectory completes. 463 * 464 * @return a trigger that is true after the trajectory completes 465 */ 466 public Trigger done() { 467 return doneDelayed(0); 468 } 469 470 /** 471 * Returns a trigger that becomes true after the trajectory completes and the given delay. 472 * 473 * @param seconds the delay after completion, in seconds 474 * @return a trigger that is true after the trajectory completes and the given delay 475 */ 476 public Trigger doneDelayed(double seconds) { 477 return timeTrigger(seconds, inactiveTimer).and(() -> isCompleted); 478 } 479 480 /** 481 * Returns a trigger that remains true for the given duration after completion. 482 * 483 * @param seconds the duration for which the trigger remains true, in seconds 484 * @return a trigger that remains true for the given duration after completion 485 */ 486 public Trigger doneFor(double seconds) { 487 return enterExitTrigger(doneDelayed(0), doneDelayed(seconds)); 488 } 489 490 /** 491 * Returns a trigger that remains true after completion until the routine becomes idle. 492 * 493 * @return a trigger that remains true after completion until the routine becomes idle 494 */ 495 public Trigger recentlyDone() { 496 return enterExitTrigger(doneDelayed(0), routine.idle().negate()); 497 } 498 499 /** 500 * A shorthand for `.done().onTrue(otherTrajectory.cmd())` 501 * 502 * @param otherTrajectory The other trajectory to run when this one is done. 503 */ 504 public void chain(AutoTrajectory otherTrajectory) { 505 done().onTrue(otherTrajectory.cmd()); 506 } 507 508 /** 509 * Creates a trigger that is true for exactly one scheduler cycle: the first cycle in which the 510 * running {@code timer} has reached {@code targetTime}. 511 */ 512 private Trigger timeTrigger(double targetTime, Timer timer) { 513 return new Trigger(() -> timer.isRunning() && timer.get() >= targetTime).risingEdge(); 514 } 515 516 /** 517 * Returns a trigger that will go true for 1 cycle when the desired time has elapsed 518 * 519 * @param timeSinceStart The time since the command started in seconds. 520 * @return A trigger that is true when timeSinceStart has elapsed. 521 */ 522 public Trigger atTime(double timeSinceStart) { 523 // The timer should never be negative so report this as a warning 524 if (timeSinceStart < 0) { 525 if (warnUser) { 526 triggerTimeNegative.addCause(name); 527 } 528 return new Trigger(() -> false); 529 } 530 531 // The timer should never exceed the total trajectory time so report this as a warning 532 if (timeSinceStart > trajectory.getTotalTime()) { 533 if (warnUser) { 534 triggerTimeAboveMax.addCause(name); 535 } 536 return new Trigger(() -> false); 537 } 538 539 return timeTrigger(timeSinceStart, activeTimer); 540 } 541 542 /** 543 * Returns a trigger that will go true for 1 cycle when the desired before the end of the 544 * trajectory time. 545 * 546 * @param timeBeforeEnd The time before the end of the trajectory. 547 * @return A trigger that is true when timeBeforeEnd has elapsed. 548 */ 549 public Trigger atTimeBeforeEnd(double timeBeforeEnd) { 550 return atTime(trajectory.getTotalTime() - timeBeforeEnd); 551 } 552 553 /** 554 * Returns a trigger that is true when the event with the given name has been reached based on 555 * time. 556 * 557 * <p>A warning will be printed to the DriverStation if the event is not found and the trigger 558 * will always be false. 559 * 560 * @param eventName The name of the event. 561 * @return A trigger that is true when the event with the given name has been reached based on 562 * time. 563 * @see <a href="https://choreo.autos/usage/editing-paths/#event-markers">Event Markers in the 564 * GUI</a> 565 */ 566 public Trigger atTime(String eventName) { 567 boolean foundEvent = false; 568 Trigger trig = new Trigger(() -> false); 569 570 for (var event : trajectory.getEvents(eventName)) { 571 trig = trig.or(atTime(event.timestamp)); 572 foundEvent = true; 573 } 574 575 // The user probably expects an event to exist if they're trying to do something at that event, 576 // report the missing event. 577 if (!foundEvent && warnUser) { 578 eventNotFound.addCause(name); 579 } 580 581 return trig; 582 } 583 584 private boolean withinTolerance(Rotation2d lhs, Rotation2d rhs, double toleranceRadians) { 585 if (Math.abs(toleranceRadians) > Math.PI) { 586 return true; 587 } 588 double dot = lhs.getCos() * rhs.getCos() + lhs.getSin() * rhs.getSin(); 589 // cos(θ) >= cos(tolerance) means |θ| <= tolerance, for tolerance in [-pi, pi], as pre-checked 590 // above. 591 return dot > Math.cos(toleranceRadians); 592 } 593 594 /** 595 * Returns a trigger that is true when the robot is within toleranceMeters of the given pose. 596 * 597 * <p>The pose is flipped if alliance flipping is enabled and the alliance supplier returns Red. 598 * 599 * <p>While alliance flipping is enabled and the alliance supplier returns empty, the trigger will 600 * return false. 601 * 602 * @param pose The pose to check against, unflipped. 603 * @param toleranceMeters The tolerance in meters. 604 * @param toleranceRadians The heading tolerance in radians. 605 * @return A trigger that is true when the robot is within toleranceMeters of the given pose. 606 */ 607 public Trigger atPose(Pose2d pose, double toleranceMeters, double toleranceRadians) { 608 Pose2d flippedPose = ChoreoAllianceFlipUtil.flip(pose); 609 return new Trigger( 610 () -> { 611 if (allianceCtx.allianceKnownOrIgnored()) { 612 final Pose2d currentPose = poseSupplier.get(); 613 final Pose2d target = allianceCtx.doFlip() ? flippedPose : pose; 614 boolean transValid = 615 currentPose.getTranslation().getDistance(target.getTranslation()) 616 < toleranceMeters; 617 boolean rotValid = 618 withinTolerance( 619 currentPose.getRotation(), target.getRotation(), toleranceRadians); 620 return transValid && rotValid; 621 } else { 622 allianceNotReady.set(true); 623 return false; 624 } 625 }) 626 .and(active()); 627 } 628 629 /** 630 * Returns a trigger that is true when the robot is within toleranceMeters and toleranceRadians of 631 * the given event's pose. 632 * 633 * <p>A warning will be printed to the DriverStation if the event is not found and the trigger 634 * will always be false. 635 * 636 * @param eventName The name of the event. 637 * @param toleranceMeters The tolerance in meters. 638 * @param toleranceRadians The heading tolerance in radians. 639 * @return A trigger that is true when the robot is within toleranceMeters of the given events 640 * pose. 641 * @see <a href="https://choreo.autos/usage/editing-paths/#event-markers">Event Markers in the 642 * GUI</a> 643 */ 644 public Trigger atPose(String eventName, double toleranceMeters, double toleranceRadians) { 645 boolean foundEvent = false; 646 Trigger trig = new Trigger(() -> false); 647 648 for (var event : trajectory.getEvents(eventName)) { 649 Optional<Pose2d> poseOpt = 650 trajectory 651 // don't mirror here because the poses are mirrored themselves 652 // this also lets atPose be called before the alliance is ready 653 .sampleAt(event.timestamp, false) 654 .map(TrajectorySample::getPose); 655 if (poseOpt.isPresent()) { 656 trig = trig.or(atPose(poseOpt.get(), toleranceMeters, toleranceRadians)); 657 foundEvent = true; 658 } 659 } 660 661 // The user probably expects an event to exist if they're trying to do something at that event, 662 // report the missing event. 663 if (!foundEvent && warnUser) { 664 eventNotFound.addCause(name); 665 } 666 667 return trig; 668 } 669 670 /** 671 * Returns a trigger that is true when the robot is within toleranceMeters of the given 672 * translation. 673 * 674 * <p>The translation is flipped if alliance flipping is enabled and the alliance supplier returns 675 * Red. 676 * 677 * <p>While alliance flipping is enabled and the alliance supplier returns empty, the trigger will 678 * return false. 679 * 680 * @param translation The translation to check against, unflipped. 681 * @param toleranceMeters The tolerance in meters. 682 * @return A trigger that is true when the robot is within toleranceMeters of the given 683 * translation. 684 */ 685 public Trigger atTranslation(Translation2d translation, double toleranceMeters) { 686 Translation2d flippedTranslation = ChoreoAllianceFlipUtil.flip(translation); 687 return new Trigger( 688 () -> { 689 if (allianceCtx.allianceKnownOrIgnored()) { 690 final Translation2d currentTrans = poseSupplier.get().getTranslation(); 691 if (allianceCtx.doFlip()) { 692 return currentTrans.getDistance(flippedTranslation) < toleranceMeters; 693 } else { 694 return currentTrans.getDistance(translation) < toleranceMeters; 695 } 696 } else { 697 allianceNotReady.set(true); 698 return false; 699 } 700 }) 701 .and(active()); 702 } 703 704 /** 705 * Returns a trigger that is true when the robot is within toleranceMeters and toleranceRadians of 706 * the given event's translation. 707 * 708 * <p>A warning will be printed to the DriverStation if the event is not found and the trigger 709 * will always be false. 710 * 711 * @param eventName The name of the event. 712 * @param toleranceMeters The tolerance in meters. 713 * @return A trigger that is true when the robot is within toleranceMeters of the given events 714 * translation. 715 * @see <a href="https://choreo.autos/usage/editing-paths/#event-markers">Event Markers in the 716 * GUI</a> 717 */ 718 public Trigger atTranslation(String eventName, double toleranceMeters) { 719 boolean foundEvent = false; 720 Trigger trig = new Trigger(() -> false); 721 722 for (var event : trajectory.getEvents(eventName)) { 723 Optional<Translation2d> translationOpt = 724 trajectory 725 // don't mirror here because the translations are mirrored themselves 726 // this also lets atTranslation be called before the alliance is ready 727 .sampleAt(event.timestamp, false) 728 .map(TrajectorySample::getPose) 729 .map(Pose2d::getTranslation); 730 if (translationOpt.isPresent()) { 731 trig = trig.or(atTranslation(translationOpt.get(), toleranceMeters)); 732 foundEvent = true; 733 } 734 } 735 736 // The user probably expects an event to exist if they're trying to do something at that event, 737 // report the missing event. 738 if (!foundEvent && warnUser) { 739 eventNotFound.addCause(name); 740 } 741 742 return trig; 743 } 744 745 /** 746 * Returns an array of all the timestamps of the events with the given name. 747 * 748 * @param eventName The name of the event. 749 * @return An array of all the timestamps of the events with the given name. 750 * @see <a href="https://choreo.autos/usage/editing-paths/#event-markers">Event Markers in the 751 * GUI</a> 752 */ 753 public double[] collectEventTimes(String eventName) { 754 double[] times = 755 trajectory.getEvents(eventName).stream() 756 .filter(e -> e.timestamp >= 0 && e.timestamp <= trajectory.getTotalTime()) 757 .mapToDouble(e -> e.timestamp) 758 .toArray(); 759 760 if (times.length == 0 && warnUser) { 761 eventNotFound.addCause("collectEvents(" + eventName + ")"); 762 } 763 764 return times; 765 } 766 767 /** 768 * Returns an array of all the poses of the events with the given name. 769 * 770 * <p>The returned poses are always unflipped. If you use them in a trigger like `atPose` or 771 * `atTranslation`, the library will automatically flip them if necessary. If you intend using 772 * them in a different context, you can use {@link ChoreoAllianceFlipUtil#flip} to flip them. 773 * 774 * @param eventName The name of the event. 775 * @return An array of all the poses of the events with the given name. 776 * @see <a href="https://choreo.autos/usage/editing-paths/#event-markers">Event Markers in the 777 * GUI</a> 778 */ 779 public Pose2d[] collectEventPoses(String eventName) { 780 double[] times = collectEventTimes(eventName); 781 Pose2d[] poses = new Pose2d[times.length]; 782 for (int i = 0; i < times.length; i++) { 783 Pose2d pose = 784 trajectory 785 .sampleAt(times[i], false) 786 .map(TrajectorySample::getPose) 787 .get(); // the event times are guaranteed to be valid 788 poses[i] = pose; 789 } 790 return poses; 791 } 792 793 @Override 794 public boolean equals(Object obj) { 795 return obj instanceof AutoTrajectory traj && name.equals(traj.name); 796 } 797 798 @Override 799 public int hashCode() { 800 return name.hashCode(); 801 } 802}