Skip to content

Renderer: image

Image-based renderer utilities.

Transforms a State into a composited RGBA image using per-entity Appearance metadata, property-derived image variants, optional group recoloring and motion glyph overlays.

Rendering Model

  1. Entities occupying the same cell are grouped into categories:
    • Background(s): appearance.background=True (e.g., floor, wall)
    • Main: highest-priority non-background entity
    • Corner Icons: up to four icon entities (appearance.icon=True) placed in tile corners (NW, NE, SW, SE)
    • Others: additional layered entities (drawn between background and main)
  2. A image path is chosen via an object + property signature lookup. If the path refers to a directory, a deterministic random selection occurs.
  3. Group-based recoloring (e.g., matching keys and locks, portal pairs) applies a hue shift while preserving shading (value channel) and saturation rules.
  4. Optional movement direction triangles are overlaid for moving entities.

Customization Hooks

  • Provide a custom image_map for alternative asset packs.
  • Replace or extend DEFAULT_GROUP_RULES to recolor other sets of entities.
  • Supply tex_lookup_fn to implement caching, animation frames, or atlas packing.

Performance Notes

  • A lightweight cache key (path, size, group, movement vector, speed) helps reuse generated PIL images across frames.
  • lru_cache on group_to_color ensures stable, deterministic colors without recomputing HSV conversions.

ImageRenderer(resolution=DEFAULT_RESOLUTION, subicon_percent=DEFAULT_SUBICON_PERCENT, image_map=None, asset_root=DEFAULT_ASSET_ROOT, tex_lookup_fn=None)

render(state)

Render convenience wrapper using stored configuration.

ObjectRendering(appearance, properties, group=None, move_dir=None, move_speed=0) dataclass

Lightweight container capturing render-relevant entity facets.

Attributes:

Name Type Description
appearance Appearance

The entity's appearance component (or a default anonymous one).

properties Tuple[str, ...]

Property component collection names (e.g. ('blocking', 'locked')) used to select image variants.

group str | None

Deterministic recolor group identifier.

move_dir tuple[int, int] | None

(dx, dy) direction for movement glyph overlay.

move_speed int

Movement speed (number of direction triangles to draw).

apply_recolor_if_group(tex, group)

Recolor wrapper that sets hue to the group's color while preserving tone.

Delegates to recolor_image_keep_tone; if no group is provided the image is returned unchanged.

choose_background(object_renderings)

Return the lowest-priority background object. Higher priority values indicate lower importance.

Raises

ValueError If no candidate background exists in the cell.

choose_corner_icons(object_renderings, main)

Return up to four icon objects (excluding main) sorted by priority.

choose_main(object_renderings)

Return the highest-priority non-background object. Lower priority values indicate higher importance.

Returns None if no non-background objects exist.

derive_groups(state, rules=DEFAULT_GROUP_RULES)

Apply grouping rules to each entity.

Later rendering stages may use groups to recolor related entities with a shared hue (e.g., all portals in a pair share the same color while still using the original image shading).

Parameters:

Name Type Description Default
state State

Immutable simulation state.

required
rules List[GroupRule]

Ordered list of functions; first non-None group returned is used.

DEFAULT_GROUP_RULES

Returns:

Type Description
dict[EntityID, str | None]

Dict[EntityID, str | None]: Mapping of entity id to chosen group id (or None if ungrouped).

get_eid_properties_map(state)

Build a mapping from eid to its component store names efficiently.

get_files_in_directory(dir) cached

List image files in a directory.

get_object_renderings(state, eids, groups, eid_properties_map)

Build rendering descriptors for entity IDs in a single cell.

Inspects component PMaps on the State to infer property labels, movement direction and speed, then packages them in ObjectRendering objects for subsequent image lookup and layering decisions.

get_path(object_asset, image_hmap)

Resolve an image path for an object asset signature.

Attempts to find the nearest matching property tuple (maximizing shared properties, minimizing unmatched) to allow images that only specify a subset of possible property labels.

group_to_color(group_id) cached

Deterministically map a group string to an RGB color.

Uses the group id as a seed to generate stable but visually distinct HSV values, then converts them to RGB.

load_image(path, size) cached

Load and resize an image, returning None if inaccessible or invalid.

render(state, resolution=DEFAULT_RESOLUTION, subicon_percent=DEFAULT_SUBICON_PERCENT, image_map=None, asset_root=DEFAULT_ASSET_ROOT, tex_lookup_fn=None, cache=None, cell_cache=None)

Render a State into a PIL Image.

Parameters:

Name Type Description Default
state State

Immutable game state to visualize.

required
resolution int

Output image width in pixels (height derived from aspect ratio).

DEFAULT_RESOLUTION
subicon_percent float

Relative size of corner icons compared to a cell's size.

DEFAULT_SUBICON_PERCENT
image_map ImageMap | None

Mapping from (appearance name, property tuple) to asset path.

None
asset_root str

Root directory containing the asset hierarchy (e.g. "assets").

DEFAULT_ASSET_ROOT
tex_lookup_fn TexLookupFn | None

Override for image loading/recoloring/overlay logic.

None
cache dict | None

Mutable memoization dict keyed by (path, size, group, move_dir, speed).

None
cell_cache dict | None

Optional per-cell composition cache (default lookup only).

None

Returns:

Type Description
Image

Image.Image: Composited RGBA image of the entire grid.

render_image(img, *, render_width, render_height, target_width, target_height)

Finalize the render by resizing if needed.

rendering_sort_key(rendering)

Deterministic sort key for composition ordering and cache stability.

select_image_from_directory(dir, seed) cached

Choose a deterministic random image file from a directory.

validate_appearance_names(state, image_map) cached

Validate that all appearance names in the state have a corresponding image.

Raises:

Type Description
ValueError

If any appearance name in the state is missing from the image map.

validate_image_map_files(image_map, asset_root) cached

Validate that all image paths in the image map exist.

Raises:

Type Description
FileNotFoundError

If any image path in the image map does not exist.