Skip to content

Writing a motion planner

A machine that follows a contour (a plotter, a dispenser, a laser, a mill) gets a list of points and a speed, and shall run through the points without stopping at each of them. The program that makes this possible is a motion planner (1). The library does not contain one, but it runs what a planner calculates: GroupPath takes the moves of a path ahead and joins them without a stop.

  1. Motion planner

    A program that turns a list of coordinates and a speed along the path, the feed rate, into moves for the motors. It looks ahead over the coming moves, decides how fast each point can be passed, and gives every move its speeds.

This chapter shows how a planner is built on the library, in two steps. The example advanced/MiniPlanner is a complete planner in one sketch: three short functions. The example advanced/PathPlanner has a larger planner, a header of about 300 lines, that takes the limits of each motor and any machine. All of it is example code, made to be read, copied and changed.

A planner in one sketch

The example advanced/MiniPlanner draws six figures on an x-y table: an ellipse, a figure eight, a Lissajous figure, a rose, a spirograph figure and a star. The table does not stop at the points of a figure. The video shows the sketch on a CoreXY table at up to 600 mm/s, with the path of the running figure, its speed, and the line of the sketch that calculates it:



The example on its table, in real time (on YouTube).
/*==========================================================================
 * MiniPlanner: a motion planner in one sketch
 *
 * An x-y table draws curved figures without stopping at their points.
 * The planner is the function plan(), with speedAt() and reachable().
 * The hardware is in Machine.h and Machine.cpp.
 *==========================================================================*/

#include "Machine.h"
using namespace TeensyStep;

advanced::GroupPath path(machine); // takes the moves of the motors ahead: no stop between them

// A figure is a list of points in mm. speed is how fast the table passes the point.
struct Point
{
    float x, y, speed;
};
const int maxPoints = 2500;
Point points[maxPoints];
int count = 0; // points of the figure
int given = 0; // points that were given to the library

const int figures        = 6;
const int turns[figures] = {3, 3, 1, 1, 3, 1}; // how often the angle t of a figure goes around
int figure               = 0;

float distance(const Point& a, const Point& b) { return hypotf(b.x - a.x, b.y - a.y); }

void addPoint(float px, float py)
{
    Point p = {px, py, 0};
    if (count > 0 && distance(points[count - 1], p) < 0.1f) return; // the same point again
    if (count < maxPoints) points[count++] = p;
}

void makePoints()
{
    count = 0;
    addPoint(0, 0); // where the table stands
    for (int i = 0; i <= 720 * turns[figure]; i++) // 720 points for each turn
    {
        float t = i * 2 * PI / 720;
        if (figure == 0) addPoint(sizeX * cosf(t), sizeY * sinf(t));                             // ellipse, three laps
        if (figure == 1) addPoint(sizeX * sinf(2 * t), sizeY * sinf(t));                         // figure eight, three laps
        if (figure == 2) addPoint(sizeX * sinf(5 * t), sizeY * sinf(4 * t));                     // Lissajous figure
        if (figure == 3) addPoint(sizeX * sinf(4 * t) * cosf(t), sizeY * sinf(4 * t) * sinf(t)); // rose with eight petals
        if (figure == 4) addPoint(sizeX * (0.6f * cosf(t) + 0.4f * cosf(7 * t / 3)),             // spirograph: a small circle
                                  sizeY * (0.6f * sinf(t) - 0.4f * sinf(7 * t / 3)));            // rolls in a large one
        if (figure == 5 && i <= 5) addPoint(sizeX * sinf(i * 4 * PI / 5), sizeY * cosf(i * 4 * PI / 5)); // star
    }
    addPoint(0, 0); // and back
}

//-------------------------------------------------------------------------
// The planner

// The speed after `way` mm with the acceleration, starting at `speed` (or before, when braking to it)
float reachable(float speed, float way) { return sqrtf(speed * speed + 2 * acceleration * way); }

// How fast may the table pass a point? It changes its direction there. `turn` is that change: 0 on a
// straight line, 1.41 for a right angle, 2 for a reversal. The velocity changes by speed * turn.
float speedAt(const Point& before, const Point& here, const Point& after)
{
    float in = distance(before, here), out = distance(here, after);
    float turn = hypotf((after.x - here.x) / out - (here.x - before.x) / in, (after.y - here.y) / out - (here.y - before.y) / in);
    if (turn < 0.0001f) return maxSpeed;
    float corner = cornerJump / turn;                           // a single corner: the jump the motors take
    float bend   = sqrtf(acceleration * (in + out) / 2 / turn); // a bend of many points: the acceleration sideways
    return fminf(maxSpeed, fminf(corner, bend));
}

void plan()
{
    points[0].speed = points[count - 1].speed = 0; // start and end at standstill
    for (int i = 1; i < count - 1; i++) points[i].speed = speedAt(points[i - 1], points[i], points[i + 1]);

    for (int i = count - 2; i > 0; i--) // backwards: slow enough to brake for what comes
        points[i].speed = fminf(points[i].speed, reachable(points[i + 1].speed, distance(points[i], points[i + 1])));
    for (int i = 1; i < count - 1; i++) // forwards: not faster than the table gets there
        points[i].speed = fminf(points[i].speed, reachable(points[i - 1].speed, distance(points[i - 1], points[i])));
}

//-------------------------------------------------------------------------

// Gives the library the next points, as many as it takes. One move runs, one waits.
void giveMoves()
{
    while (given < count && path.room() > 0)
    {
        advanced::PathMove move;
        move.length        = distance(points[given - 1], points[given]); // in mm: so the speeds are in mm/s
        move.speed         = maxSpeed;
        move.speedAtTarget = points[given].speed;
        move.acceleration  = acceleration;

        int32_t steps[2];
        toSteps(points[given].x, points[given].y, steps);
        path.add(steps, 2, move);
        given++;

        if (given == count / turns[figure]) path.overrideSpeed(1); // on at full speed after the first turn
    }
}

void startFigure()
{
    makePoints();
    plan();
    given = 1; // point 0 is where the table stands

    path.overrideSpeed(turns[figure] > 1 ? 0.2f : 1); // a figure of several turns starts at a fifth of the planned speeds
}

void waitForStart()
{
    Serial.println("Put the table to its centre, then send a character to start");
    Serial.clear();
    while (Serial.read() < 0) {}
}

void setup()
{
    setupMachine();
    waitForStart();
    startFigure();
}

void loop()
{
    giveMoves(); // the next move has to be there before the one that runs arrives

    if (given == count && !machine.isMoving()) // the figure is done
    {
        delay(400);
        figure = (figure + 1) % figures;
        if (figure == 0) waitForStart(); // all figures are drawn
        startFigure();
    }
}

The sketch has three parts: the points of a figure, the planner, and the function that gives the moves to the library. It contains no pins and no steps; the hardware is in two files of its own, see The machine.

The points

makePoints() fills the list points with the figure: the position of the table at the start, the points of a formula (720 for each turn of its angle; some figures take three turns), and the start position again. All positions are in mm. A curve is a row of short straight pieces, since a group of the library moves on straight lines.

The speed at each point

The planner decides one thing: how fast the table passes each point. speedAt() looks at a point and its two neighbours. Where the direction changes, the velocity of the table changes at once, by the speed times turn (1). Two limits follow from it:

  1. turn

    The size of the change of direction at a point: the distance between the directions before and after it, each taken as a line of the length 1. It is 0 on a straight line, 1.41 at a right angle and 2 where the path reverses.

  2. A single corner. The motors take a change of velocity without a ramp only up to a certain size, cornerJump. With 100 mm/s, a right angle is passed at 100 / 1.41 = 71 mm/s.

  3. A bend of many points. Every point of a bend changes the velocity a little, and all of them together are an acceleration sideways. The sketch keeps it within acceleration. For a circle this gives the known relation speed² = acceleration × radius: a circle of 25 mm radius is run at 296 mm/s with 3,500 mm/s².

The lower of the two limits is the speed at the point, and never more than maxSpeed.

Looking ahead

A speed that a point allows is of no use if the table cannot brake in time for the next tight bend or for the end of the figure. plan() therefore goes over the points twice, with reachable(), the speed that the acceleration gives over the way between two points:

  1. Backward, from the end. The figure ends at standstill. Each point may be at most as fast as the table can brake from, down to the speed of the point after it.
  2. Forward, from the start. The figure starts at standstill. Each point may be at most as fast as the table gets on the way from the point before it.

After these two loops every point has a speed that the table can reach and can brake from.

Giving the moves

giveMoves() hands the points to the GroupPath of the two motors, one move for each point. A move gets the length of its way in mm; with it, the library takes all speeds of the move in mm/s and converts them for the motors. The speed at the target is the speed the planner has calculated for the point. The ramps within a move are made by the library.

One move runs in the library and one waits, and room() tells whether the next one can be given. loop() calls giveMoves() all the time, so the next move is there before the one that runs arrives.

A path that is planned can be run slower at every point, so the planner has nothing to calculate for it: a figure of several turns starts with overrideSpeed(0.2f), at a fifth of its speeds, and goes on at the planned speeds after its first turn, without a stop. See Override and hold.

The machine

Everything that depends on the hardware is in Machine.h and Machine.cpp. The example is written for a CoreXY table driven by a Teensy MicroMod on the driver board mmStep; for another machine these two files are changed, and the sketch stays as it is.

  • The values of the table in mm: its highest speed, its acceleration, cornerJump, and the room the figures may use.
  • toSteps() calculates the positions of the motors for a point in mm. On the CoreXY table of the example motor A makes the sum of x and y and motor B their difference. With one motor for each axis it is one multiplication for each motor.
  • The limits of the motors follow from those of the table. On a CoreXY table a motor is fastest on a diagonal, 1.41 times as fast as the table; motorFactor holds this number.
  • The drivers. Their enable inputs are not on pins of the processor but on a port expander. setEnable() with a function lets the library switch them on before a move and off after it, see An enable signal that is not on a pin.
Machine.h and Machine.cpp
// The machine of the example MiniPlanner: everything that depends on the hardware.
//
// A CoreXY x-y table, driven by a Teensy MicroMod on the driver board mmStep (github.com/luni64/mmStep).
// For another machine, change the values here and the functions in Machine.cpp; the planner in the sketch
// stays as it is.
#pragma once

#include "TeensyStepAdvanced.h"

// What the table can do, in mm
const float maxSpeed     = 600;  // mm/s along the path
const float acceleration = 3500; // mm/s^2 along the path, and as much sideways in a bend
const float cornerJump   = 100;  // mm/s: how much the velocity may change at a point without a ramp

// The figures stay within this distance from the centre, where the table stands at the start
const float sizeX = 25, sizeY = 55; // mm

extern TeensyStep::StepperGroup machine; // the motors of the table

void setupMachine();                             // drivers, limits of the motors
void toSteps(float x, float y, int32_t steps[2]); // the positions of the motors for a point in mm
#include "Machine.h"
#include "Arduino.h"
#include "Wire.h"
using namespace TeensyStep;

//-------------------------------------------------------------------------
// The driver board mmStep
//
// STEP and DIR of its four drivers are pins of the Teensy MicroMod. Enable and step mode of the drivers are
// on a port expander (MCP23017, I2C address 0x20): port A, bits 0 to 3 for driver 3 (EN, M0, M1, M2) and
// bits 4 to 7 for driver 4; port B in the same way for the drivers 1 and 2. EN is active low.

static const uint8_t IODIRA = 0x00, IODIRB = 0x01, GPIOA = 0x12, GPIOB = 0x13; // registers of the expander

static void writeExpander(uint8_t reg, uint8_t value)
{
    Wire.beginTransmission(0x20);
    Wire.write(reg);
    Wire.write(value);
    Wire.endTransmission();
}

static void setupMMBoard()
{
    Wire.begin();
    writeExpander(GPIOA, 0x11); // EN high: all four drivers are off
    writeExpander(GPIOB, 0x11);
    writeExpander(IODIRA, 0x00); // then all pins of the expander become outputs
    writeExpander(IODIRB, 0x00);
}

// Switches the drivers 3 and 4 on or off, with 1/16 step (M2 high)
static void enableDrivers(bool on)
{
    writeExpander(GPIOA, on ? 0x88 : 0x99);
}

//-------------------------------------------------------------------------
// The machine: a CoreXY table on the drivers 3 and 4

static Stepper motorA(9, 26); // STEP, DIR
static Stepper motorB(45, 6);
StepperGroup machine{motorA, motorB};

static const float stepsPerMm = 3200 / 24.0f; // 1/16 step; one turn of the pulley moves the belt 24 mm

// How much faster than the table a motor can be. On a CoreXY a motor is fastest when the table moves
// diagonally: 1.41 times the speed of the table. With one motor for each axis the factor is 1.
static const float motorFactor = 1.41f;

void setupMachine()
{
    setupMMBoard();
    enableDrivers(false);

    for (Stepper* motor : {&motorA, &motorB})
    {
        // The library calls enableDrivers(): on 200 ms before a move, off 2 s after it
        motor->setEnable(enableDrivers, 200, 2000);

        // The limits of the motors follow from those of the table. They are 10 % above what the planner
        // asks for, since the points are rounded to steps.
        motor->setMaxSpeed(1.1f * motorFactor * maxSpeed * stepsPerMm);
        motor->setAcceleration(1.1f * motorFactor * acceleration * stepsPerMm);
    }
}

// CoreXY: both motors turn for a move along one axis
void toSteps(float x, float y, int32_t steps[2])
{
    steps[0] = lroundf((x + y) * stepsPerMm);
    steps[1] = lroundf((x - y) * stepsPerMm);
}

Find the values of the table by trial

The acceleration and the jump a machine follows depend on its motors, drivers and load. Start with low values, and raise them only as far as the machine draws the figures without losing steps.

What this planner leaves out

The planner of the sketch knows the table, not the motors: its limits are speeds and accelerations of the path, and one factor stands for the kinematics. That is enough for a machine whose motors are alike. The planner of the following sections takes the limits of each motor and the kinematics as data, and uses what the motors can do in each direction.

A planner with limits for each motor

The example advanced/PathPlanner uses the planner of Planner.h, a header in the folder of the sketch.

/*==========================================================================
 * PathPlanner: an x-y table runs a path without stopping at its points
 *
 * The planner in Planner.h, a part of this example, decides how fast each
 * point of the path (in mm) can be passed. See the manual for how it works.
 *==========================================================================*/

#include "Planner.h" // includes TeensyStepAdvanced.h
using namespace TeensyStep;

Stepper x(2, 3);
Stepper y(4, 5);
StepperGroup xy{x, y};

// What the motors can do: maximum speed (steps/s), acceleration (steps/s^2), and the largest
// change of speed without a ramp (steps/s)
const planner::MotorLimits limits[2] = {
    {20'000, 50'000, 500}, // x
    {20'000, 50'000, 500}, // y
};

// One motor for each axis, 100 steps per mm
const planner::Kinematics table = planner::Kinematics::plain({100, 100});

planner::Segment segments[100]; // room for the path
planner::Path path(segments, 100, table, limits);
planner::PathRunner runner(xy);

void makePath()
{
    const float feed = 80; // mm/s

    path.start({0, 0}); // where the motors stand
    path.add({60, 0}, feed); // a rectangle
    path.add({60, 40}, feed);
    path.add({0, 40}, feed);
    path.add({0, 0}, feed);

    path.add({45, 20}, feed); // to a circle of 15 mm around (30, 20)
    for (int i = 1; i <= 72; i++)
    {
        float angle = i * 2 * PI / 72;
        path.add({30 + 15 * cosf(angle), 20 + 15 * sinf(angle)}, feed);
    }
    path.add({0, 0}, feed); // and back

    path.plan(); // calculates the speeds
}

void setup()
{
    x.setMaxSpeed(limits[0].maxSpeed).setAcceleration(limits[0].acceleration); // the same limits as the planner has
    y.setMaxSpeed(limits[1].maxSpeed).setAcceleration(limits[1].acceleration);

    makePath();
    runner.start(path);
}

void loop()
{
    runner.giveMoves(); // the next move has to be there before the one that runs arrives

    if (!runner.isRunning()) // the path is done: again after a second
    {
        delay(1000);
        runner.start(path);
    }
}

The sketch describes the machine (two motors, their limits, 100 steps per mm), lists the points of the path in mm, and lets the planner calculate the speeds with plan(). runner.giveMoves() in loop() hands the moves to the library.

The path of the example, and the speed along the path over the time
The path of the example (left) and the speed along it (right), as the library runs it: nearly a stop at each corner of the rectangle, 55 mm/s and more on the circle. The curves of this chapter are the output of the example's planner and the library, not drawings.

What the planner does and what the library does

The planner (Planner.h) The library (GroupPath)
converts the points from mm to steps of the motors moves the motors on a straight line to these steps
decides how fast each point can be passed passes the point at that speed and goes on with the next move
gives each move its highest speed and its acceleration, in mm converts them for the motors and makes the ramps
hands the moves over in time keeps one move waiting behind the one that runs

The planner works in four steps, which the following sections describe: from the points to the motors, the limits of each segment (1), the speed at each junction (2), and the look-ahead over the whole path.

  1. Segment

    The straight piece of the path between two points. Each segment becomes one move of the group.

  2. Junction

    The point where two segments meet.

From the points to the motors

The points of a path are given in the coordinates of the machine, here x and y in mm. The library moves motors, in steps. How the positions of the motors follow from the coordinates is the kinematics (1) of the machine. The example describes it as one factor for each pair of motor and axis:

  1. Kinematics

    The relation between the coordinates of a machine and the positions of its motors. On an x-y table with one motor for each axis it is the number of steps per mm. On other machines a motor moves several axes at once.

// one motor for each axis: 100 steps per mm in x, 100 in y
planner::Kinematics table = planner::Kinematics::plain({100, 100});

// CoreXY: motor A = x + y, motor B = x - y
planner::Kinematics coreXY = planner::Kinematics::coreXY(100, 100);

This form covers every machine whose motors follow from the axes by multiplication and addition. On such a machine a straight line of the axes is a straight line of the motors, which is what a group of the library moves on. A machine without this property (a robot arm, a delta printer) needs its lines cut into short segments by the planner.

For every point, the planner calculates the targets of the motors from the point itself and rounds them to steps (Path::add()). It does not add up the ways of the segments, so the rounding errors do not add up along the path either.

The planner also keeps the length of each segment in mm. This is what the library needs to take the speeds of a move in mm/s, see A move and its speeds: the planner never converts a speed to steps of a motor.

The limits of a segment

Along a segment every motor runs at a fixed share of the speed of the path: the steps it makes per mm of the path. A motor of the example that makes 100 steps per mm of a segment in x runs at 8,000 steps/s when the path runs at 80 mm/s. On a diagonal at 45° both motors make 70.7 steps per mm of the path.

From these shares the planner derives two limits for each segment (Path::add()):

  • The highest speed is the feed rate, or less if a motor would exceed its maximum speed.
  • The acceleration along the path is as high as the motors allow in this direction. With motors of 50,000 steps/s², the example accelerates at 500 mm/s² along x and at 707 mm/s² on a diagonal, where both motors work.

The speed at a junction

Where two segments meet, the direction of the path changes at once. The speed of every motor jumps: at a corner of 90° from x to y, the x motor goes from the full speed of the path to standstill, and the y motor from standstill to the full speed.

A stepper motor follows such a jump without a ramp only up to a certain size, about its pull-in speed. The planner takes this size for each motor as maxJump and passes a junction as fast as the jumps of all motors allow (Path::plan(), step 1):

Junction of the example Largest jump of a motor Speed at the junction with maxJump = 500 steps/s
Corner of the rectangle, 90° 100 steps/s for each mm/s of the path 5 mm/s
Two segments of the circle, 5° about 9 steps/s for each mm/s of the path about 55 mm/s
Two segments on one line none the speed of the segments

Two things make a contour faster: a higher maxJump, as far as the motors follow it without losing steps, and smaller angles between the segments. A circle of 36 segments is run at about 30 mm/s with the values of the example, the circle of 72 segments at 55 mm/s.

Find maxJump by trial

The jump a motor follows depends on the motor, its driver and current, and on the load. Start with the pull-in speed at which the motor starts reliably, and raise the value only as far as the machine runs the path without losing steps.

Looking ahead

The speed at a junction is not only limited by the junction itself. The path has to be able to slow down for what comes later: for a sharp corner three short segments ahead, or for the end of the path. The planner therefore goes over the whole path twice (Path::plan(), steps 2 and 3):

  1. Backward, from the end. The path ends at standstill. Each junction may be at most as fast as the segment behind it can brake from, down to the speed of the next junction.
  2. Forward, from the start. The path starts at standstill. Each junction may be at most as fast as the segment before it can accelerate to.

After these two passes every segment has a speed at its start, a speed at its end and a highest speed, and each of them can be reached with the acceleration of the segment. The example plans with the whole acceleration of the motors; the library runs such a plan without a warning.

Giving the moves to the library

One move of the path runs in the library and one waits. PathRunner::giveMoves() hands over the next segments as long as room() of the GroupPath reports room, each with its length, its highest speed, its speed at the end and its acceleration:

advanced::PathMove move;
move.length        = segment.length;        // mm
move.speed         = segment.vMax;          // mm/s
move.speedAtTarget = segment.vOut;          // mm/s
move.acceleration  = segment.acceleration;  // mm/s²
moves.add(segment.target, 2, move);         // targets of the motors in steps
  • In time. The next move has to be there before the move that runs arrives. loop() therefore has to come by more often than the shortest segment takes: a segment of the example's circle takes about 20 ms. If the move is late, the group runs on along its line until it comes, see Rules.
  • From loop() or from the interrupt. Preparing a move takes about 3 µs on a Teensy 4.1 and 35 µs on a Teensy 3.6. Called from loop(), as in the example, it delays no step. A sketch whose loop() is too slow can give the moves in the function of onRoom() instead, at the price of that time in the step interrupt.

Override and hold

A path that is planned for its speeds can be run slower at every point, so the planner has nothing to calculate for these two functions of the library:

runner.moves.overrideSpeed(0.5f); // the path at half its speeds
runner.moves.overrideSpeed(0);    // hold: brake along the path and stand on it
runner.moves.overrideSpeed(1);    // go on at the planned speeds
The speed along the path with and without a hold
A hold on the circle of the example: the group brakes through the segments that follow, stands on the path, and goes on.

While the path is held, giveMoves() goes on as before: the group needs the following moves to brake along the path. See Override and hold for the details, and for how a path that is held is given up.

Another machine: CoreXY

On a CoreXY machine two motors move the head together through one belt: motor A makes the sum of the ways in x and y, motor B their difference. A move along x turns both motors in the same direction, a move along y in opposite directions, and on a diagonal only one of them turns. For the planner this is another kinematics and nothing else. In the sketch of the example one line changes, and the points of the path stay in x and y:

// 80 steps of a motor move the head by 1 mm along x or y
const planner::Kinematics table = planner::Kinematics::coreXY(80, 80);

The limits follow from the kinematics by themselves. Along x and y both motors share the work, so the head accelerates at 625 mm/s² with the motors of the example (1); on a diagonal one motor does it alone, at 442 mm/s².

  1. Where the numbers come from

    A motor accelerates at 50,000 steps/s². Along x each motor makes 80 steps per mm of the path: 50,000 / 80 = 625 mm/s². On a diagonal one motor makes 113 steps per mm of the path (80 × √2), the other none: 50,000 / 113 = 442 mm/s².

What the example does not do

  • Arcs and curves. The planner knows straight segments only. A curve is cut into short segments by the sketch, as the circle of the example.
  • A limit of the jerk. The acceleration changes at once, as in all ramps of the library.
  • Planning while the path runs. The whole path is planned before it starts. A planner that takes points from a host while it runs (G-code) plans a window of segments and keeps the path able to stop at the end of what it knows.
  • Speeds above the plan. The override reaches up to 1. A faster run needs a new plan.

The planner of the example

Planner.h
#pragma once

/*==========================================================================
 * Planner.h: a small motion planner for TeensyStep
 *
 * Example code, made to be read, copied and changed. It is not a part of
 * the library.
 *
 * A path is a list of points in mm with a feed rate. The planner turns it
 * into moves of the motors and decides how fast each point can be passed,
 * so that the path is run without a stop where the motors allow it. The
 * library runs the moves (advanced::GroupPath).
 *
 *   axes        the coordinates of the points (x, y, ...), in mm
 *   motors      what the library moves, in steps; as many as axes
 *   kinematics  how the positions of the motors follow from the axes
 *   segment     the straight piece of the path between two points
 *   junction    the point where two segments meet. The direction of the
 *               path changes there at once, and with it the speed of
 *               every motor. A junction is passed as fast as the motors
 *               can follow such a jump (MotorLimits::maxJump).
 *
 * Use:
 *   planner::Path path(buffer, size, kinematics, limits);
 *   path.start({0, 0});            the point where the motors stand
 *   path.add({50, 0}, 80);         a segment to this point at 80 mm/s
 *   ...
 *   path.plan();                   calculates the speeds
 *   runner.start(path);            planner::PathRunner runner(group);
 *   runner.giveMoves();            in loop(): hands the moves to the library
 *
 * Limits of this planner: straight segments only (cut an arc into short
 * ones), acceleration without a limit of the jerk, and the whole path is
 * planned before it starts.
 *==========================================================================*/

#include "TeensyStepAdvanced.h"
#include <cmath>
#include <cstdint>
#include <initializer_list>

namespace planner
{
    constexpr unsigned maxAxes = 4;

    //----------------------------------------------------------------------------------------------------
    // Kinematics: steps of motor i = sum over the axes j of m[i][j] * mm of axis j. A machine whose motors
    // follow from the axes like this moves its motors on a straight line when the axes move on a straight
    // line, which is what a group of the library does.

    struct Kinematics
    {
        unsigned axes             = 0;
        float m[maxAxes][maxAxes] = {};

        /// One motor for each axis, with its steps per mm.
        static Kinematics plain(std::initializer_list<float> stepsPerMm)
        {
            Kinematics k;
            for (float s : stepsPerMm)
            {
                if (k.axes == maxAxes) break;
                k.m[k.axes][k.axes] = s;
                k.axes++;
            }
            return k;
        }

        /// CoreXY: motor A = x + y, motor B = x - y. A negative value reverses an axis.
        static Kinematics coreXY(float stepsPerMmX, float stepsPerMmY)
        {
            Kinematics k;
            k.axes    = 2;
            k.m[0][0] = stepsPerMmX; // A = x + y
            k.m[0][1] = stepsPerMmY;
            k.m[1][0] = stepsPerMmX; // B = x - y
            k.m[1][1] = -stepsPerMmY;
            return k;
        }

        void toMotors(const double* mm, double* steps) const
        {
            for (unsigned i = 0; i < axes; i++)
            {
                steps[i] = 0;
                for (unsigned j = 0; j < axes; j++) steps[i] += (double)m[i][j] * mm[j];
            }
        }
    };

    /// What a motor can do. Give the motors of the library the same maximum speed and acceleration.
    struct MotorLimits
    {
        float maxSpeed;     ///< steps/s
        float acceleration; ///< steps/s^2
        float maxJump;      ///< steps/s: the largest change of its speed without a ramp, about its pull-in speed
    };

    /// A segment, as planned. Speeds are along the path, in mm/s.
    struct Segment
    {
        int32_t target[maxAxes]; ///< positions of the motors at its end, steps
        int32_t delta[maxAxes];  ///< ways of the motors, steps
        unsigned lead;           ///< the motor with the longest way
        float length;            ///< mm
        float feed;              ///< the speed that was asked for
        float vMax;              ///< the speed it may have: the feed rate, or less if a motor would be too fast
        float acceleration;      ///< mm/s^2: as much as the motors allow in its direction
        float vIn, vOut;         ///< speed at its start and at its end
        float vPeak;             ///< the highest speed on its way

        /// Seconds the segment takes: a ramp from vIn to vPeak, a piece at vPeak, a ramp to vOut.
        float duration() const
        {
            double a = acceleration, up = (vPeak - vIn) / a, down = (vPeak - vOut) / a;
            double ramps = (2.0 * vPeak * vPeak - (double)vIn * vIn - (double)vOut * vOut) / (2 * a); // mm
            double rest  = length - ramps;
            return (float)(up + down + (rest > 0 ? rest / vPeak : 0));
        }

        /// Steps of the motor with the longest way per mm of the path.
        float leadStepsPerMm() const { return (float)(delta[lead] < 0 ? -delta[lead] : delta[lead]) / length; }
    };

    //----------------------------------------------------------------------------------------------------
    // The path: start(), add() for every point, plan(). Then the segments can be read and run.

    class Path
    {
     public:
        /// @param buffer room for the segments, `capacity` of them; it has to exist as long as the path
        /// @param limits one entry for each motor
        Path(Segment* buffer, unsigned capacity, const Kinematics& kinematics, const MotorLimits* limits)
            : seg(buffer), capacity(capacity), kin(kinematics)
        {
            for (unsigned i = 0; i < kin.axes; i++) lim[i] = limits[i];
        }

        /// Begins a new path at this point (mm). The motors stand still there.
        void start(std::initializer_list<float> mm) { start(mm.begin()); }
        void start(const float* mm)
        {
            n = 0;
            double steps[maxAxes];
            for (unsigned j = 0; j < kin.axes; j++) lastMm[j] = mm[j];
            kin.toMotors(lastMm, steps);
            for (unsigned i = 0; i < kin.axes; i++) lastSteps[i] = (int32_t)std::lround(steps[i]);
        }

        /// Adds a segment from the last point to this one, at this feed rate (mm/s). A point that is less
        /// than one step from the last one is left out (and returns true).
        /// @return false: the buffer is full, or the feed rate is not positive
        bool add(std::initializer_list<float> mm, float feed) { return add(mm.begin(), feed); }
        bool add(const float* mm, float feed);

        /// Calculates the speeds of all segments. The path ends at standstill.
        void plan();

        unsigned size() const { return n; }
        const Segment& operator[](unsigned i) const { return seg[i]; }

        float duration() const ///< seconds for the whole path, after plan()
        {
            double t = 0;
            for (unsigned k = 0; k < n; k++) t += seg[k].duration();
            return (float)t;
        }

     private:
        Segment* seg;
        unsigned capacity, n = 0;
        Kinematics kin;
        MotorLimits lim[maxAxes];
        double lastMm[maxAxes]     = {}; // the end of the last segment, as it was given
        int32_t lastSteps[maxAxes] = {}; // and where the motors are there
    };

    inline bool Path::add(const float* mm, float feed)
    {
        if (!(feed > 0)) return false;

        // The targets of the motors come from the point itself, not from the last targets plus a way, so
        // that rounding to steps does not add up along the path.
        double point[maxAxes] = {}, steps[maxAxes] = {};
        int32_t target[maxAxes];
        bool moves = false;
        for (unsigned j = 0; j < kin.axes; j++) point[j] = mm[j];
        kin.toMotors(point, steps);
        for (unsigned i = 0; i < kin.axes; i++)
        {
            target[i] = (int32_t)std::lround(steps[i]);
            if (target[i] != lastSteps[i]) moves = true;
        }
        if (!moves) return true; // less than a step: the next segment starts where this one would have
        if (n == capacity) return false;

        Segment& s    = seg[n];
        double square = 0;
        for (unsigned j = 0; j < kin.axes; j++) square += (point[j] - lastMm[j]) * (point[j] - lastMm[j]);
        double length = std::sqrt(square);

        // The speed of a motor is the speed along the path times the steps the motor makes per mm of the
        // path. From this: how fast the path may be, and how much it may accelerate, without a motor
        // exceeding its limits.
        double vMax = feed, acc = 1e30;
        int32_t longest = 0;
        s.lead          = 0;
        for (unsigned i = 0; i < kin.axes; i++)
        {
            s.target[i] = target[i];
            s.delta[i]  = target[i] - lastSteps[i];
            int32_t way = s.delta[i] < 0 ? -s.delta[i] : s.delta[i];
            if (way > longest)
            {
                longest = way;
                s.lead  = i;
            }
            if (way == 0) continue;
            double perMm = way / length;
            if (lim[i].maxSpeed / perMm < vMax) vMax = lim[i].maxSpeed / perMm;
            if (lim[i].acceleration / perMm < acc) acc = lim[i].acceleration / perMm;
        }
        s.length       = (float)length;
        s.feed         = feed;
        s.vMax         = (float)vMax;
        s.acceleration = (float)acc;
        s.vIn = s.vOut = s.vPeak = 0;

        for (unsigned j = 0; j < kin.axes; j++) lastMm[j] = point[j];
        for (unsigned i = 0; i < kin.axes; i++) lastSteps[i] = target[i];
        n++;
        return true;
    }

    inline void Path::plan()
    {
        if (n == 0) return;

        // 1. The highest speed at each junction: neither of the two segments is faster, and no motor
        //    changes its speed by more than its jump limit.
        for (unsigned k = 0; k + 1 < n; k++)
        {
            const Segment &a = seg[k], &b = seg[k + 1];
            double v = a.vMax < b.vMax ? a.vMax : b.vMax;
            for (unsigned i = 0; i < kin.axes; i++)
            {
                // the jump of motor i in steps/s, for each mm/s along the path
                double change = std::fabs(b.delta[i] / (double)b.length - a.delta[i] / (double)a.length);
                if (change * v > lim[i].maxJump) v = lim[i].maxJump / change;
            }
            seg[k].vOut = (float)v;
        }
        seg[n - 1].vOut = 0; // the path ends at standstill

        // 2. Backward, from the end: a junction is not faster than the segment behind it can brake from.
        for (unsigned k = n - 1; k > 0; k--)
        {
            const Segment& s = seg[k];
            double reachable = std::sqrt((double)s.vOut * s.vOut + 2.0 * s.acceleration * s.length);
            if (seg[k - 1].vOut > reachable) seg[k - 1].vOut = (float)reachable;
        }

        // 3. Forward, from the start: a junction is not faster than the segment before it can accelerate
        //    to. Then the highest speed on the way: that of the segment, or the top of a triangle if the
        //    segment is too short to reach it.
        for (unsigned k = 0; k < n; k++)
        {
            Segment& s       = seg[k];
            s.vIn            = k ? seg[k - 1].vOut : 0;
            double energy    = 2.0 * s.acceleration * s.length;
            double reachable = std::sqrt((double)s.vIn * s.vIn + energy);
            if (s.vOut > reachable) s.vOut = (float)reachable;
            double top = std::sqrt((energy + (double)s.vIn * s.vIn + (double)s.vOut * s.vOut) / 2);
            s.vPeak    = (float)(s.vMax < top ? s.vMax : top);
        }
    }

    //----------------------------------------------------------------------------------------------------
    // Runs a planned path with a group of the library: one move for each segment, given ahead while the
    // one before it runs. The motors of the group are the motors of the path, in the same order, and they
    // stand at the start of the path (Stepper::setPositionCounter()).

    class PathRunner
    {
     public:
        explicit PathRunner(TeensyStep::StepperGroup& group) : moves(group), group(group) {}

        /// Starts the path: giveMoves() hands it to the library from now on. The path has to exist until
        /// isRunning() returns false.
        void start(const Path& p)
        {
            path  = &p;
            given = 0;
            error = TeensyStep::errorCode::OK;
        }

        /// Gives the library as many moves as it takes. Call it from loop(), more often than the shortest
        /// segment takes: the next move has to be there before the one that runs arrives.
        void giveMoves()
        {
            while (hasMore() && moves.room() > 0) giveNext();
        }

        /// Gives the next move. Speeds and acceleration go as they were planned, in mm; the library
        /// converts them for the motors. @return the code of GroupPath::add()
        TeensyStep::errorCode giveNext()
        {
            const Segment& s = (*path)[given];
            TeensyStep::advanced::PathMove move;
            move.length        = s.length;
            move.speed         = s.vMax;
            move.speedAtTarget = s.vOut;
            move.acceleration  = s.acceleration;
            TeensyStep::errorCode code = moves.add(s.target, group.size(), move);
            if (TeensyStep::isError(code))
                error = code; // the path is given up; the moves that were given are still run
            else
                given = given + 1;
            return code;
        }

        bool hasMore() const { return path && given < path->size() && !TeensyStep::isError(error); } ///< moves are left to give
        bool isRunning() const { return hasMore() || group.isMoving(); }
        unsigned movesGiven() const { return given; }
        TeensyStep::errorCode lastError() const { return error; } ///< an error ended the path

        /// The moves in the library: overrideSpeed() runs the path slower (0: hold), getSpeed() returns the
        /// speed along the path in mm/s.
        TeensyStep::advanced::GroupPath moves;

     private:
        TeensyStep::StepperGroup& group;
        const Path* path        = nullptr;
        volatile unsigned given = 0;
        TeensyStep::errorCode error = TeensyStep::errorCode::OK;
    };
}