Docs / Shaping functions

Shaping functions: catalog and IDs

Creating a function from its ID, the categories, what a function says about itself, a curve picker, and saving a curve with its parameters.

Color legend plain property method

Code that knows its curve writes new CubicEaseOut(). Code that lets a designer, a setting or a save file choose the curve works with IDs: every function of the library has a ShapingFunctionId, belongs to a ShapingFunctionCategory, can be created from its ID and listed by the catalog, and is saved as a number that never changes. Names are colored by what they are: a property or a method.

Creating a function by ID

ShapingFunctionFactory.Create turns an ID into a function:

ShapingFunctionId id = settings.FadeCurve; // ShapingFunctionId.SineEaseInOut, say

BaseShapingFunction fade = ShapingFunctionFactory.Create(id);

Each call creates a new instance with its parameters at their defaults, so setting the parameters of one never changes another. The factory knows only the library’s own functions: it throws ArgumentOutOfRangeException for ShapingFunctionId.Custom, the ID every custom function shares, and for a number the enum doesn’t define, such as one read from a damaged file. Check an ID that comes from outside the game before creating its function:

var known = Enum.IsDefined(id) && id != ShapingFunctionId.Custom;

BaseShapingFunction fade = ShapingFunctionFactory.Create(known ? id : ShapingFunctionId.Linear);

ShapingFunctionFactory method

Method Description
Create(ShapingFunctionId id) Static. A new instance of the function, with its parameters at their defaults. Throws ArgumentOutOfRangeException for Custom and for values the enum doesn’t define.

Categories

Each function belongs to one of 15 categories, its family: Back, Bezier, Bounce and so on. ShapingFunctionCatalog lists the categories and the functions in each, for a picker or a menu:

foreach (ShapingFunctionCategory category in ShapingFunctionCatalog.GetCategories())
{
    Console.WriteLine(category);

    foreach (ShapingFunctionId id in ShapingFunctionCatalog.GetFunctions(category))
        Console.WriteLine($"    {id}");
}

The categories and the functions come in the order the enums declare them, the same on every run and in every version, so a list built from the catalog doesn’t reshuffle. List the functions with the catalog rather than with Enum.GetValues<ShapingFunctionId>(): the enum also holds Custom, which the factory rejects.

ShapingFunctionCatalog methods

Method Description
GetCategories() Static. Every category that has functions, as an IReadOnlyCollection<ShapingFunctionCategory>, in declaration order. Custom isn’t among them.
GetFunctions(ShapingFunctionCategory category) Static. The IDs of the category’s functions, as an IReadOnlyList<ShapingFunctionId>, in declaration order. Throws ArgumentOutOfRangeException for Custom and for values the enum doesn’t define.

Categories and their functions

Every category and every ID has an explicit number. A number never changes, and one that is retired is never used again, so the numbers are safe to save.

Category Number Functions, with their numbers
Back 0 BackEaseIn 0, BackEaseInOut 1, BackEaseOut 2
Bezier 1 BezierCubic 3, BezierQuadratic 4
Bounce 2 BounceEaseIn 5, BounceEaseInOut 6, BounceEaseOut 7
Circular 3 CircularDoubleSeat 8, CircularDoubleSigmoid 9, CircularEaseIn 10, CircularEaseInOut 11, CircularEaseOut 12
Elastic 4 ElasticEaseIn 13, ElasticEaseInOut 14, ElasticEaseOut 15
Elliptical 5 EllipticalDoubleSeat 16, EllipticalDoubleSigmoid 17
Exponential 6 ExponentialDoubleSeat 18, ExponentialEaseIn 19, ExponentialEaseInOut 20, ExponentialEaseOut 21, LogisticSigmoid 22
Linear 7 Linear 23
Quadratic 8 QuadraticEaseIn 24, QuadraticEaseInOut 25, QuadraticEaseOut 26, QuadraticThroughAGivenPoint 27
Cubic 9 CubicDoubleSeat 28, CubicEaseIn 29, CubicEaseInOut 30, CubicEaseOut 31
Quartic 10 QuarticEaseIn 32, QuarticEaseInOut 33, QuarticEaseOut 34
Quintic 11 QuinticEaseIn 35, QuinticEaseInOut 36, QuinticEaseOut 37
Hexic 12 BlinnWyvillCosineApproximation 38
NOrder 13 DoubleOddPolynomialSeat 39, DoublePolynomialSigmoid 40
Sine 14 SineEaseIn 41, SineEaseInOut 42, SineEaseOut 43
Custom −1 Every custom function, each with the ID Custom, −1. The catalog lists neither.

What a function says about itself

A function created from an ID is a BaseShapingFunction, which says what it is without a cast:

BaseShapingFunction fn = ShapingFunctionFactory.Create(ShapingFunctionId.CubicEaseInOut);

ShapingFunctionId fnId = fn.Id;                 // CubicEaseInOut: the ID it was created from
ShapingFunctionCategory category = fn.Category; // Cubic: the catalog's category for it
string name = fn.Name;                          // "Cubic EaseInOut": a name to show
int? order = fn.Order;                          // 3: the degree of its polynomials, null for none
bool parametric = fn.Parametric;                // false: it has none of A to D and no N
int parameterCount = fn.ParameterCount;         // 0: how many of A to D it takes, 0 to 4
bool hasOrder = fn.HasVariableOrder;            // false: whether it has an order N

Show Name to people, and save Id: only the numbers are promised never to change.

BaseShapingFunction properties

Property Type Description
Category ShapingFunctionCategory Read-only. The family the function belongs to, the category the catalog lists it under. Custom for a custom function.
HasVariableOrder bool Read-only. Whether the function has a settable order N, through INOrder.
Id ShapingFunctionId Read-only. Which function it is; the factory creates another of it from this. Custom for a custom function.
Name string Read-only. A name to show, such as "Cubic EaseInOut". Each function of the library has its own.
Order int? Read-only. The degree of the polynomials the curve is made of, from 1 for Linear to 6 for Blinn-Wyvill. null for curves that aren’t polynomials and for the two NOrder functions.
ParameterCount int Read-only. How many of A, B, C and D the function takes, 0 to 4.
Parametric bool Read-only. Whether the function has any parameter, A to D or N.

A curve picker

An editor’s curve picker lists the categories and their functions, shows sliders for the parameters of the one chosen, and draws its curve. The UI is the editor’s own; this class is what it needs from the library:

using System.Numerics;
using BorrowedTorch.ShapingFunctions;

public sealed class CurvePicker
{
    public BaseShapingFunction Selected { get; private set; } = new Linear();

    // the rows of the list: each category, then its functions under their names
    public IEnumerable<(ShapingFunctionCategory Category, ShapingFunctionId Id, string Name)> Rows()
    {
        foreach (var category in ShapingFunctionCatalog.GetCategories())
        foreach (var id in ShapingFunctionCatalog.GetFunctions(category))
            yield return (category, id, ShapingFunctionFactory.Create(id).Name);
    }

    public void Select(ShapingFunctionId id)
    {
        Selected = ShapingFunctionFactory.Create(id);
    }

    // the sliders to show: "AB" for a function with A and B
    public string Sliders => "ABCD"[..Selected.ParameterCount];

    public bool ShowsOrder => Selected.HasVariableOrder;

    // sets a parameter and gives back its value as kept, for the slider to show
    public float SetParameter(char name, float value)
    {
        switch (name)
        {
            case 'A' when Selected is IOneParameter p:
                p.A = value;
                return p.A;
            case 'B' when Selected is ITwoParameters p:
                p.B = value;
                return p.B;
            case 'C' when Selected is IThreeParameters p:
                p.C = value;
                return p.C;
            case 'D' when Selected is IFourParameters p:
                p.D = value;
                return p.D;
            default:
                throw new ArgumentOutOfRangeException(nameof(name));
        }
    }

    public int SetOrder(int n)
    {
        var order = (INOrder)Selected;
        order.N = n;
        return order.N;
    }

    // the curve to draw: input across, output up
    public Vector2[] Preview(int segments = 100)
    {
        var points = new Vector2[segments + 1];

        for (var i = 0; i <= segments; i++)
        {
            var x = i / (float)segments;
            points[i] = new Vector2(x, Selected.CalculateOutput(x));
        }

        return points;
    }
}

SetParameter returns the value the function kept, because the function clamps it: a slider dragged to 0 for the A of a seat shows 0.00001. Give the preview room above 1 and below 0: the elastic curves reach from −0.37 to 1.37, so a graph from −0.4 to 1.4 holds every curve of the library.

Saving a curve

A saved curve is its ID and its parameters. This record holds them, reads them from a function and creates the function again, and serializes as it is with System.Text.Json:

using BorrowedTorch.ShapingFunctions;

public sealed record CurveSettings(int Id, float A = 0, float B = 0, float C = 0, float D = 0, int N = 1)
{
    public static CurveSettings From(BaseShapingFunction fn)
    {
        if (fn.Id == ShapingFunctionId.Custom)
            throw new ArgumentException("A custom function has no ID to save.", nameof(fn));

        return new CurveSettings((int)fn.Id,
            fn is IOneParameter a ? a.A : 0,
            fn is ITwoParameters b ? b.B : 0,
            fn is IThreeParameters c ? c.C : 0,
            fn is IFourParameters d ? d.D : 0,
            fn is INOrder n ? n.N : 1);
    }

    public BaseShapingFunction Create()
    {
        var fn = ShapingFunctionFactory.Create((ShapingFunctionId)Id);

        if (fn is IOneParameter a) a.A = A;
        if (fn is ITwoParameters b) b.B = B;
        if (fn is IThreeParameters c) c.C = C;
        if (fn is IFourParameters d) d.D = D;
        if (fn is INOrder n) n.N = N;

        return fn;
    }
}

The ID is saved as its number, which never changes; the name of an enum member isn’t promised to. A file edited by hand can’t break a curve, since the parameters are clamped when they are set, but an ID the enum doesn’t define makes Create throw: check it as above when the file comes from elsewhere.

A custom function shares the ID Custom with every other custom function, so its ID can’t say which one it was. The custom functions page saves them under names of their own.