🖋️ text_renders#
auto.text_renders: replace every render key of a text component with a font glyph.
{"render": "steel_ingot"} anywhere a text component can appear (item lore, source lore, a
tellraw, a manual dialog) becomes a bitmap glyph showing that item, so packs can put pictures in
chat and tooltips without hand-managing a font.
The pass runs on the generated files rather than on the definitions:
by that point every item component has already been serialised into loot tables, give commands and dialogs,
so one scan covers all of them at once.
- CONSUMED_KEYS: tuple[str, ...] = ('render', 'height', 'ascent', 'resolution')[source]#
Keys a render node owns; every other key is carried over onto the glyph component.
- get_emitter(
- config: TextRendersConfig | None = None,
The emitter owning this build’s glyphs, created on first use.
Held on
Mem(and reset byplugins.initialize) so the build pass andresolve_renders()draw glyph characters from the same allocator.- Parameters:
config – Configuration, read from the context when omitted.
- Returns:
The emitter for the current build.
- Return type:
- build_replacements(
- requests: list[RenderRequest],
- glyphs: dict[GlyphKey, str],
- font: str,
Turn resolved requests into the slices rewriting a file’s text.
- Parameters:
requests – Requests found in one file.
glyphs – Glyph key -> glyph character.
font – Fully qualified font id to attach to each glyph.
- Returns:
Slices to overwrite; requests whose image could not be resolved are left untouched.
- Return type:
list[Replacement]
- resolve_renders(
- component: TextComponent,
- config: TextRendersConfig | None = None,
Replace every
rendernode of an in-memory text component with its glyph.The build-wide pass already covers everything written to a file, so this is only needed when the glyph string itself is wanted right away, for instance to measure a line.
- Parameters:
component – Component to convert (never mutated).
config – Configuration, read from the context when omitted.
- Returns:
A copy where every render node became a glyph component.
- Return type:
TextComponent
- beet_default(ctx: Context) None[source]#
Main entry point for the text renders plugin.
Scans every generated datapack file for
renderkeys, generates one glyph per distinct(item id, height, ascent, resolution)combination, then rewrites the files to use them.- Parameters:
ctx – The beet context.
config#
Typed configuration for the text renders, read from ctx.meta["stewbeet"]["text_renders"].
- ICON_ID: str = 'ICON'[source]#
Reserved render id resolving to the project
pack.pnginstead of an item.
- DEFAULT_HEIGHT: int = 16[source]#
On-screen glyph height in pixels, used when a render node omits its own “height”.
- DEFAULT_RESOLUTION: int = 0[source]#
Texture height used when a render node omits its own “resolution”. 0 keeps the source image untouched.
- TEXT_CENTER_ABOVE_BASELINE: int = 3[source]#
Vertical center of a line of text, in pixels above the baseline.
Minecraft draws its 8px font with ascent 7, so a character spans from 7px above the baseline down to 1px below it, putting the middle of the text band 3px above the baseline.
- TEXTURE_FOLDER: str = 'font/renders'[source]#
Resource pack folder, relative to textures/, holding the generated glyphs.
- RESOURCE_PATH_ALLOWED: str = 'abcdefghijklmnopqrstuvwxyz0123456789/._-'[source]#
The only characters Minecraft accepts in the path half of a resource location.
- to_resource_path(name: str) str[source]#
Lowercase a generated name and replace anything Minecraft would reject in a resource path.
Minecraft refuses the whole font, not just the offending glyph, when a provider names a texture outside
[a-z0-9/._-]: it fails the resource pack reload with “Not a valid resource location”. The reservedICONid is what hits this in practice, since it reaches the texture name as written, but any item id carrying an uppercase letter would do the same.>>> to_resource_path("ICON_128x128") 'icon_128x128' >>> to_resource_path("demo_steel_ingot_16x16") 'demo_steel_ingot_16x16' >>> to_resource_path("Weird Name!") 'weird_name_'
- class TextRendersConfig(
- *,
- project_id: str,
- font_name: str = 'renders',
- default_height: int = 16,
- default_resolution: int = 0,
- cache_assets: bool = True,
- allow_oversized: bool | None = None,
Bases:
objectTyped mirror of the
text_rendersstewbeet config block.>>> config = TextRendersConfig(project_id="mypack") >>> config.font 'mypack:renders' >>> config.default_height 16 >>> TextRendersConfig(project_id="mypack", font_name="glyphs").font 'mypack:glyphs'
- default_resolution: int[source]#
Texture height used when a render node omits its own “resolution”. 0 keeps the source image untouched.
- allow_oversized: bool | None[source]#
Whether a render too big for one glyph may be cut into several, or None to ask in the terminal.
- classmethod from_meta(
- ctx: Context,
Build a
TextRendersConfigfrom the beet context meta.
- default_ascent(height: int) int[source]#
Baseline offset centering a glyph of
heightpixels on the surrounding line of text.A bitmap glyph’s top sits
ascentpixels above the baseline, so centering its middle on the text band givesascent = height / 2 + 3, which lands on 7 for an 8px glyph, exactly what vanilla uses. Minecraft rejects a provider whose ascent exceeds its height, so tiny glyphs are clamped and sit slightly low.>>> default_ascent(8) # same as vanilla's 8px font 7 >>> default_ascent(10), default_ascent(16), default_ascent(64) (8, 11, 35) >>> default_ascent(4) # clamped: ascent may never exceed height 4
- scale_to_height(
- size: tuple[int, int],
- height: int,
Size of an image scaled to
heightpixels tall, keeping its aspect ratio.Minecraft derives a bitmap glyph’s on-screen width from the texture’s aspect ratio, so the texture only needs scaling. Item renders are stored untouched by default, and this shrinks them for a pack trading sharpness for a smaller download.
>>> scale_to_height((16, 16), 64) # square source stays square (64, 64) >>> scale_to_height((32, 16), 64) # a 2:1 source keeps its ratio (128, 64) >>> scale_to_height((16, 16), 16) # already the right height (16, 16) >>> scale_to_height((3, 40), 4) # never collapses to a zero width (1, 4)
- fitting_resolution(size: tuple[int, int], limit: int) int[source]#
Largest texture height keeping both sides of an image within
limitpixels.This is the fallback for a render whose splicing was turned down: the picture is stored as one glyph again, shrunk just enough for Minecraft to display it at all.
>>> fitting_resolution((1000, 370), 256) # a wide image is bound by its width 94 >>> fitting_resolution((512, 512), 256) 256 >>> fitting_resolution((64, 64), 256) # already small enough to keep untouched 64
- first_frame_box(
- size: tuple[int, int],
Crop box isolating the first frame of a vertical animation strip, None when the image is not one.
An animated Minecraft texture is a column of square frames, so a source taller than it is wide by a whole number of frames would otherwise render as a long ribbon. This is the same heuristic
stewbeet.plugins.resource_pack.check_power_of_2uses to recognise animated textures.>>> first_frame_box((16, 96)) # animated: 6 frames of 16x16 (0, 0, 16, 16) >>> first_frame_box((16, 16)) is None True >>> first_frame_box((64, 32)) is None # wider than tall, not a strip True
confirm#
One-time confirmation before a build starts baking renders too big for a single glyph.
Splicing a picture into a grid of glyphs is cheap to write and expensive to ship:
a 1000x370 logo becomes eight textures the resource pack has to carry.
The question is asked in the terminal the first time a project runs into it,
and the answer is remembered in .beet_cache so later builds stay quiet.
meta.stewbeet.text_renders.allow_oversized answers it up front and skips the prompt.
- CACHE_NAME: str = 'stewbeet_text_renders'[source]#
beet cache holding the remembered answer, next to the rest of the project cache.
- prompt() bool | None[source]#
The answer typed in the terminal, or None when there is nobody to answer.
A build driven by a script, a CI job or an editor has no terminal to read from, and blocking one forever on a question is worse than the pack size it was meant to save.
- Returns:
True to cut the render into glyphs, False to shrink it, None when unanswered.
- Return type:
bool | None
- ask_oversized(
- item_id: str,
- stored: tuple[int, int],
- tiles: int,
Ask once whether renders bigger than a font atlas may be baked, and remember the answer.
Answering no shrinks the render down to a single glyph instead, which keeps the pack small at the cost of sharpness. Outside a terminal (a CI build, a watch loop) there is nobody to answer, so the render is baked and the reason is printed rather than silently changing what gets built.
- Parameters:
item_id – Render that ran into the limit.
stored – Pixel size its texture would be stored at.
tiles – Number of glyph textures it would be cut into.
- Returns:
True to splice the render, False to shrink it to a single glyph.
- Return type:
bool
emit#
Turning render requests into font glyphs.
One GlyphAllocator collects every provider of the build. Each distinct
(item id, height, ascent, resolution) gets its own glyph character, while the textures backing
them are written once per (item id, stored pixels), so several glyphs can share one image.
A render Minecraft cannot fit in a single glyph (more than 256 texture pixels on a side, or floating above the baseline) is cut into a grid instead: several glyphs and the spacing putting them back together, which the text component carries as one string of characters like any other glyph.
- GlyphKey = GlyphKey[source]#
Identity of a glyph: item id, displayed height, ascent, and texture resolution.
- class GlyphEmitter(config: ~stewbeet.plugins.auto.text_renders.config.TextRendersConfig, glyphs: dict[~stewbeet.plugins.auto.text_renders.emit.GlyphKey, str] = <factory>, chars_by_provider: dict[tuple[str, int, int], str] = <factory>, written: int = 0, oversized: bool | None = None)[source]#
Bases:
objectAllocates a glyph per distinct render request and writes the resulting font.
>>> emitter = GlyphEmitter(config=TextRendersConfig(project_id="demo")) >>> emitter.texture_name("demo:steel_ingot", (16, 16)) 'font/renders/demo_steel_ingot_16x16' >>> emitter.texture_name("minecraft:stone", (64, 64)) # named after the stored pixels, not the displayed height 'font/renders/minecraft_stone_64x64'
- config: TextRendersConfig[source]#
Font name, default height, default resolution and cache flag.
- allocator: GlyphAllocator[source]#
Collects the providers of every emitted glyph.
- glyphs: dict[GlyphKey, str][source]#
Glyph key -> glyph characters, so the same render costs one provider.
- chars_by_provider: dict[tuple[str, int, int], str][source]#
(texture, ascent, height) -> glyph character. Two requests landing on the same provider share it.
- written: int[source]#
Providers already merged into the font, so calling
emit()again never duplicates them.
- oversized: bool | None[source]#
Answer to the oversized-render question, asked at most once per build.
- texture_name(
- item_id: str,
- stored: tuple[int, int],
Resource pack texture name (relative to
textures/) for an item stored atstoredpixels.The name follows the stored pixels rather than the displayed height, so the same image shown at several heights is only written once. It also goes through
to_resource_path(), without which the reservedICONid would name a texture Minecraft refuses to load.
- source_images(
- item_ids: set[str],
Resolve the PNG backing each item, batching the renders and the downloads.
The reserved
ICONid resolves to the projectpack.pnginstead of an item.
- allow_oversized(
- item_id: str,
- layout: SpliceLayout,
Whether a render too big for one glyph may be cut into several.
The configured answer wins; without one the question is asked in the terminal and remembered, then reused for the rest of the build.
- warn_capped(
- item_id: str,
- layout: SpliceLayout,
- wanted: tuple[int, int],
Tell the author when the ascent forced a render to be stored smaller than it asked for.
Minecraft refuses a glyph whose ascent exceeds its height, so the topmost tile has to span from the top of the picture down to the baseline and fit in one glyph on its own. Cutting that row thinner does not help, since every row above the baseline still reaches it: only a smaller ascent does, which is why the message names the one that would have worked. Snapping to a whole multiple of the displayed height is not a cap, so it stays silent.
- provider_char(
- file: str,
- ascent: int,
- height: int,
Glyph character of the
(file, ascent, height)provider, registering it on first use.Two renders differing only in ascent are two glyphs sharing one texture, while two that resolve identically share the glyph itself.
- prepare(
- opened: Image,
- frame: tuple[int, int, int, int] | None,
- size: tuple[int, int],
The source image in RGBA, cropped to its first animation frame and resized to
size.
- single_glyph(
- item_id: str,
- opened: Image,
- frame: tuple[int, int, int, int] | None,
- stored: tuple[int, int],
- height: int,
- ascent: int,
One glyph showing the whole image, the shape every render small enough to fit takes.
The stored texture keeps the source aspect ratio: Minecraft has no width to set, it derives the on-screen width from the texture itself.
- spliced_glyph(
- item_id: str,
- opened: Image,
- frame: tuple[int, int, int, int] | None,
- layout: SpliceLayout,
A grid of glyphs showing one image, with the spacing that puts it back together.
Each row is drawn left to right, a negative space brings the pen back to the left edge before the next one, and the rows hang from decreasing ascents. Every tile is followed by the spacing correcting Minecraft’s own advance, so the tiles touch without overlapping.
- Parameters:
item_id – Fully qualified item id, used to name the textures.
opened – Source image, still at its original size.
frame – First frame of an animation strip, or None.
layout – Grid to cut, from
plan_splice().
- Returns:
The glyph characters to write in the text component, in drawing order.
- Return type:
str
- emit(
- requests: list[RenderRequest],
Generate one glyph per distinct request, and write the font.
Requests whose glyph already exists are skipped, so calling this again only pays for the new ones and never re-renders or re-downloads an image.
- Parameters:
requests – Every render node found in the build.
- Returns:
Glyph key -> glyph characters, missing images left out.
- Return type:
dict
- render_glyph(
- key: GlyphKey,
- opened: Image,
The characters drawing one requested image: one glyph, or a grid of them when too big or floating over the baseline.
- fitted_layout(
- item_id: str,
- native: tuple[int, int],
- height: int,
- ascent: int,
- resolution: int,
The grid an image is cut into and the size it is stored at, no grid when one glyph holds it on the baseline.
Too big for one glyph, or floating over the baseline, both make a grid, which may still come out as a single tile once an image that may not stay oversized has its resolution capped to what fits.
scan#
Finding render nodes inside already-generated files.
Everything here works on fragments of text rather than parsed JSON: by the time this plugin runs,
text components live inside mcfunction commands and SNBT payloads where keys may be unquoted and strings single-quoted,
so json.loads is not an option. Only the render, height, ascent and resolution fragments of a node are touched;
every other key is left exactly as written.
- RENDER_RE: Pattern[str] = re.compile('\n\t(?P<key_quote>["\'])?render(?(key_quote)(?P=key_quote)) # Match "render", \'render\', or render\n\t\\s*:\\s* # Match the colon and spaces\n\t(?P<q, re.VERBOSE)[source]#
Matches the
"render": "<item id>"fragment of a text component.
- HEIGHT_RE: Pattern[str] = re.compile('(?:["\']?height["\']?)\\s*:\\s*(\\d+)')[source]#
Matches a sibling
"height": <int>fragment.
- ASCENT_RE: Pattern[str] = re.compile('(?:["\']?ascent["\']?)\\s*:\\s*(-?\\d+)')[source]#
Matches a sibling
"ascent": <int>fragment.
- RESOLUTION_RE: Pattern[str] = re.compile('(?:["\']?resolution["\']?)\\s*:\\s*(\\d+)')[source]#
Matches a sibling
"resolution": <int>fragment.
- TEXT_KEY_RE: Pattern[str] = re.compile('(?:["\']?text["\']?)\\s*:')[source]#
Matches a sibling
"text":key, which a render node must not carry.
- class RenderRequest(
- item_id: str,
- height: int,
- ascent: int,
- resolution: int,
- start: int,
- end: int,
- drops: tuple[tuple[int, int], ...],
Bases:
objectOne
rendernode found in a file, and everything needed to rewrite it.>>> request = RenderRequest(item_id="mypack:steel_ingot", height=16, ascent=7, resolution=64, start=0, end=10, drops=()) >>> request.glyph_key ('mypack:steel_ingot', 16, 7, 64)
- top_level_search(
- node: str,
- pattern: Pattern[str],
Search
patternin a serialized object, ignoring matches nested in a sub-object.nodestarts at its own opening brace, so a match belongs to the node itself only when the brace depth at that point is exactly 1. Braces inside quoted strings are skipped.>>> import re >>> height = re.compile(r'"height"\s*:\s*(\d+)') >>> top_level_search('{"render":"a","height":8}', height).group(1) '8' >>> top_level_search('{"render":"a","hover":{"height":8}}', height) is None True >>> top_level_search('{"render":"a{","height":4}', height).group(1) '4'
- after_string(text: str, opening: int) int[source]#
Index just past the string literal whose quote is at
opening, escapes included.>>> after_string("'a\\'b' + c", 0) 6
- widen_to_comma(
- string: str,
- start: int,
- end: int,
Grow a key:value span to swallow one neighbouring comma, so removing it keeps valid syntax.
The comma after the fragment is preferred; the one before is used when the fragment is last.
>>> widen_to_comma('{"a":1,"b":2}', 7, 12) # trailing fragment: eats the comma before it (6, 12) >>> widen_to_comma('{"a":1,"b":2}', 1, 6) # leading fragment: eats the comma after it (1, 7)
- merge_spans(
- string: str,
- spans: list[tuple[int, int]],
Group the consumed siblings into spans that can be removed without breaking the syntax.
Neighbouring siblings are joined first (they are separated by a single comma, which goes away with them), and only the resulting group claims one outer comma. Widening each sibling before joining would instead strand the comma sitting in front of the group.
>>> merge_spans('{"a":1,"b":2,"c":3}', [(7, 12), (13, 18)]) # two neighbours: one group ((6, 18),) >>> merge_spans('{"a":1,"b":2,"c":3}', [(7, 12)]) # a single sibling in the middle ((7, 13),) >>> merge_spans('{"a":1}', []) ()
- qualify(item_id: str, project_id: str, icon_id: str) str[source]#
Namespace a bare render id with the project namespace, leaving the reserved icon alone.
>>> qualify("steel_ingot", "mypack", "ICON") 'mypack:steel_ingot' >>> qualify("minecraft:stone", "mypack", "ICON") 'minecraft:stone' >>> qualify("mechanization:tin_ore", "mypack", "ICON") 'mechanization:tin_ore' >>> qualify("ICON", "mypack", "ICON") 'ICON'
- find_requests(
- string: str,
- project_id: str,
- default_height: int,
- icon_id: str,
- default_resolution: int = 0,
Collect every
rendernode of a file’s text, one request per node in file order.- Parameters:
project_id – Namespace bare ids belong to.
default_height – Displayed height used when a node omits its own.
icon_id – Reserved id standing for the project logo.
default_resolution – Texture height used when a node omits its own.
>>> requests = find_requests('tellraw @a {"render":"steel_ingot","height":8}', "mypack", 16, "ICON") >>> requests[0].item_id, requests[0].height, requests[0].ascent ('mypack:steel_ingot', 8, 7) >>> find_requests('tellraw @a {"render":"minecraft:stone"}', "mypack", 16, "ICON")[0].glyph_key ('minecraft:stone', 16, 11, 0)