This library smooths raw freehand input and predicts the input's motion to minimize display latency. It turns noisy pointer input from touch/stylus/etc. into the beautiful stroke patterns of brushes/markers/pens/etc.
Be advised that this library was designed to model handwriting, and as such, prioritizes smooth, good-looking curves over precise recreation of the input.
This library is designed to have minimal dependencies; the library itself relies only on the C++ Standard Library and Abseil, and the tests use the GoogleTest framework.
Ink Stroke Modeler can be built and the tests run from the GitHub repo root with:
bazel test ...
To use Ink Stroke Modeler in another Bazel project, put the following in the
MODULE.bazel
file to download the code from GitHub head and set up
dependencies:
git_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "ink_stroke_modeler",
remote = "https://github.com/google/ink-stroke-modeler.git",
branch = "main",
)
If you want to depend on a specific version, you can specify a commit in
git_repository
instead of a branch. Or if you want to use a local checkout of Ink Stroke
Modeler instead, use the
local_repository
workspace rule instead of git_repository
.
Since Ink Stroke Modeler requires C++20, it must be built with
--cxxopt='-std=c++20'
(or similar indicating a newer version). You can put the
following in your project's .bazelrc
to use this by default:
build --cxxopt='-std=c++20'
Then you can include the following in your targets' deps
:
@ink_stroke_modeler//ink_stroke_modeler:stroke_modeler
:ink_stroke_modeler/stroke_modeler.h
@ink_stroke_modeler//ink_stroke_modeler:types
:ink_stroke_modeler/types.h
@ink_stroke_modeler//ink_stroke_modeler:params
:ink_stroke_modeler/types.h
Ink Stroke Modeler can be built and the tests run from the GitHub repo root with:
cmake .
cmake --build .
ctest
To use Ink Stroke Modeler in another CMake project, you can add the project as a submodule:
git submodule add https://github.com/google/ink-stroke-modeler
And then include it in your CMakeLists.txt
, requiring at least C++20:
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# If you want to use installed (or already fetched) versions of Abseil and/or
# GTest (for example, if you've installed libabsl-dev and libgtest-dev), add:
# set(INK_STROKE_MODELER_FIND_ABSL ON)
# set(INK_STROKE_MODELER_FIND_GTEST ON)
add_subdirectory(ink-stroke-modeler)
Then you can depend on the following with target_link_libraries
:
InkStrokeModeler::stroke_modeler
:ink_stroke_modeler/stroke_modeler.h
InkStrokeModeler::types
:ink_stroke_modeler/types.h
InkStrokeModeler::params
:ink_stroke_modeler/types.h
CMake does not have a mechanism for enforcing target visibility, but consumers
should depend only on the non-test top-level targets defined in
ink_stroke_modeler/CMakeLists.txt
.
The CMake build uses the abstractions defined in
cmake/InkBazelEquivalents.cmake
to structure targets in a way that's similar
to the Bazel BUILD files to make it easier to keep those in sync. The main
difference is that CMake has a flat structure for target names, e.g.
@com_google_absl//absl/status:statusor
in Bazel is absl::statusor
in CMake.
This means that targets need to be given unique names within the entire project
in CMake.
Ink Stroke Modeler is intended to be built into consumers from source. But sometimes a packaged version is needed, for example to integrate with other build systems that wrap CMake. To test the packaging and export of Ink Stroke Modeler targets, you can install the dependencies with something like:
sudo apt install libabsl-dev googletest
And then run:
cmake -DINK_STROKE_MODELER_FIND_DEPENDENCIES=ON \
-DCMAKE_INSTALL_PREFIX=$HOME/cmake .
make install
Or to build fetched dependencies from source instead of using installed ones:
cmake -DCMAKE_INSTALL_PREFIX=$HOME/cmake .
make install
Set CMAKE_INSTALL_PREFIX
to point the install somewhere other than system
library paths.
The Ink Stroke Modeler API is in the namespace ink::stroke_model
. The primary
surface of the API is the StrokeModeler
class, found in stroke_modeler.h
.
You'll also simple data types and operators in types.h
, and the parameters
which determine the behavior of the model in params.h
.
To begin, you'll need choose parameters for the model (the parameters for your
use case may vary; see params.h
), instantiate a StrokeModeler
, and set the
parameters via StrokeModeler::Reset()
:
StrokeModelParams params{
.wobble_smoother_params{
.timeout{.04}, .speed_floor = 1.31, .speed_ceiling = 1.44},
.position_modeler_params{.spring_mass_constant = 11.f / 32400,
.drag_constant = 72.f},
.sampling_params{.min_output_rate = 180,
.end_of_stroke_stopping_distance = .001,
.end_of_stroke_max_iterations = 20},
.stylus_state_modeler_params{.max_input_samples = 20},
.prediction_params = StrokeEndPredictorParams()};
StrokeModeler modeler;
if (absl::Status status = modeler.Reset(params); !status.ok()) {
// Handle error.
}
You may also call Reset()
on an already-initialized StrokeModeler
to set new
parameters; this also clears the in-progress stroke, if any. If the Update
or
Predict
functions are called before Reset
, they will return
absl::FailedPreconditionError
.
To use the model, pass in an Input
object to StrokeModeler::Update()
each
time you receive an input event. This appends to a std::vector<Result>
of
stroke smoothing results:
Input input{
.event_type = Input::EventType::kDown,
.position{2, 3}, // x, y coordinates in some consistent units
.time{.2}, // Time in some consistent units
// The following fields are optional:
.pressure = .2, // Pressure from 0 to 1
.orientation = M_PI // Angle in plane of screen in radians
.tilt = 0, // Angle elevated from plane of screen in radians
};
if (absl::Status status = modeler.Update(input, smoothed_stroke);
!status.ok()) {
// Handle error...
return status;
}
// Do something with the smoothed stroke so far...
return absl::OkStatus();
Input
s are expected to come in a stream, starting with a kDown
event,
followed by zero or more kMove
events, and ending with a kUp
event. If the
modeler is given out-of-order inputs or duplicate inputs, it will return
absl::InvalidArgumentError
. Input.time
may not be before the time
of the
previous input.
Input
s are expected to come from a single stroke produced with an input
device. Extraneous inputs, like touches with the palm of the hand in
touch-screen stylus input, should be filtered before passing the correct input
events to Update
. If the input device allows for multiple strokes at once (for
example, drawing with two fingers simultaneously), the inputs for each stroke
must be passed to separate StrokeModeler
instances.
The time
values of the returned Result
objects start at the time
of the
first input and end either at the time of the last Input
(for in-progress
strokes) or a hair after (for completed ones). The position of the first
Result
exactly matches the position of the first Input
and the position
of
the last Result
attempts to very closely match the match the position
of the
last Input
, wile the Result
objects in the middle have their position
adjusted to smooth out and interpolate between the input values.
To construct a prediction, call StrokeModeler::Predict()
while an input stream
is in-progress. This takes a std::vector<Result>
and replaces the contents
with the new prediction:
if (absl::Status status = modeler.Predict(predicted_stroke); !status.ok) {
// Handle error...
return status;
}
// Do something with the new prediction...
return absl::OkStatus();
If no input stream is in-progress, it will instead return
absl::FailedPreconditionError
.
When the model is configured with StrokeEndPredictorParams
, the last Result
returned by Predict
will have a time
slightly after the most recent Input
.
(This is the same as the points that would be added to the Result
s returned by
Update
if the most recent input was kUp
instead of kMove
.) When the model
is configured with KalmanPredictorParams
, the prediction may take more time to
"catch up" with the position of the last input, then take an additional interval
to extend the stroke beyond that position.
The state of the most recent stroke can be represented by concatenating the
vectors of Result
s returned by a series of successful calls to Update
,
starting with the most recent kDown
event. If the input stream does not end
with a kUp
event, you can optionally append the vector of Result
s returned
by the most recent call to Predict
.
(Note: Mathematical formulas below are rendered with MathJax, which GitHub's native Markdown rendering does not support. You can view the rendered version on GitHub pages.)
The design goals for this library were:
- Minimize overall latency.
- Accurate reproduction of intent for drawing and handwriting (preservation of inflection points).
- Smooth digitizer noise (high frequency).
- Smooth human created noise (low and high frequency). For example:
- For most people, drawing with direct mouse input is very accurate, but looks bad.
- For most people, drawing with a real pen looks bad. We should capture some of the differences between professional and amateur pen control.
At a high level, we start with an assumption that all reported input events are estimates (from both the person and hardware). We keep track of an idealized pen constrained by a physical model of motion (mass, friction, etc.) and feed these position estimates into this idealized pen. This model lags behind reported events, as with most smoothing algorithms, but because we have the modeled representation we can sample its location at arbitrary and even future times. Using this, we predict forward from the delayed model to estimate where we will go. The actual implementation is fairly simple: a fixed timestep Euler integration to update the model, in which input events are treated as spring forces on that model.
Like many real-time smoothing algorithms, the stroke modeler lags behind the raw input. To compensate for this, the stroke modeler has the capability to predict the upcoming points, which are used to "catch up" to the raw input.
Typically, we expect the stroke modeler to receive raw inputs in real-time; for each input it receives, it produces one or more modeled results.
When asked for a prediction, the stroke modeler computes it based on its current state -- this means that the prediction is invalid as soon as the next input is received.
NOTE: The definitions and algorithms in this document are defined as though the input streams are given as a complete set of data, even though the engine actually receives raw inputs one by one. It's written this way for ease of understanding.
However, one of the features of these algorithms is that any result that has been constructed will remain the same even if more inputs are added, i.e. if we view the algorithm as a function
$$F$$ that maps from an input stream to a set of results, then$$F({i_0, \ldots, i_j}) \subseteq F({i_0, \ldots, i_j, i_{j + 1}})$$ . Applying the algorithm in real-time is then effectively the same as evaluating the function on increasingly large subsets of the input stream, i.e.$$F({i_0}), F({i_0, i_1}), F({i_0, i_1, i_2}), \ldots$$
Definition: We define the pressure
Definition: We define the tilt
Definition: We define the orientation
NOTE: In the code, we use a sentinel value of -1 to represent unreported pressure, tilt, or orientation.
Definition: A raw input is a struct
Vec2
position, Time
, float
representing the pressure, float
representing tilt, and
float
representing orientation. For any raw input
Definition: An input stream is a finite sequence of raw inputs, ordered by
time strictly non-decreasing, such that the first raw input is the kDown
, and
each subsequent raw input is a kMove
, with the exception of the final one,
which may alternatively be the kUp
. Additionally, we say that a complete
input stream is a one such that the final raw input is the kUp
.
Definition: A tip state is a struct
Vec2
position, Vec2
velocity, and Time
. Similarly to
raw input, for a tip state
Definition: A stylus state is a struct
float
representing the pressure, float
representing tilt, and float
representing orientation. As above,
for a stylus state
Definition: We define the rounding function
Definition: We define the linear interpolation function
Definition: We define the normalization function
Definition: We define the clamp function
The positions of the raw input tend to have some noise, due to discretization on the digitizer or simply an unsteady hand. This noise produces wobbles in the model and prediction, especially at slow speeds.
To reduce high-frequency noise, we take a time-variant moving average of the position instead of the position itself -- this serves as a low-pass filter. This, however, introduces some lag between the raw input position and the filtered position. To compensate for that, we use a linearly-interpolated value between the filtered and raw position, based on the moving average of the velocity of the input.
Algorithm #1: Given an input stream
NOTE: The values of
$$\Delta$$ ,$$v_{min}$$ , and$$v_{max}$$ are taken fromWobbleSmootherParams
:
$$\Delta$$ =timeout
$$v_{min}$$ =speed_floor
$$v_{max}$$ =speed_ceiling
For each raw input
We then calculate the moving averages of position
NOTE: In the above equations, the square braces denote the Iverson bracket.
We then normalize
Finally, we construct raw input
Input packets may come in at a variety of rates, depending on the platform and input device. Before performing position modeling, we upsample the input to some minimum rate.
Algorithm #2: Given an input stream
NOTE: The value of 1 / SamplingParams::min_output_rate
.
We construct a sequence
We then construct a sequence of sequences
The position of the pen is modeled as a weight connected by a spring to an anchor. The anchor moves along the resampled raw inputs, pulling the weight along with it across a surface, with some amount of friction. We then use Euler integration to solve for the position of the pen.
NOTE: For simplicity, we say that the spring has a relaxed length of zero, and that the anchor is unafected by outside forces such as friction or the drag from the pen.
Lemma: We can model the position of the pen with the following ordinary differential equation:
where
Proof: From the positions of the pen and the anchor, we can use Hooke's Law to find the force exerted by the spring:
Combining the above with Newton's Second Law of Motion, we can then find the
acceleration of the pen
We also apply a drag to the pen, applying an acceleration of
NOTE: This isn't exactly how you would calculate friction of an object being
dragged across a surface. However, if you assume that
From the equations of motion, we know that
Algorithm #3: Given an incomplete input stream
NOTE: When modeling a stroke, we choose StrokeEndPredictor
also makes use of this algorithm with different initial values, however.
We define the function
Because the spring constant and mass are so closely coupled in our model, we
combine them into a single "shape mass" constant
NOTE: The values of PositionModelerParams::spring_mass_constant
and
PositionModelerParams::drag_constant
, respectively.
We define
Finally, we construct tip state
The position modeling algorithm, like many real-time smoothing algorithms, tends to trail behind the raw inputs by some distance. At the end of the stroke, we iterate on the position modeling algorithm a few additional times, using the final raw input position as the anchor, to allow the stroke to "catch up."
Algorithm #4: Given the final anchor position
NOTE: The values of
$$\Delta_{initial}$$ ,$$K_{max}$$ , and$$d_{stop}$$ are taken fromSamplingParams
:
$$\Delta_{initial}$$ =min_output_rate
$$K_{max}$$ =end_of_stroke_max_iterations
$$d_{stop}$$ =end_of_stroke_stopping_distance
Let
If the distance traveled
We then construct the segment
Once we have found a suitable candidate, we let
If the remaining distance
As mentioned above, the position modeling algorithm tends to trail behind the raw inputs. In addition to correcting for this at the end-of-stroke, we construct a set of predicted tip states every frame to present the illusion of lower latency.
The are two predictors: the StrokeEndPredictor
(found in
internal/prediction/stroke_end_predictor.h
) uses a slight variation of the
end-of-stroke algorithm, and the KalmanPredictor
(found in
internal/prediction/kalman_predictor.h
) uses a Kalman filter to estimate the
current state of the pen tip and construct a cubic prediction.
Regardless of the strategy used, the predictor is fed each position and timestamp of raw input as it is received by the model. The model's most recent tip state is given to the predictor when the predicted tip states are constructed.
The StrokeEndPredictor
constructs a prediction using algorithm #4 to model
what the stroke would be if the last raw input had been a kUp
, letting
The KalmanPredictor
uses a pair of
Kalman filters, one each for the
x- and y-components, to estimate the current state of the pen from the given
inputs.
The Kalman filter implementation operates on the assumption that all states have one unit of time between them; because of this, we need to rescale the estimation to account for the actual input and output rates. Additionally, our experiments suggest that linear predictions look and feel better than non-linear ones; as such, we also provide weight factors that may be used to reduce the effect of the acceleration and jerk coefficients on the estimate and prediction.
Once we have the estimated state, we construct the prediction in two parts, each of which is a sequence of tip states described by a cubic polynomial curve. The first smoothly connects the last tip state to the estimate state, and the second projects where the expected position of the pen is in the future.
Algorithm #5: Given a process noise factor
The difference in time between states,
The state transition model is derived from the equations of motion: given
The process noise covariance is modeled as noisy force; from the equations of motion, we can say that the impact of that noise on each state is equal to:
The measurement model is simply $$\begin{bmatrix}1 & 0 & 0 & 0\end{bmatrix}$$, representing the fact that we only observe the position of the input.
The measurement noise covariance is set to
NOTE: The values of
$$\epsilon_p$$ and$$\epsilon_m$$ are taken fromKalmanPredictorParams
:
$$\epsilon_p$$ =process_noise
$$\epsilon_m$$ =measurement_noise
Algorithm #6: Given the input stream
We first determine the average amount of time
We then construct the state estimate:
NOTE: The values of
$$N_{max}$$ ,$$w_a$$ , and$$w_j$$ are taken fromKalmanPredictorParams
:
$$N_{max}$$ =max_time_samples
$$w_a$$ =acceleration_weight
$$w_j$$ =jerk_weight
Algorithm #7: Given the last tip state produced
NOTE: The value of 1 / SamplingParams::min_output_rate
.
We first determine how many points to sample along the curve, based on the velocities at the endpoints, and the distance between them:
From this, we say that the time when the connecting curve reaches the estimated
pen position is
NOTE: The full derivation of KalmanPredictor::ConstructCubicConnector
, in
internal/prediction/kalman_predictor.cc
.
We construct the times at which to sample the curve
Algorithm #8: Given the number of raw inputs received so far
There are four coefficients that factor into the confidence:
- A sample ratio
$$\gamma_s$$ , which captures how many raw inputs have been observed so far. The rationale for this coefficient is that, as we accumulate more observations, the error in any individual observation affects the estimate less. - An error coefficient
$$\gamma_\varepsilon$$ , based on the distance between the estimated state and the last observed state. The rationale for this coefficient is that it should be indicative of the variance in the distribution used for the estimate. - A speed coefficient
$$\gamma_V$$ , based on the approximate speed that the prediction travels at. The rationale for this coefficient is that when the prediction travels slowly, changes in direction become more jarring, appearing wobbly. - A linearity coefficient
$$\gamma_\mu$$ , based on how the much the cubic prediction differs from a linear one. The rationale for this coefficient is that testers have expressed that linear predictions look and feel better.
We first construct the final positions
We then construct the coefficients as follows:
Finally, we take the product of the coefficients to find the confidence
NOTE: The value of
$$t_p$$ =KalmanPredictorParams::prediction_interval
, and the values of$$N_s$$ ,$$\varepsilon_{max}$$ ,$$V_{min}$$ ,$$V_{max}$$ ,$$\mu_max$$ , and$$B_\mu$$ are taken fromKalmanPredictorParams::ConfidenceParams
:
$$N_s$$ =desired_number_of_samples
$$\varepsilon_{max}$$ =max_estimation_distance
$$V_{min}$$ =min_travel_speed
$$V_{max}$$ =max_travel_speed
$$\mu_{max}$$ =max_linear_deviation
$$B_\mu$$ =baseline_linearity_confidence
Algorithm #9: Given the target time between inputs
We first determine the number of tip states
We then iteratively construct a cubic prediction of the state at intervals of
We let
Once the tip states have been modeled, we need to construct stylus states for each of them. For input streams that contain stylus information, we find the closest pair of sequential raw inputs within a set window, and interpolate between them to get pressure, tilt, and orientation. For input streams that don't contain any stylus information, we simply leave the pressure, tilt, and orientation unspecified.
Algorithm #10: Given an input stream
NOTE: The value of StylusStateModelerParams::max_input_samples
.
We first construct line segments
We next find the index
We define
Finally, we construct the stylus state