# 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: .. code-block:: pycon

    >>>
    >> 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): .. code-block:: pycon

    >>>
    >> 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: .. code-block:: pycon

    >>>
    >> 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, by default the varLib.instancer will keep the axis and the corresponding deltas, whereas mutator implicitly drops the axis at its default coordinate. To obtain the same behavior as mutator, pass the static=True parameter or the –static CLI option.

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; .. code-block:: pycon

      >>>
      >> font = instancer.instantiateVariableFont(varfont, {"wght": None})

L2

  dropping one or more axes while pinning them at non-default locations; .. code-block:: pycon

      >>>
      >> 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. .. code-block:: pycon

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

L4

  moving the default location of an axis, by specifying (min,defalt,max) values: .. code-block:: pycon

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

Both TrueType-flavored (glyf+gvar) variable and CFF2 variable fonts are supported.

fontTools.varLib.instancer.AxisRange(minimum, maximum)

fontTools.varLib.instancer.NormalizedAxisRange(minimum, maximum)

class fontTools.varLib.instancer.AxisTriple(minimum: float | None, default: float | None, maximum: float | None)

  Bases: `Sequence`

  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.

  minimum: float | None
  default: float | None
  maximum: float | None
  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).

  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.

class fontTools.varLib.instancer.NormalizedAxisTriple(minimum: float, default: float, maximum: float)

  Bases: `AxisTriple`

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

  minimum: float
  default: float
  maximum: float

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

  Bases: `AxisTriple`

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

  minimum: float
  default: float
  maximum: float
  distanceNegative: float | None = 1
  distancePositive: float | None = 1
  reverse_negate()
  renormalizeValue(v, extrapolate=True)

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

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

  Bases: `_BaseAxisLimits`

  Maps axis tags (str) to AxisTriple values.

  limitAxesAndPopulateDefaults(varfont) → AxisLimits

    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

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

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

class fontTools.varLib.instancer.NormalizedAxisLimits(*args, **kwargs)

  Bases: `_BaseAxisLimits`

  Maps axis tags (str) to NormalizedAxisTriple values.

class fontTools.varLib.instancer.OverlapMode(*values)

  Bases: `IntEnum`

  KEEP_AND_DONT_SET_FLAGS = 0
  KEEP_AND_SET_FLAGS = 1
  REMOVE = 2
  REMOVE_AND_IGNORE_ERRORS = 3

fontTools.varLib.instancer.instantiateVARC(varfont, axisLimits)

fontTools.varLib.instancer.instantiateTupleVariationStore(variations, axisLimits, origCoords=None, endPts=None)

  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.changeTupleVariationsAxisLimits(variations, axisLimits)

fontTools.varLib.instancer.changeTupleVariationAxisLimit(var, axisTag, axisLimit)

fontTools.varLib.instancer.instantiateCFF2(varfont, axisLimits, *, round=<built-in function round>, specialize=True, generalize=False, downgrade=False)

fontTools.varLib.instancer.instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True)

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

fontTools.varLib.instancer.instantiateGvar(varfont, axisLimits, optimize=True)

fontTools.varLib.instancer.setCvarDeltas(cvt, deltas)

fontTools.varLib.instancer.instantiateCvar(varfont, axisLimits)

fontTools.varLib.instancer.setMvarDeltas(varfont, deltas)

fontTools.varLib.instancer.verticalMetricsKeptInSync(varfont)

  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

fontTools.varLib.instancer.instantiateMVAR(varfont, axisLimits)

fontTools.varLib.instancer.instantiateHVAR(varfont, axisLimits)

fontTools.varLib.instancer.instantiateVVAR(varfont, axisLimits)

fontTools.varLib.instancer.instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits, hierarchical=False)

  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.instantiateOTL(varfont, axisLimits)

fontTools.varLib.instancer.downgradeCFF2ToCFF(varfont)

fontTools.varLib.instancer.instantiateAvar(varfont, axisLimits)

fontTools.varLib.instancer.isInstanceWithinAxisRanges(location, axisRanges)

fontTools.varLib.instancer.instantiateFvar(varfont, axisLimits)

fontTools.varLib.instancer.instantiateSTAT(varfont, axisLimits)

fontTools.varLib.instancer.axisValuesFromAxisLimits(stat, axisLimits)

fontTools.varLib.instancer.setMacOverlapFlags(glyfTable)

fontTools.varLib.instancer.normalize(value, triple, avarMapping)

fontTools.varLib.instancer.sanityCheckVariableTables(varfont)

fontTools.varLib.instancer.instantiateVariableFont(varfont, axisLimits, inplace=False, optimize=True, overlap=OverlapMode.KEEP_AND_SET_FLAGS, updateFontNames=False, *, downgradeCFF2=False, static=False)

  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.

    - static (bool) – if True, generate a full instance (static font) instead of a partial instance (variable font).

fontTools.varLib.instancer.setRibbiBits(font)

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

fontTools.varLib.instancer.parseLimits(limits: Iterable[str]) → Dict[str, AxisTriple | None]

fontTools.varLib.instancer.parseArgs(args)

  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.main(args=None)

  Partially instantiate a variable font