instancer

Partially instantiate a variable font.

The module exports an instantiateVariableFont function and CLI that allow to create full instances (i.e. static fonts) from variable fonts, as well as “partial” variable fonts that only contain a subset of the original variation space.

For example, if you wish to pin the width axis to a given location while also restricting the weight axis to 400..700 range, you can do:

$ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700

See fonttools varLib.instancer –help for more info on the CLI options.

The module’s entry point is the instantiateVariableFont function, which takes a TTFont object and a dict specifying either axis coodinates or (min, max) ranges, and returns a new TTFont representing either a partial VF, or full instance if all the VF axes were given an explicit coordinate.

E.g. here’s how to pin the wght axis at a given location in a wght+wdth variable font, keeping only the deltas associated with the wdth axis:

| >>> from fontTools import ttLib
| >>> from fontTools.varLib import instancer
| >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
| >>> [a.axisTag for a in varfont["fvar"].axes]  # the varfont's current axes
| ['wght', 'wdth']
| >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
| >>> [a.axisTag for a in partial["fvar"].axes]  # axes left after pinning 'wght'
| ['wdth']

If the input location specifies all the axes, the resulting instance is no longer ‘variable’ (same as using fontools varLib.mutator):

>>> instance = instancer.instantiateVariableFont(
… varfont, {“wght”: 700, “wdth”: 67.5}
… )
>>> “fvar” not in instance
True

If one just want to drop an axis at the default location, without knowing in advance what the default value for that axis is, one can pass a None value:

>>> instance = instancer.instantiateVariableFont(varfont, {“wght”: None})
>>> len(varfont[“fvar”].axes)
1

From the console script, this is equivalent to passing wght=drop as input.

This module is similar to fontTools.varLib.mutator, which it’s intended to supersede. Note that, unlike varLib.mutator, when an axis is not mentioned in the input location, the varLib.instancer will keep the axis and the corresponding deltas, whereas mutator implicitly drops the axis at its default coordinate.

The module supports all the following “levels” of instancing, which can of course be combined:

L1

dropping one or more axes while leaving the default tables unmodified;

>>> font = instancer.instantiateVariableFont(varfont, {“wght”: None})
L2

dropping one or more axes while pinning them at non-default locations;

>>> font = instancer.instantiateVariableFont(varfont, {“wght”: 700})
L3

restricting the range of variation of one or more axes, by setting either a new minimum or maximum, potentially – though not necessarily – dropping entire regions of variations that fall completely outside this new range.

>>> font = instancer.instantiateVariableFont(varfont, {“wght”: (100, 300)})
L4

moving the default location of an axis, by specifying (min,defalt,max) values:

>>> font = instancer.instantiateVariableFont(varfont, {“wght”: (100, 300, 700)})

Currently only TrueType-flavored variable fonts (i.e. containing ‘glyf’ table) are supported, but support for CFF2 variable fonts will be added soon.

The discussion and implementation of these features are tracked at https://github.com/fonttools/fonttools/issues/1537

class fontTools.varLib.instancer.AxisLimits(*args, **kwargs)[source]

Maps axis tags (str) to AxisTriple values.

defaultLocation() Dict[str, float]

Return a dict of default axis values.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
limitAxesAndPopulateDefaults(varfont) AxisLimits[source]

Return a new AxisLimits with defaults filled in from fvar table.

If all axis limits already have defaults, return self.

normalize(varfont, usingAvar=True) NormalizedAxisLimits[source]

Return a new NormalizedAxisLimits with normalized -1..0..+1 values.

If usingAvar is True, the avar table is used to warp the default normalization.

pinnedLocation() Dict[str, float]

Return a location dict with only the pinned axes.

values() an object providing a view on D's values
fontTools.varLib.instancer.AxisRange(minimum, maximum)[source]
class fontTools.varLib.instancer.AxisTriple(minimum: float | None, default: float | None, maximum: float | None)[source]

A triple of (min, default, max) axis values.

Any of the values can be None, in which case the limitRangeAndPopulateDefaults() method can be used to fill in the missing values based on the fvar axis values.

count(value) integer -- return number of occurrences of value
default: float | None
classmethod expand(v: AxisTriple | float | Tuple[float, float] | Tuple[float, float, float]) AxisTriple[source]

Convert a single value or a tuple into an AxisTriple.

If the input is a single value, it is interpreted as a pin at that value. If the input is a tuple, it is interpreted as (min, max) or (min, default, max).

index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

limitRangeAndPopulateDefaults(fvarTriple) AxisTriple[source]

Return a new AxisTriple with the default value filled in.

Set default to fvar axis default if the latter is within the min/max range, otherwise set default to the min or max value, whichever is closer to the fvar axis default. If the default value is already set, return self.

maximum: float | None
minimum: float | None
class fontTools.varLib.instancer.NormalizedAxisLimits(*args, **kwargs)[source]

Maps axis tags (str) to NormalizedAxisTriple values.

defaultLocation() Dict[str, float]

Return a dict of default axis values.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pinnedLocation() Dict[str, float]

Return a location dict with only the pinned axes.

values() an object providing a view on D's values
fontTools.varLib.instancer.NormalizedAxisRange(minimum, maximum)[source]
class fontTools.varLib.instancer.NormalizedAxisTriple(minimum: float, default: float, maximum: float)[source]

A triple of (min, default, max) normalized axis values.

count(value) integer -- return number of occurrences of value
default: float
classmethod expand(v: AxisTriple | float | Tuple[float, float] | Tuple[float, float, float]) AxisTriple

Convert a single value or a tuple into an AxisTriple.

If the input is a single value, it is interpreted as a pin at that value. If the input is a tuple, it is interpreted as (min, max) or (min, default, max).

index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

limitRangeAndPopulateDefaults(fvarTriple) AxisTriple

Return a new AxisTriple with the default value filled in.

Set default to fvar axis default if the latter is within the min/max range, otherwise set default to the min or max value, whichever is closer to the fvar axis default. If the default value is already set, return self.

maximum: float
minimum: float
class fontTools.varLib.instancer.NormalizedAxisTripleAndDistances(minimum: float, default: float, maximum: float, distanceNegative: float | None = 1, distancePositive: float | None = 1)[source]

A triple of (min, default, max) normalized axis values, with distances between min and default, and default and max, in the pre-normalized space.

count(value) integer -- return number of occurrences of value
default: float
distanceNegative: float | None = 1
distancePositive: float | None = 1
classmethod expand(v: AxisTriple | float | Tuple[float, float] | Tuple[float, float, float]) AxisTriple

Convert a single value or a tuple into an AxisTriple.

If the input is a single value, it is interpreted as a pin at that value. If the input is a tuple, it is interpreted as (min, max) or (min, default, max).

index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

limitRangeAndPopulateDefaults(fvarTriple) AxisTriple

Return a new AxisTriple with the default value filled in.

Set default to fvar axis default if the latter is within the min/max range, otherwise set default to the min or max value, whichever is closer to the fvar axis default. If the default value is already set, return self.

maximum: float
minimum: float
renormalizeValue(v, extrapolate=True)[source]

Renormalizes a normalized value v to the range of this axis, considering the pre-normalized distances as well as the new axis limits.

reverse_negate()[source]
class fontTools.varLib.instancer.OverlapMode(value)[source]

An enumeration.

KEEP_AND_DONT_SET_FLAGS = 0
KEEP_AND_SET_FLAGS = 1
REMOVE = 2
REMOVE_AND_IGNORE_ERRORS = 3
as_integer_ratio()

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

denominator

the denominator of a rational number in lowest terms

from_bytes(byteorder, *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.

signed

Indicates whether two’s complement is used to represent the integer.

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

to_bytes(length, byteorder, *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

fontTools.varLib.instancer.axisValuesFromAxisLimits(stat, axisLimits)[source]
fontTools.varLib.instancer.changeTupleVariationAxisLimit(var, axisTag, axisLimit)[source]
fontTools.varLib.instancer.changeTupleVariationsAxisLimits(variations, axisLimits)[source]
fontTools.varLib.instancer.instantiateAvar(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateCFF2(varfont, axisLimits, *, round=<built-in function round>, specialize=True, generalize=False, downgrade=False)[source]
fontTools.varLib.instancer.instantiateCvar(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateFvar(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateGvar(varfont, axisLimits, optimize=True)[source]
fontTools.varLib.instancer.instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True)[source]

Remove? https://github.com/fonttools/fonttools/pull/2266

fontTools.varLib.instancer.instantiateHVAR(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits)[source]

Compute deltas at partial location, and update varStore in-place.

Remove regions in which all axes were instanced, or fall outside the new axis limits. Scale the deltas of the remaining regions where only some of the axes were instanced.

The number of VarData subtables, and the number of items within each, are not modified, in order to keep the existing VariationIndex valid. One may call VarStore.optimize() method after this to further optimize those.

Parameters:
  • varStore – An otTables.VarStore object (Item Variation Store)

  • fvarAxes – list of fvar’s Axis objects

  • axisLimits – NormalizedAxisLimits: mapping axis tags to normalized min/default/max axis coordinates. May not specify coordinates/ranges for all the fvar axes.

Returns:

to be added to the default instance, of type dict of floats

keyed by VariationIndex compound values: i.e. (outer << 16) + inner.

Return type:

defaultDeltas

fontTools.varLib.instancer.instantiateMVAR(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateOTL(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateSTAT(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateTupleVariationStore(variations, axisLimits, origCoords=None, endPts=None)[source]

Instantiate TupleVariation list at the given location, or limit axes’ min/max.

The ‘variations’ list of TupleVariation objects is modified in-place. The ‘axisLimits’ (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes have minimum == default == maximum.

A ‘full’ instance (i.e. static font) is produced when all the axes are pinned to single coordinates; a ‘partial’ instance (i.e. a less variable font) is produced when some of the axes are omitted, or restricted with a new range.

Tuples that do not participate are kept as they are. Those that have 0 influence at the given location are removed from the variation store. Those that are fully instantiated (i.e. all their axes are being pinned) are also removed from the variation store, their scaled deltas accummulated and returned, so that they can be added by the caller to the default instance’s coordinates. Tuples that are only partially instantiated (i.e. not all the axes that they participate in are being pinned) are kept in the store, and their deltas multiplied by the scalar support of the axes to be pinned at the desired location.

Parameters:
  • variations – List[TupleVariation] from either ‘gvar’ or ‘cvar’.

  • axisLimits – NormalizedAxisLimits: map from axis tags to (min, default, max) normalized coordinates for the full or partial instance.

  • origCoords – GlyphCoordinates: default instance’s coordinates for computing ‘gvar’ inferred points (cf. table__g_l_y_f._getCoordinatesAndControls).

  • endPts – List[int]: indices of contour end points, for inferring ‘gvar’ deltas.

Returns:

the overall delta adjustment after applicable deltas were summed.

Return type:

List[float]

fontTools.varLib.instancer.instantiateVARC(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateVVAR(varfont, axisLimits)[source]
fontTools.varLib.instancer.instantiateVariableFont(varfont, axisLimits, inplace=False, optimize=True, overlap=OverlapMode.KEEP_AND_SET_FLAGS, updateFontNames=False, *, downgradeCFF2=False)[source]

Instantiate variable font, either fully or partially.

Depending on whether the axisLimits dictionary references all or some of the input varfont’s axes, the output font will either be a full instance (static font) or a variable font with possibly less variation data.

Parameters:
  • varfont – a TTFont instance, which must contain at least an ‘fvar’ table.

  • axisLimits – a dict keyed by axis tags (str) containing the coordinates (float) along one or more axes where the desired instance will be located. If the value is None, the default coordinate as per ‘fvar’ table for that axis is used. The limit values can also be (min, max) tuples for restricting an axis’s variation range. The default axis value must be included in the new range.

  • inplace (bool) – whether to modify input TTFont object in-place instead of returning a distinct object.

  • optimize (bool) – if False, do not perform IUP-delta optimization on the remaining ‘gvar’ table’s deltas. Possibly faster, and might work around rendering issues in some buggy environments, at the cost of a slightly larger file size.

  • overlap (OverlapMode) – variable fonts usually contain overlapping contours, and some font rendering engines on Apple platforms require that the OVERLAP_SIMPLE and OVERLAP_COMPOUND flags in the ‘glyf’ table be set to force rendering using a non-zero fill rule. Thus we always set these flags on all glyphs to maximise cross-compatibility of the generated instance. You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS. If you want to remove the overlaps altogether and merge overlapping contours and components, you can pass OverlapMode.REMOVE (or REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this requires the skia-pathops package (available to pip install). The overlap parameter only has effect when generating full static instances.

  • updateFontNames (bool) – if True, update the instantiated font’s name table using the Axis Value Tables from the STAT table. The name table and the style bits in the head and OS/2 table will be updated so they conform to the R/I/B/BI model. If the STAT table is missing or an Axis Value table is missing for a given axis coordinate, a ValueError will be raised.

  • downgradeCFF2 (bool) – if True, downgrade the CFF2 table to CFF table when possible ie. full instancing of all axes. This is useful for compatibility with older software that does not support CFF2. Defaults to False. Note that this operation also removes overlaps within glyph shapes, as CFF does not support overlaps but CFF2 does.

fontTools.varLib.instancer.isInstanceWithinAxisRanges(location, axisRanges)[source]
fontTools.varLib.instancer.main(args=None)[source]

Partially instantiate a variable font

fontTools.varLib.instancer.normalize(value, triple, avarMapping)[source]
fontTools.varLib.instancer.parseArgs(args)[source]

Parse argv.

Returns:

3-tuple (infile, axisLimits, options) axisLimits is either a Dict[str, Optional[float]], for pinning variation axes to specific coordinates along those axes (with None as a placeholder for an axis’ default value); or a Dict[str, Tuple(float, float)], meaning limit this axis to min/max range. Axes locations are in user-space coordinates, as defined in the “fvar” table.

fontTools.varLib.instancer.parseLimits(limits: Iterable[str]) Dict[str, AxisTriple | None][source]
fontTools.varLib.instancer.sanityCheckVariableTables(varfont)[source]
fontTools.varLib.instancer.setCvarDeltas(cvt, deltas)[source]
fontTools.varLib.instancer.setMacOverlapFlags(glyfTable)[source]
fontTools.varLib.instancer.setMvarDeltas(varfont, deltas)[source]
fontTools.varLib.instancer.setRibbiBits(font)[source]

Set the head.macStyle and OS/2.fsSelection style bits appropriately.

fontTools.varLib.instancer.verticalMetricsKeptInSync(varfont)[source]

Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.

When applying MVAR deltas to the OS/2 table, if the ascender, descender and line gap change but they were the same as the respective hhea metrics in the original font, this context manager ensures that hhea metrcs also get updated accordingly. The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts to have the hhea metrics be equal to those for compat reasons.

https://learn.microsoft.com/en-us/typography/opentype/spec/mvar https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal https://github.com/fonttools/fonttools/issues/3297