plcopen 0.22.0
载入中...
搜索中...
未找到
time_optimal.h
浏览该文件的文档.
1#pragma once
2
3// Time-optimal jerk-limited state-to-state planner (A9 v2 — Y2).
4//
5// Scope: arbitrary (position, velocity, acceleration) to arbitrary target
6// (position, velocity, acceleration). Nonzero initial acceleration reduces
7// through an exact zeroing ramp; nonzero target acceleration uses a symmetric
8// targeting ramp (or quintic correction fallback when v_eff exceeds v_max).
9//
10// Method: the velocity profile is entry-ramp -> cruise -> exit-ramp, where a
11// ramp between two velocities is the classic jerk-limited shape (triangular or
12// trapezoidal acceleration) with the closed-form pair
13// t(va→vb) = 2·sqrt(|Δv|/j) if |Δv| ≤ a²/j
14// = |Δv|/a + a/j otherwise
15// d(va→vb) = (va + vb)/2 · t (antisymmetric velocity shape)
16// Ramps crossing zero split at v = 0 so the PLCopen acceleration bound applies
17// while |v| grows and the deceleration bound while |v| shrinks. The covered
18// distance D(vc) of the cruise-velocity candidate vc is continuous and
19// monotone on [max(v0,vt), vmax] and on [-vmax, min(v0,vt)] — but NOT in
20// between: splitting the direct v0→vt ramp in two adds jerk phases and extra
21// distance, so the solver first selects the monotone branch by comparing the
22// distance against the direct-ramp distance, then bisects inside that branch;
23// overshoot-and-return cases fall out of the same formulation with a negative
24// cruise velocity. Phase durations are then
25// floored to the integer cycle domain (staying inside the envelope) and one
26// final quintic segment corrects the quantization residue to hit the target
27// state exactly — the same grow-until-feasible pattern the baseline planner
28// uses. Not RT: planning-domain only.
29
30#include <cmath>
31#include <cstdint>
32
33#include "otg/profile1d.h"
34#include "rt/cycle.h"
35#include "rt/error.h"
36
37namespace plcopen::core::otg
38{
39
40namespace detail
41{
42
44{
45 double duration = 0.0;
46 double distance = 0.0;
47};
48
49// Jerk-limited ramp between same-direction velocities under one bound.
50inline RampTiming ramp_timing(double va, double vb, double bound, double jerk)
51{
52 const double delta = std::fabs(vb - va);
53 if(delta <= 0.0) {
54 return {0.0, 0.0};
55 }
56 double duration = 0.0;
57 if(delta <= bound * bound / jerk) {
58 duration = 2.0 * std::sqrt(delta / jerk);
59 } else {
60 duration = delta / bound + bound / jerk;
61 }
62 return {duration, 0.5 * (va + vb) * duration};
63}
64
65// Bound selection: PLCopen acceleration while |v| grows, deceleration while
66// |v| shrinks. Callers guarantee va and vb do not straddle zero.
67inline double ramp_bound(double va, double vb, const Limits1D &limits)
68{
69 return std::fabs(vb) > std::fabs(va) ? limits.max_acceleration : limits.max_deceleration;
70}
71
72inline RampTiming ramp_between(double va, double vb, const Limits1D &limits)
73{
74 if((va < 0.0 && vb > 0.0) || (va > 0.0 && vb < 0.0)) {
75 const RampTiming first = ramp_timing(va, 0.0, limits.max_deceleration, limits.max_jerk);
76 const RampTiming second = ramp_timing(0.0, vb, limits.max_acceleration, limits.max_jerk);
77 return {first.duration + second.duration, first.distance + second.distance};
78 }
79 return ramp_timing(va, vb, ramp_bound(va, vb, limits), limits.max_jerk);
80}
81
82inline double ramp_chain_distance(double v0, double vc, double vt, const Limits1D &limits)
83{
84 return ramp_between(v0, vc, limits).distance + ramp_between(vc, vt, limits).distance;
85}
86
87// One constant-jerk phase appended to the profile in the integer cycle domain.
88// Durations are floored so the envelope of the continuous solution is never
89// exceeded; the quantization residue is corrected by the final quintic.
91 State1D &state,
92 double jerk,
93 double continuous_duration,
94 bool force_finish_derivatives = false,
95 double finish_velocity = 0.0,
96 double finish_acceleration = 0.0)
97{
98 constexpr double kMaxPhaseCycles = 1.0e15;
99 if(!std::isfinite(continuous_duration) || continuous_duration < 0.0 ||
100 continuous_duration > kMaxPhaseCycles) {
102 }
103 const std::int64_t cycles = static_cast<std::int64_t>(std::floor(continuous_duration));
104 if(cycles < 1) {
105 return rt::ErrorCode::ok;
106 }
107
108 Segment1D segment{};
109 segment.duration_cycles = cycles;
110 segment.start = state;
111 segment.c0 = state.position;
112 segment.c1 = state.velocity;
113 segment.c2 = 0.5 * state.acceleration;
114 segment.c3 = jerk / 6.0;
115 // sample_segment clamps to segment.finish at the duration, so the finish
116 // state must be evaluated directly from the polynomial.
117 const double x = static_cast<double>(cycles);
118 segment.finish = State1D{
119 segment.c0 + segment.c1 * x + segment.c2 * x * x + segment.c3 * x * x * x,
120 segment.c1 + 2.0 * segment.c2 * x + 3.0 * segment.c3 * x * x,
121 state.acceleration + jerk * x,
122 };
123 if(force_finish_derivatives) {
124 const double velocity_tolerance =
125 1e-12 * (1.0 + std::fabs(finish_velocity));
126 const double acceleration_tolerance =
127 1e-12 * (1.0 + std::fabs(finish_acceleration));
128 if(!std::isfinite(finish_velocity) ||
129 !std::isfinite(finish_acceleration) ||
130 std::fabs(segment.finish.velocity - finish_velocity) >
131 velocity_tolerance ||
132 std::fabs(segment.finish.acceleration - finish_acceleration) >
133 acceleration_tolerance) {
135 }
136 // Exact phase algebra can retain a final floating-point residue.
137 // Normalize only a derivative already equal within the proof bound.
138 segment.finish.velocity = finish_velocity;
139 segment.finish.acceleration = finish_acceleration;
140 }
141
142 const rt::ErrorCode pushed = profile.add_segment(segment);
143 if(pushed != rt::ErrorCode::ok) {
144 return pushed;
145 }
146 state = segment.finish;
147 return rt::ErrorCode::ok;
148}
149
150// Ramp quantization strategy. floored keeps the continuous-time jerk and
151// floors the phase durations — closest to time-optimal, leaving a residue for
152// the final quintic correction (which can fail for large residues; the caller
153// treats that construction as one candidate). exact uses ceil'd phase counts
154// with the adjusted jerk j' = Δv/(n1·(n1+n2)) so the end velocity is hit
155// exactly and the chained acceleration returns exactly to zero — always
156// feasible, but slower on cycle-scale ramps.
157enum class RampRounding
158{
161};
162
163// Appends one jerk-limited ramp between same-direction velocities.
165 State1D &state,
166 double vb,
167 const Limits1D &limits,
168 RampRounding rounding,
169 bool force_finish_derivatives = false)
170{
171 const double va = state.velocity;
172 const double target_acceleration = state.acceleration;
173 const double delta = vb - va;
174 if(delta == 0.0) {
175 return rt::ErrorCode::ok;
176 }
177 const double bound = ramp_bound(va, vb, limits);
178 const double jerk = limits.max_jerk;
179
180 double jerk_phase = 0.0;
181 double hold_phase = 0.0;
182 if(std::fabs(delta) <= bound * bound / jerk) {
183 jerk_phase = std::sqrt(std::fabs(delta) / jerk);
184 } else {
185 jerk_phase = bound / jerk;
186 hold_phase = std::fabs(delta) / bound - bound / jerk;
187 }
188
189 if(rounding == RampRounding::floored) {
190 const double direction = delta > 0.0 ? 1.0 : -1.0;
191 rt::ErrorCode pushed = push_cubic_phase(profile, state, direction * jerk, jerk_phase);
192 if(pushed != rt::ErrorCode::ok) {
193 return pushed;
194 }
195 if(hold_phase > 0.0) {
196 pushed = push_cubic_phase(profile, state, 0.0, hold_phase);
197 if(pushed != rt::ErrorCode::ok) {
198 return pushed;
199 }
200 }
201 return push_cubic_phase(profile, state, -direction * jerk, jerk_phase);
202 }
203
204 if(!std::isfinite(jerk_phase) || jerk_phase < 0.0 || jerk_phase > 1.0e15 ||
205 !std::isfinite(hold_phase) || hold_phase < 0.0 || hold_phase > 1.0e15) {
207 }
208 const std::int64_t n1 =
209 static_cast<std::int64_t>(std::ceil(jerk_phase)) > 0
210 ? static_cast<std::int64_t>(std::ceil(jerk_phase))
211 : 1;
212 const std::int64_t n2 = static_cast<std::int64_t>(std::ceil(hold_phase));
213 const double adjusted_jerk =
214 delta / (static_cast<double>(n1) * static_cast<double>(n1 + n2));
215
216 rt::ErrorCode pushed =
217 push_cubic_phase(profile, state, adjusted_jerk, static_cast<double>(n1));
218 if(pushed != rt::ErrorCode::ok) {
219 return pushed;
220 }
221 if(n2 > 0) {
222 pushed = push_cubic_phase(profile, state, 0.0, static_cast<double>(n2));
223 if(pushed != rt::ErrorCode::ok) {
224 return pushed;
225 }
226 }
227 return push_cubic_phase(
228 profile, state, -adjusted_jerk, static_cast<double>(n1),
229 force_finish_derivatives, vb, target_acceleration);
230}
231
233 State1D &state,
234 double vb,
235 const Limits1D &limits,
236 RampRounding rounding)
237{
238 const double va = state.velocity;
239 if((va < 0.0 && vb > 0.0) || (va > 0.0 && vb < 0.0)) {
240 const rt::ErrorCode pushed = push_ramp(profile, state, 0.0, limits, rounding);
241 if(pushed != rt::ErrorCode::ok) {
242 return pushed;
243 }
244 }
245 return push_ramp(profile, state, vb, limits, rounding);
246}
247
248// Smallest feasible quintic duration for zero boundary accelerations. Longer
249// durations then relax the internal peaks, so feasibility is monotone and the
250// minimum is found exactly by doubling to an upper bound and bisecting (with
251// nonzero boundary accelerations this monotonicity does not hold).
253 Target1D to,
254 const Limits1D &limits)
255{
256 const auto feasible = [&](std::int64_t cycles) {
257 return within_limits(make_quintic_segment(from, to, cycles), limits);
258 };
259
260 std::int64_t high = 1;
261 int attempts = 0;
262 while(!feasible(high)) {
263 high *= 2;
264 if(++attempts > 40) {
266 }
267 }
268 std::int64_t low = high / 2;
269 while(low + 1 < high) {
270 const std::int64_t middle = low + (high - low) / 2;
271 if(feasible(middle)) {
272 high = middle;
273 } else {
274 low = middle;
275 }
276 }
278}
279
280// Minimal feasible quintic correction to the exact target state. Both
281// boundary accelerations are zero here (the phase construction guarantees
282// it), which is what makes feasibility monotone in the duration and the
283// bisection in min_feasible_quintic_cycles valid.
285 State1D state,
286 Target1D to,
287 const Limits1D &limits)
288{
289 const bool at_target = state.position == to.position && state.velocity == to.velocity &&
290 state.acceleration == to.acceleration;
291 if(at_target && profile.segment_count() > 0) {
292 return rt::ErrorCode::ok;
293 }
294
295 if(state.acceleration == 0.0 && to.acceleration == 0.0) {
296 const rt::Result<std::int64_t> cycles = min_feasible_quintic_cycles(state, to, limits);
297 if(!cycles) {
298 return cycles.error();
299 }
300 return profile.add_segment(make_quintic_segment(state, to, cycles.value()));
301 }
302
303 const double dp = std::fabs(to.position - state.position);
304 const double dv = std::fabs(to.velocity - state.velocity);
305 const double da = std::fabs(to.acceleration - state.acceleration);
306 double estimate = 1.0;
307 if(dp > 0.0) {
308 const double by_vel = dp / limits.max_velocity;
309 if(by_vel > estimate) estimate = by_vel;
310 }
311 if(dv > 0.0) {
312 const double by_accel = dv / limits.max_acceleration;
313 if(by_accel > estimate) estimate = by_accel;
314 }
315 if(da > 0.0) {
316 const double by_jerk = 8.0 * da / limits.max_jerk;
317 if(by_jerk > estimate) estimate = by_jerk;
318 }
319 if(!std::isfinite(estimate) || estimate > static_cast<double>(MaxPlanCycles)) {
321 }
322 std::int64_t cycles = static_cast<std::int64_t>(std::ceil(estimate));
323 if(cycles < 1) cycles = 1;
324 for(int attempt = 0; attempt < 80; ++attempt) {
325 if(cycles < 1 || cycles > MaxPlanCycles) {
327 }
328 const Segment1D segment = make_quintic_segment(state, to, cycles);
329 if(within_limits(segment, limits)) {
330 return profile.add_segment(segment);
331 }
332 cycles = cycles + cycles / 4 + 1;
333 }
335}
336
337// Solve for three constant-jerk phase values (j1,j2,j3) with durations
338// (d1,d2,d3) that connect state (a0,v0,p0) to target (at,vt,pt).
339// Returns {j1,j2,j3,1} on success, {0,0,0,0} if singular.
340struct CubicSolution { double j1, j2, j3; bool valid; };
341inline CubicSolution solve_3cubic(double a0, double v0, double p0,
342 double at, double vt, double pt,
343 double d1, double d2, double d3)
344{
345 const double T = d1 + d2 + d3;
346 double A[3][3], b[3];
347 A[0][0] = d1;
348 A[0][1] = d2;
349 A[0][2] = d3;
350 b[0] = at - a0;
351 A[1][0] = d1 * (T - d1 * 0.5);
352 A[1][1] = d2 * (T - d1 - d2 * 0.5);
353 A[1][2] = d3 * d3 * 0.5;
354 b[1] = vt - v0 - a0 * T;
355 A[2][0] = d1 * d1 * d1 / 6.0 + d1 * d1 * d2 * 0.5 + d1 * d2 * d2 * 0.5
356 + (d1 * d1 * 0.5 + d1 * d2) * d3 + d1 * d3 * d3 * 0.5;
357 A[2][1] = d2 * d2 * d2 / 6.0 + d2 * d2 * d3 * 0.5 + d2 * d3 * d3 * 0.5;
358 A[2][2] = d3 * d3 * d3 / 6.0;
359 b[2] = pt - (p0 + v0 * T + a0 * (d1 * d1 * 0.5 + d1 * d2 + d2 * d2 * 0.5
360 + (d1 + d2) * d3 + d3 * d3 * 0.5));
361 const double D = A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1])
362 - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0])
363 + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]);
364 if(std::fabs(D) < 1e-20) {
365 return {0.0, 0.0, 0.0, false};
366 }
367 auto col = [&](int c) {
368 double M[3][3];
369 for(int i = 0; i < 3; ++i) {
370 for(int j = 0; j < 3; ++j) {
371 M[i][j] = A[i][j];
372 }
373 M[i][c] = b[i];
374 }
375 return M[0][0] * (M[1][1] * M[2][2] - M[1][2] * M[2][1])
376 - M[0][1] * (M[1][0] * M[2][2] - M[1][2] * M[2][0])
377 + M[0][2] * (M[1][0] * M[2][1] - M[1][1] * M[2][0]);
378 };
379 return {col(0) / D, col(1) / D, col(2) / D, true};
380}
381
382// Checks whether a single constant-jerk phase respects velocity and
383// acceleration limits. Acceleration is linear → extremes at endpoints.
384// Velocity is quadratic → one interior extremum at t = -a0/j.
385inline bool check_cubic_phase_limits(double a0, double v0, double jerk,
386 double dur, const Limits1D &limits)
387{
388 const double a_end = a0 + jerk * dur;
389 if(a0 > limits.max_acceleration + 1e-12 ||
390 a0 < -limits.max_deceleration - 1e-12 ||
391 a_end > limits.max_acceleration + 1e-12 ||
392 a_end < -limits.max_deceleration - 1e-12) {
393 return false;
394 }
395 const double v_end = v0 + a0 * dur + jerk * dur * dur * 0.5;
396 double peak_v = std::fmax(std::fabs(v0), std::fabs(v_end));
397 if(std::fabs(jerk) > 1e-15) {
398 const double t_ext = -a0 / jerk;
399 if(t_ext > 0.0 && t_ext < dur) {
400 const double v_ext = v0 + a0 * t_ext + jerk * t_ext * t_ext * 0.5;
401 if(std::fabs(v_ext) > peak_v) {
402 peak_v = std::fabs(v_ext);
403 }
404 }
405 }
406 return peak_v <= limits.max_velocity + 1e-12;
407}
408
409// One full multiphase candidate: acceleration-zeroing reduction, entry ramp,
410// cruise, exit ramp, and the exact quintic correction.
412 Target1D to,
413 const Limits1D &limits,
414 double cruise_velocity,
415 double cruise_duration,
416 RampRounding rounding)
417{
418 Profile1D profile{};
419 State1D state = from;
420 if(from.acceleration != 0.0) {
421 const double zero_cycles = std::ceil(std::fabs(from.acceleration) / limits.max_jerk);
422 const double zero_jerk = -from.acceleration / zero_cycles;
423 const rt::ErrorCode pushed = push_cubic_phase(profile, state, zero_jerk, zero_cycles);
424 if(pushed != rt::ErrorCode::ok) {
425 return rt::Result<Profile1D>::failure(pushed);
426 }
427 state.acceleration = 0.0;
428 }
429
430 rt::ErrorCode built =
431 push_ramp_with_crossing(profile, state, cruise_velocity, limits, rounding);
432 if(built != rt::ErrorCode::ok) {
433 return rt::Result<Profile1D>::failure(built);
434 }
435 if(cruise_duration > 0.0 && cruise_velocity != 0.0) {
436 built = push_cubic_phase(profile, state, 0.0, cruise_duration);
437 if(built != rt::ErrorCode::ok) {
438 return rt::Result<Profile1D>::failure(built);
439 }
440 }
441 built = push_ramp_with_crossing(profile, state, to.velocity, limits, rounding);
442 if(built != rt::ErrorCode::ok) {
443 return rt::Result<Profile1D>::failure(built);
444 }
445 built = push_quintic_correction(profile, state, to, limits);
446 if(built != rt::ErrorCode::ok) {
447 return rt::Result<Profile1D>::failure(built);
448 }
449 if(profile.segment_count() == 0 || profile.duration_cycles() < 1) {
451 }
452 return rt::Result<Profile1D>::success(profile);
453}
454
455// Cruise-velocity refinement for nonzero target velocities. The generic
456// construction leaves a position residue to a correction quintic at the
457// boundary velocity; with integer durations that quintic must "burn"
458// |residue - vt*T| against the acceleration/jerk limits, which costs
459// hundreds of cycles when vt sits near the velocity limit (A4 finding).
460// Here the residue is absorbed upstream instead: an integer cruise duration
461// whose cruise velocity is refined by fixed-point iteration until the
462// quantized ramps plus the cruise land on the target within dust — no
463// correction segment at all.
465 Target1D to,
466 const Limits1D &limits,
467 double cruise_hint)
468{
469 if(cruise_hint == 0.0) {
471 }
472
473 // Entry-acceleration reduction (same construction as build_multiphase).
474 Profile1D reduction{};
475 State1D reduced = from;
476 if(from.acceleration != 0.0) {
477 const double zero_cycles = std::ceil(std::fabs(from.acceleration) / limits.max_jerk);
478 const double zero_jerk = -from.acceleration / zero_cycles;
479 const rt::ErrorCode pushed =
480 push_cubic_phase(reduction, reduced, zero_jerk, zero_cycles);
481 if(pushed != rt::ErrorCode::ok) {
482 return rt::Result<Profile1D>::failure(pushed);
483 }
484 reduced.acceleration = 0.0;
485 }
486 const double distance = to.position - reduced.position;
487
488 // Quantized total distance at a given cruise velocity (exact-rounded
489 // ramps plus n integer cruise cycles).
490 const auto chained = [&](double velocity, std::int64_t cycles, double &total) {
491 Profile1D scratch = reduction;
492 State1D state = reduced;
493 rt::ErrorCode built =
494 push_ramp_with_crossing(scratch, state, velocity, limits, RampRounding::exact);
495 if(built != rt::ErrorCode::ok) {
496 return built;
497 }
498 built = push_ramp_with_crossing(scratch, state, to.velocity, limits,
500 if(built != rt::ErrorCode::ok) {
501 return built;
502 }
503 total = (state.position - reduced.position) +
504 velocity * static_cast<double>(cycles);
505 return rt::ErrorCode::ok;
506 };
507
508 // Pick the integer cruise-cycle count at the hint velocity, then bisect
509 // the cruise velocity so the quantized chain lands exactly on the target
510 // (the fixed-point form contracts too slowly when the ramp time is
511 // comparable to the cruise time).
512 const double direction = cruise_hint > 0.0 ? 1.0 : -1.0;
513 const double vmax = limits.max_velocity;
514 double probe_total = 0.0;
515 if(chained(direction * vmax, 0, probe_total) != rt::ErrorCode::ok) {
517 }
518 const double remaining_at_vmax = distance - probe_total;
519 if(!(remaining_at_vmax * direction > 0.0)) {
520 // No cruise room: not a cruise-regime case; the generic candidates
521 // handle it.
523 }
524 const double base_cycles_f = std::fabs(remaining_at_vmax) / vmax;
525 if(!std::isfinite(base_cycles_f) || base_cycles_f > 1.0e15) {
527 }
528 const std::int64_t base_cycles =
529 static_cast<std::int64_t>(std::ceil(base_cycles_f));
530
531 // The quantized chain distance is piecewise-smooth in the cruise velocity
532 // (ramp phase counts jump); if the root lands exactly on a jump the dust
533 // check below fails. Adding cruise cycles shifts the root into a smooth
534 // stretch, so a handful of attempts settles it.
535 double cruise_velocity = 0.0;
536 std::int64_t cruise_cycles = 0;
537 bool solved = false;
538 for(std::int64_t attempt = 0; attempt < 4 && !solved; ++attempt) {
539 std::int64_t cycles = base_cycles + attempt;
540 if(cycles < 1) {
541 cycles = 1;
542 }
543 double low = direction * vmax * 1e-9;
544 double high = direction * vmax;
545 double low_total = 0.0;
546 double high_total = 0.0;
547 if(chained(low, cycles, low_total) != rt::ErrorCode::ok ||
548 chained(high, cycles, high_total) != rt::ErrorCode::ok) {
549 continue;
550 }
551 if(!((low_total - distance) * (high_total - distance) <= 0.0)) {
552 continue;
553 }
554 double candidate = high;
555 for(int iteration = 0; iteration < 96; ++iteration) {
556 const double middle = 0.5 * (low + high);
557 double total = 0.0;
558 if(chained(middle, cycles, total) != rt::ErrorCode::ok) {
559 break;
560 }
561 if((total - distance) * direction >= 0.0) {
562 high = middle;
563 } else {
564 low = middle;
565 }
566 candidate = 0.5 * (low + high);
567 }
568 double settled = 0.0;
569 if(chained(candidate, cycles, settled) != rt::ErrorCode::ok) {
570 continue;
571 }
572 if(std::fabs(settled - distance) <= 1e-9 * (1.0 + std::fabs(to.position))) {
573 cruise_velocity = candidate;
574 cruise_cycles = cycles;
575 solved = true;
576 }
577 }
578 if(!solved) {
580 }
581
582 // Final assembly with the refined cruise velocity.
583 Profile1D profile = reduction;
584 State1D state = reduced;
585 rt::ErrorCode built = push_ramp_with_crossing(profile, state, cruise_velocity, limits,
587 if(built != rt::ErrorCode::ok) {
588 return rt::Result<Profile1D>::failure(built);
589 }
590 built = push_cubic_phase(profile, state, 0.0, static_cast<double>(cruise_cycles));
591 if(built != rt::ErrorCode::ok) {
592 return rt::Result<Profile1D>::failure(built);
593 }
594 built = push_ramp_with_crossing(profile, state, to.velocity, limits,
596 if(built != rt::ErrorCode::ok) {
597 return rt::Result<Profile1D>::failure(built);
598 }
599
600 // Endpoint dust must be negligible: the whole point of this candidate is
601 // that no residue-burning correction is needed.
602 const double dust_bound = 1e-9 * (1.0 + std::fabs(to.position));
603 if(std::fabs(state.position - to.position) > dust_bound ||
604 std::fabs(state.velocity - to.velocity) > 1e-12 ||
605 std::fabs(state.acceleration) > 1e-12) {
607 }
608 if(profile.segment_count() == 0 || profile.duration_cycles() < 1) {
610 }
611 return rt::Result<Profile1D>::success(profile);
612}
613
614} // namespace detail
615
616// Time-optimal jerk-limited plan. Nonzero initial accelerations reduce to the
617// zero-acceleration problem through one exact zeroing ramp: n0 = ceil(|a0|/j)
618// integer cycles with the adjusted jerk -a0/n0 (magnitude ≤ j) bring the
619// acceleration to exactly zero. Nonzero target accelerations use a symmetric
620// targeting ramp: nt = ceil(|at|/j) cycles with jerk at/nt appended after the
621// main chain; the solver plans to an effective target (p_eff, v_eff, 0). When
622// |v_eff| > v_max the targeting ramp is omitted and the quintic correction
623// handles the acceleration transition directly. The result reuses Profile1D,
624// so the RT-side sample() path is unchanged.
626{
627 if(!is_finite(from) || !is_finite(to) || !is_finite(limits) || limits.max_velocity <= 0.0 ||
628 limits.max_acceleration <= 0.0 || limits.max_deceleration <= 0.0 ||
629 limits.max_jerk <= 0.0) {
631 }
632 if(to.acceleration > limits.max_acceleration ||
633 to.acceleration < -limits.max_deceleration) {
635 }
636 // The entry velocity may exceed the limit (takeover by a command with a
637 // tighter velocity limit): the entry ramp is monotone toward the cruise
638 // velocity, which the selection caps at ±vmax, so the profile drops into
639 // the envelope and never leaves it again.
640 if(std::fabs(to.velocity) > limits.max_velocity ||
641 from.acceleration > limits.max_acceleration ||
642 from.acceleration < -limits.max_deceleration) {
644 }
645
646 // Reduction exit state (the zeroing ramp itself is built per candidate).
647 State1D state = from;
648 if(from.acceleration != 0.0) {
649 const double zero_cycles = std::ceil(std::fabs(from.acceleration) / limits.max_jerk);
650 state.velocity = from.velocity + 0.5 * from.acceleration * zero_cycles;
651 state.position = from.position + from.velocity * zero_cycles +
652 from.acceleration * zero_cycles * zero_cycles / 3.0;
653 state.acceleration = 0.0;
654 }
655
656 Target1D eff = to;
657 double tramp_j = 0.0;
658 double tramp_n = 0.0;
659 if(to.acceleration != 0.0) {
660 const double n = std::ceil(std::fabs(to.acceleration) / limits.max_jerk);
661 const double dv = 0.5 * to.acceleration * n;
662 if(std::fabs(to.velocity - dv) <= limits.max_velocity) {
663 eff.velocity = to.velocity - dv;
664 eff.position = to.position - eff.velocity * n
665 - to.acceleration * n * n / 6.0;
666 eff.acceleration = 0.0;
667 tramp_j = to.acceleration / n;
668 tramp_n = n;
669 }
670 }
671
672 const double distance = eff.position - state.position;
673 const double v0 = state.velocity;
674 const double vt = eff.velocity;
675
676 // Cruise-velocity selection. D(vc) is continuous but NOT monotone across
677 // the whole span: between the boundary velocities, splitting the direct
678 // ramp in two adds jerk phases and extra distance (a bump), so a global
679 // bisection can land on a spurious crossing — e.g. a negative cruise
680 // velocity for a short forward move (B9 finding). The direct-ramp
681 // distance selects the monotone branch; if the branch bracket does not
682 // enclose the distance (boundary velocities outside the envelope after a
683 // takeover), the full span is the fallback — no worse than before.
684 double cruise_velocity = 0.0;
685 double cruise_duration = 0.0;
686 const double d_at_vmax = detail::ramp_chain_distance(v0, limits.max_velocity, vt, limits);
687 const double d_at_vmin = detail::ramp_chain_distance(v0, -limits.max_velocity, vt, limits);
688 if(d_at_vmax <= distance) {
689 cruise_velocity = limits.max_velocity;
690 cruise_duration = (distance - d_at_vmax) / limits.max_velocity;
691 } else if(d_at_vmin >= distance) {
692 cruise_velocity = -limits.max_velocity;
693 cruise_duration = (distance - d_at_vmin) / (-limits.max_velocity);
694 } else {
695 const double d_direct = detail::ramp_between(v0, vt, limits).distance;
696 double low = -limits.max_velocity;
697 double high = limits.max_velocity;
698 if(distance >= d_direct) {
699 const double branch_low = v0 > vt ? v0 : vt;
700 if(branch_low >= -limits.max_velocity && branch_low <= limits.max_velocity &&
701 detail::ramp_chain_distance(v0, branch_low, vt, limits) <= distance) {
702 low = branch_low;
703 }
704 } else {
705 const double branch_high = v0 < vt ? v0 : vt;
706 if(branch_high >= -limits.max_velocity && branch_high <= limits.max_velocity &&
707 detail::ramp_chain_distance(v0, branch_high, vt, limits) >= distance) {
708 high = branch_high;
709 }
710 }
711 for(int iteration = 0; iteration < 128; ++iteration) {
712 const double middle = 0.5 * (low + high);
713 if(detail::ramp_chain_distance(v0, middle, vt, limits) < distance) {
714 low = middle;
715 } else {
716 high = middle;
717 }
718 }
719 cruise_velocity = 0.5 * (low + high);
720 cruise_duration = 0.0;
721 }
722
723 // Candidate selection, shortest feasible wins:
724 // - floored multiphase: continuous-time jerks with floored durations —
725 // closest to time-optimal, but its correction can fail for cycle-scale
726 // ramps whose phases round away;
727 // - exact multiphase: integer phases with adjusted jerks — always
728 // feasible, slower on cycle-scale ramps;
729 // - minimal single quintic (zero boundary accelerations only: the
730 // feasibility bisection is monotone only there);
731 // - baseline plan(): makes the "never slower than the baseline planner"
732 // promise hold by construction (its duration guess is not minimal, so
733 // it is not sufficient on its own).
734 Profile1D best{};
735 bool have_best = false;
736
737 const auto consider = [&](const rt::Result<Profile1D> &candidate) {
738 if(candidate && candidate.value().duration_cycles() >= 1 &&
739 candidate.value().duration_cycles() <= MaxPlanCycles &&
740 (!have_best || candidate.value().duration_cycles() < best.duration_cycles())) {
741 best = candidate.value();
742 have_best = true;
743 }
744 };
745
746 const auto tramp = [&](rt::Result<Profile1D> r) -> rt::Result<Profile1D> {
747 if(!r || tramp_n < 1.0) return r;
748 Profile1D p = r.value();
749 State1D s = sample(p, rt::CycleTick::from_cycles(p.duration_cycles()));
750 s.acceleration = 0.0;
751 const rt::ErrorCode e = detail::push_cubic_phase(p, s, tramp_j, tramp_n);
754 };
755
756 consider(tramp(detail::build_multiphase(from, eff, limits, cruise_velocity, cruise_duration,
758 consider(tramp(detail::build_multiphase(from, eff, limits, cruise_velocity, cruise_duration,
760 if(eff.velocity != 0.0) {
761 consider(tramp(detail::build_refined_cruise(from, eff, limits, cruise_velocity)));
762 }
763 if(from.acceleration == 0.0) {
764 const rt::Result<std::int64_t> minimal =
765 detail::min_feasible_quintic_cycles(from, eff, limits);
766 if(minimal) {
767 Profile1D single{};
768 if(single.add_segment(make_quintic_segment(from, eff, minimal.value())) ==
770 consider(tramp(rt::Result<Profile1D>::success(single)));
771 }
772 }
773 }
774 // Estimate-anchored single quintic (B9 finding): the continuous-time
775 // chain duration (zeroing ramp + entry ramp + cruise + exit ramp) bounds
776 // the optimum from below, and a single quintic supports nonzero entry
777 // accelerations directly. In the bump zone the quantized multiphase
778 // chains leave a position residue whose correction burns dozens of
779 // cycles at the boundary velocity; a quintic near the continuous-time
780 // duration lands exactly with no correction. Feasibility is not monotone
781 // here, so this probes a bounded window upward from the estimate instead
782 // of bisecting.
783 {
784 double estimate = cruise_duration +
785 detail::ramp_between(v0, cruise_velocity, limits).duration +
786 detail::ramp_between(cruise_velocity, vt, limits).duration;
787 if(from.acceleration != 0.0) {
788 estimate += std::ceil(std::fabs(from.acceleration) / limits.max_jerk);
789 }
790 if(std::isfinite(estimate) && estimate <= 1.0e15) {
791 std::int64_t cycles = static_cast<std::int64_t>(std::ceil(estimate));
792 if(cycles < 1) {
793 cycles = 1;
794 }
795 // Shape guard: with one-directional boundary conditions a winning
796 // quintic must not wiggle backward (the forward-only quality
797 // contract); reversal-shaped candidates stay with the multiphase
798 // constructions.
799 const bool forward = from.velocity >= 0.0 && eff.velocity >= 0.0 &&
800 eff.position >= from.position;
801 const bool backward = from.velocity <= 0.0 && eff.velocity <= 0.0 &&
802 eff.position <= from.position;
803 for(int attempt = 0; attempt < 16; ++attempt, ++cycles) {
804 if(cycles < 1 || cycles > MaxPlanCycles) {
805 break;
806 }
807 const Segment1D segment = make_quintic_segment(from, eff, cycles);
808 if(!within_limits(segment, limits)) {
809 continue;
810 }
811 bool shape_ok = true;
812 if(forward || backward) {
813 const std::int64_t q = segment.duration_cycles / 96;
814 const std::int64_t r = segment.duration_cycles % 96;
815 for(int i = 0; i <= 96 && shape_ok; ++i) {
816 const std::int64_t idx = static_cast<std::int64_t>(i);
817 const std::int64_t cycle = q * idx + (r * idx) / 96;
818 const double velocity = sample_segment(segment, cycle).velocity;
819 if((forward && velocity < -1e-9) || (backward && velocity > 1e-9)) {
820 shape_ok = false;
821 }
822 }
823 }
824 if(shape_ok) {
825 Profile1D single{};
826 if(single.add_segment(segment) == rt::ErrorCode::ok) {
827 consider(tramp(rt::Result<Profile1D>::success(single)));
828 }
829 break;
830 }
831 }
832 }
833 }
834 consider(plan(from, to, limits));
835
836 if(!have_best) {
838 }
840}
841
842// Fixed-time jerk-limited plan: produce a profile with exactly total_cycles
843// duration that hits the target state to within 1e-9 and stays within limits.
844// Returns infeasible if total_cycles is shorter than the time-optimal duration.
845// Method: single-quintic candidate (works for large T), plus a multiphase chain
846// whose cruise velocity is bisected so that the ramp chain plus integer cruise
847// covers the target distance in the prescribed time, with a minimal quintic
848// correction absorbing the quantization residue.
850 Limits1D limits,
851 std::int64_t total_cycles)
852{
853 if(!is_finite(from) || !is_finite(to) || !is_finite(limits) || limits.max_velocity <= 0.0 ||
854 limits.max_acceleration <= 0.0 || limits.max_deceleration <= 0.0 ||
855 limits.max_jerk <= 0.0 || total_cycles < 1) {
857 }
858 if(total_cycles > MaxPlanCycles) {
860 }
861
862 const rt::Result<Profile1D> optimal = plan_time_optimal(from, to, limits);
863 if(!optimal) {
864 return optimal;
865 }
866 if(optimal.value().duration_cycles() == total_cycles) {
867 return optimal;
868 }
869 const bool below_tmin = optimal.value().duration_cycles() > total_cycles;
870
871 // Candidate 1: single quintic spanning the full duration.
872 {
873 const Segment1D seg = make_quintic_segment(from, to, total_cycles);
874 if(within_limits(seg, limits)) {
875 Profile1D p{};
876 if(p.add_segment(seg) == rt::ErrorCode::ok) {
878 }
879 }
880 }
881
882 // Reduction ramps (same as plan_time_optimal).
883 std::int64_t n0_cycles = 0;
884 State1D reduced = from;
885 if(from.acceleration != 0.0) {
886 const double n = std::ceil(std::fabs(from.acceleration) / limits.max_jerk);
887 if(!std::isfinite(n) || n > 1.0e15) {
889 }
890 n0_cycles = static_cast<std::int64_t>(n);
891 reduced.velocity = from.velocity + 0.5 * from.acceleration * n;
892 reduced.position = from.position + from.velocity * n +
893 from.acceleration * n * n / 3.0;
894 reduced.acceleration = 0.0;
895 }
896
897 Target1D eff = to;
898 double tramp_j = 0.0;
899 std::int64_t nt_cycles = 0;
900 if(to.acceleration != 0.0) {
901 const double n = std::ceil(std::fabs(to.acceleration) / limits.max_jerk);
902 if(!std::isfinite(n) || n > 1.0e15) {
904 }
905 const double dv = 0.5 * to.acceleration * n;
906 if(std::fabs(to.velocity - dv) <= limits.max_velocity) {
907 eff.velocity = to.velocity - dv;
908 eff.position = to.position - eff.velocity * n
909 - to.acceleration * n * n / 6.0;
910 eff.acceleration = 0.0;
911 tramp_j = to.acceleration / n;
912 nt_cycles = static_cast<std::int64_t>(n);
913 }
914 }
915
916 const std::int64_t available = total_cycles - n0_cycles - nt_cycles;
917 if(available < 1) {
919 }
920
921 // Candidate 1a: split via optimal midpoint — sample the optimal at
922 // cycle k, build two quintics (from→mid in k, mid→to in total-k).
923 // The longer second segment absorbs the extra time gently.
924 if(!below_tmin) {
925 const std::int64_t t_min = optimal.value().duration_cycles();
926 const std::int64_t max_k = t_min - 1 < total_cycles - 1
927 ? t_min - 1
928 : total_cycles - 1;
929 for(std::int64_t k = 1; k <= max_k; ++k) {
930 const State1D mid =
932 const Target1D mid_t{mid.position, mid.velocity, mid.acceleration};
933 const Segment1D seg1 = make_quintic_segment(from, mid_t, k);
934 const Segment1D seg2 = make_quintic_segment(mid, to, total_cycles - k);
935 if(within_limits(seg1, limits) && within_limits(seg2, limits)) {
936 Profile1D p{};
937 if(p.add_segment(seg1) == rt::ErrorCode::ok &&
938 p.add_segment(seg2) == rt::ErrorCode::ok) {
940 }
941 }
942 }
943 }
944
945 // Candidate 1c: idle insertion at zero-velocity points in the optimal.
946 // Velocity-reversal profiles cross v=0 with a=0 at segment boundaries;
947 // inserting zero-jerk idle cycles there preserves all subsequent segments
948 // and extends the total duration by the inserted amount.
949 if(!below_tmin) {
950 const std::int64_t extra =
951 total_cycles - optimal.value().duration_cycles();
952 if(extra > 0 &&
953 optimal.value().segment_count() < Profile1D::MaxSegments) {
954 for(std::size_t si = 0;
955 si < optimal.value().segment_count(); ++si) {
956 const State1D &es = optimal.value().segment(si).finish;
957 if(std::fabs(es.velocity) > 1e-12 ||
958 std::fabs(es.acceleration) > 1e-12) {
959 continue;
960 }
961 Profile1D p{};
962 bool ok = true;
963 for(std::size_t j = 0; j <= si && ok; ++j) {
964 ok = (p.add_segment(optimal.value().segment(j)) ==
966 }
967 if(ok) {
968 State1D idle = es;
970 p, idle, 0.0,
971 static_cast<double>(extra)) ==
973 }
974 for(std::size_t j = si + 1;
975 j < optimal.value().segment_count() && ok; ++j) {
976 ok = (p.add_segment(optimal.value().segment(j)) ==
978 }
979 if(ok && p.duration_cycles() == total_cycles) {
981 }
982 }
983 }
984 }
985
986 // Candidate 1b: zeroing ramp + inner quintic + targeting ramp.
987 // Covers the case where available cycles are too few for entry/exit ramps
988 // but sufficient for a single quintic spanning the reduced→effective gap.
989 {
990 const auto try_inner_quintic = [&]() -> rt::Result<Profile1D> {
991 Profile1D p{};
992 State1D state = reduced;
993 if(from.acceleration != 0.0) {
994 state = from;
995 const double zero_jerk = -from.acceleration /
996 static_cast<double>(n0_cycles);
997 const rt::ErrorCode e =
998 detail::push_cubic_phase(p, state, zero_jerk,
999 static_cast<double>(n0_cycles));
1000 if(e != rt::ErrorCode::ok) {
1002 }
1003 state.acceleration = 0.0;
1004 }
1005 const Segment1D inner =
1006 make_quintic_segment(state, eff, available);
1007 if(!within_limits(inner, limits)) {
1010 }
1011 const rt::ErrorCode e1 = p.add_segment(inner);
1012 if(e1 != rt::ErrorCode::ok) {
1014 }
1015 if(nt_cycles > 0) {
1016 State1D s = sample(p,
1017 rt::CycleTick::from_cycles(p.duration_cycles()));
1018 s.acceleration = 0.0;
1019 const rt::ErrorCode e2 =
1020 detail::push_cubic_phase(p, s, tramp_j,
1021 static_cast<double>(nt_cycles));
1022 if(e2 != rt::ErrorCode::ok) {
1024 }
1025 }
1026 if(p.duration_cycles() != total_cycles) {
1029 }
1031 };
1032 const rt::Result<Profile1D> inner = try_inner_quintic();
1033 if(inner) {
1034 return inner;
1035 }
1036 }
1037
1038 // Candidate 1b': zeroing ramp + quintic directly to target (no targeting
1039 // ramp). When nt_cycles > 0 the standard 1b leaves too few cycles for
1040 // the inner quintic; here we give all remaining cycles to a quintic that
1041 // handles the acceleration transition itself.
1042 if(nt_cycles > 0) {
1043 Profile1D p{};
1044 State1D state = from;
1045 bool ok = true;
1046 if(n0_cycles > 0) {
1047 const double zero_jerk = -from.acceleration /
1048 static_cast<double>(n0_cycles);
1049 ok = (detail::push_cubic_phase(p, state, zero_jerk,
1050 static_cast<double>(n0_cycles)) ==
1052 state.acceleration = 0.0;
1053 }
1054 if(ok) {
1055 const std::int64_t inner_cycles = total_cycles - n0_cycles;
1056 if(inner_cycles >= 1) {
1057 const Segment1D seg =
1058 make_quintic_segment(state, to, inner_cycles);
1059 if(within_limits(seg, limits)) {
1060 ok = (p.add_segment(seg) == rt::ErrorCode::ok);
1061 if(ok && p.duration_cycles() == total_cycles) {
1063 }
1064 }
1065 }
1066 }
1067 }
1068
1069 // Candidate 1d: 3-cubic solve. Three constant-jerk phases whose jerks
1070 // are determined by a linear solve (acceleration, velocity, position
1071 // end-state constraints). Covers short-profile cases where quintic
1072 // segments oscillate too aggressively.
1073 if(total_cycles <= 20) {
1074 for(std::int64_t d1 = 1; d1 <= total_cycles - 2; ++d1) {
1075 for(std::int64_t d2 = 1; d2 <= total_cycles - d1 - 1; ++d2) {
1076 const std::int64_t d3 = total_cycles - d1 - d2;
1078 from.acceleration, from.velocity, from.position,
1079 to.acceleration, to.velocity, to.position,
1080 static_cast<double>(d1), static_cast<double>(d2),
1081 static_cast<double>(d3));
1082 if(!sol.valid) continue;
1083 if(std::fabs(sol.j1) > limits.max_jerk + 1e-12 ||
1084 std::fabs(sol.j2) > limits.max_jerk + 1e-12 ||
1085 std::fabs(sol.j3) > limits.max_jerk + 1e-12) {
1086 continue;
1087 }
1088 double a = from.acceleration, v = from.velocity;
1089 const double jerks[3] = {sol.j1, sol.j2, sol.j3};
1090 const std::int64_t durs[3] = {d1, d2, d3};
1091 bool ok = true;
1092 for(int ph = 0; ph < 3 && ok; ++ph) {
1094 a, v, jerks[ph], static_cast<double>(durs[ph]),
1095 limits);
1096 v += a * static_cast<double>(durs[ph])
1097 + jerks[ph] * static_cast<double>(durs[ph])
1098 * static_cast<double>(durs[ph]) * 0.5;
1099 a += jerks[ph] * static_cast<double>(durs[ph]);
1100 }
1101 if(!ok) continue;
1102 Profile1D p{};
1103 State1D state = from;
1104 ok = true;
1105 for(int ph = 0; ph < 3 && ok; ++ph) {
1107 p, state, jerks[ph],
1108 static_cast<double>(durs[ph])) ==
1110 }
1111 if(ok && p.duration_cycles() == total_cycles) {
1113 }
1114 }
1115 }
1116 }
1117
1118 // Candidate 1e: 4-cubic with sweep. First phase jerk is swept over
1119 // [-j_max, j_max]; the remaining three are solved via 3-cubic. Handles
1120 // cases where 3 phases cannot simultaneously satisfy jerk and
1121 // acceleration limits.
1122 if(total_cycles <= 20 && total_cycles >= 4) {
1123 for(std::int64_t d1 = 1; d1 <= total_cycles - 3 && d1 <= 3; ++d1) {
1124 for(std::int64_t d2 = 1; d2 <= total_cycles - d1 - 2; ++d2) {
1125 for(std::int64_t d3 = 1;
1126 d3 <= total_cycles - d1 - d2 - 1; ++d3) {
1127 const std::int64_t d4 = total_cycles - d1 - d2 - d3;
1128 if(d4 < 1) continue;
1129 const double dd1 = static_cast<double>(d1);
1130 for(int trial = -250; trial <= 250; ++trial) {
1131 const double j1 = trial * 0.01;
1132 if(std::fabs(j1) > limits.max_jerk) continue;
1133 const double a1 = from.acceleration + j1 * dd1;
1134 const double v1 = from.velocity
1135 + from.acceleration * dd1 + j1 * dd1 * dd1 * 0.5;
1136 const double p1 = from.position
1137 + from.velocity * dd1
1138 + from.acceleration * dd1 * dd1 * 0.5
1139 + j1 * dd1 * dd1 * dd1 / 6.0;
1140 const detail::CubicSolution sol =
1142 a1, v1, p1,
1143 to.acceleration, to.velocity, to.position,
1144 static_cast<double>(d2),
1145 static_cast<double>(d3),
1146 static_cast<double>(d4));
1147 if(!sol.valid) continue;
1148 if(std::fabs(sol.j1) > limits.max_jerk + 1e-12 ||
1149 std::fabs(sol.j2) > limits.max_jerk + 1e-12 ||
1150 std::fabs(sol.j3) > limits.max_jerk + 1e-12) {
1151 continue;
1152 }
1153 double a = from.acceleration, v = from.velocity;
1154 const double jerks[4] = {j1, sol.j1, sol.j2, sol.j3};
1155 const std::int64_t durs[4] = {d1, d2, d3, d4};
1156 bool ok = true;
1157 for(int ph = 0; ph < 4 && ok; ++ph) {
1159 a, v, jerks[ph],
1160 static_cast<double>(durs[ph]), limits);
1161 const double dd = static_cast<double>(durs[ph]);
1162 v += a * dd + jerks[ph] * dd * dd * 0.5;
1163 a += jerks[ph] * dd;
1164 }
1165 if(!ok) continue;
1166 Profile1D p{};
1167 State1D state = from;
1168 ok = true;
1169 for(int ph = 0; ph < 4 && ok; ++ph) {
1171 p, state, jerks[ph],
1172 static_cast<double>(durs[ph])) ==
1174 }
1175 if(ok && p.duration_cycles() == total_cycles) {
1177 }
1178 }
1179 }
1180 }
1181 }
1182 }
1183
1184 // Candidate 1f: quintic-cubic hybrid. Backward-propagate a constant-jerk
1185 // tail from the target to obtain a midpoint; build a quintic from the
1186 // starting state to that midpoint. The quintic handles the smooth bulk of
1187 // the motion while the short cubic tail delivers the final acceleration.
1188 if(total_cycles <= 20) {
1189 for(std::int64_t k = 1; k < total_cycles; ++k) {
1190 const std::int64_t tail = total_cycles - k;
1191 const double dd = static_cast<double>(tail);
1192 for(int trial = -250; trial <= 250; ++trial) {
1193 const double jt = trial * 0.01;
1194 if(std::fabs(jt) > limits.max_jerk) continue;
1195 const double a_mid = to.acceleration - jt * dd;
1196 const double v_mid = to.velocity - a_mid * dd
1197 - jt * dd * dd * 0.5;
1198 const double p_mid = to.position - v_mid * dd
1199 - a_mid * dd * dd * 0.5
1200 - jt * dd * dd * dd / 6.0;
1202 a_mid, v_mid, jt, dd, limits)) {
1203 continue;
1204 }
1205 const Target1D mt{p_mid, v_mid, a_mid};
1206 const Segment1D head = make_quintic_segment(from, mt, k);
1207 if(!within_limits(head, limits)) {
1208 continue;
1209 }
1210 Profile1D p{};
1211 if(p.add_segment(head) != rt::ErrorCode::ok) continue;
1212 State1D state{p_mid, v_mid, a_mid};
1213 if(detail::push_cubic_phase(p, state, jt, dd) !=
1215 continue;
1216 }
1217 if(p.duration_cycles() == total_cycles) {
1219 }
1220 }
1221 }
1222 }
1223
1224 if(below_tmin) {
1226 }
1227
1228 const double distance = eff.position - reduced.position;
1229 const double vt = eff.velocity;
1230
1231 // For a given cruise velocity vc, compute the total distance covered in
1232 // 'available' cycles using exact-rounded ramps + integer cruise + minimal
1233 // quintic correction.
1234 const auto try_build = [&](double vc) -> rt::Result<Profile1D> {
1235 Profile1D profile{};
1236 State1D state = reduced;
1237
1238 // Zeroing ramp.
1239 if(from.acceleration != 0.0) {
1240 state = from;
1241 const double zero_jerk = -from.acceleration /
1242 static_cast<double>(n0_cycles);
1243 const rt::ErrorCode e =
1244 detail::push_cubic_phase(profile, state, zero_jerk,
1245 static_cast<double>(n0_cycles));
1246 if(e != rt::ErrorCode::ok) {
1248 }
1249 state.acceleration = 0.0;
1250 }
1251
1252 // Entry ramp v0 → vc (exact rounding).
1254 profile, state, vc, limits, detail::RampRounding::exact);
1255 if(built != rt::ErrorCode::ok) {
1256 return rt::Result<Profile1D>::failure(built);
1257 }
1258 const double pos_after_entry = state.position;
1259 const std::int64_t cycles_after_entry = profile.duration_cycles();
1260
1261 // Measure exit ramp dimensions without building (probe).
1262 Profile1D exit_probe{};
1263 State1D exit_state{0.0, vc, 0.0};
1265 exit_probe, exit_state, vt, limits, detail::RampRounding::exact);
1266 if(built != rt::ErrorCode::ok) {
1267 return rt::Result<Profile1D>::failure(built);
1268 }
1269 const std::int64_t exit_ramp_cycles = exit_probe.duration_cycles();
1270 const double exit_ramp_dp = exit_state.position;
1271
1272 const std::int64_t remaining =
1273 available - (cycles_after_entry - n0_cycles) - exit_ramp_cycles;
1274 if(remaining < 1) {
1276 }
1277
1278 // Ideal cruise cycles to cover the distance exactly.
1279 std::int64_t n_cruise_start = 0;
1280 if(std::fabs(vc) > 1e-15) {
1281 const double ideal =
1282 (distance - (pos_after_entry - reduced.position) - exit_ramp_dp) / vc;
1283 if(!std::isfinite(ideal)) {
1285 }
1286 if(ideal >= static_cast<double>(remaining - 1)) {
1287 n_cruise_start = remaining - 1;
1288 } else if(ideal <= 0.0) {
1289 n_cruise_start = 0;
1290 } else {
1291 n_cruise_start = static_cast<std::int64_t>(std::floor(ideal));
1292 }
1293 }
1294
1295 // Try reducing cruise to give the quintic more room for the residue.
1296 bool cruise_ok = false;
1297 for(std::int64_t n_cruise = n_cruise_start; n_cruise >= 0; --n_cruise) {
1298 const std::int64_t n_quintic = remaining - n_cruise;
1299 if(n_quintic < 1) continue;
1300
1301 Profile1D inner_profile = profile;
1302 State1D inner_state = state;
1303
1304 if(n_cruise > 0) {
1306 inner_profile, inner_state, 0.0,
1307 static_cast<double>(n_cruise));
1308 if(built != rt::ErrorCode::ok) continue;
1309 }
1310
1312 inner_profile, inner_state, vt, limits,
1314 if(built != rt::ErrorCode::ok) continue;
1315
1316 const Segment1D correction =
1317 make_quintic_segment(inner_state, eff, n_quintic);
1318 if(!within_limits(correction, limits)) continue;
1319 built = inner_profile.add_segment(correction);
1320 if(built != rt::ErrorCode::ok) continue;
1321
1322 profile = inner_profile;
1323 state = inner_state;
1324 cruise_ok = true;
1325 break;
1326 }
1327 if(!cruise_ok) {
1329 }
1330
1331 // Targeting ramp.
1332 if(nt_cycles > 0) {
1333 State1D s = sample(profile,
1335 s.acceleration = 0.0;
1337 profile, s, tramp_j, static_cast<double>(nt_cycles));
1338 if(built != rt::ErrorCode::ok) {
1339 return rt::Result<Profile1D>::failure(built);
1340 }
1341 }
1342
1343 if(profile.duration_cycles() != total_cycles) {
1345 }
1346 return rt::Result<Profile1D>::success(profile);
1347 };
1348
1349 // Candidate 2: bisect cruise velocity in [0, direction * v_max].
1350 // The distance D(vc) at maximum cruise is continuous (piecewise) and
1351 // monotone in the sign-correct direction: higher |vc| → more distance
1352 // per unit time.
1353 const double direction = distance >= 0.0 ? 1.0 : -1.0;
1354 {
1357
1358 double lo = 0.0;
1359 double hi = direction * limits.max_velocity;
1360
1361 for(int iter = 0; iter < 96; ++iter) {
1362 const double mid = 0.5 * (lo + hi);
1363 const rt::Result<Profile1D> candidate = try_build(mid);
1364 if(candidate) {
1365 best = candidate;
1366 hi = mid;
1367 } else {
1368 lo = mid;
1369 }
1370 }
1371 if(best) {
1372 return best;
1373 }
1374
1375 // Also test vc = 0 (pure ramps + quintic correction, no cruise).
1376 const rt::Result<Profile1D> at_zero = try_build(0.0);
1377 if(at_zero) {
1378 return at_zero;
1379 }
1380 }
1381
1382 // Candidate 3: negative direction (overshoot-and-return).
1383 {
1384 double lo = 0.0;
1385 double hi = -direction * limits.max_velocity;
1386
1387 for(int iter = 0; iter < 64; ++iter) {
1388 const double mid = 0.5 * (lo + hi);
1389 const rt::Result<Profile1D> candidate = try_build(mid);
1390 if(candidate) {
1391 return candidate;
1392 }
1393 lo = mid;
1394 }
1395 }
1396
1398}
1399
1400} // namespace plcopen::core::otg
rt::ErrorCode add_segment(const Segment1D &segment)
std::size_t segment_count() const
std::int64_t duration_cycles() const
static constexpr std::size_t MaxSegments
static constexpr CycleTick from_cycles(std::int64_t cycles)
定义 cycle.h:42
constexpr const T & value() const
定义 error.h:49
constexpr ErrorCode error() const
定义 error.h:44
static constexpr Result success(const T &value)
定义 error.h:24
static constexpr Result failure(ErrorCode error)
定义 error.h:29
double ramp_chain_distance(double v0, double vc, double vt, const Limits1D &limits)
rt::ErrorCode push_quintic_correction(Profile1D &profile, State1D state, Target1D to, const Limits1D &limits)
bool check_cubic_phase_limits(double a0, double v0, double jerk, double dur, const Limits1D &limits)
rt::ErrorCode push_ramp_with_crossing(Profile1D &profile, State1D &state, double vb, const Limits1D &limits, RampRounding rounding)
rt::Result< std::int64_t > min_feasible_quintic_cycles(State1D from, Target1D to, const Limits1D &limits)
double ramp_bound(double va, double vb, const Limits1D &limits)
rt::Result< Profile1D > build_multiphase(State1D from, Target1D to, const Limits1D &limits, double cruise_velocity, double cruise_duration, RampRounding rounding)
CubicSolution solve_3cubic(double a0, double v0, double p0, double at, double vt, double pt, double d1, double d2, double d3)
rt::ErrorCode push_cubic_phase(Profile1D &profile, State1D &state, double jerk, double continuous_duration, bool force_finish_derivatives=false, double finish_velocity=0.0, double finish_acceleration=0.0)
rt::Result< Profile1D > build_refined_cruise(State1D from, Target1D to, const Limits1D &limits, double cruise_hint)
RampTiming ramp_between(double va, double vb, const Limits1D &limits)
rt::ErrorCode push_ramp(Profile1D &profile, State1D &state, double vb, const Limits1D &limits, RampRounding rounding, bool force_finish_derivatives=false)
RampTiming ramp_timing(double va, double vb, double bound, double jerk)
rt::Result< Profile1D > plan(State1D from, Target1D to, Limits1D limits)
rt::Result< Profile1D > plan_time_optimal(State1D from, Target1D to, Limits1D limits)
rt::Result< Profile1D > solve_fixed_time(State1D from, Target1D to, Limits1D limits, std::int64_t total_cycles)
bool is_finite(State1D state)
Segment1D make_quintic_segment(State1D from, Target1D to, std::int64_t cycles)
State1D sample_segment(const Segment1D &segment, std::int64_t cycle)
constexpr std::int64_t MaxPlanCycles
bool within_limits(const Segment1D &segment, Limits1D limits)
State1D sample(const Profile1D &profile, rt::CycleTick tick)