Porytiles
Loading...
Searching...
No Matches
porytiles Namespace Reference

Namespaces

namespace  anim
 
namespace  attr
 
namespace  detail
 
namespace  details
 
namespace  di
 
namespace  metatile
 
namespace  pal
 
namespace  tile
 

Classes

struct  AbsolutePosition
 Position state for a color assigned to a specific palette slot. More...
 
struct  AlignmentFailureCounts
 Detailed records of alignment failures during Indirect link application and chain resolution. More...
 
class  Animation
 A complete tileset animation with name, configuration, and frame data. More...
 
class  AnimCodeGenerator
 Generates C header code for tileset animations. More...
 
class  AnimCodeParser
 Parses C code to extract tileset animation parameters using callback chain discovery. More...
 
class  AnimDecompiler
 Decompiles indexed animation tiles to RGBA format. More...
 
class  AnimFrame
 Represents a single frame of an animation, containing tiles and a frame name. More...
 
class  AnimJsonParser
 Parses and writes animation configuration JSON files (anim.json). More...
 
class  AnimKeyFrameMangler
 Service that mangles duplicate key frame tiles to make them unique. More...
 
struct  AnimOverrideEntry
 A manual override that maps a specific metatile entry to an animation subtile. More...
 
class  AnimParams
 Configuration parameters for a single tileset animation. More...
 
struct  AnimTileMatch
 Result of matching a tile against animation keyframes. More...
 
class  AnimTileMatcher
 Matches tiles against animation keyframe tiles for compilation. More...
 
class  AnsiStyledTextFormatter
 TextFormatter implementation that applies ANSI escape codes for terminal styling. More...
 
class  AppConfig
 Interface that defines a complete app layer configuration. More...
 
class  ArrayDeclaration
 Represents a parsed C pointer array declaration. More...
 
class  ArtifactChecksumProvider
 Abstract service for managing artifact checksums. More...
 
class  ArtifactKey
 A type-safe wrapper for artifact keys. More...
 
class  AsciiTilePrinter
 A TilePrinter implementation that generates ASCII art tiles with formatting based on the provided TextFormatter. More...
 
class  AttributesCsvLoader
 A service that loads metatile attributes from a CSV file. More...
 
struct  BacktrackingParams
 Per-strategy parameters for the BacktrackingStrategy packing algorithm. More...
 
class  BacktrackingStrategy
 Packing strategy that assigns tiles to palettes using BFS/DFS backtracking with a fallback matrix. More...
 
class  BaseGameDetector
 Detects the base game of a decompilation project. More...
 
class  BehaviorMapProvider
 Abstract interface for providing two-way metatile behavior mappings. More...
 
class  BestFusionStrategy
 Greedy palette packing algorithm using weighted cost optimization. More...
 
class  BufferedUserDiagnostics
 Testing implementation of UserDiagnostics that buffers all diagnostic output. More...
 
class  CanonicalPixelTile
 A PixelTile representation that stores the canonical (lexicographically minimal) orientation among all flipped variants. More...
 
class  CanonicalShapeTile
 A ShapeTile representation that stores the canonical (lexicographically minimal) orientation among all flipped variants. More...
 
class  ChainableResult
 A result type that maintains a chainable sequence of errors for debugging and error reporting. More...
 
class  ChainableResult< void, E >
 Template specialization of ChainableResult for void success type. More...
 
struct  CliOptionMeta
 Metadata for a single CLI option, used for shell completion generation. More...
 
class  CliOptionProvider
 ConfigProvider implementation that reads values from CLI options. More...
 
struct  CliOptionStorage
 Storage struct for CLI option values. More...
 
class  ColorIndex
 Represents a color index value for palette operations. More...
 
class  ColorIndexMap
 A bidirectional mapping between pixel color values and sequential integer indices. More...
 
class  ColorPalettePrinter
 
class  ColorSet
 A set of colors represented as a bitset. More...
 
class  CompilePrimaryTileset
 Use case for compiling a primary Tileset. More...
 
class  CompileSecondaryTileset
 Use case for compiling a secondary Tileset. More...
 
struct  ConfigPODField
 A lightweight wrapper for per-field configuration values with source metadata. More...
 
class  ConfigProvider
 An interface which config implementations can use to load config values. More...
 
class  ConfigValue
 A container that wraps a configuration value with its name and source information. More...
 
class  CParserContext
 Context object providing rich error formatting for C/C++ parsing. More...
 
class  CParserFacade
 High-level facade for parsing C/C++ source files. More...
 
class  CreatePrimaryTileset
 Use case for creating a new primary Tileset from scratch. More...
 
class  CreateSecondaryTileset
 Use case for creating a new secondary Tileset from scratch. More...
 
class  DecompilePrimaryTileset
 Use case for decompiling a primary Tileset. More...
 
class  DefaultProvider
 A default implementation of ConfigProvider that provides sensible default values. More...
 
class  DefineStatement
 Represents a parsed #define preprocessor statement. More...
 
class  DesignatedInitializerField
 Represents a single designated initializer field from a C struct initialization. More...
 
class  DiagnosticTagFilter
 Regex-based include/exclude filter for diagnostic tags. More...
 
class  DomainConfig
 Interface that defines a complete domain layer configuration. More...
 
class  DynamicCasedName
 A smart string wrapper that preserves word structure for lossless case format conversion. More...
 
class  EncounterTypeMapProvider
 Abstract interface for providing two-way metatile encounter type mappings. More...
 
class  EnumDeclaration
 Represents a parsed C enum declaration. More...
 
class  EnumMember
 Represents a single member (constant) within a C enum declaration. More...
 
class  Error
 Abstract interface for all error types used in ChainableResult error chains. More...
 
class  FileHighlightPrinter
 A service for printing file lines with highlighted lines and line numbers. More...
 
class  FilePalLoader
 A service interface that loads a fixed-length Palette from a given file. More...
 
class  FilePalSaver
 A service interface that saves a fixed-length Palette to a given file. More...
 
class  FilteredUserDiagnostics
 Decorator that applies tag-based filtering to any UserDiagnostics implementation. More...
 
struct  FirstWriterWinsDetail
 Detail record for a single first-writer-wins conflict during Indirect link application. More...
 
class  FormatParam
 A text parameter with associated styling for formatted output. More...
 
class  FormattableError
 General-purpose error implementation with formatted message support. More...
 
struct  FrameLoadResult
 Result of loading an animation frame from a PNG file. More...
 
class  FunctionCallInfo
 Represents a parsed function call expression within a token stream. More...
 
class  FunctionDefinition
 Represents a parsed C function definition. More...
 
class  HeaderBehaviorMapProvider
 Loads behavior mappings from a C/C++ header file containing behavior definitions. More...
 
class  HeaderDefineProvider
 A ConfigProvider implementation that reads configuration values from #define directives in a header file. More...
 
class  HeaderEncounterTypeMapProvider
 Loads encounter type mappings from a C/C++ header file containing encounter definitions. More...
 
class  HeaderTerrainTypeMapProvider
 Loads terrain type mappings from a C/C++ header file containing terrain definitions. More...
 
class  Image
 A template for two-dimensional images with arbitrarily typed pixel values. More...
 
class  ImageLoadError
 
class  ImageTileizer
 Service for converting images into collections of 8x8 tiles. More...
 
class  ImportPrimaryTileset
 Use case for importing a primary Tileset. More...
 
class  IncbinDeclaration
 Represents a parsed INCBIN array declaration from C source code. More...
 
class  IncbinDeclarationAppender
 Appends INCBIN declarations for Porytiles-managed tileset assets. More...
 
class  IndexPixel
 Represents an indexed color pixel. More...
 
struct  IndirectLink
 Instruction linking a source color to a reference color in another palette. More...
 
struct  IndirectPosition
 Position state for a color whose slot is determined by another color in another palette. More...
 
class  InfraConfig
 Interface that defines a complete infra layer configuration. More...
 
class  JascPalLoader
 An implementation of FilePalLoader that loads palettes from JASC-PAL (Paintshop Pro) pal files. More...
 
class  JascPalSaver
 An implementation of FilePalSaver that saves palettes to JASC-PAL (Paintshop Pro) pal files. More...
 
class  LayerImageMetatileizer
 Service for converting layer images into collections of metatiles. More...
 
class  LayerModeConverter
 
struct  LayerValue
 A small container that holds an optional-wrapped value, validation state, and metadata about the value source. More...
 
class  LayoutMetadataProvider
 Abstract interface for querying layout metadata by name. More...
 
class  LazyLayeredConfig
 A Config implementation that lazily pulls a config value by consulting multiple priority-ordered backing ConfigProviders . More...
 
class  Lexer
 Lexical analyzer for C/C++ source code. More...
 
struct  MangleResult
 Result of the mangling operation. More...
 
class  Metatile
 The core tileset entity - a 2x2 grid of PixelTile objects arranged into three layers. More...
 
class  MetatileAttribute
 Represents the attributes of a single metatile. More...
 
class  MetatileDecompiler
 
class  MetatilesHeaderProvider
 A ConfigProvider that auto-detects metatile attribute size from metatiles.h declarations. More...
 
class  NoopArtifactChecksumProvider
 An implementation of ArtifactChecksumProvider that just does nothing. More...
 
class  NullUserDiagnostics
 Silent diagnostics implementation that suppresses all output. More...
 
struct  OverloadAndRemoveParams
 Per-strategy parameters for the OverloadAndRemoveStrategy packing algorithm. More...
 
class  OverloadAndRemoveStrategy
 Packing strategy that assigns tiles to palettes using overload-and-remove with multi-start. More...
 
class  OverrideConfigProvider
 A ConfigProvider that overrides selected config values for a single scope. More...
 
class  PackableTile
 Wraps a ColorSet with a tile ID for tracking during palette packing. More...
 
class  PackedPalette
 Represents a hardware palette after packing with accumulated colors and assigned tiles. More...
 
struct  PackingInput
 Input data aggregate for the low-level palette packing algorithm. More...
 
struct  PackingOutput
 The final palette assignments after a successful packing operation. More...
 
struct  PackingParams
 The input parameters for a packing operation. More...
 
class  PackingStrategy
 Abstract interface for palette packing algorithms. More...
 
struct  PackingStrategyParams
 Container for per-strategy packing parameters. More...
 
class  Palette
 A generic palette container for colors that support transparency checking. More...
 
class  PaletteHint
 Represents a palette hint for the palette packing algorithm. More...
 
class  PaletteIndex
 Represents a palette index value within a particular palette. More...
 
struct  PaletteMatchResult
 Result type for palette matching operations. More...
 
class  PalettePacker
 Domain service that packs ColorSets into hardware palettes. More...
 
struct  PalettePacking
 Result from the high-level tile packing operation. More...
 
class  PalettePool
 Manages allocation of hardware palette indexes with stack-based checkout semantics. More...
 
class  PalettePrinter
 A collection of printer functions for the Palette and related types. More...
 
class  Parser
 Parser for C preprocessor constructs. More...
 
struct  PerAnimOverride
 Per-animation configuration override for animation decompilation. More...
 
struct  PixelMangleChange
 A single pixel modification within a tile. More...
 
class  PixelTile
 An 8x8 tile backed by literal-array-based per-pixel storage of an arbitrary pixel type. More...
 
class  PlainTextFormatter
 TextFormatter implementation that strips all styling from text. More...
 
class  PngIndexedImageLoader
 An image loader that reads PNG files to create an Image with an index pixel type. More...
 
class  PngIndexedImageSaver
 An image saver that saves PNG files from an Image with an index pixel type. More...
 
class  PngRgbaImageLoader
 An image loader that reads PNG files to create an Image with an Rgba32 pixel type. More...
 
class  PngRgbaImageSaver
 An image saver that saves PNG files from an Image with an Rgba32 pixel type. More...
 
class  PorymapLayoutComponent
 
class  PorymapTilesetComponent
 
class  PorytilesFormatter
 Custom CLI11 formatter for cleaner help output. More...
 
class  PorytilesLayoutComponent
 
class  PorytilesTilesetComponent
 
class  PorytilesTilesetManager
 Abstract interface for querying Porytiles tileset ownership. More...
 
struct  PostResolutionMismatchDetail
 Detail record for a post-resolution slot mismatch. More...
 
struct  PrefilledDestinationConflictDetail
 Detail record for a single prefilled destination conflict during Indirect chain resolution. More...
 
class  PrefilledPalette
 Pre-assigned palette with wildcard support for palette packing. More...
 
struct  PrefilledSourceConflictDetail
 Detail record for a single prefilled source conflict during Indirect link application. More...
 
class  PrimaryTilesetDecompiler
 
class  PrimaryTilesetImporter
 Domain service interface for importing vanilla (non-Porytiles-managed) tilesets into a PorymapTilesetComponent. More...
 
class  ProjectArtifactChecksumProvider
 Pokeemerald project filesystem-based implementation of ArtifactChecksumProvider. More...
 
class  ProjectLayoutMetadata
 Represents parsed metadata for a single layout from layouts.json. More...
 
class  ProjectLayoutMetadataProvider
 Provides a pokeemerald project filesystem-based implementation for LayoutMetadataProvider. More...
 
class  ProjectPorytilesTilesetManager
 Manages Porytiles-owned tilesets via TilesetManifest JSON files. More...
 
class  ProjectPrimaryTilesetImporter
 Infra-layer implementation of PrimaryTilesetImporter for pokeemerald project structure. More...
 
class  ProjectTilesetAnimsModifier
 Modifies tileset_anims.c to include Porytiles-managed animation code headers. More...
 
class  ProjectTilesetArtifactKeyProvider
 Provides a pokeemerald project filesystem-based implementation for TilesetArtifactKeyProvider. More...
 
class  ProjectTilesetArtifactPaths
 Represents resolved filesystem paths for tileset artifacts from INCBIN declarations. More...
 
class  ProjectTilesetArtifactReader
 Provides a filesystem-based implementation for TilesetArtifactReader. More...
 
class  ProjectTilesetArtifactWriter
 Provides a filesystem-based implementation for TilesetArtifactWriter. More...
 
class  ProjectTilesetMetadata
 Represents raw parsed metadata from a tileset struct in headers.h. More...
 
class  ProjectTilesetMetadataProvider
 Provides a pokeemerald project filesystem-based implementation for TilesetMetadataProvider. More...
 
class  ProjectTilesetMetadataWriter
 Provides surgical update capability for tileset metadata in headers.h files. More...
 
class  ProjectVanillaAnimImporter
 Imports vanilla animation metadata and frame data as IndexPixel tiles. More...
 
struct  ProvenanceChainLink
 A container that pairs a provider name with its LayerValue response. More...
 
class  Rgba32
 Represents a 32-bit RGBA color. More...
 
struct  RgbColor
 RGB color representation for extracting color components from Style values. More...
 
struct  ShapeGroup
 A group of tiles that share the same canonical shape but have different color assignments. More...
 
struct  ShapeGroupMember
 A member of a ShapeGroup, representing one tile that shares a canonical shape with other members. More...
 
struct  ShapeGroupMetadata
 Metadata that maps PackableTile IDs to shape group membership for sharing-aware packing. More...
 
class  ShapeMask
 Represents which pixels in an 8x8 tile are non-transparent. More...
 
class  ShapeTile
 An 8x8 tile backed by mask-based storage that maps shape regions to pixel values. More...
 
struct  SourcePosition
 Represents a position within source content. More...
 
class  StderrStyledUserDiagnostics
 Concrete implementation of UserDiagnostics that outputs structured messages to stderr, optionally with colored formatting. More...
 
class  StreamDigest
 Computes the MD5 digest of an input stream. More...
 
struct  StringViewSourceLoc
 A wrapper for std::string_view with a taggable std::source_location. More...
 
class  StructInitializerDeclaration
 Represents a parsed C struct variable declaration with its initializer fields. More...
 
class  StructVariableDeclaration
 Represents a parsed C struct variable declaration. More...
 
class  Style
 Text styling class supporting formatting, foreground colors, and background colors. More...
 
class  TerrainTypeMapProvider
 Abstract interface for providing two-way metatile terrain type mappings. More...
 
class  TextFormatter
 Abstract base class for applying text styling with context-aware formatting. More...
 
struct  TileMangleRecord
 Record of all pixel modifications made to a single tile during mangling. More...
 
class  TilemapEntry
 Represents a tilemap entry referencing a tile with palette and flip attributes. More...
 
class  TilePrinter
 A collection of printer functions for various tile types. More...
 
class  Tileset
 A complete tileset containing both Porytiles and Porymap components. More...
 
class  TilesetArtifactKeyProvider
 Abstract interface for generating keys and discovering tileset artifacts in a backing store. More...
 
class  TilesetArtifactReader
 Abstract interface for reading tileset artifacts from a backing store into a Tileset object. More...
 
class  TilesetArtifactWriter
 Abstract interface for writing tileset artifacts from a Tileset object to a backing store. More...
 
class  TilesetCompiler
 Service that compiles a Tileset (primary or secondary). More...
 
struct  TilesetCompileValidatorServices
 Parameter store for common services used by tileset compile validators. More...
 
class  TilesetCreator
 Domain service for creating new tilesets from scratch. More...
 
class  TilesetManifest
 Stores manifest metadata for Porytiles-managed tilesets. More...
 
class  TilesetMetadataProvider
 Abstract interface for querying tileset metadata by name. More...
 
class  TilesetRepo
 Repository interface for the Tileset aggregate root. More...
 
class  TilesPngWorkspace
 A workspace for managing canonical IndexPixel tiles destined for tiles.png output. More...
 
class  Token
 Represents a lexical token from C source code. More...
 
struct  UndeterminedPosition
 Position state for a color that has not yet been assigned a palette slot. More...
 
class  UserDiagnostics
 Abstract class for structured error reporting and diagnostic output. More...
 
class  YamlFileProvider
 A ConfigProvider implementation that reads configuration values from multiple YAML files with priority. More...
 

Concepts

concept  SupportsTransparency
 Concept that requires a type to support transparency checks.
 

Typedefs

using PerAnimOverrides = std::unordered_map< std::string, PerAnimOverride >
 Per-animation configuration map.
 
using ColorPosition = std::variant< UndeterminedPosition, AbsolutePosition, IndirectPosition >
 The position state of a color during palette construction.
 
using DefineValue = std::variant< std::int64_t, std::string, std::monostate >
 Represents the value of a #define statement.
 
using FormattedMessageBuilder = std::function< std::vector< std::string >(const TextFormatter &)>
 Function type for building formatted messages with TextFormatter access.
 

Enumerations

enum class  PrimaryPairingMode { off , manual , automatic }
 Controls how a secondary tileset finds its partner primary for compilation. More...
 
enum class  AnimKeyFrameResolutionStrategy { error , warning , mangle }
 Strategy for handling duplicate key frame tiles in animation decompilation. More...
 
enum class  AnimMultiPalSubtileResolutionStrategy { error , warning , split }
 Strategy for handling animation subtiles referenced with multiple palettes. More...
 
enum class  AnimPalResolutionStrategy {
  scan_local_metatiles , palette_00 , palette_01 , palette_02 ,
  palette_03 , palette_04 , palette_05 , palette_06 ,
  palette_07 , palette_08 , palette_09 , palette_10 ,
  palette_11 , palette_12 , palette_13 , palette_14 ,
  palette_15 , internal_png_pal , scan_all_tilesets
}
 Strategy for determining which palette to use when decompiling animation tiles. More...
 
enum class  ArtifactEditMode { locked , patch , optimize }
 Specifies whether artifacts (tiles or palettes) can be modified during patch compilation. More...
 
enum class  FrameLinking { automatic , manual , hybrid }
 Controls how animation frames are linked to metatile entries. More...
 
enum class  PackingStrategyType { best_fusion , backtracking , overload_and_remove }
 Selects the palette packing algorithm to use during tileset compilation. More...
 
enum class  SearchAlgorithm { dfs , bfs }
 Search algorithm used by BacktrackingStrategy. More...
 
enum class  ShuffleStrategy { single_ffd , noisy_ffd , random }
 Controls how tile orderings are generated during multi-start packing. More...
 
enum class  TileSharingAlignment { off , greedy , optimal }
 Controls palette slot alignment strategy for tile sharing deduplication. More...
 
enum class  TileSharingPacking { off , biased , optimal }
 Controls whether palette packing considers tile sharing shape group membership. More...
 
enum class  TilesPalMode { true_color , greyscale }
 Controls how tiles.png is rendered. More...
 
enum class  BaseGame { pokeemerald , pokefirered , pokeruby , pokeemerald_expansion }
 Identifies the target base game for a decompilation project. More...
 
enum class  LayerMode { dual , triple }
 Specifies whether a metatile uses dual-layer or triple-layer mode. More...
 
enum class  LayerType : unsigned int { normal = 0 , covered = 1 , split = 2 }
 Specifies which layers of a metatile are used for rendering. More...
 
enum class  ExportFlipMode { canonical , original }
 Defines whether flip transformations should be applied during image export. More...
 
enum class  ExportTrimMode { include_trailing_transparent , trim_trailing_transparent }
 Defines how trailing transparent tiles should be handled during image export. More...
 
enum class  ValidationState { not_provided , valid , invalid }
 Represents the validation state of a configuration value from a ConfigProvider. More...
 
enum class  TokenType : std::uint8_t {
  end_of_file , hash , kw_define , kw_undef ,
  kw_include , kw_ifdef , kw_ifndef , kw_if ,
  kw_else , kw_elif , kw_endif , kw_defined ,
  kw_pragma , kw_enum , identifier , integer_literal ,
  string_literal , char_literal , plus , minus ,
  star , slash , percent , ampersand ,
  pipe , caret , tilde , exclaim ,
  less , greater , equal , question ,
  colon , less_less , greater_greater , ampersand_ampersand ,
  pipe_pipe , equal_equal , exclaim_equal , less_equal ,
  greater_equal , left_paren , right_paren , left_brace ,
  right_brace , left_bracket , right_bracket , comma ,
  semicolon , period , newline , unknown
}
 Enumeration of token types recognized by the C parser lexer. More...
 
enum class  AnsiColorMode { plain , colors_256 , colors_24_bit }
 
enum class  PredefinedColor : std::uint8_t {
  none , black , red , green ,
  yellow , blue , magenta , cyan ,
  white
}
 Predefined color options for text styling. More...
 
enum class  ConfigScopeType { tileset , layout }
 Specifies the scope type for configuration value lookups. More...
 

Functions

std::optional< PrimaryPairingModeprimary_pairing_mode_from_str (const std::string &str)
 Parses a string into a PrimaryPairingMode with fuzzy matching.
 
std::string to_string (const PrimaryPairingMode m)
 Converts a PrimaryPairingMode to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const PrimaryPairingMode m)
 Stream insertion operator for PrimaryPairingMode.
 
ChainableResult< std::unique_ptr< Tileset > > resolve_partner_primary (const std::string &tileset_name, const ConfigValue< PrimaryPairingMode > &pairing_mode, const ConfigValue< std::vector< std::string > > &partners, const TilesetRepo *tileset_repo, const TilesetMetadataProvider *metadata_provider, const LayoutMetadataProvider *layout_metadata_provider, const PorytilesTilesetManager *tileset_manager, const UserDiagnostics *diag)
 Resolves the partner primary tileset for a secondary tileset.
 
template<typename T >
std::vector< std::string > format_config_note (const TextFormatter &format, const ConfigValue< T > &config)
 Format a ConfigValue into diagnostic note lines.
 
template<typename T >
std::vector< std::string > format_config_note_with_separator (const TextFormatter &format, const ConfigValue< T > &config)
 Format a ConfigValue into diagnostic note lines with a separator.
 
std::vector< std::string > build_global_color_limit_lines (const TextFormatter &format, std::size_t color_count_limit, const ConfigValue< std::size_t > &num_pals)
 Builds note lines explaining the global color count limit for primary tileset compilation.
 
std::vector< std::string > build_subtraction_limit_lines (const TextFormatter &format, std::string_view label, std::size_t computed_limit, const ConfigValue< std::size_t > &total_cfg, const ConfigValue< std::size_t > &primary_cfg)
 Builds note lines explaining a derived limit computed as total minus primary.
 
template<std::size_t N>
std::vector< std::string > build_porymap_pal_highlight_lines (const TextFormatter &format, const PalettePrinter &pal_printer, const std::string &message, const Palette< Rgba32, N > &pal, const std::string &pal_label, const std::vector< std::size_t > &violating_slots)
 Builds note lines displaying a Porymap palette with highlighted violating slots.
 
template<std::size_t N>
std::vector< std::string > build_porytiles_pal_highlight_lines (const TextFormatter &format, const PalettePrinter &pal_printer, const std::string &message, const Palette< Rgba32, N > &pal, const std::string &pal_label, const std::vector< std::size_t > &violating_slots)
 Builds note lines displaying a Porytiles palette with highlighted violating slots.
 
std::vector< std::string > build_pal_hint_highlight_lines (const TextFormatter &format, const PalettePrinter &pal_printer, const std::string &message, const PaletteHint &hint, const std::string &pal_label, const std::vector< std::size_t > &violating_slots)
 Builds note lines displaying a palette hint with highlighted violating slots.
 
std::vector< std::string > build_tile_sharing_color_version_tile_lines (const TextFormatter &format, const TilePrinter &tile_printer, const std::vector< PixelTile< Rgba32 > > &pixel_tiles, const Rgba32 &extrinsic_transparency, const std::vector< std::size_t > &color_version_tile_indices)
 Builds note lines showing ASCII art for each color version tile in a sharing group.
 
std::vector< std::string > build_primary_tile_color_version_lines (const TextFormatter &format, const TilePrinter &tile_printer, const std::vector< PackingParams::PrimaryTileRef > &primary_tiles, const Rgba32 &extrinsic_transparency, const std::vector< std::pair< std::size_t, std::size_t > > &primary_color_version_entries, std::size_t version_offset)
 Builds note lines showing ASCII art for each primary tile color version in a sharing group.
 
std::vector< std::string > build_truncated_tile_ref_lines (const TextFormatter &format, const std::vector< std::size_t > &tile_indices)
 Builds truncated tile reference lines, displaying up to 8 entries 2-per-line with ellipsis.
 
std::vector< std::string > build_per_palette_tile_ref_lines (const TextFormatter &format, const std::map< std::size_t, std::vector< std::size_t > > &members_by_pal)
 Builds per-palette tile reference lines with a header and truncated listing for each palette.
 
std::vector< std::string > build_representative_tile_per_palette_lines (const TextFormatter &format, const TilePrinter &tile_printer, const std::vector< PixelTile< Rgba32 > > &pixel_tiles, const Rgba32 &extrinsic_transparency, const std::map< std::size_t, std::vector< std::size_t > > &members_by_pal)
 Builds note lines showing one representative tile (ASCII art) per palette.
 
std::vector< std::string > build_primary_representative_tile_per_palette_lines (const TextFormatter &format, const TilePrinter &tile_printer, const std::vector< PackingParams::PrimaryTileRef > &primary_tiles, const Rgba32 &extrinsic_transparency, const std::map< std::size_t, std::vector< std::size_t > > &primary_members_by_pal)
 Builds note lines showing one representative primary tile (ASCII art) per palette.
 
template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(); }
PaletteMatchResult< ColorType > match_tile_to_palette (const PixelTile< ColorType > &tile, const Palette< ColorType, N > &palette)
 Matches a PixelTile against a Palette (intrinsic transparency only).
 
template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PaletteMatchResult< ColorType > match_tile_to_palette (const PixelTile< ColorType > &tile, const Palette< ColorType, N > &palette, const ColorType &extrinsic)
 Matches a PixelTile against a Palette (extrinsic transparency).
 
template<SupportsTransparency ColorType, typename PaletteContainer >
requires requires(const ColorType &c) { c.is_transparent(c); }
std::vector< PaletteMatchResult< ColorType > > match_or_best (const PixelTile< ColorType > &tile, const PaletteContainer &palettes, const ColorType &extrinsic, std::size_t top_n)
 Finds the best palette match(es) for a tile (extrinsic transparency).
 
template<SupportsTransparency PixelType, typename TransparencyPredicate >
ShapeTile< PixelType > shape_tile_from_pixel_tile (const PixelTile< PixelType > &pixel_tile, TransparencyPredicate is_transparent_pred)
 Converts a PixelTile to a ShapeTile by grouping pixels by color into ShapeMasks.
 
template<SupportsTransparency PixelType>
requires requires(const PixelType &c) { c.is_transparent(c); }
std::vector< ShapeGroup< PixelType > > analyze_shape_groups (const std::vector< PixelTile< PixelType > > &tiles, const PixelType &extrinsic)
 Analyzes a collection of pixel tiles and groups them by canonical shape for tile sharing analysis.
 
template<SupportsTransparency PixelType>
requires requires(const PixelType &p) { p.is_transparent(); }
ShapeTile< ColorIndexfrom_pixel_tile (const PixelTile< PixelType > &pixel_tile, const ColorIndexMap< PixelType > &color_index_map)
 Converts a PixelTile to a ShapeTile<ColorIndex> using a ColorIndexMap (intrinsic transparency).
 
template<SupportsTransparency PixelType>
requires requires(const PixelType &p) { p.is_transparent(p); }
ShapeTile< ColorIndexfrom_pixel_tile (const PixelTile< PixelType > &pixel_tile, const ColorIndexMap< PixelType > &color_index_map, const PixelType &extrinsic)
 Converts a PixelTile to a ShapeTile<ColorIndex> using a ColorIndexMap (extrinsic transparency).
 
template<SupportsTransparency PixelType>
PixelTile< PixelType > from_shape_tile (const ShapeTile< ColorIndex > &shape_tile, const ColorIndexMap< PixelType > &color_index_map)
 Converts a ShapeTile<ColorIndex> to a PixelTile using a ColorIndexMap.
 
template<SupportsTransparency PixelType>
ShapeTile< PixelType > shape_tile_to_pixel_colors (const ShapeTile< ColorIndex > &shape_tile, const ColorIndexMap< PixelType > &color_index_map)
 Converts a ShapeTile<ColorIndex> to a ShapeTile<PixelType> using a ColorIndexMap.
 
template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(); }
PixelTile< ColorType > color_tile_from_index_tile (const PixelTile< IndexPixel > &index_tile, const Palette< ColorType, N > &palette)
 Converts a PixelTile<IndexPixel> to a PixelTile<ColorType> using a palette (intrinsic transparency).
 
template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PixelTile< ColorType > color_tile_from_index_tile (const PixelTile< IndexPixel > &index_tile, const Palette< ColorType, N > &palette, const ColorType &extrinsic)
 Converts a PixelTile<IndexPixel> to a PixelTile<ColorType> using a palette (extrinsic transparency).
 
template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PixelTile< IndexPixelindex_tile_from_color_tile (const PixelTile< ColorType > &tile, const Palette< ColorType, N > &palette)
 Converts a PixelTile<ColorType> to indexed form using a palette (intrinsic transparency only).
 
template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PixelTile< IndexPixelindex_tile_from_color_tile (const PixelTile< ColorType > &tile, const Palette< ColorType, N > &palette, const ColorType &extrinsic)
 Converts a PixelTile<ColorType> to indexed form using a palette (extrinsic transparency).
 
template<typename PixelType >
std::vector< PixelTile< PixelType > > extract_tiles_from_image (const Image< PixelType > &img, std::size_t tile_offset, std::size_t tile_count, std::size_t tiles_per_row=16)
 Extracts a subset of 8x8 tiles from a tileset image at a specific offset.
 
template<typename PixelType >
std::vector< PixelTile< PixelType > > extract_tiles_from_image (const Image< PixelType > &img)
 Extracts all 8x8 tiles from an image in row-major order.
 
template<typename PixelType >
PixelTile< PixelType > extract_single_tile (const Image< PixelType > &img, std::size_t tile_idx, std::size_t tiles_per_row=metatile::metatiles_per_row *metatile::tiles_per_side)
 Extracts a single tile from an image at a given tile index.
 
ChainableResult< void > validate_metatile_count (const TilesetCompileValidatorServices &services, const std::string &tileset_name, bool is_secondary, const std::vector< Metatile< Rgba32 > > &metatiles)
 Validates that the metatile count does not exceed the configured limit.
 
ChainableResult< void > validate_porymap_pal (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const Palette< Rgba32, pal::max_size > &pal, std::size_t pal_index)
 Validates a Porymap palette for correctness according to GBA hardware constraints.
 
ChainableResult< void > validate_porytiles_pal (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const Palette< Rgba32, pal::max_size > &pal, std::size_t pal_index)
 Validates a user-specified Porytiles override palette for correctness.
 
ChainableResult< void > validate_pal_hint (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const PaletteHint &hint)
 Validates a user-specified palette hint for correctness.
 
ChainableResult< void > validate_alpha_channels (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const std::vector< Metatile< Rgba32 > > &metatiles, const std::map< std::string, Animation< Rgba32 > > &anims)
 Validates that all pixel alpha channels in provided input have valid values.
 
ChainableResult< void > validate_layer_mode (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const std::vector< Metatile< Rgba32 > > &metatiles)
 Validates that metatiles conform to the configured layer mode.
 
ChainableResult< void > validate_tile_color_count (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const std::vector< Metatile< Rgba32 > > &metatiles, const std::map< std::string, Animation< Rgba32 > > &anims)
 Validates that each individual tile does not exceed the per-tile color limit.
 
ChainableResult< void > validate_global_color_count (const TilesetCompileValidatorServices &services, const std::string &tileset_name, bool is_secondary, const std::vector< Metatile< Rgba32 > > &metatiles, const std::map< std::string, Animation< Rgba32 > > &anims, const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &porytiles_pals, const std::vector< PaletteHint > &hints)
 Validates that the total unique color count across all input does not exceed the global limit.
 
ChainableResult< void > validate_precision_loss (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const std::vector< Metatile< Rgba32 > > &metatiles, const std::map< std::string, Animation< Rgba32 > > &anims, const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &porytiles_pals, const std::vector< PaletteHint > &hints, const std::optional< std::array< Palette< Rgba32, pal::max_size >, pal::num_pals > > &porymap_pals)
 Validates that no colors will suffer unacceptable precision loss during GBA color conversion.
 
ChainableResult< void > validate_anim_frames (const TilesetCompileValidatorServices &services, const std::string &tileset_name, const std::map< std::string, Animation< Rgba32 > > &anims)
 Validates animation frames for correctness according to tileset compilation constraints.
 
std::optional< AnimKeyFrameResolutionStrategyanim_key_frame_resolution_strategy_from_str (const std::string &str)
 Parses a string into a AnimKeyFrameResolutionStrategy with fuzzy matching.
 
std::string to_string (const AnimKeyFrameResolutionStrategy m)
 Converts a AnimKeyFrameResolutionStrategy to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const AnimKeyFrameResolutionStrategy m)
 Stream insertion operator for AnimKeyFrameResolutionStrategy.
 
std::optional< AnimMultiPalSubtileResolutionStrategyanim_multi_pal_subtile_resolution_strategy_from_str (const std::string &str)
 Parses a string into a AnimMultiPalSubtileResolutionStrategy with fuzzy matching.
 
std::string to_string (const AnimMultiPalSubtileResolutionStrategy m)
 Converts a AnimMultiPalSubtileResolutionStrategy to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const AnimMultiPalSubtileResolutionStrategy m)
 Stream insertion operator for AnimMultiPalSubtileResolutionStrategy.
 
std::optional< AnimPalResolutionStrategyanim_pal_resolution_strategy_from_str (const std::string &str)
 Parses a string into a AnimPalResolutionStrategy with fuzzy matching.
 
std::string to_string (const AnimPalResolutionStrategy m)
 Converts a AnimPalResolutionStrategy to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const AnimPalResolutionStrategy m)
 Stream insertion operator for AnimPalResolutionStrategy.
 
std::optional< ArtifactEditModeartifact_edit_mode_from_str (const std::string &str)
 Parses a string into a ArtifactEditMode with fuzzy matching.
 
std::string to_string (const ArtifactEditMode m)
 Converts a ArtifactEditMode to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const ArtifactEditMode m)
 Stream insertion operator for ArtifactEditMode.
 
ChainableResult< ConfigValue< Rgba32 > > rgba_alpha_component_opaque (const ConfigValue< Rgba32 > &val)
 Validates that an Rgba32 alpha component is opaque.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > require_packing_strategy_backtracking (const ConfigValue< T > &val, const ConfigInterface &config, ConfigScopeType type, const std::string &scope, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that 'biased' or 'optimal' tile sharing packing requires 'backtracking' packing strategy.
 
std::optional< FrameLinkingframe_linking_from_str (const std::string &str)
 Parses a string into a FrameLinking with fuzzy matching.
 
std::string to_string (const FrameLinking m)
 Converts a FrameLinking to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const FrameLinking m)
 Stream insertion operator for FrameLinking.
 
std::string to_string (const PackingStrategyParams &params)
 Converts a PackingStrategyParams to a human-readable string.
 
std::ostream & operator<< (std::ostream &os, const PackingStrategyParams &params)
 Stream insertion operator for PackingStrategyParams.
 
std::optional< PackingStrategyTypepacking_strategy_type_from_str (const std::string &str)
 Parses a string into a PackingStrategyType with fuzzy matching.
 
std::string to_string (const PackingStrategyType m)
 Converts a PackingStrategyType to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const PackingStrategyType m)
 Stream insertion operator for PackingStrategyType.
 
std::string to_string (const PerAnimOverrides &configs)
 Converts an PerAnimOverride map to a human-readable string.
 
std::ostream & operator<< (std::ostream &os, const PerAnimOverrides &configs)
 Stream insertion operator for AnimConfigs.
 
std::optional< SearchAlgorithmsearch_algorithm_from_str (const std::string &str)
 Parses a string into a SearchAlgorithm with fuzzy matching.
 
std::string to_string (const SearchAlgorithm m)
 Converts a SearchAlgorithm to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const SearchAlgorithm m)
 Stream insertion operator for SearchAlgorithm.
 
std::optional< ShuffleStrategyshuffle_strategy_from_str (const std::string &str)
 Parses a string into a ShuffleStrategy with fuzzy matching.
 
std::string to_string (const ShuffleStrategy m)
 Converts a ShuffleStrategy to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const ShuffleStrategy m)
 Stream insertion operator for ShuffleStrategy.
 
std::optional< TileSharingAlignmenttile_sharing_alignment_from_str (const std::string &str)
 Parses a string into a TileSharingAlignment with fuzzy matching.
 
std::string to_string (const TileSharingAlignment m)
 Converts a TileSharingAlignment to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const TileSharingAlignment m)
 Stream insertion operator for TileSharingAlignment.
 
std::optional< TileSharingPackingtile_sharing_packing_from_str (const std::string &str)
 Parses a string into a TileSharingPacking with fuzzy matching.
 
std::string to_string (const TileSharingPacking m)
 Converts a TileSharingPacking to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const TileSharingPacking m)
 Stream insertion operator for TileSharingPacking.
 
std::optional< TilesPalModetiles_pal_mode_from_str (const std::string &str)
 Parses a string into a TilesPalMode with fuzzy matching.
 
std::string to_string (const TilesPalMode m)
 Converts a TilesPalMode to its canonical string representation.
 
std::ostream & operator<< (std::ostream &os, const TilesPalMode m)
 Stream insertion operator for TilesPalMode.
 
std::optional< BaseGamebase_game_from_str (const std::string &s)
 Converts a string to BaseGame.
 
std::string to_string (BaseGame game)
 Converts BaseGame to string representation.
 
std::ostream & operator<< (std::ostream &os, const BaseGame game)
 Stream insertion operator for BaseGame.
 
ColorSet color_set_union (const ColorSet &a, const ColorSet &b)
 Computes the union of two ColorSets.
 
ColorSet color_set_intersection (const ColorSet &a, const ColorSet &b)
 Computes the intersection of two ColorSets.
 
std::size_t color_set_count (const ColorSet &set)
 Counts the number of colors in a ColorSet.
 
bool is_subset (const ColorSet &a, const ColorSet &b)
 Checks if one ColorSet is a subset of another.
 
std::size_t intersection_size (const ColorSet &a, const ColorSet &b)
 Computes the intersection size between two ColorSets.
 
std::size_t union_size (const ColorSet &a, const ColorSet &b)
 Computes the union size of two ColorSets.
 
template<typename Func >
void for_each_color (const ColorSet &set, Func &&func)
 Iterates over each color index in a ColorSet.
 
LayerMode layer_mode_from_val (std::size_t s)
 Converts a numeric value to LayerMode.
 
std::optional< LayerModelayer_mode_from_str (const std::string &s)
 Converts a string to LayerMode.
 
std::string to_string (LayerMode mode)
 Converts LayerMode to string representation.
 
std::ostream & operator<< (std::ostream &os, const LayerMode mode)
 Stream insertion operator for LayerMode.
 
std::string to_string (LayerType layer_type)
 Converts LayerType to string representation.
 
ChainableResult< LayerTypelayer_type_from_int (unsigned int i)
 Converts an integer to LayerType.
 
std::string to_string (const Rgba32 &rgba)
 
std::ostream & operator<< (std::ostream &os, const Rgba32 &rgba)
 Stream insertion operator for Rgba32.
 
std::vector< Rgba32standard_greyscale_pal ()
 Returns the standard 16-color greyscale palette used for indexed tile output.
 
std::vector< IndirectLinkbuild_indirect_links (const std::vector< ShapeGroup< Rgba32 > > &shape_groups, const std::map< std::size_t, std::size_t > &tile_pal_assignments, const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &base_pals, const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &prefilled_pals)
 Builds Indirect links from shape groups and pre-computed palette assignments.
 
std::vector< PackedPaletteinitialize_packed_palettes (const std::set< PrefilledPalette > &prefilled_pals, PalettePool &pal_pool, std::size_t pal_capacity)
 Initializes packed palettes from prefilled palettes.
 
std::map< std::size_t, std::size_t > build_global_multiplicity_map (const std::vector< PackableTile > &tiles, const std::vector< PackableTile > &hints)
 Builds a GLOBAL multiplicity map from all input tiles.
 
double compute_average_multiplicity (const std::vector< PackableTile > &tiles, const std::vector< PackableTile > &hints)
 Computes the average multiplicity of the input tiles (problem difficulty metric).
 
std::map< std::size_t, std::size_t > build_palette_local_multiplicity (const PackedPalette &palette, const std::map< PackableTile::Id, ColorSet > &tile_colors_map)
 Builds a PALETTE-LOCAL multiplicity map for a specific palette.
 
double compute_weighted_cost_in_palette (const ColorSet &tile_colors, const PackedPalette &palette, const std::map< PackableTile::Id, ColorSet > &tile_colors_map)
 Computes the weighted cost of placing a tile in a specific palette.
 
double compute_palette_local_efficiency (const ColorSet &tile_colors, const std::map< std::size_t, std::size_t > &local_mult)
 Computes the palette-local efficiency of a tile within its palette.
 
double compute_weighted_cost_in_palette_fast (const ColorSet &tile_colors, const PackedPalette &palette)
 Computes the weighted cost of placing a tile in a palette using cached counts.
 
double compute_palette_local_efficiency_fast (const ColorSet &tile_colors, const PackedPalette &palette)
 Computes the palette-local efficiency of a tile using cached counts.
 
std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_palsbuild_all_output_palettes (const std::vector< PackedPalette > &packed_pals, const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &prefilled_pals, const ColorIndexMap< Rgba32 > &color_map, const Rgba32 &default_slot_zero, const std::vector< IndirectLink > &indirect_links, AlignmentFailureCounts *failure_counts=nullptr)
 Builds all output palettes from packed palettes and Indirect links in a single call.
 
bool palette_contains_sibling (const PackableTile::Id &tile_id, const PackedPalette &palette, const ShapeGroupMetadata &metadata)
 Checks whether a palette already contains a sibling of the given tile (same shape group, different tile).
 
double compute_sharing_penalty (const PackableTile &tile, const PackedPalette &palette, const ShapeGroupMetadata &metadata, double sharing_weight=0.5)
 Computes the sharing penalty for placing a tile in a palette.
 
std::string to_string (const PackableTile::Id &id)
 
std::string to_string (const PaletteHint &hint)
 Converts a PaletteHint to its string representation.
 
std::ostream & operator<< (std::ostream &os, const PaletteHint &hint)
 Stream output operator for PaletteHint.
 
ShapeGroupMetadata build_shape_group_metadata (const std::vector< ShapeGroup< Rgba32 > > &shape_groups, const std::vector< PackableTile::Id > &combined_index_to_id)
 Builds ShapeGroupMetadata from shape groups and a combined-index-to-ID mapping.
 
template<SupportsTransparency PixelType, typename LoaderType >
ChainableResult< FrameLoadResult< PixelType > > load_animation_frame_from_png (const std::filesystem::path &png_path, const std::string &frame_name, const LoaderType &loader)
 Loads an animation frame from a PNG file.
 
ChainableResult< std::vector< TilemapEntry > > parse_metatiles_bin (const std::filesystem::path &path)
 Parses a metatiles.bin file into TilemapEntry objects.
 
ChainableResult< std::vector< MetatileAttribute > > parse_emerald_metatile_attributes (const std::filesystem::path &path)
 Parses a metatile_attributes.bin file for Emerald format.
 
ChainableResult< std::vector< MetatileAttribute > > parse_firered_metatile_attributes (const std::filesystem::path &path)
 Parses a metatile_attributes.bin file for FireRed format.
 
ChainableResult< std::unique_ptr< Image< IndexPixel > > > load_indexed_png (const std::filesystem::path &path, const PngIndexedImageLoader &loader)
 Loads an indexed PNG file (e.g., tiles.png).
 
ChainableResult< Palette< Rgba32, pal::max_size > > load_porymap_palette (const std::filesystem::path &path, const FilePalLoader &loader)
 Loads a Porymap palette file (e.g., 00.pal).
 
std::vector< CliOptionMetaget_cli_option_metadata ()
 Get all CLI option metadata for completion generation.
 
void register_config_options (CLI::App &app, CliOptionStorage &storage)
 Registers all config options with a CLI11 App.
 
std::vector< FunctionCallInfofind_function_calls (const std::vector< Token > &tokens, const std::string &target_function_name)
 Finds all calls to a specific function within a token stream.
 
std::vector< FunctionCallInfofind_all_function_calls (const std::vector< Token > &tokens)
 Finds all function call expressions within a token stream.
 
std::string token_type_name (TokenType type)
 Returns a human-readable name for a token type.
 
template<typename T >
std::vector< std::pair< T, unsigned int > > counts_to_descending_list (const std::map< T, unsigned int > &counts)
 Converts a map of counts to a sorted vector of key-count pairs.
 
std::string to_string (const DynamicCasedName &value)
 Converts a DynamicCasedName to its snake_case string representation.
 
std::ostream & operator<< (std::ostream &os, const DynamicCasedName &value)
 Stream insertion operator for DynamicCasedName.
 
std::filesystem::path create_tmpdir ()
 Creates a unique temporary directory.
 
bool files_are_identical (const std::filesystem::path &file_a, const std::filesystem::path &file_b)
 Checks if two files have identical contents.
 
std::filesystem::path strip_all_extensions (const std::filesystem::path &path)
 Strips all extensions from a path, returning the path with only the stem.
 
template<typename T , typename F >
auto transform (const std::vector< T > &input, F &&func) -> std::vector< std::invoke_result_t< F, const T & > >
 Transforms a vector of type T into a vector of type U using a mapping function.
 
template<typename U , typename T >
requires std::constructible_from<U, T>
auto transform (const std::vector< T > &input) -> std::vector< U >
 Transforms a vector of type T into a vector of type U using direct type construction.
 
template<typename T , typename F >
auto transform (const std::set< T > &input, F &&func) -> std::set< std::invoke_result_t< F, const T & > >
 Transforms a set of type T into a set of type U using a mapping function.
 
template<typename U , typename T >
requires std::constructible_from<U, T>
auto transform (const std::set< T > &input) -> std::set< U >
 Transforms a set of type T into a set of type U using direct type construction.
 
void set_panic_stacktrace_enabled (bool enabled)
 Enables or disables stacktrace generation on panic.
 
bool is_panic_stacktrace_enabled ()
 Returns whether stacktrace generation is enabled on panic.
 
void panic (const StringViewSourceLoc &s)
 Unconditionally terminates the program with a panic message.
 
void assert_or_panic (bool condition, const StringViewSourceLoc &s)
 Conditionally panics if the given condition is false.
 
template<typename T >
std::expected< T, std::string > parse_int (std::string_view int_string, const int base)
 
template<typename T >
std::expected< T, std::string > parse_int (std::string_view int_string)
 
constexpr uint8_t reverse_bits (uint8_t b)
 Reverses the bits in a byte.
 
std::string extract_function_name (const std::source_location &location=std::source_location::current())
 Extracts the function name from a source location.
 
bool check_full_string_match (const std::string &str, const std::string &pattern)
 Checks if a string fully matches a regular expression pattern.
 
std::string trim_prefix (const std::string &str, const std::string &prefix)
 Removes a prefix from a string if present.
 
void trim (std::string &string)
 Removes leading and trailing whitespace from a string in-place.
 
std::vector< std::string > split (std::string input, const std::string &delimiter)
 Splits a string into tokens based on a delimiter.
 
std::string & trim_line_ending (std::string &line)
 Removes line ending characters from a string in-place.
 
std::string trim_line_ending (const std::string &line)
 Removes line ending characters from a string.
 
template<typename T >
std::string int_to_hex_str (T t)
 Converts an integer value to a hexadecimal string with "0x" prefix.
 
template<typename T >
std::string pad_two_digits (T t)
 Converts an integer value to a minimum two-digit wide string representation.
 
std::string to_string (const std::string &str)
 Identity function for to_string with std::string input.
 
std::string to_string (bool value)
 Converts a boolean to its string representation.
 
template<typename T >
std::string to_string (const std::vector< T > &vec)
 Converts a vector to a string representation with curly brace delimiters.
 
std::string to_pascal_case (const std::string &s)
 Converts a string to PascalCase format.
 
std::string to_snake_case (const std::string &s)
 Converts a string to snake_case format.
 
std::string to_lower_str (const std::string &input)
 Converts all characters in a string to lowercase.
 
std::string pal_filename (std::size_t pal_index)
 Constructs a palette filename from a palette index.
 
std::string extract_tileset_shorthand (const std::string &tileset_name)
 Extracts the Pascal-case tileset short name from the full name.
 
DynamicCasedName extract_tileset_cased_name (const std::string &tileset_name)
 Extracts the tileset short name and wraps it in a DynamicCasedName.
 
constexpr Style rgb_fg_style (std::uint8_t r, std::uint8_t g, std::uint8_t b)
 Creates a Style value with a custom RGB foreground color.
 
constexpr Style rgb_bg_style (std::uint8_t r, std::uint8_t g, std::uint8_t b)
 Creates a Style value with a custom RGB background color.
 
constexpr Style rgb_style (std::uint8_t r, std::uint8_t g, std::uint8_t b)
 Creates a Style value with a custom RGB foreground color (backward compatibility alias).
 
std::string to_string (ConfigScopeType type)
 Converts a ConfigScopeType enum value to its string representation.
 
std::optional< ConfigScopeTypefrom_string (const std::string &str)
 Parses a string into a ConfigScopeType enum value.
 
ChainableResult< ConfigValue< std::size_t > > size_t_val_greater_than_zero (const ConfigValue< std::size_t > &val)
 Validates that a size_t config value is greater than zero.
 
ChainableResult< ConfigValue< std::size_t > > size_t_val_two_or_four (const ConfigValue< std::size_t > &val)
 Validates that a size_t config value is either 2 or 4.
 
ChainableResult< ConfigValue< std::size_t > > size_t_val_eight_or_twelve (const ConfigValue< std::size_t > &val)
 Validates that a size_t config value is either 8 or 12.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > compare_greater_than (const ConfigValue< T > &val, const ConfigInterface &config, ConfigScopeType type, const std::string &scope, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that the current value is greater than another config value.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > compare_less_than (const ConfigValue< T > &val, const ConfigInterface &config, ConfigScopeType type, const std::string &scope, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that the current value is less than another config value.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > compare_greater_equal (const ConfigValue< T > &val, const ConfigInterface &config, ConfigScopeType type, const std::string &scope, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that the current value is greater than or equal to another config value.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > compare_less_equal (const ConfigValue< T > &val, const ConfigInterface &config, ConfigScopeType type, const std::string &scope, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that the current value is less than or equal to another config value.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > compare_equal (const ConfigValue< T > &val, const ConfigInterface &config, const std::string &scope_param, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that the current value is equal to another config value.
 
template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > compare_not_equal (const ConfigValue< T > &val, const ConfigInterface &config, const std::string &scope_param, const std::string &other_field_name, FetchFunc fetch_other)
 Validates that the current value is not equal to another config value.
 

Variables

constexpr std::string_view diagnostic_separator = "--------"
 
constexpr std::size_t num_colors = pal::max_size * pal::num_pals
 Maximum allowable color count for GBA hardware.
 
constexpr std::size_t colors_per_pal = 16
 
constexpr Rgba32 rgba_black {0, 0, 0, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_white {255, 255, 255, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_grey {128, 128, 128, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_red {255, 0, 0, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_green {0, 255, 0, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_blue {0, 0, 255, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_yellow {255, 255, 0, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_magenta {255, 0, 255, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_cyan {0, 255, 255, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_purple {128, 0, 255, Rgba32::alpha_opaque}
 
constexpr Rgba32 rgba_lime {128, 255, 128, Rgba32::alpha_opaque}
 
const std::unordered_set< std::string > valid_yaml_paths
 Set of valid YAML configuration paths.
 
const std::unordered_set< std::string > valid_yaml_map_prefixes
 Set of YAML path prefixes that represent map-type configuration values.
 

Typedef Documentation

◆ ColorPosition

The position state of a color during palette construction.

Colors transition through states during palette building:

Definition at line 65 of file color_position.hpp.

◆ DefineValue

using porytiles::DefineValue = typedef std::variant<std::int64_t, std::string, std::monostate>

Represents the value of a #define statement.

DefineValue captures the different types of values a #define can have:

  • Integer value (evaluated from expression)
  • String literal
  • Empty (for flag-like defines with no value)

Definition at line 21 of file define_statement.hpp.

◆ FormattedMessageBuilder

using porytiles::FormattedMessageBuilder = typedef std::function<std::vector<std::string>(const TextFormatter &)>

Function type for building formatted messages with TextFormatter access.

FormattedMessageBuilder is a function type that receives a TextFormatter reference and returns a vector of formatted message lines. This pattern is used in UserDiagnostics to allow diagnostic messages to be generated with appropriate styling based on the output context (TTY vs non-TTY).

The builder function can use the TextFormatter to style text dynamically, enabling conditional formatting that adapts to the output destination.

Example usage:

++
diag.warn("tag", [&name](const TextFormatter &fmt) {
return std::vector{fmt.format("Error in '{}'", FormatParam{name, Style::bold | Style::red})};
});
A text parameter with associated styling for formatted output.
static const Style red
Red foreground color.
static const Style bold
Bold text formatting.
Abstract base class for applying text styling with context-aware formatting.
virtual std::string format(const std::string &format_str, const std::vector< FormatParam > &params) const
Formats a string with styled parameters using fmtlib syntax.

Definition at line 623 of file text_formatter.hpp.

◆ PerAnimOverrides

using porytiles::PerAnimOverrides = typedef std::unordered_map<std::string, PerAnimOverride>

Per-animation configuration map.

Maps animation names to their PerAnimOverride entries. When an animation's name is present in this map, the mapped configuration is used instead of (or merged with) the global defaults. Animations not listed in the map fall back entirely to the global settings.

Definition at line 20 of file per_anim_overrides.hpp.

Enumeration Type Documentation

◆ AnimKeyFrameResolutionStrategy

Strategy for handling duplicate key frame tiles in animation decompilation.

When decompiling animations, it's possible for multiple key frame tiles to be identical. This is problematic because during recompilation, identical tiles cannot be distinguished. This enum determines how to handle such cases.

Enumerator
error 

Emit a formatted error and fail decompilation.

warning 

Emit a warning and continue decompilation.

mangle 

Mangle duplicate tiles to make them unique, then backport changes to tiles.png.

Definition at line 30 of file anim_key_frame_resolution_strategy.hpp.

◆ AnimMultiPalSubtileResolutionStrategy

Strategy for handling animation subtiles referenced with multiple palettes.

When decompiling animations using the scan_local_metatiles strategy, a single tile index can be referenced by multiple metatile entries with different palette indices. This is valid GBA behavior (the hardware selects palette per metatile entry, not per tile), but Porytiles cannot represent multiple palette variants in a single RGBA layer PNG. This enum determines how to handle such cases.

Enumerator
error 

Emit a formatted error and fail decompilation.

warning 

Emit a warning and continue decompilation using the lowest palette index.

split 

Split the animation into separate animations for each palette variant (not yet implemented).

Definition at line 32 of file anim_multi_pal_subtile_resolution_strategy.hpp.

◆ AnimPalResolutionStrategy

Strategy for determining which palette to use when decompiling animation tiles.

When decompiling animation tiles, the decompiler needs to know which tileset palette to use for converting indexed pixels to RGBA. This enum determines the strategy used to find that palette. The strategy is applied directly.

Enumerator
scan_local_metatiles 

Scan local tileset metatile entries to find palette references for the animation tiles.

palette_00 

Use palette 00 directly.

palette_01 

Use palette 01 directly.

palette_02 

Use palette 02 directly.

palette_03 

Use palette 03 directly.

palette_04 

Use palette 04 directly.

palette_05 

Use palette 05 directly.

palette_06 

Use palette 06 directly.

palette_07 

Use palette 07 directly.

palette_08 

Use palette 08 directly.

palette_09 

Use palette 09 directly.

palette_10 

Use palette 10 directly.

palette_11 

Use palette 11 directly.

palette_12 

Use palette 12 directly.

palette_13 

Use palette 13 directly.

palette_14 

Use palette 14 directly.

palette_15 

Use palette 15 directly.

internal_png_pal 

Use the Porymap-component frame PNG internal palette, if present.

scan_all_tilesets 

Scan layouts config and find all tilesets paired with current tileset, see if an index is present in any.

Definition at line 30 of file anim_pal_resolution_strategy.hpp.

◆ AnsiColorMode

enum class porytiles::AnsiColorMode
strong
Enumerator
plain 
colors_256 
colors_24_bit 

Definition at line 7 of file ansi_styled_text_formatter.hpp.

◆ ArtifactEditMode

enum class porytiles::ArtifactEditMode
strong

Specifies whether artifacts (tiles or palettes) can be modified during patch compilation.

Controls the behavior of tile and palette handling when compiling a tileset patch. In locked mode, the compiler must use only the existing artifacts from the base tileset without modifications. In patch mode, the compiler can modify unused or "open" slots as needed. In optimize mode, artifacts are cleared and packed optimally (Porytiles1 behavior).

Enumerator
locked 

Artifacts cannot be edited; must use existing from base tileset.

patch 

Artifacts can be freely edited in "open" slots during compilation.

optimize 

The Porytiles1 behavior; artifact is cleared and packed optimally.

Definition at line 31 of file artifact_edit_mode.hpp.

◆ BaseGame

enum class porytiles::BaseGame
strong

Identifies the target base game for a decompilation project.

Different base games use different binary formats for metatile attributes:

  • pokeemerald / pokeruby / pokeemerald_expansion: 2-byte attributes (behavior + layer type)
  • pokefirered: 4-byte attributes (behavior + terrain + encounter type + layer type + more)
Enumerator
pokeemerald 
pokefirered 
pokeruby 
pokeemerald_expansion 

Definition at line 20 of file base_game.hpp.

◆ ConfigScopeType

enum class porytiles::ConfigScopeType
strong

Specifies the scope type for configuration value lookups.

ConfigScopeType determines how configuration providers should interpret the scope parameter when fetching configuration values. This allows the same configuration key to have different values depending on whether it's being used in a tileset or layout context.

For example, the YAML provider might look for tileset-specific configuration in data/tilesets/primary/<tileset_dir>/porytiles.yaml when using ConfigScopeType::tileset, while layout-specific configuration might be loaded from the layout directory when using ConfigScopeType::layout.

Enumerator
tileset 

Configuration scoped to a specific tileset.

When using this scope type, the scope parameter should be the tileset name, and providers will look for tileset-specific configuration values.

layout 

Configuration scoped to a specific layout.

When using this scope type, the scope parameter should be the layout name, and providers will look for layout-specific configuration values.

Note
Layout configuration support is not yet fully implemented in all providers.

Definition at line 20 of file config_scope_type.hpp.

◆ ExportFlipMode

enum class porytiles::ExportFlipMode
strong

Defines whether flip transformations should be applied during image export.

This enum controls whether tiles are exported in their canonical (lexicographically minimal) form or with flip transformations applied to restore their original orientations.

Enumerator
canonical 

Export tiles in canonical form without applying flip transformations.

Tiles are exported exactly as stored in the workspace - in their canonical (lexicographically minimal) orientation. This is appropriate for fresh compilations where there is no "original" tile orientation to preserve.

original 

Export tiles in original form by applying stored flip transformations.

Tiles are exported with h_flip and v_flip transformations applied to restore their original pixel arrangements as they were before canonicalization. This enables round-trip preservation of tile orientations, which is particularly useful in patch builds.

Definition at line 23 of file tiles_png_workspace.hpp.

◆ ExportTrimMode

enum class porytiles::ExportTrimMode
strong

Defines how trailing transparent tiles should be handled during image export.

This enum controls whether the exported image should include all tiles up to the workspace capacity or trim trailing transparent tiles to produce a more compact output.

Enumerator
include_trailing_transparent 

Include all tiles up to workspace capacity, even if trailing tiles are transparent.

This mode exports a full image with dimensions calculated to accommodate all tiles in the workspace, including any transparent tiles at the end. This is the default behavior and maintains compatibility with existing code.

trim_trailing_transparent 

Trim trailing transparent tiles from the exported image.

This mode finds the last non-transparent tile and exports only tiles up to and including that tile, producing a more compact image. If all tiles are transparent, the image will contain only tile 0.

Definition at line 52 of file tiles_png_workspace.hpp.

◆ FrameLinking

enum class porytiles::FrameLinking
strong

Controls how animation frames are linked to metatile entries.

In automatic mode, Porytiles generates and uses key.png for frame linking. In manual mode, Porytiles uses explicit overrides specified in anim.json.

Enumerator
automatic 

Use key.png for frame linking.

manual 

Use manual overrides in anim.json.

hybrid 

Automatic key.png linking plus manual override pass (not yet implemented).

Definition at line 29 of file frame_linking.hpp.

◆ LayerMode

enum class porytiles::LayerMode
strong

Specifies whether a metatile uses dual-layer or triple-layer mode.

In dual-layer mode, a metatile uses 8 tile entries (bottom and middle layers). In triple-layer mode, a metatile uses 12 tile entries (bottom, middle, and top layers).

Enumerator
dual 
triple 

Definition at line 21 of file layer.hpp.

◆ LayerType

enum class porytiles::LayerType : unsigned int
strong

Specifies which layers of a metatile are used for rendering.

  • normal: Uses middle and top layers
  • covered: Uses bottom and middle layers
  • split: Uses bottom and top layers
Enumerator
normal 
covered 
split 

Definition at line 97 of file layer.hpp.

◆ PackingStrategyType

enum class porytiles::PackingStrategyType
strong

Selects the palette packing algorithm to use during tileset compilation.

Controls which algorithm is used to assign tiles to palettes. Each strategy offers different trade-offs between speed, solution quality, and configurability. Backtracking is the default and handles the widest range of inputs. Best Fusion is fast but may fail on hard instances. Overload-And-Remove uses multi-start retries to escape local optima.

Enumerator
best_fusion 

Greedy weighted-cost packing (fast, no retries).

backtracking 

DFS/BFS backtracking search (default).

overload_and_remove 

Greedy with overload-and-remove multi-start retries.

Definition at line 31 of file packing_strategy_type.hpp.

◆ PredefinedColor

enum class porytiles::PredefinedColor : std::uint8_t
strong

Predefined color options for text styling.

PredefinedColor represents the standard 8 ANSI colors that can be used for both foreground and background text styling. The 'none' value indicates no color is set.

Enumerator
none 

No color set.

black 

Black color.

red 

Red color.

green 

Green color.

yellow 

Yellow color.

blue 

Blue color.

magenta 

Magenta color.

cyan 

Cyan color.

white 

White color.

Definition at line 22 of file text_formatter.hpp.

◆ PrimaryPairingMode

enum class porytiles::PrimaryPairingMode
strong

Controls how a secondary tileset finds its partner primary for compilation.

When compiling a secondary tileset, the compiler needs the compiled primary tileset to produce correct global tile indices and palette references. This mode controls how the partner primary is resolved.

Enumerator
off 

Skip primary loading entirely. Compile as a standalone secondary.

manual 

Use the partner primary specified via primary_pairing_partners config.

automatic 

Scan layout metadata to find the partner primary automatically.

Definition at line 30 of file primary_pairing_mode.hpp.

◆ SearchAlgorithm

enum class porytiles::SearchAlgorithm
strong

Search algorithm used by BacktrackingStrategy.

Controls whether the backtracking search explores the solution space using depth-first or breadth-first traversal. DFS uses in-place mutation with undo for memory efficiency, while BFS uses visited-state deduplication and a dual-queue heuristic.

Enumerator
dfs 

Depth-first search with in-place mutation and undo.

bfs 

Breadth-first search with dual-queue heuristic and visited-state deduplication.

Definition at line 30 of file search_algorithm.hpp.

◆ ShuffleStrategy

enum class porytiles::ShuffleStrategy
strong

Controls how tile orderings are generated during multi-start packing.

The packing algorithm can attempt multiple tile orderings to find a valid solution. This enum controls the strategy used to generate those orderings after the initial FFD (First Fit Decreasing) attempt.

Enumerator
single_ffd 

One FFD attempt only, no multi-start retries.

noisy_ffd 

FFD first, then perturbed FFD orderings that preserve the large-first property.

random 

FFD first, then fully random shuffles (original behavior).

Definition at line 30 of file shuffle_strategy.hpp.

◆ TileSharingAlignment

Controls palette slot alignment strategy for tile sharing deduplication.

When set to off, palettes are filled sequentially with no sharing attempt. When greedy, indirect links align palette slot indices for color-isomorphic tiles. When optimal, a CSP-based solver finds globally optimal alignment (not yet implemented).

Enumerator
off 

Pure sequential fill with no sharing alignment (default).

greedy 

Best-effort alignment via indirect link resolution.

optimal 

CSP-based globally optimal alignment (not yet implemented).

Definition at line 30 of file tile_sharing_alignment.hpp.

◆ TileSharingPacking

enum class porytiles::TileSharingPacking
strong

Controls whether palette packing considers tile sharing shape group membership.

When set to off, the packer ignores shape groups entirely. When biased, a soft cost penalty steers shape group siblings toward different palettes. When optimal, co-placing siblings is rejected outright (not yet implemented).

Enumerator
off 

Packing ignores shape group membership (default).

biased 

Soft penalty steers shape group siblings toward different palettes.

optimal 

Hard constraint rejecting sibling co-placement (not yet implemented).

Definition at line 30 of file tile_sharing_packing.hpp.

◆ TilesPalMode

enum class porytiles::TilesPalMode
strong

Controls how tiles.png is rendered.

Controls how tiles.png is rendered.

Enumerator
true_color 

Render tiles with true colors from the palette.

greyscale 

Render tiles in greyscale (useful for debugging).

Definition at line 27 of file tiles_pal_mode.hpp.

◆ TokenType

enum class porytiles::TokenType : std::uint8_t
strong

Enumeration of token types recognized by the C parser lexer.

TokenType defines all token categories the lexer can produce. The initial implementation focuses on tokens needed for #define parsing, but additional token types are included for future expansion to support functions, conditionals, and other C constructs.

Enumerator
end_of_file 
hash 
kw_define 
kw_undef 
kw_include 
kw_ifdef 
kw_ifndef 
kw_if 
kw_else 
kw_elif 
kw_endif 
kw_defined 
kw_pragma 
kw_enum 
identifier 
integer_literal 
string_literal 
char_literal 
plus 
minus 
star 
slash 
percent 
ampersand 
pipe 
caret 
tilde 
exclaim 
less 
greater 
equal 
question 
colon 
less_less 
greater_greater 
ampersand_ampersand 
pipe_pipe 
equal_equal 
exclaim_equal 
less_equal 
greater_equal 
left_paren 
right_paren 
left_brace 
right_brace 
left_bracket 
right_bracket 
comma 
semicolon 
period 
newline 
unknown 

Definition at line 19 of file token.hpp.

◆ ValidationState

enum class porytiles::ValidationState
strong

Represents the validation state of a configuration value from a ConfigProvider.

This enum distinguishes between three different states when a ConfigProvider attempts to supply a configuration value:

  • not_provided: The provider does not supply this configuration value (try next provider)
  • valid: The provider supplies a valid configuration value (use this value)
  • invalid: The provider attempted to supply a value, but it failed validation (stop and report error)
Enumerator
not_provided 
valid 
invalid 

Definition at line 19 of file layer_value.hpp.

Function Documentation

◆ analyze_shape_groups()

template<SupportsTransparency PixelType>
requires requires(const PixelType &c) { c.is_transparent(c); }
std::vector< ShapeGroup< PixelType > > porytiles::analyze_shape_groups ( const std::vector< PixelTile< PixelType > > &  tiles,
const PixelType &  extrinsic 
)

Analyzes a collection of pixel tiles and groups them by canonical shape for tile sharing analysis.

This algorithm detects color-isomorphic tiles, i.e. tiles that share the same geometric structure (ShapeMask layout) but have different color assignments. These are candidates for tile sharing via palette slot alignment.

The shape-based grouping approach is inspired by borytiles by ishax-kos (https://github.com/ishax-kos/borytiles), specifically its tileset.rs module. Borytiles represents tiles as Shape_indexable_tile (a BTreeMap<Tile_mask,Color_index>), groups them by Shape (the set of Tile_mask keys), and canonicalizes via get_ideal_flip (lexicographically minimal flip variant). Porytiles adapts these concepts into ShapeTile, ShapeMask, and CanonicalShapeTile respectively.

The algorithm:

  1. For each tile, creates a ShapeTile<PixelType> directly from the pixel data
  2. Canonicalizes each ShapeTile (finds lexicographically minimal flip variant via shape-only comparison)
  3. Groups tiles by canonical shape using shape-only comparison (ignoring color values)
  4. Within each group, collects members with their color mappings and flip flags
  5. Returns only groups with 2+ members that have distinct color assignments

Groups where all members have identical colors are excluded. They represent exact duplicates, not sharing candidates.

Template Parameters
PixelTypeThe pixel type, must support extrinsic transparency
Parameters
tilesThe input pixel tiles to analyze
extrinsicThe extrinsic transparency color
Returns
Vector of ShapeGroups, each containing 2+ members with distinct colors sharing the same canonical shape

Definition at line 85 of file shape_group_analyzer.hpp.

◆ anim_key_frame_resolution_strategy_from_str()

std::optional< AnimKeyFrameResolutionStrategy > porytiles::anim_key_frame_resolution_strategy_from_str ( const std::string &  str)
inline

Parses a string into a AnimKeyFrameResolutionStrategy with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 60 of file anim_key_frame_resolution_strategy.hpp.

◆ anim_multi_pal_subtile_resolution_strategy_from_str()

std::optional< AnimMultiPalSubtileResolutionStrategy > porytiles::anim_multi_pal_subtile_resolution_strategy_from_str ( const std::string &  str)
inline

Parses a string into a AnimMultiPalSubtileResolutionStrategy with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 62 of file anim_multi_pal_subtile_resolution_strategy.hpp.

◆ anim_pal_resolution_strategy_from_str()

std::optional< AnimPalResolutionStrategy > porytiles::anim_pal_resolution_strategy_from_str ( const std::string &  str)
inline

Parses a string into a AnimPalResolutionStrategy with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 124 of file anim_pal_resolution_strategy.hpp.

◆ artifact_edit_mode_from_str()

std::optional< ArtifactEditMode > porytiles::artifact_edit_mode_from_str ( const std::string &  str)
inline

Parses a string into a ArtifactEditMode with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 61 of file artifact_edit_mode.hpp.

◆ assert_or_panic()

void porytiles::assert_or_panic ( bool  condition,
const StringViewSourceLoc s 
)

Conditionally panics if the given condition is false.

This function checks the provided condition and if it evaluates to false, formats and prints a panic message with source location information, then aborts the program. If the condition is true, the function returns normally.

Parameters
conditionThe condition to check
sThe StringViewSourceLoc containing the panic message and location

Definition at line 53 of file panic.cpp.

◆ base_game_from_str()

std::optional< BaseGame > porytiles::base_game_from_str ( const std::string &  s)
inline

Converts a string to BaseGame.

Parameters
sThe string to convert (e.g. "pokeemerald", "pokefirered", "pokeruby", "pokeemerald-expansion")
Returns
The corresponding BaseGame, or std::nullopt if the string is invalid

Definition at line 28 of file base_game.hpp.

◆ build_all_output_palettes()

std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > porytiles::build_all_output_palettes ( const std::vector< PackedPalette > &  packed_pals,
const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &  prefilled_pals,
const ColorIndexMap< Rgba32 > &  color_map,
const Rgba32 default_slot_zero,
const std::vector< IndirectLink > &  indirect_links,
AlignmentFailureCounts failure_counts = nullptr 
)

Builds all output palettes from packed palettes and Indirect links in a single call.

Constructs final Rgba32 palettes from PackedPalette color sets using a six-phase algorithm. This function serves both TileSharingAlignment::off and TileSharingAlignment::greedy modes. When indirect_links is empty (off mode), Phases 2, 4, and 5 are no-ops and the function degenerates to: initialize positions, sequential fill, materialize output. The TileSharingAlignment::optimal mode will use a separate CSP-based algorithm and will not call this function.

The multi-phase approach (sequential fill skipping Indirect colors, then resolving Indirect chains to Absolute positions) is inspired by the Indirection resolution in the assign_palettes function from borytiles by ishax-kos (https://github.com/ishax-kos/borytiles), specifically its compilation.rs module. Porytiles separates the phases more explicitly and adds eviction logic for slot conflicts with non-prefilled colors.

Phase 1: Initialize position maps. For each palette, slot 0 gets its prefilled or default color. Prefilled non-wildcard slots become AbsolutePosition. Remaining colors from the PackedPalette start as UndeterminedPosition.

Phase 2: Apply Indirect links. For each IndirectLink, if the source color is still Undetermined, set it to IndirectPosition{ref_pal, ref_color}. Already-Absolute or already-Indirect colors are skipped (first-writer-wins prevents cycles). No-op when indirect_links is empty.

Phase 3: Sequential fill (skip Indirect). For each palette, collect slots already used by Absolute positions. Assign each remaining Undetermined color to the next free slot as Absolute. Indirect colors are skipped; they don't compete for slots. After this phase, all reference colors (which are Undetermined, not Indirect) have stable Absolute positions, enabling Indirect chain resolution in Phase 4.

Phase 4: Resolve Indirect chains with eviction. For each Indirect color, follow the chain ref_pal[ref_color] until hitting an Absolute position. Cap at pal::num_pals iterations for cycle detection (panics on cycle or broken chain, both of which are internal invariant violations). Place the color at the resolved slot. If the target slot is occupied by a non-prefilled color, evict the occupant to the next free slot (panics if no free slot exists; Phase 3 guarantees one free slot per Indirect color). If the slot conflicts with a prefilled position, skip (best-effort). No-op when indirect_links is empty.

Phase 5: Fallback fill for unresolved Indirects. Any Indirect colors that failed resolution in Phase 4 (prefilled destination conflict) are assigned sequential free slots, identical to Phase 3's logic but targeting IndirectPosition instead of UndeterminedPosition. Ensures all colors get placed even if Indirect alignment fails. No-op when indirect_links is empty.

Phase 6: Build final palettes. Materializes all AbsolutePosition colors into Palette<Rgba32> output objects. Places prefilled slots first, then all resolved colors at their Absolute positions.

The sequential fill iteration order matches the existing for_each_color + color_map path from the old build_output_palette to preserve identical palette layouts when no links are present (manual mode compatibility).

Parameters
packed_palsThe packed palette results from the packer.
prefilled_palsThe original prefilled input palettes (locked slots).
color_mapThe color-to-index mapping for reverse lookup.
default_slot_zeroThe default color for slot 0 if no prefilled palette exists.
indirect_linksThe Indirect link instructions (empty for off mode).
failure_countsOptional output pointer for alignment failure counters. When non-null, incremented at each Phase 2, Phase 4, and Phase 5 skip point. Caller retains ownership.
Returns
Array of optional palettes, indexed by hardware palette index.

Definition at line 61 of file palette_builder.cpp.

◆ build_global_color_limit_lines()

std::vector< std::string > porytiles::build_global_color_limit_lines ( const TextFormatter format,
std::size_t  color_count_limit,
const ConfigValue< std::size_t > &  num_pals 
)
inline

Builds note lines explaining the global color count limit for primary tileset compilation.

This function creates and returns standardized note lines explaining how the global color count limit is calculated. It is used in error messages when the user exceeds the maximum number of unique colors allowed in a tileset.

The generated note includes:

  • A statement of the limit value
  • The formula for calculating the limit (num_pals_in_primary * nontransparent_colors_per_pal)
  • The prettified configuration value showing the source of the num_pals setting
Parameters
formatThe TextFormatter for styling
color_count_limitThe calculated color count limit value
num_palsThe configuration value for the number of palettes in primary
Returns
Vector of formatted lines describing the color count limit configuration

Definition at line 94 of file diagnostic_stencils.hpp.

◆ build_global_multiplicity_map()

std::map< std::size_t, std::size_t > porytiles::build_global_multiplicity_map ( const std::vector< PackableTile > &  tiles,
const std::vector< PackableTile > &  hints 
)

Builds a GLOBAL multiplicity map from all input tiles.

Computes μ(α) = count of tiles containing color α, across ALL input tiles. This is the multiplicity metric from Definition 2.5 of Grange et al. (2017).

Example: If color index 42 appears in 5 different input tiles, then map[42] = 5.

Primary use cases (see Section 4.3-4.4 of Grange et al.):

  • Computing average multiplicity for problem difficulty estimation
  • Algorithm selection based on instance characteristics
Warning
This function computes GLOBAL multiplicity across all tiles. For palette placement decisions, use build_palette_local_multiplicity() instead. Global multiplicity does NOT help distinguish between palettes.
Parameters
tilesThe regular tiles to count colors from
hintsThe hint tiles to count colors from (processed same as regular tiles)
Returns
Map from color index to count of tiles containing that color
See also
compute_average_multiplicity Convenience function that computes the scalar difficulty metric
build_palette_local_multiplicity For palette-specific multiplicity used in placement decisions

Definition at line 8 of file packing_metrics.cpp.

◆ build_indirect_links()

std::vector< IndirectLink > porytiles::build_indirect_links ( const std::vector< ShapeGroup< Rgba32 > > &  shape_groups,
const std::map< std::size_t, std::size_t > &  tile_pal_assignments,
const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &  base_pals,
const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &  prefilled_pals 
)

Builds Indirect links from shape groups and pre-computed palette assignments.

For each shape group whose members span multiple palettes, generates IndirectLink instructions that tie corresponding colors together. The links reference colors (not absolute slots), so they remain valid even when final palette slot positions differ from the base palettes used for slot mapping.

This algorithm is inspired by the account_for_palette_swaps function in borytiles by ishax-kos (https://github.com/ishax-kos/borytiles), specifically its compilation.rs module. Borytiles groups tiles by shape, detects same-shape tiles in different palettes, and sets Indirect links pairing corresponding colors. Porytiles extends this with a conflict-minimization heuristic for reference member selection and integrates the link generation into a multi-phase pipeline with diagnostic reporting.

Algorithm per shape group:

  1. Look up each member's palette from tile_pal_assignments (authoritative packing assignments)
  2. Skip groups where fewer than 2 members resolve or all members are in the same palette
  3. Pick a reference member using a conflict-minimization heuristic (fewest prefilled-slot conflicts)
  4. For each non-reference member in a different palette, emit IndirectLink for each corresponding color pair (identified by matching ShapeMask keys)
Parameters
shape_groupsThe analyzed shape groups from ShapeGroupAnalyzer.
tile_pal_assignmentsPre-computed mapping from combined tile index to hardware palette index. Built by the packer from the authoritative packing assignments, ensuring consistency with eligibility determination.
base_palsBase palettes built with sequential fill only (no links), used for slot mapping during reference member selection heuristic.
prefilled_palsThe original prefilled input palettes (to detect locked slots during reference selection).
Returns
Vector of IndirectLink instructions, potentially empty if no sharing opportunities exist.

Definition at line 11 of file indirect_link_builder.cpp.

◆ build_pal_hint_highlight_lines()

std::vector< std::string > porytiles::build_pal_hint_highlight_lines ( const TextFormatter format,
const PalettePrinter pal_printer,
const std::string &  message,
const PaletteHint hint,
const std::string &  pal_label,
const std::vector< std::size_t > &  violating_slots 
)
inline

Builds note lines displaying a palette hint with highlighted violating slots.

This function generates and returns formatted note lines showing a palette hint with specific color slots highlighted to indicate violations. Palette hints are user-provided color specifications that guide the palette assignment algorithm, and this function helps diagnose issues when hints contain invalid or conflicting colors.

The generated note includes:

  • A header identifying the palette hint by label and custom message
  • The palette hint rendered with violating slots visually highlighted
Parameters
formatThe TextFormatter for styling
pal_printerThe palette printer for rendering palette visualizations
messageA custom message describing the issue with the palette hint
hintThe palette hint to display
pal_labelThe human-readable label identifying this palette hint
violating_slotsThe indices of slots that should be highlighted as violations
Returns
Vector of formatted lines describing the palette hint with highlights

Definition at line 254 of file diagnostic_stencils.hpp.

◆ build_palette_local_multiplicity()

std::map< std::size_t, std::size_t > porytiles::build_palette_local_multiplicity ( const PackedPalette palette,
const std::map< PackableTile::Id, ColorSet > &  tile_colors_map 
)

Builds a PALETTE-LOCAL multiplicity map for a specific palette.

Computes μ_p(α) = count of tiles in palette p containing color α.

This is the key metric for the "weightBySymbol" calculation in the reference implementation (solver_tools.py, line 92). Unlike global multiplicity, this varies per palette based on which tiles are currently assigned to it.

Example: If palette P has 3 assigned tiles, and 2 of them contain color 42, then the returned map has map[42] = 2.

Note
The tile_colors_map must include entries for:
  • All regular tiles (keyed by TileIndex)
  • All hint tiles (keyed by TileIndex)
  • All prefilled palette system tiles (keyed by PrefilledPaletteId)
Parameters
paletteThe palette to analyze
tile_colors_mapMap from tile ID to ColorSet for ALL known tiles
Returns
Map from color index to count of tiles in THIS palette containing that color
See also
compute_weighted_cost_in_palette Which uses this for placement decisions
compute_palette_local_efficiency Which uses this for removal decisions

Definition at line 45 of file packing_metrics.cpp.

◆ build_per_palette_tile_ref_lines()

std::vector< std::string > porytiles::build_per_palette_tile_ref_lines ( const TextFormatter format,
const std::map< std::size_t, std::vector< std::size_t > > &  members_by_pal 
)
inline

Builds per-palette tile reference lines with a header and truncated listing for each palette.

For each palette in the ordered map, emits a "Palette 'XX.pal': N tilemap entries:" header followed by a truncated tile reference listing via build_truncated_tile_ref_lines(). Uses std::map for deterministic ascending iteration order.

Parameters
formatThe TextFormatter for styling
members_by_palMap from palette index to the tile indices assigned to that palette
Returns
Vector of formatted lines with per-palette groupings

Definition at line 406 of file diagnostic_stencils.hpp.

◆ build_porymap_pal_highlight_lines()

template<std::size_t N>
std::vector< std::string > porytiles::build_porymap_pal_highlight_lines ( const TextFormatter format,
const PalettePrinter pal_printer,
const std::string &  message,
const Palette< Rgba32, N > &  pal,
const std::string &  pal_label,
const std::vector< std::size_t > &  violating_slots 
)

Builds note lines displaying a Porymap palette with highlighted violating slots.

This function generates and returns formatted note lines showing a Porymap palette with specific color slots highlighted to indicate violations. It is used to provide visual feedback when palette-related errors occur during tileset compilation, specifically for palettes originating from Porymap assets.

The generated note includes:

  • A header identifying the Porymap palette by label and custom message
  • The palette rendered with violating slots visually highlighted
Template Parameters
NThe size of the palette (number of color slots)
Parameters
formatThe TextFormatter for styling
pal_printerThe palette printer for rendering palette visualizations
messageA custom message describing the issue with the palette
palThe palette to display
pal_labelThe human-readable label identifying this palette
violating_slotsThe indices of slots that should be highlighted as violations
Returns
Vector of formatted lines describing the palette with highlights

Definition at line 180 of file diagnostic_stencils.hpp.

◆ build_porytiles_pal_highlight_lines()

template<std::size_t N>
std::vector< std::string > porytiles::build_porytiles_pal_highlight_lines ( const TextFormatter format,
const PalettePrinter pal_printer,
const std::string &  message,
const Palette< Rgba32, N > &  pal,
const std::string &  pal_label,
const std::vector< std::size_t > &  violating_slots 
)

Builds note lines displaying a Porytiles palette with highlighted violating slots.

This function generates and returns formatted note lines showing a Porytiles palette with specific color slots highlighted to indicate violations. It is used to provide visual feedback when palette-related errors occur during tileset compilation.

The generated note includes:

  • A header identifying the Porytiles palette by label and custom message
  • The palette rendered with violating slots visually highlighted
Template Parameters
NThe size of the palette (number of color slots)
Parameters
formatThe TextFormatter for styling
pal_printerThe palette printer for rendering palette visualizations
messageA custom message describing the issue with the palette
palThe palette to display
pal_labelThe human-readable label identifying this palette
violating_slotsThe indices of slots that should be highlighted as violations
Returns
Vector of formatted lines describing the palette with highlights

Definition at line 218 of file diagnostic_stencils.hpp.

◆ build_primary_representative_tile_per_palette_lines()

std::vector< std::string > porytiles::build_primary_representative_tile_per_palette_lines ( const TextFormatter format,
const TilePrinter tile_printer,
const std::vector< PackingParams::PrimaryTileRef > &  primary_tiles,
const Rgba32 extrinsic_transparency,
const std::map< std::size_t, std::vector< std::size_t > > &  primary_members_by_pal 
)
inline

Builds note lines showing one representative primary tile (ASCII art) per palette.

For each palette in the ordered map, renders the first primary tile in that palette's member list as ASCII art with a "Representative shape for palette 'XX.pal' (primary metatile ...):" header. The primary metatile coordinate identifies the first slot in the paired primary's triple-layerized metatiles where the underlying (tile, palette) pair was first seen. Used in Phase 3 tile sharing diagnostics for cross-tileset members.

Parameters
formatThe TextFormatter for styling
tile_printerThe TilePrinter for rendering tile ASCII art
primary_tilesThe primary tiles collection (each entry is a PackingParams::PrimaryTileRef)
extrinsic_transparencyThe extrinsic transparency color
primary_members_by_palMap from palette index to the primary tile indices assigned to that palette
Returns
Vector of formatted lines showing one representative primary tile per palette

Definition at line 470 of file diagnostic_stencils.hpp.

◆ build_primary_tile_color_version_lines()

std::vector< std::string > porytiles::build_primary_tile_color_version_lines ( const TextFormatter format,
const TilePrinter tile_printer,
const std::vector< PackingParams::PrimaryTileRef > &  primary_tiles,
const Rgba32 extrinsic_transparency,
const std::vector< std::pair< std::size_t, std::size_t > > &  primary_color_version_entries,
std::size_t  version_offset 
)
inline

Builds note lines showing ASCII art for each primary tile color version in a sharing group.

For each primary tile color version entry, emits a "Color version N (primary metatile ..., palette 'XX.pal'):" line followed by the ASCII art representation of that tile. The primary metatile coordinate identifies the first slot in the paired primary's triple-layerized metatiles where the underlying (tile, palette) pair was first seen. The version numbering continues after the secondary color versions via version_offset.

Parameters
formatThe TextFormatter for styling
tile_printerThe TilePrinter for rendering tile ASCII art
primary_tilesThe primary tiles collection (each entry is a PackingParams::PrimaryTileRef)
extrinsic_transparencyThe extrinsic transparency color
primary_color_version_entriesPairs of (tile_index, pal_index) for each distinct primary color version
version_offsetThe number of secondary color versions already displayed (for numbering continuation)
Returns
Vector of formatted lines showing each primary color version tile

Definition at line 321 of file diagnostic_stencils.hpp.

◆ build_representative_tile_per_palette_lines()

std::vector< std::string > porytiles::build_representative_tile_per_palette_lines ( const TextFormatter format,
const TilePrinter tile_printer,
const std::vector< PixelTile< Rgba32 > > &  pixel_tiles,
const Rgba32 extrinsic_transparency,
const std::map< std::size_t, std::vector< std::size_t > > &  members_by_pal 
)
inline

Builds note lines showing one representative tile (ASCII art) per palette.

For each palette in the ordered map, renders the first tile in that palette's member list as ASCII art with a "Representative shape for palette 'XX.pal' (metatile header):" header. Used in Phase 3 tile sharing diagnostics.

Parameters
formatThe TextFormatter for styling
tile_printerThe TilePrinter for rendering tile ASCII art
pixel_tilesThe full collection of pixel tiles (indexed by tile index)
extrinsic_transparencyThe extrinsic transparency color
members_by_palMap from palette index to the tile indices assigned to that palette
Returns
Vector of formatted lines showing one representative tile per palette

Definition at line 434 of file diagnostic_stencils.hpp.

◆ build_shape_group_metadata()

ShapeGroupMetadata porytiles::build_shape_group_metadata ( const std::vector< ShapeGroup< Rgba32 > > &  shape_groups,
const std::vector< PackableTile::Id > &  combined_index_to_id 
)

Builds ShapeGroupMetadata from shape groups and a combined-index-to-ID mapping.

The combined_index_to_id vector maps each index in the combined tile vector (used by analyze_shape_groups()) back to its corresponding PackableTile::Id. This allows shape group membership to be expressed in terms of PackableTile::Id values, which strategies use for tile identification during packing.

Parameters
shape_groupsThe shape groups produced by analyze_shape_groups().
combined_index_to_idParallel vector mapping combined tile indices to PackableTile::Id values.
Precondition
Every member.tile_index in shape_groups must be a valid index into combined_index_to_id.
Returns
ShapeGroupMetadata with tile-to-group and group-to-members mappings.

Definition at line 5 of file shape_group_metadata.cpp.

◆ build_subtraction_limit_lines()

std::vector< std::string > porytiles::build_subtraction_limit_lines ( const TextFormatter format,
std::string_view  label,
std::size_t  computed_limit,
const ConfigValue< std::size_t > &  total_cfg,
const ConfigValue< std::size_t > &  primary_cfg 
)
inline

Builds note lines explaining a derived limit computed as total minus primary.

Used in secondary tileset diagnostics where a limit is derived by subtracting a primary config value from a total config value (e.g. metatile limit = num_metatiles_total - num_metatiles_in_primary). The output shows the computed limit, the subtraction formula with both config canonical names and values, and prettified config notes for both source config values separated by a visual divider.

Parameters
formatThe TextFormatter for styling
labelA human-readable label for the limit (e.g. "Metatile limit")
computed_limitThe derived limit value (total - primary)
total_cfgThe ConfigValue for the total count
primary_cfgThe ConfigValue for the primary count
Returns
Vector of formatted lines describing the subtraction-based limit

Definition at line 131 of file diagnostic_stencils.hpp.

◆ build_tile_sharing_color_version_tile_lines()

std::vector< std::string > porytiles::build_tile_sharing_color_version_tile_lines ( const TextFormatter format,
const TilePrinter tile_printer,
const std::vector< PixelTile< Rgba32 > > &  pixel_tiles,
const Rgba32 extrinsic_transparency,
const std::vector< std::size_t > &  color_version_tile_indices 
)
inline

Builds note lines showing ASCII art for each color version tile in a sharing group.

For each color version tile index, emits a "Color version N (metatile header):" line followed by the ASCII art representation of that tile. Used in Phase 1 and Phase 2 tile sharing diagnostics.

Parameters
formatThe TextFormatter for styling
tile_printerThe TilePrinter for rendering tile ASCII art
pixel_tilesThe full collection of pixel tiles (indexed by tile index)
extrinsic_transparencyThe extrinsic transparency color
color_version_tile_indicesTile indices for each distinct color version
Returns
Vector of formatted lines showing each color version tile

Definition at line 284 of file diagnostic_stencils.hpp.

◆ build_truncated_tile_ref_lines()

std::vector< std::string > porytiles::build_truncated_tile_ref_lines ( const TextFormatter format,
const std::vector< std::size_t > &  tile_indices 
)
inline

Builds truncated tile reference lines, displaying up to 8 entries 2-per-line with ellipsis.

Formats tile indices as metatile message headers, 2 per line, up to a maximum of 8 displayed entries. If there are more than 8, appends an "... and N more." line. The caller is responsible for providing any header line. This function only emits the tile reference listing.

Parameters
formatThe TextFormatter for styling
tile_indicesThe tile indices to display
Returns
Vector of formatted lines listing the tile references

Definition at line 358 of file diagnostic_stencils.hpp.

◆ check_full_string_match()

bool porytiles::check_full_string_match ( const std::string &  str,
const std::string &  pattern 
)
inline

Checks if a string fully matches a regular expression pattern.

This function compiles the provided pattern into a regex and performs a full string match against the input string. Panics if the pattern is invalid.

Parameters
strThe string to match against the pattern
patternThe regular expression pattern
Precondition
pattern must be a valid regular expression
Returns
True if the entire string matches the pattern, false otherwise

Definition at line 43 of file string_utils.hpp.

◆ color_set_count()

std::size_t porytiles::color_set_count ( const ColorSet set)

Counts the number of colors in a ColorSet.

Returns the number of bits set to true in the ColorSet.

Parameters
setThe ColorSet to count
Returns
The number of colors in the set

Definition at line 44 of file color_set.cpp.

◆ color_set_intersection()

ColorSet porytiles::color_set_intersection ( const ColorSet a,
const ColorSet b 
)

Computes the intersection of two ColorSets.

Returns a new ColorSet containing only colors present in both sets.

Parameters
aThe first ColorSet
bThe second ColorSet
Returns
A ColorSet containing the intersection of both sets

Definition at line 32 of file color_set.cpp.

◆ color_set_union()

ColorSet porytiles::color_set_union ( const ColorSet a,
const ColorSet b 
)

Computes the union of two ColorSets.

Returns a new ColorSet containing all colors present in either set.

Parameters
aThe first ColorSet
bThe second ColorSet
Returns
A ColorSet containing the union of both sets

Definition at line 20 of file color_set.cpp.

◆ color_tile_from_index_tile() [1/2]

template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(); }
PixelTile< ColorType > porytiles::color_tile_from_index_tile ( const PixelTile< IndexPixel > &  index_tile,
const Palette< ColorType, N > &  palette 
)

Converts a PixelTile<IndexPixel> to a PixelTile<ColorType> using a palette (intrinsic transparency).

This function takes an indexed tile (where each pixel contains a palette index) and converts it to a color tile by looking up the actual color for each index in the provided palette. Index 0 pixels are mapped to the default- constructed ColorType{} (intrinsic transparency representation).

This overload is only available for color types that support intrinsic transparency.

Template Parameters
ColorTypeThe color type of the palette and output tile, must support intrinsic transparency
Parameters
index_tileThe PixelTile containing IndexPixel values to convert
paletteThe Palette containing the colors to look up
Precondition
palette is not empty
All non-zero indices in index_tile are within the bounds of the palette [1, palette.size())
Returns
A PixelTile<ColorType> where each pixel is the palette color corresponding to the index in index_tile

Definition at line 402 of file tile_converters.hpp.

◆ color_tile_from_index_tile() [2/2]

template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PixelTile< ColorType > porytiles::color_tile_from_index_tile ( const PixelTile< IndexPixel > &  index_tile,
const Palette< ColorType, N > &  palette,
const ColorType &  extrinsic 
)

Converts a PixelTile<IndexPixel> to a PixelTile<ColorType> using a palette (extrinsic transparency).

This function takes an indexed tile (where each pixel contains a palette index) and converts it to a color tile by looking up the actual color for each index in the provided palette. Index 0 pixels are mapped to the provided extrinsic transparency color.

This overload is only available for color types that support extrinsic transparency.

Template Parameters
ColorTypeThe color type of the palette and output tile, must support extrinsic transparency
Parameters
index_tileThe PixelTile containing IndexPixel values to convert
paletteThe Palette containing the colors to look up
extrinsicThe extrinsic transparency color to use for index 0 pixels
Precondition
palette is not empty
All non-zero indices in index_tile are within the bounds of the palette [1, palette.size())
Returns
A PixelTile<ColorType> where each pixel is the palette color corresponding to the index in index_tile

Definition at line 427 of file tile_converters.hpp.

◆ compare_equal()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::compare_equal ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
const std::string &  scope_param,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that the current value is equal to another config value.

Template Parameters
TThe type of the config values being compared (must support operator==)
ConfigInterfaceThe config interface type (DomainConfig, AppConfig, or InfraConfig)
FetchFuncCallable type that fetches the other config value
Parameters
valThe config value being validated
configThe config interface to fetch other values from
scope_paramThe scope parameter (tileset or layout name)
other_field_nameThe name of the other field to compare against
fetch_otherCallable that fetches the other config value
Returns
ChainableResult containing either the original value or an error

Definition at line 366 of file xcut_config_validators.hpp.

◆ compare_greater_equal()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::compare_greater_equal ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
ConfigScopeType  type,
const std::string &  scope,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that the current value is greater than or equal to another config value.

Template Parameters
TThe type of the config values being compared (must support operator>=)
ConfigInterfaceThe config interface type (DomainConfig, AppConfig, or InfraConfig)
FetchFuncCallable type that fetches the other config value
Parameters
valThe config value being validated
configThe config interface to fetch other values from
typeThe config scope type (tileset or layout)
scopeThe scope name (tileset or layout name)
other_field_nameThe name of the other field to compare against
fetch_otherCallable that fetches the other config value
Returns
ChainableResult containing either the original value or an error

Definition at line 306 of file xcut_config_validators.hpp.

◆ compare_greater_than()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::compare_greater_than ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
ConfigScopeType  type,
const std::string &  scope,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that the current value is greater than another config value.

This cross-field validator compares the current config value against another config value. It fetches the other value using the provided lambda and performs a greater-than comparison. If the comparison fails, returns a detailed error message showing both values and their sources.

Template Parameters
TThe type of the config values being compared (must support operator>)
ConfigInterfaceThe config interface type (DomainConfig, AppConfig, or InfraConfig)
FetchFuncCallable type that fetches the other config value
Parameters
valThe config value being validated
configThe config interface to fetch other values from
typeThe config scope type (tileset or layout)
scopeThe scope name (tileset or layout name)
other_field_nameThe name of the other field to compare against
fetch_otherCallable that fetches the other config value
Returns
ChainableResult containing either the original value or an error

Definition at line 252 of file xcut_config_validators.hpp.

◆ compare_less_equal()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::compare_less_equal ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
ConfigScopeType  type,
const std::string &  scope,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that the current value is less than or equal to another config value.

Template Parameters
TThe type of the config values being compared (must support operator<=)
ConfigInterfaceThe config interface type (DomainConfig, AppConfig, or InfraConfig)
FetchFuncCallable type that fetches the other config value
Parameters
valThe config value being validated
configThe config interface to fetch other values from
typeThe config scope type (tileset or layout)
scopeThe scope name (tileset or layout name)
other_field_nameThe name of the other field to compare against
fetch_otherCallable that fetches the other config value
Returns
ChainableResult containing either the original value or an error

Definition at line 340 of file xcut_config_validators.hpp.

◆ compare_less_than()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::compare_less_than ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
ConfigScopeType  type,
const std::string &  scope,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that the current value is less than another config value.

Template Parameters
TThe type of the config values being compared (must support operator<)
ConfigInterfaceThe config interface type (DomainConfig, AppConfig, or InfraConfig)
FetchFuncCallable type that fetches the other config value
Parameters
valThe config value being validated
configThe config interface to fetch other values from
typeThe config scope type (tileset or layout)
scopeThe scope name (tileset or layout name)
other_field_nameThe name of the other field to compare against
fetch_otherCallable that fetches the other config value
Returns
ChainableResult containing either the original value or an error

Definition at line 279 of file xcut_config_validators.hpp.

◆ compare_not_equal()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::compare_not_equal ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
const std::string &  scope_param,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that the current value is not equal to another config value.

Template Parameters
TThe type of the config values being compared (must support operator!=)
ConfigInterfaceThe config interface type (DomainConfig, AppConfig, or InfraConfig)
FetchFuncCallable type that fetches the other config value
Parameters
valThe config value being validated
configThe config interface to fetch other values from
scope_paramThe scope parameter (tileset or layout name)
other_field_nameThe name of the other field to compare against
fetch_otherCallable that fetches the other config value
Returns
ChainableResult containing either the original value or an error

Definition at line 391 of file xcut_config_validators.hpp.

◆ compute_average_multiplicity()

double porytiles::compute_average_multiplicity ( const std::vector< PackableTile > &  tiles,
const std::vector< PackableTile > &  hints 
)

Computes the average multiplicity of the input tiles (problem difficulty metric).

Computes Card(T) / |A|, where:

  • Card(T) = sum of all tile sizes (total color references across all tiles)
  • |A| = number of unique colors

This metric is proposed in Section 4.3 of Grange et al. (2017) as a predictor of problem difficulty, with r=0.784 correlation to actual algorithm performance variance.

Interpretation:

  • Low values (~1-5): Problem approaches standard Bin Packing (little color sharing)
  • Medium values (~5-20): Moderate color sharing, typical Pagination instances
  • High values (>20): Dense color sharing, more challenging for heuristics

Algorithm selection guidance (Section 4.4.2):

  • avg_mult < 15: Overload-and-Remove competitive with genetic algorithms
  • 15 <= avg_mult < 35: Genetic algorithms preferred, Overload-and-Remove acceptable
  • 35 <= avg_mult < 40: Greedy algorithms become competitive
  • avg_mult >= 40: Best Fusion optimal for speed/quality tradeoff
Parameters
tilesThe regular tiles to analyze
hintsThe hint tiles to analyze
Returns
Average multiplicity (Card(T) / |A|), or 0.0 if no colors exist
See also
build_global_multiplicity_map Which this function uses internally

Definition at line 24 of file packing_metrics.cpp.

◆ compute_palette_local_efficiency()

double porytiles::compute_palette_local_efficiency ( const ColorSet tile_colors,
const std::map< std::size_t, std::size_t > &  local_mult 
)

Computes the palette-local efficiency of a tile within its palette.

This implements the "actualEfficiencies" metric from the reference implementation (solver_tools.py, line 94):

efficiency = 1 - (weightedCost / tile_size)

Where weightedCost uses PALETTE-LOCAL multiplicity.

Interpretation:

  • Efficiency = 0: No sharing (all colors unique to this tile in the palette)
  • Efficiency = 1: Perfect sharing (all colors shared with many other tiles)

Used by Overload-and-Remove for REMOVAL decisions: when a palette is overloaded, the tile with the LOWEST efficiency (worst color sharing within THIS palette) is removed first. This corresponds to the paper's criterion of minimizing the |t|/|t|_p ratio.

Parameters
tile_colorsThe ColorSet of the tile to evaluate
local_multThe palette-local multiplicity map (from build_palette_local_multiplicity)
Returns
Efficiency in [0, 1] (higher means better sharing within this palette)
See also
build_palette_local_multiplicity Which provides the local_mult parameter

Definition at line 79 of file packing_metrics.cpp.

◆ compute_palette_local_efficiency_fast()

double porytiles::compute_palette_local_efficiency_fast ( const ColorSet tile_colors,
const PackedPalette palette 
)

Computes the palette-local efficiency of a tile using cached counts.

This is an optimized version of compute_palette_local_efficiency() that uses the PackedPalette's cached color counts array instead of a separately-built multiplicity map.

The formula is the same: efficiency = 1 - (weightedCost / tile_size).

Parameters
tile_colorsThe ColorSet of the tile to evaluate
paletteThe palette containing the tile (must have up-to-date color_counts)
Returns
Efficiency in [0, 1] (higher means better sharing)
See also
compute_palette_local_efficiency The non-cached version

Definition at line 111 of file packing_metrics.cpp.

◆ compute_sharing_penalty()

double porytiles::compute_sharing_penalty ( const PackableTile tile,
const PackedPalette palette,
const ShapeGroupMetadata metadata,
double  sharing_weight = 0.5 
)

Computes the sharing penalty for placing a tile in a palette.

Returns 0.0 if the tile is not in a shape group or no sibling is present in the palette. Otherwise returns sharing_weight multiplied by the tile's color count. This penalty is added to the base weighted cost to deprioritize palettes that already contain a sibling, steering shape group members toward different palettes.

Parameters
tileThe tile being placed.
paletteThe candidate palette.
metadataThe shape group metadata.
sharing_weightThe penalty multiplier (default 0.5).
Returns
The sharing penalty to add to the base cost.

Definition at line 30 of file sharing_metrics.cpp.

◆ compute_weighted_cost_in_palette()

double porytiles::compute_weighted_cost_in_palette ( const ColorSet tile_colors,
const PackedPalette palette,
const std::map< PackableTile::Id, ColorSet > &  tile_colors_map 
)

Computes the weighted cost of placing a tile in a specific palette.

This implements the "weightedCostIn" metric from the reference implementation (solver_tools.py, lines 61-66):

weightedCost = sum(1 / (1 + μ_p(α))) for each color α in the tile

Where μ_p(α) is the PALETTE-LOCAL multiplicity (count of tiles in this palette containing color α).

Interpretation:

  • Colors already well-represented in the palette (high μ_p) contribute less cost
  • Colors new to the palette (μ_p = 0) contribute maximum cost (1.0 each)
  • Lower total cost means better color overlap with the palette

Used by both Best Fusion and Overload-and-Remove for placement decisions: tiles are placed on the palette with the LOWEST weighted cost.

Parameters
tile_colorsThe ColorSet of the tile to be placed
paletteThe candidate palette to evaluate
tile_colors_mapMap from tile ID to ColorSet for ALL known tiles
Returns
Weighted cost (lower is better, minimum is tile_size when perfect overlap)
See also
build_palette_local_multiplicity Which provides the μ_p values

Definition at line 59 of file packing_metrics.cpp.

◆ compute_weighted_cost_in_palette_fast()

double porytiles::compute_weighted_cost_in_palette_fast ( const ColorSet tile_colors,
const PackedPalette palette 
)

Computes the weighted cost of placing a tile in a palette using cached counts.

This is an optimized version of compute_weighted_cost_in_palette() that uses the PackedPalette's cached color counts array instead of rebuilding the multiplicity map. This provides O(colors) complexity instead of O(tiles × colors).

The formula is the same: weightedCost = sum(1 / (1 + μ_p(α))) for each color α in the tile.

Parameters
tile_colorsThe ColorSet of the tile to be placed
paletteThe candidate palette (must have up-to-date color_counts)
Returns
Weighted cost (lower is better)
See also
compute_weighted_cost_in_palette The non-cached version

Definition at line 101 of file packing_metrics.cpp.

◆ counts_to_descending_list()

template<typename T >
std::vector< std::pair< T, unsigned int > > porytiles::counts_to_descending_list ( const std::map< T, unsigned int > &  counts)

Converts a map of counts to a sorted vector of key-count pairs.

This function transforms a map where keys are associated with counts into a vector of pairs, sorted in descending order by count value. Items with higher counts appear first in the resulting vector. This is useful for prioritizing or ranking items based on their frequency or occurrence count.

Template Parameters
TThe type of the keys in the count map
Parameters
countsA map where keys are associated with their count values
Returns
A vector of key-count pairs sorted in descending order by count
Postcondition
The returned vector contains all entries from the input map
The returned vector is sorted such that result[i].second >= result[i+1].second for all valid i

Definition at line 25 of file count_map_to_list.hpp.

◆ create_tmpdir()

std::filesystem::path porytiles::create_tmpdir ( )
inline

Creates a unique temporary directory.

Creates a new directory in the system's temporary directory path with a random hex suffix. The directory name follows the pattern "porytiles_<random_hex>". If directory creation fails (e.g., due to a collision), it retries up to 1000 times before panicking.

Returns
The path to the newly created temporary directory.
Postcondition
The returned path points to an existing, empty directory.

Definition at line 24 of file filesystem_utils.hpp.

◆ extract_function_name()

std::string porytiles::extract_function_name ( const std::source_location &  location = std::source_location::current())

Extracts the function name from a source location.

This function extracts the function name from a std::source_location and parses it to return just the simple function name without qualifiers, parameters, or return type.

For example, given:

  • GCC: "std::size_t porytiles::LazyLayeredConfig::num_tiles_primary(const std::string&) const"
  • Clang: "porytiles::LazyLayeredConfig::num_tiles_primary"

Both would return: "num_tiles_primary"

Parameters
locationThe source location from which to extract the function name (defaults to caller's location)
Returns
The simple function name without qualifiers

Definition at line 8 of file source_locations.cpp.

◆ extract_single_tile()

template<typename PixelType >
PixelTile< PixelType > porytiles::extract_single_tile ( const Image< PixelType > &  img,
std::size_t  tile_idx,
std::size_t  tiles_per_row = metatile::metatiles_per_row * metatile::tiles_per_side 
)

Extracts a single tile from an image at a given tile index.

Convenience wrapper around extract_tiles_from_image for single-tile extraction. Useful for extracting individual tiles for diagnostic visualization.

Template Parameters
PixelTypeThe pixel type of the image and resulting tile
Parameters
imgThe source tileset image
tile_idxThe tile index to extract (0-based)
tiles_per_rowThe number of tiles per row in the source image (default 16 for standard tiles.png)
Returns
The extracted PixelTile at the specified index

Definition at line 121 of file tile_extractors.hpp.

◆ extract_tiles_from_image() [1/2]

template<typename PixelType >
std::vector< PixelTile< PixelType > > porytiles::extract_tiles_from_image ( const Image< PixelType > &  img)

Extracts all 8x8 tiles from an image in row-major order.

This function divides the input image into 8x8 pixel tiles and returns them as a vector. Tiles are extracted in row-major order: starting from the top-left corner, proceeding left-to-right across each row, then top-to-bottom across rows.

This is a convenience overload that delegates to the offset/count version with tile_offset=0 and tile_count equal to the total number of tiles in the image.

Template Parameters
PixelTypeThe pixel type of the image and resulting tiles
Parameters
imgThe source image to extract tiles from
Precondition
Image width must be a multiple of 8
Image height must be a multiple of 8
Returns
Vector of extracted PixelTiles in row-major order

Definition at line 90 of file tile_extractors.hpp.

◆ extract_tiles_from_image() [2/2]

template<typename PixelType >
std::vector< PixelTile< PixelType > > porytiles::extract_tiles_from_image ( const Image< PixelType > &  img,
std::size_t  tile_offset,
std::size_t  tile_count,
std::size_t  tiles_per_row = 16 
)

Extracts a subset of 8x8 tiles from a tileset image at a specific offset.

This function extracts tile_count tiles starting from tile_offset, treating the image as a linear sequence of tiles arranged in rows of tiles_per_row width. Tiles are numbered in row-major order starting from the top-left.

For example, with tiles_per_row=16 (standard tiles.png format):

  • tile_offset=0 is at position (0,0)
  • tile_offset=15 is at position (0,15*8)
  • tile_offset=16 is at position (8,0) (first tile of second row)
Template Parameters
PixelTypeThe pixel type of the image and resulting tiles
Parameters
imgThe source tileset image
tile_offsetThe starting tile index (0-based)
tile_countThe number of tiles to extract
tiles_per_rowThe number of tiles per row in the source image
Precondition
Image width must be a multiple of 8
Image height must be a multiple of 8
tile_offset + tile_count must not exceed the total tiles in the image
Returns
Vector of extracted PixelTiles

Definition at line 36 of file tile_extractors.hpp.

◆ extract_tileset_cased_name()

DynamicCasedName porytiles::extract_tileset_cased_name ( const std::string &  tileset_name)
inline

Extracts the tileset short name and wraps it in a DynamicCasedName.

Removes the "gTileset_" prefix from a tileset name if present, then constructs a DynamicCasedName from the resulting shorthand. This combines extract_tileset_shorthand() and DynamicCasedName construction into a single convenience function, which is the most common usage pattern across the codebase.

Parameters
tileset_nameThe full tileset name (e.g., "gTileset_General")
Returns
A DynamicCasedName wrapping the short name (e.g., DynamicCasedName{"General"})
Examples

Definition at line 446 of file string_utils.hpp.

◆ extract_tileset_shorthand()

std::string porytiles::extract_tileset_shorthand ( const std::string &  tileset_name)
inline

Extracts the Pascal-case tileset short name from the full name.

Removes the "gTileset_" prefix from a tileset name if present. This is commonly needed when generating animation variable names or parsing animation code, where the short name (e.g., "General") is used instead of the full name (e.g., "gTileset_General").

Parameters
tileset_nameThe full tileset name (e.g., "gTileset_General")
Returns
The short name (e.g., "General"), or the original string if prefix not present
Examples
  • "gTileset_General" -> "General"
  • "gTileset_Petalburg" -> "Petalburg"
  • "General" -> "General" (no prefix, unchanged)

Definition at line 421 of file string_utils.hpp.

◆ files_are_identical()

bool porytiles::files_are_identical ( const std::filesystem::path &  file_a,
const std::filesystem::path &  file_b 
)
inline

Checks if two files have identical contents.

Compares two files using a two-stage approach for efficiency. First, it checks if the files have the same size (a fast metadata check). If sizes match, it computes MD5 digests of both files and compares them. Returns false if the second file doesn't exist, if either file cannot be opened, or if the contents differ.

Parameters
file_aPath to the first file (must exist).
file_bPath to the second file (may or may not exist).
Returns
True if both files exist and have identical contents, false otherwise.

Definition at line 60 of file filesystem_utils.hpp.

◆ find_all_function_calls()

std::vector< FunctionCallInfo > porytiles::find_all_function_calls ( const std::vector< Token > &  tokens)

Finds all function call expressions within a token stream.

Unlike find_function_calls(), this returns ALL function calls regardless of name. This is useful for discovering what functions are called within a code block.

Parameters
tokensThe token stream to search
Returns
Vector of FunctionCallInfo for all function calls found

Definition at line 92 of file function_call_info.cpp.

◆ find_function_calls()

std::vector< FunctionCallInfo > porytiles::find_function_calls ( const std::vector< Token > &  tokens,
const std::string &  target_function_name 
)

Finds all calls to a specific function within a token stream.

Searches for patterns of the form identifier(target_name) + lparen + ... + rparen and extracts the function call information including arguments. Arguments are split by comma tokens at the top level (parentheses are tracked to handle nested calls).

This is useful for finding specific macro or function calls within a function body, e.g., finding all AppendTilesetAnimToBuffer(...) calls within a queue function.

Parameters
tokensThe token stream to search
target_function_nameThe function name to search for
Returns
Vector of FunctionCallInfo for all matching calls

Definition at line 70 of file function_call_info.cpp.

◆ for_each_color()

template<typename Func >
void porytiles::for_each_color ( const ColorSet set,
Func &&  func 
)

Iterates over each color index in a ColorSet.

Calls the provided function for each color index that is set in the ColorSet. The function is called with a std::size_t representing the color index.

This implementation uses efficient bit scanning to skip over zero bits, reducing iteration from O(256) to O(k) where k is the number of set bits (typically 5-15 for tiles).

Template Parameters
FuncA callable type accepting std::size_t
Parameters
setThe ColorSet to iterate over
funcThe function to call for each set color index

Definition at line 133 of file color_set.hpp.

◆ format_config_note()

template<typename T >
std::vector< std::string > porytiles::format_config_note ( const TextFormatter format,
const ConfigValue< T > &  config 
)

Format a ConfigValue into diagnostic note lines.

Shared helper that constructs the standard format for displaying configuration values in note diagnostics. The output includes a header line showing the config name and value, followed by a blank line, then the full prettified configuration context.

Template Parameters
TThe underlying type of the ConfigValue
Parameters
formatThe TextFormatter for styling
configThe ConfigValue to format
Returns
Vector of formatted lines ready for note output

Definition at line 40 of file diagnostic_stencils.hpp.

◆ format_config_note_with_separator()

template<typename T >
std::vector< std::string > porytiles::format_config_note_with_separator ( const TextFormatter format,
const ConfigValue< T > &  config 
)

Format a ConfigValue into diagnostic note lines with a separator.

This method is the same as format_config_note, but it includes a separator section above the config note. This is useful for cases where the caller is already printing some other information and wants some visual separation between that info and the config printout.

Template Parameters
TThe underlying type of the ConfigValue
Parameters
formatThe TextFormatter for styling
configThe ConfigValue to format
Returns
Vector of formatted lines ready for note output

Definition at line 67 of file diagnostic_stencils.hpp.

◆ frame_linking_from_str()

std::optional< FrameLinking > porytiles::frame_linking_from_str ( const std::string &  str)
inline

Parses a string into a FrameLinking with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 59 of file frame_linking.hpp.

◆ from_pixel_tile() [1/2]

template<SupportsTransparency PixelType>
requires requires(const PixelType &p) { p.is_transparent(); }
ShapeTile< ColorIndex > porytiles::from_pixel_tile ( const PixelTile< PixelType > &  pixel_tile,
const ColorIndexMap< PixelType > &  color_index_map 
)

Converts a PixelTile to a ShapeTile<ColorIndex> using a ColorIndexMap (intrinsic transparency).

This function creates a ShapeTile<ColorIndex> from a PixelTile by mapping each unique non-transparent color to its corresponding color index from the ColorIndexMap. For each color index, a ShapeMask is constructed that marks all pixel positions containing that color.

This overload is only available for pixel types that support intrinsic transparency (e.g., IndexPixel).

The conversion process:

  1. Iterates through all 64 pixels in the PixelTile
  2. Skips intrinsically transparent pixels
  3. For each non-transparent pixel, looks up its color index in the ColorIndexMap
  4. Panics if a non-transparent pixel is not found in the ColorIndexMap
  5. Builds ShapeMasks for each unique color index
  6. Returns a ShapeTile<ColorIndex> mapping ShapeMasks to color indices
Template Parameters
PixelTypeThe pixel type of the input tile, must support intrinsic transparency
Parameters
pixel_tileThe PixelTile to convert
color_index_mapThe ColorIndexMap providing color-to-index mappings
Precondition
All non-transparent pixels in pixel_tile must be present in color_index_map
Returns
A ShapeTile<ColorIndex> with ShapeMasks mapped to color indices

Definition at line 232 of file tile_converters.hpp.

◆ from_pixel_tile() [2/2]

template<SupportsTransparency PixelType>
requires requires(const PixelType &p) { p.is_transparent(p); }
ShapeTile< ColorIndex > porytiles::from_pixel_tile ( const PixelTile< PixelType > &  pixel_tile,
const ColorIndexMap< PixelType > &  color_index_map,
const PixelType &  extrinsic 
)

Converts a PixelTile to a ShapeTile<ColorIndex> using a ColorIndexMap (extrinsic transparency).

This function creates a ShapeTile<ColorIndex> from a PixelTile by mapping each unique non-transparent color to its corresponding color index from the ColorIndexMap. For each color index, a ShapeMask is constructed that marks all pixel positions containing that color.

This overload is only available for pixel types that support extrinsic transparency (e.g., Rgba32). Transparency is determined using both intrinsic (alpha=0) and extrinsic (matching the provided value) checks.

The conversion process:

  1. Iterates through all 64 pixels in the PixelTile
  2. Skips pixels that are either intrinsically or extrinsically transparent
  3. For each non-transparent pixel, looks up its color index in the ColorIndexMap
  4. Panics if a non-transparent pixel is not found in the ColorIndexMap
  5. Builds ShapeMasks for each unique color index
  6. Returns a ShapeTile<ColorIndex> mapping ShapeMasks to color indices
Template Parameters
PixelTypeThe pixel type of the input tile, must support extrinsic transparency
Parameters
pixel_tileThe PixelTile to convert
color_index_mapThe ColorIndexMap providing color-to-index mappings
extrinsicThe extrinsic transparency value to check pixels against
Precondition
All non-transparent pixels in pixel_tile must be present in color_index_map
Returns
A ShapeTile<ColorIndex> with ShapeMasks mapped to color indices

Definition at line 266 of file tile_converters.hpp.

◆ from_shape_tile()

template<SupportsTransparency PixelType>
PixelTile< PixelType > porytiles::from_shape_tile ( const ShapeTile< ColorIndex > &  shape_tile,
const ColorIndexMap< PixelType > &  color_index_map 
)

Converts a ShapeTile<ColorIndex> to a PixelTile using a ColorIndexMap.

This function creates a PixelTile<InputPixelType> from a ShapeTile<ColorIndex> by looking up the actual color for each ColorIndex in the ColorIndexMap and setting the corresponding pixels in the result tile.

The conversion process:

  1. Creates a default PixelTile<InputPixelType> (all pixels transparent)
  2. Iterates through each (ShapeMask, ColorIndex) pair in the ShapeTile
  3. Looks up the actual color from the ColorIndexMap using the ColorIndex
  4. Panics if a ColorIndex is not found in the ColorIndexMap
  5. For each bit set in the ShapeMask, sets the corresponding pixel in the PixelTile to that color
  6. Panics if masks overlap (indicates programmer error in ShapeTile construction)
  7. Returns the completed PixelTile
Template Parameters
PixelTypeThe pixel type of the output tile, must support transparency
Parameters
shape_tileThe ShapeTile<ColorIndex> to convert
color_index_mapThe ColorIndexMap providing index-to-color mappings
Precondition
All ColorIndex values in shape_tile must be present in color_index_map
ShapeMasks in shape_tile must not overlap
Returns
A PixelTile<PixelType> with pixels set according to the ShapeTile's masks and colors

Definition at line 299 of file tile_converters.hpp.

◆ from_string()

std::optional< ConfigScopeType > porytiles::from_string ( const std::string &  str)
inline

Parses a string into a ConfigScopeType enum value.

This function attempts to parse a string representation into its corresponding ConfigScopeType enum value. The parsing is case-sensitive and expects exact matches for "tileset" or "layout".

Parameters
strThe string to parse
Returns
An optional containing the parsed ConfigScopeType, or std::nullopt if the string doesn't match any known scope type
Note
This function performs exact string matching. "Tileset" or "TILESET" will not match.

Definition at line 79 of file config_scope_type.hpp.

◆ get_cli_option_metadata()

std::vector< CliOptionMeta > porytiles::get_cli_option_metadata ( )
inline

Get all CLI option metadata for completion generation.

Returns
Vector of CliOptionMeta for all CLI-configurable options

Definition at line 31 of file cli_completion_data.hpp.

◆ index_tile_from_color_tile() [1/2]

template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PixelTile< IndexPixel > porytiles::index_tile_from_color_tile ( const PixelTile< ColorType > &  tile,
const Palette< ColorType, N > &  palette 
)

Converts a PixelTile<ColorType> to indexed form using a palette (intrinsic transparency only).

This function converts a color tile to an indexed tile by finding each non-transparent pixel's color in the palette and storing the corresponding palette index. Intrinsically transparent pixels (those reporting true from parameterless is_transparent()) are mapped to index 0.

This overload is only available for color types that support intrinsic transparency.

Template Parameters
ColorTypeThe color type of the tile and palette, must support intrinsic transparency
Parameters
tileThe PixelTile to convert to indexed form
paletteThe Palette containing the color-to-index mapping
Precondition
All non-transparent colors in the tile must exist in the palette
Returns
A PixelTile<IndexPixel> where each pixel is the palette index corresponding to the color

Definition at line 452 of file tile_converters.hpp.

◆ index_tile_from_color_tile() [2/2]

template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PixelTile< IndexPixel > porytiles::index_tile_from_color_tile ( const PixelTile< ColorType > &  tile,
const Palette< ColorType, N > &  palette,
const ColorType &  extrinsic 
)

Converts a PixelTile<ColorType> to indexed form using a palette (extrinsic transparency).

This function converts a color tile to an indexed tile by finding each non-transparent pixel's color in the palette and storing the corresponding palette index. Both intrinsically transparent pixels (alpha=0) and extrinsically transparent pixels (matching the extrinsic parameter) are mapped to index 0.

This overload is only available for color types that support extrinsic transparency.

Template Parameters
ColorTypeThe color type of the tile and palette, must support extrinsic transparency
Parameters
tileThe PixelTile to convert to indexed form
paletteThe Palette containing the color-to-index mapping
extrinsicThe extrinsic transparency value to check pixels against
Precondition
All non-transparent colors in the tile must exist in the palette
Returns
A PixelTile<IndexPixel> where each pixel is the palette index corresponding to the color

Definition at line 477 of file tile_converters.hpp.

◆ initialize_packed_palettes()

std::vector< PackedPalette > porytiles::initialize_packed_palettes ( const std::set< PrefilledPalette > &  prefilled_pals,
PalettePool pal_pool,
std::size_t  pal_capacity 
)

Initializes packed palettes from prefilled palettes.

This function sets up the initial palette state for packing algorithms by creating PackedPalette objects for each prefilled palette that's available in the pool. For each prefilled palette:

  • Checks out the corresponding slot from the palette pool
  • Calculates effective capacity accounting for "wasted" slots from duplicate colors
  • Pre-populates with fixed colors via a "system" PackableTile

After this function returns, the caller can use the modified palette pool for strategy-specific initialization (e.g., creating empty palettes for remaining slots).

Parameters
prefilled_palsThe prefilled palettes to initialize from
pal_poolThe palette pool; available slots for prefilled palettes will be checked out
pal_capacityThe base capacity for each palette (typically 15 for GBA hardware)
Returns
Vector of initialized PackedPalette objects for the prefilled palettes

Definition at line 7 of file packing_initializer.cpp.

◆ int_to_hex_str()

template<typename T >
std::string porytiles::int_to_hex_str ( t)

Converts an integer value to a hexadecimal string with "0x" prefix.

This function formats the given integer value as a lowercase hexadecimal string prefixed with "0x". For example, int_to_hex_str(255) returns "0xff".

Template Parameters
TAn integral type that can be formatted as hexadecimal
Parameters
tThe integer value to convert
Returns
A string containing the hexadecimal representation with "0x" prefix

Definition at line 174 of file string_utils.hpp.

◆ intersection_size()

std::size_t porytiles::intersection_size ( const ColorSet a,
const ColorSet b 
)

Computes the intersection size between two ColorSets.

Returns the count of colors present in both sets.

Parameters
aThe first ColorSet
bThe second ColorSet
Returns
The number of colors in the intersection

Definition at line 58 of file color_set.cpp.

◆ is_panic_stacktrace_enabled()

bool porytiles::is_panic_stacktrace_enabled ( )

Returns whether stacktrace generation is enabled on panic.

Returns
True if stacktraces will be generated, false otherwise

Definition at line 38 of file panic.cpp.

◆ is_subset()

bool porytiles::is_subset ( const ColorSet a,
const ColorSet b 
)

Checks if one ColorSet is a subset of another.

Returns true if every color in set 'a' is also present in set 'b'. An empty set is a subset of any set.

Parameters
aThe potential subset
bThe potential superset
Returns
true if a is a subset of b, false otherwise

Definition at line 49 of file color_set.cpp.

◆ layer_mode_from_str()

std::optional< LayerMode > porytiles::layer_mode_from_str ( const std::string &  s)
inline

Converts a string to LayerMode.

Parameters
sThe string to convert (must be "dual" or "triple")
Returns
The corresponding LayerMode, or std::nullopt if the string is invalid

Definition at line 49 of file layer.hpp.

◆ layer_mode_from_val()

LayerMode porytiles::layer_mode_from_val ( std::size_t  s)
inline

Converts a numeric value to LayerMode.

Accepts 8 for dual-layer mode or 12 for triple-layer mode.

Parameters
sThe numeric value (must be 8 or 12)
Returns
The corresponding LayerMode

Definition at line 32 of file layer.hpp.

◆ layer_type_from_int()

ChainableResult< LayerType > porytiles::layer_type_from_int ( unsigned int  i)
inline

Converts an integer to LayerType.

Parameters
iThe integer value (must be 0, 1, or 2)
Returns
ChainableResult containing the LayerType or an error

Definition at line 125 of file layer.hpp.

◆ load_animation_frame_from_png()

template<SupportsTransparency PixelType, typename LoaderType >
ChainableResult< FrameLoadResult< PixelType > > porytiles::load_animation_frame_from_png ( const std::filesystem::path &  png_path,
const std::string &  frame_name,
const LoaderType &  loader 
)

Loads an animation frame from a PNG file.

This template function provides the shared logic for loading animation frame PNG files. It handles the common workflow of:

  1. Loading the PNG via the provided loader
  2. Calculating frame dimensions in tiles (width_tiles, height_tiles)
  3. Extracting tiles from the image in row-major order
  4. Creating an AnimFrame with the specified name and extracted tiles
  5. Copying the image's palette to the frame if present

The function is parameterized by pixel type and loader type, allowing it to work with both:

Template Parameters
PixelTypeThe pixel type for tiles; must satisfy SupportsTransparency concept
LoaderTypeThe PNG loader type; must have a load_from_file(path) method returning ChainableResult
Parameters
png_pathThe absolute path to the PNG file to load
frame_nameThe name to assign to the frame (e.g., "0", "1", "key")
loaderThe PNG image loader instance to use
Precondition
PNG file must exist at png_path
Image dimensions must be multiples of 8 (tile size)
Returns
FrameLoadResult containing the AnimFrame and its dimensions, or error if loading fails

Definition at line 82 of file anim_frame_loader.hpp.

◆ load_indexed_png()

ChainableResult< std::unique_ptr< Image< IndexPixel > > > porytiles::load_indexed_png ( const std::filesystem::path &  path,
const PngIndexedImageLoader loader 
)

Loads an indexed PNG file (e.g., tiles.png).

Uses the provided loader to read an indexed-color PNG file and return the image data.

Parameters
pathAbsolute path to the PNG file
loaderThe PNG loader service to use
Precondition
File must exist and be a valid indexed PNG
Returns
The loaded indexed image, or error if loading fails

Definition at line 165 of file porymap_artifact_parsers.cpp.

◆ load_porymap_palette()

ChainableResult< Palette< Rgba32, pal::max_size > > porytiles::load_porymap_palette ( const std::filesystem::path &  path,
const FilePalLoader loader 
)

Loads a Porymap palette file (e.g., 00.pal).

Uses the provided loader to read a palette file in JASC or other supported format.

Parameters
pathAbsolute path to the palette file
loaderThe palette loader service to use
Precondition
File must exist and be a valid palette file
Returns
The loaded palette, or error if loading fails

Definition at line 177 of file porymap_artifact_parsers.cpp.

◆ match_or_best()

template<SupportsTransparency ColorType, typename PaletteContainer >
requires requires(const ColorType &c) { c.is_transparent(c); }
std::vector< PaletteMatchResult< ColorType > > porytiles::match_or_best ( const PixelTile< ColorType > &  tile,
const PaletteContainer &  palettes,
const ColorType &  extrinsic,
std::size_t  top_n 
)

Finds the best palette match(es) for a tile (extrinsic transparency).

This function matches a tile against a container of palettes and returns the best match(es):

  • If any palettes completely cover the tile, returns ALL complete matches (ignoring top_n)
  • If no palettes completely cover the tile, returns up to top_n best matches sorted by quality

Quality is determined by the number of missing_colors (fewer is better). If multiple palettes have the same number of missing colors, they maintain their original order in the palettes container.

This overload supports both intrinsic (alpha=0) and extrinsic transparency checking. This overload is only available for color types that support extrinsic transparency.

Template Parameters
ColorTypeThe color type of the palette and tile, must support extrinsic transparency
PaletteContainerA container type (e.g., std::vector, std::array) holding Palette objects
Parameters
tileThe PixelTile to match against the palettes
palettesThe container of Palettes to check for color coverage
extrinsicThe extrinsic transparency value to check pixels against
top_nMaximum number of results to return when no complete match exists (ignored if complete matches found)
Precondition
palettes is not empty
top_n > 0
All palettes are not empty
All palettes have extrinsic color in slot 0
Returns
A vector of PaletteMatchResult, either all complete matches or top_n best non-matches
Postcondition
The returned vector is non-empty and exhibits coverage homogeneity: all PaletteMatchResult elements possess identical is_covered values. This property enables deterministic match classification via examination of any single element, conventionally the first: results.at(0).is_covered. The function partitions the result space into two mutually exclusive sets (complete matches (is_covered = true) or partial matches (is_covered = false)), never returning a heterogeneous mixture.

Definition at line 223 of file palette_matchers.hpp.

◆ match_tile_to_palette() [1/2]

template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(); }
PaletteMatchResult< ColorType > porytiles::match_tile_to_palette ( const PixelTile< ColorType > &  tile,
const Palette< ColorType, N > &  palette 
)

Matches a PixelTile against a Palette (intrinsic transparency only).

This function determines whether the provided palette contains all non-transparent colors present in the tile. Only intrinsically transparent pixels (those reporting true from parameterless is_transparent()) are treated as transparent.

This overload is only available for color types that support intrinsic transparency.

The matching process:

  1. Extracts all unique non-transparent colors from the tile
  2. For each color, checks if it exists in the palette
  3. Categorizes colors as either "covered" or "missing"
  4. Returns a result indicating coverage status and the color sets
Template Parameters
ColorTypeThe color type of the palette and tile, must support intrinsic transparency
NThe palette size (0 for dynamic, non-zero for fixed-size)
Parameters
tileThe PixelTile to match against the palette
paletteThe Palette to check for color coverage
Precondition
The Palette is not empty
Returns
A PaletteMatchResult indicating whether the palette covers the tile and which colors are covered/missing

Definition at line 151 of file palette_matchers.hpp.

◆ match_tile_to_palette() [2/2]

template<SupportsTransparency ColorType, std::size_t N = 0>
requires requires(const ColorType &c) { c.is_transparent(c); }
PaletteMatchResult< ColorType > porytiles::match_tile_to_palette ( const PixelTile< ColorType > &  tile,
const Palette< ColorType, N > &  palette,
const ColorType &  extrinsic 
)

Matches a PixelTile against a Palette (extrinsic transparency).

This function determines whether the provided palette contains all non-transparent colors present in the tile. Both intrinsically transparent pixels (alpha=0) and extrinsically transparent pixels (matching the extrinsic parameter) are treated as transparent.

This overload is only available for color types that support extrinsic transparency.

Template Parameters
ColorTypeThe color type of the palette and tile, must support extrinsic transparency
NThe palette size (0 for dynamic, non-zero for fixed-size)
Parameters
tileThe PixelTile to match against the palette
paletteThe Palette to check for color coverage
extrinsicThe extrinsic transparency value to check pixels against
Precondition
The Palette is not empty
The extrinsic transparency must match the color in slot 0 of the Palette
Returns
A PaletteMatchResult indicating whether the palette covers the tile and which colors are covered/missing

Definition at line 180 of file palette_matchers.hpp.

◆ operator<<() [1/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const AnimKeyFrameResolutionStrategy  m 
)
inline

Stream insertion operator for AnimKeyFrameResolutionStrategy.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 130 of file anim_key_frame_resolution_strategy.hpp.

◆ operator<<() [2/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const AnimMultiPalSubtileResolutionStrategy  m 
)
inline

Stream insertion operator for AnimMultiPalSubtileResolutionStrategy.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 132 of file anim_multi_pal_subtile_resolution_strategy.hpp.

◆ operator<<() [3/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const AnimPalResolutionStrategy  m 
)
inline

Stream insertion operator for AnimPalResolutionStrategy.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 695 of file anim_pal_resolution_strategy.hpp.

◆ operator<<() [4/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const ArtifactEditMode  m 
)
inline

Stream insertion operator for ArtifactEditMode.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 125 of file artifact_edit_mode.hpp.

◆ operator<<() [5/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const BaseGame  game 
)
inline

Stream insertion operator for BaseGame.

Parameters
osThe output stream
gameThe BaseGame to output
Returns
The output stream

Definition at line 73 of file base_game.hpp.

◆ operator<<() [6/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const DynamicCasedName value 
)
inline

Stream insertion operator for DynamicCasedName.

Parameters
osThe output stream.
valueThe DynamicCasedName to output.
Returns
Reference to the output stream.

Definition at line 205 of file dynamic_cased_name.hpp.

◆ operator<<() [7/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const FrameLinking  m 
)
inline

Stream insertion operator for FrameLinking.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 126 of file frame_linking.hpp.

◆ operator<<() [8/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const LayerMode  mode 
)
inline

Stream insertion operator for LayerMode.

Parameters
osThe output stream
modeThe LayerMode to output
Returns
The output stream

Definition at line 84 of file layer.hpp.

◆ operator<<() [9/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const PackingStrategyParams params 
)
inline

Stream insertion operator for PackingStrategyParams.

Parameters
osThe output stream
paramsThe params to output
Returns
Reference to the output stream

Definition at line 145 of file packing_strategy_params.hpp.

◆ operator<<() [10/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const PackingStrategyType  m 
)
inline

Stream insertion operator for PackingStrategyType.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 137 of file packing_strategy_type.hpp.

◆ operator<<() [11/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const PaletteHint hint 
)
inline

Stream output operator for PaletteHint.

Outputs the name of the palette hint to the stream.

Parameters
osThe output stream
hintThe PaletteHint to output
Returns
Reference to the output stream

Definition at line 71 of file palette_hint.hpp.

◆ operator<<() [12/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const PerAnimOverrides configs 
)
inline

Stream insertion operator for AnimConfigs.

Parameters
osThe output stream
configsThe configs map to output
Returns
Reference to the output stream

Definition at line 59 of file per_anim_overrides.hpp.

◆ operator<<() [13/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const PrimaryPairingMode  m 
)
inline

Stream insertion operator for PrimaryPairingMode.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 133 of file primary_pairing_mode.hpp.

◆ operator<<() [14/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const Rgba32 rgba 
)
inline

Stream insertion operator for Rgba32.

Allows Rgba32 objects to be written to output streams using the << operator. Uses the bracketed component format (e.g., "[R, G, B, A]").

Parameters
osThe output stream
rgbaThe Rgba32 color to output
Returns
Reference to the output stream

Definition at line 125 of file rgba32.hpp.

◆ operator<<() [15/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const SearchAlgorithm  m 
)
inline

Stream insertion operator for SearchAlgorithm.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 129 of file search_algorithm.hpp.

◆ operator<<() [16/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const ShuffleStrategy  m 
)
inline

Stream insertion operator for ShuffleStrategy.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 136 of file shuffle_strategy.hpp.

◆ operator<<() [17/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const TileSharingAlignment  m 
)
inline

Stream insertion operator for TileSharingAlignment.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 124 of file tile_sharing_alignment.hpp.

◆ operator<<() [18/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const TileSharingPacking  m 
)
inline

Stream insertion operator for TileSharingPacking.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 124 of file tile_sharing_packing.hpp.

◆ operator<<() [19/19]

std::ostream & porytiles::operator<< ( std::ostream &  os,
const TilesPalMode  m 
)
inline

Stream insertion operator for TilesPalMode.

Parameters
osThe output stream
mThe value to output
Returns
Reference to the output stream

Definition at line 126 of file tiles_pal_mode.hpp.

◆ packing_strategy_type_from_str()

std::optional< PackingStrategyType > porytiles::packing_strategy_type_from_str ( const std::string &  str)
inline

Parses a string into a PackingStrategyType with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 61 of file packing_strategy_type.hpp.

◆ pad_two_digits()

template<typename T >
std::string porytiles::pad_two_digits ( t)

Converts an integer value to a minimum two-digit wide string representation.

For example: pad_two_digits(3) returns "03", pad_two_digits(13) returns "13", pad_two_digits(133) returns "133".

Template Parameters
TAn integral type to be formatted
Parameters
tThe integer value to convert
Returns
A string containing the padded representation

Definition at line 191 of file string_utils.hpp.

◆ pal_filename()

std::string porytiles::pal_filename ( std::size_t  pal_index)
inline

Constructs a palette filename from a palette index.

This function formats a palette index as a two-digit padded number with the ".pal" extension. For example, pal_filename(3) returns "03.pal", pal_filename(12) returns "12.pal".

Parameters
pal_indexThe palette index to format
Returns
A string in the format "XX.pal" where XX is the zero-padded index

Definition at line 400 of file string_utils.hpp.

◆ palette_contains_sibling()

bool porytiles::palette_contains_sibling ( const PackableTile::Id tile_id,
const PackedPalette palette,
const ShapeGroupMetadata metadata 
)

Checks whether a palette already contains a sibling of the given tile (same shape group, different tile).

Looks up the tile's PackableTile::Id in the metadata to find its shape group, then scans the palette's assigned tile IDs for any other tile belonging to the same group. This is an O(G * N) check where G is the group size (typically 2-5) and N is the number of tiles in the palette.

Parameters
tile_idThe ID of the tile being placed.
paletteThe candidate palette to check.
metadataThe shape group metadata mapping tile IDs to groups.
Returns
true if the palette contains at least one sibling from the same shape group.

Definition at line 7 of file sharing_metrics.cpp.

◆ panic()

void porytiles::panic ( const StringViewSourceLoc s)

Unconditionally terminates the program with a panic message.

This function formats and prints a panic message containing the source location and user message, then aborts the program. The function never returns.

Parameters
sThe StringViewSourceLoc containing the panic message and location

Definition at line 43 of file panic.cpp.

◆ parse_emerald_metatile_attributes()

ChainableResult< std::vector< MetatileAttribute > > porytiles::parse_emerald_metatile_attributes ( const std::filesystem::path &  path)

Parses a metatile_attributes.bin file for Emerald format.

Reads a binary file containing 2-byte metatile attribute entries. Each entry encodes:

  • Bits 0-7: terrain/behavior value
  • Bits 12-15: layer type
Parameters
pathAbsolute path to the metatile_attributes.bin file
Precondition
File must exist and be readable
File size must be a multiple of 2 bytes (attr::bytes_per_attr_emerald)
Returns
Vector of parsed MetatileAttribute objects, or error if file is invalid/corrupted

Definition at line 58 of file porymap_artifact_parsers.cpp.

◆ parse_firered_metatile_attributes()

ChainableResult< std::vector< MetatileAttribute > > porytiles::parse_firered_metatile_attributes ( const std::filesystem::path &  path)

Parses a metatile_attributes.bin file for FireRed format.

Reads a binary file containing 4-byte metatile attribute entries. Each entry encodes:

  • Bits 0-8: behavior value (9 bits)
  • Bits 9-13: terrain type (5 bits)
  • Bits 14-17: attribute 2 (4 bits)
  • Bits 18-23: attribute 3 (6 bits)
  • Bits 24-26: encounter type (3 bits)
  • Bits 27-28: attribute 5 (2 bits)
  • Bits 29-30: layer type (2 bits)
  • Bit 31: attribute 7 (1 bit)
Parameters
pathAbsolute path to the metatile_attributes.bin file
Precondition
File must exist and be readable
File size must be a multiple of 4 bytes (attr::bytes_per_attr_firered)
Returns
Vector of parsed MetatileAttribute objects, or error if file is invalid/corrupted

Definition at line 96 of file porymap_artifact_parsers.cpp.

◆ parse_int() [1/2]

template<typename T >
std::expected< T, std::string > porytiles::parse_int ( std::string_view  int_string)

Definition at line 31 of file parse_int.hpp.

◆ parse_int() [2/2]

template<typename T >
std::expected< T, std::string > porytiles::parse_int ( std::string_view  int_string,
const int  base 
)

Definition at line 10 of file parse_int.hpp.

◆ parse_metatiles_bin()

ChainableResult< std::vector< TilemapEntry > > porytiles::parse_metatiles_bin ( const std::filesystem::path &  path)

Parses a metatiles.bin file into TilemapEntry objects.

Reads a binary file containing 2-byte tilemap entries. Each entry encodes:

  • Bits 0-9: tile index (10 bits)
  • Bit 10: horizontal flip flag
  • Bit 11: vertical flip flag
  • Bits 12-15: palette index (4 bits)
Parameters
pathAbsolute path to the metatiles.bin file
Precondition
File must exist and be readable
File size must be a multiple of 2 bytes
Returns
Vector of parsed TilemapEntry objects, or error if file is invalid/corrupted

Definition at line 9 of file porymap_artifact_parsers.cpp.

◆ primary_pairing_mode_from_str()

std::optional< PrimaryPairingMode > porytiles::primary_pairing_mode_from_str ( const std::string &  str)
inline

Parses a string into a PrimaryPairingMode with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 60 of file primary_pairing_mode.hpp.

◆ register_config_options()

void porytiles::register_config_options ( CLI::App &  app,
CliOptionStorage storage 
)

Registers all config options with a CLI11 App.

This function adds all config values as CLI options to the provided CLI::App. The options are grouped under "Config Options" and will populate the corresponding fields in the CliOptionStorage struct when parsed.

Parameters
appThe CLI11 App to register options with
storageThe storage struct that will hold parsed values

Definition at line 14 of file cli_option_registration.cpp.

◆ require_packing_strategy_backtracking()

template<typename T , typename ConfigInterface , typename FetchFunc >
ChainableResult< ConfigValue< T > > porytiles::require_packing_strategy_backtracking ( const ConfigValue< T > &  val,
const ConfigInterface &  config,
ConfigScopeType  type,
const std::string &  scope,
const std::string &  other_field_name,
FetchFunc  fetch_other 
)

Validates that 'biased' or 'optimal' tile sharing packing requires 'backtracking' packing strategy.

When tile sharing packing is set to TileSharingPacking::biased or TileSharingPacking::optimal, the packing strategy must be PackingStrategyType::backtracking. If tile sharing packing is TileSharingPacking::off, no constraint is enforced. This is a cross-field validator that fetches the packing strategy from the config interface.

Template Parameters
TThe type of the config value (expected to be TileSharingPacking)
ConfigInterfaceThe config interface type (e.g., DomainConfig)
FetchFuncCallable type that fetches the packing strategy config value
Parameters
valThe tile sharing packing config value being validated
configThe config interface to fetch the packing strategy from
typeThe config scope type (tileset or layout)
scopeThe scope name (tileset or layout name)
other_field_nameThe name of the packing strategy field
fetch_otherCallable that fetches the packing strategy config value
Returns
ChainableResult containing either the original value or an error

Definition at line 76 of file domain_config_validators.hpp.

◆ resolve_partner_primary()

ChainableResult< std::unique_ptr< Tileset > > porytiles::resolve_partner_primary ( const std::string &  tileset_name,
const ConfigValue< PrimaryPairingMode > &  pairing_mode,
const ConfigValue< std::vector< std::string > > &  partners,
const TilesetRepo tileset_repo,
const TilesetMetadataProvider metadata_provider,
const LayoutMetadataProvider layout_metadata_provider,
const PorytilesTilesetManager tileset_manager,
const UserDiagnostics diag 
)

Resolves the partner primary tileset for a secondary tileset.

Given a secondary tileset name and pairing configuration, determines which primary tileset to pair with. Supports three pairing modes:

  • off: No primary pairing, returns nullptr.
  • manual: Uses the first entry from the configured partners list.
  • automatic: Scans project layouts to find which primary is paired with this secondary.

After resolution, validates that the partner primary exists and is Porytiles-managed, then loads and returns it.

Parameters
tileset_nameThe name of the secondary tileset being compiled or created.
pairing_modeThe configured primary pairing mode, wrapped with source provenance.
partnersThe configured list of partner primary tileset names, wrapped with source provenance.
tileset_repoRepository for loading tileset data.
metadata_providerProvider for checking tileset existence.
layout_metadata_providerProvider for scanning project layouts (used in automatic mode).
tileset_managerManager for checking Porytiles ownership.
diagDiagnostics interface for warnings.
Returns
The loaded partner primary Tileset, nullptr if pairing is off, or an error.

Definition at line 14 of file secondary_tileset_helpers.cpp.

◆ reverse_bits()

constexpr uint8_t porytiles::reverse_bits ( uint8_t  b)
constexpr

Reverses the bits in a byte.

This function reverses the order of all 8 bits in a byte. For example, the byte 0b10110010 would be reversed to 0b01001101.

Parameters
bThe byte to reverse
Returns
The byte with its bits reversed

Definition at line 17 of file reverse_bits.hpp.

◆ rgb_bg_style()

constexpr Style porytiles::rgb_bg_style ( std::uint8_t  r,
std::uint8_t  g,
std::uint8_t  b 
)
constexpr

Creates a Style value with a custom RGB background color.

Constructs a Style value with an RGB background color using the provided red, green, and blue channel values. The resulting Style can be combined with formatting flags and foreground colors using the | operator:

++
Style custom = rgb_bg_style(64, 64, 64) | Style::bold;
Style with_fg = Style::red | rgb_bg_style(255, 255, 0);
Text styling class supporting formatting, foreground colors, and background colors.
constexpr Style rgb_bg_style(std::uint8_t r, std::uint8_t g, std::uint8_t b)
Creates a Style value with a custom RGB background color.
Parameters
rRed channel value (0-255)
gGreen channel value (0-255)
bBlue channel value (0-255)
Returns
A Style value with RGB background color

Definition at line 380 of file text_formatter.hpp.

◆ rgb_fg_style()

constexpr Style porytiles::rgb_fg_style ( std::uint8_t  r,
std::uint8_t  g,
std::uint8_t  b 
)
constexpr

Creates a Style value with a custom RGB foreground color.

Constructs a Style value with an RGB foreground color using the provided red, green, and blue channel values. The resulting Style can be combined with formatting flags and background colors using the | operator:

++
Style custom = rgb_fg_style(255, 128, 0) | Style::bold;
Style with_bg = rgb_fg_style(255, 128, 0) | Style::bg_black;
static const Style bg_black
Black background color.
constexpr Style rgb_fg_style(std::uint8_t r, std::uint8_t g, std::uint8_t b)
Creates a Style value with a custom RGB foreground color.
Parameters
rRed channel value (0-255)
gGreen channel value (0-255)
bBlue channel value (0-255)
Returns
A Style value with RGB foreground color

Definition at line 359 of file text_formatter.hpp.

◆ rgb_style()

constexpr Style porytiles::rgb_style ( std::uint8_t  r,
std::uint8_t  g,
std::uint8_t  b 
)
constexpr

Creates a Style value with a custom RGB foreground color (backward compatibility alias).

This function is an alias for rgb_fg_style() to maintain backward compatibility with code that used the previous enum-based API. New code should prefer rgb_fg_style() for clarity.

Parameters
rRed channel value (0-255)
gGreen channel value (0-255)
bBlue channel value (0-255)
Returns
A Style value with RGB foreground color

Definition at line 397 of file text_formatter.hpp.

◆ rgba_alpha_component_opaque()

ChainableResult< ConfigValue< Rgba32 > > porytiles::rgba_alpha_component_opaque ( const ConfigValue< Rgba32 > &  val)
inline

Validates that an Rgba32 alpha component is opaque.

Parameters
valThe config value to validate.
Returns
ChainableResult containing either the original value or a FormattableError if validation fails.
Postcondition
If successful, the returned value is guaranteed to have opaque alpha value.

Definition at line 33 of file domain_config_validators.hpp.

◆ search_algorithm_from_str()

std::optional< SearchAlgorithm > porytiles::search_algorithm_from_str ( const std::string &  str)
inline

Parses a string into a SearchAlgorithm with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 56 of file search_algorithm.hpp.

◆ set_panic_stacktrace_enabled()

void porytiles::set_panic_stacktrace_enabled ( bool  enabled)

Enables or disables stacktrace generation on panic.

When disabled, panic will still print the error message and source location, but skip the expensive stacktrace generation. This is useful for test suites with many intentional panics where stacktrace overhead is undesirable. Defaults to enabled.

Parameters
enabledWhether to generate stacktraces on panic

Definition at line 33 of file panic.cpp.

◆ shape_tile_from_pixel_tile()

template<SupportsTransparency PixelType, typename TransparencyPredicate >
ShapeTile< PixelType > porytiles::shape_tile_from_pixel_tile ( const PixelTile< PixelType > &  pixel_tile,
TransparencyPredicate  is_transparent_pred 
)

Converts a PixelTile to a ShapeTile by grouping pixels by color into ShapeMasks.

For each unique non-transparent color in the tile, creates a ShapeMask marking which pixels have that color, then maps the mask to the color value. This produces a ShapeTile where the keys (ShapeMasks) represent the geometric structure and the values (PixelType) represent the color assignments.

This is a direct conversion that does not require a ColorIndexMap, unlike the from_pixel_tile() functions in tile_converters.hpp which produce ShapeTile<ColorIndex>.

Template Parameters
PixelTypeThe pixel type, must support transparency checking
Parameters
pixel_tileThe input pixel tile to convert
is_transparent_predPredicate that returns true if a pixel is transparent
Returns
A ShapeTile with color-to-mask mappings

Definition at line 34 of file shape_group_analyzer.hpp.

◆ shape_tile_to_pixel_colors()

template<SupportsTransparency PixelType>
ShapeTile< PixelType > porytiles::shape_tile_to_pixel_colors ( const ShapeTile< ColorIndex > &  shape_tile,
const ColorIndexMap< PixelType > &  color_index_map 
)

Converts a ShapeTile<ColorIndex> to a ShapeTile<PixelType> using a ColorIndexMap.

This function creates a ShapeTile<PixelType> from a ShapeTile<ColorIndex> by looking up the actual color for each ColorIndex in the ColorIndexMap. The ShapeMasks remain the same, but the color values change from indices to actual pixel colors.

The conversion process:

  1. Creates an empty ShapeTile<PixelType> result
  2. Iterates through each (ShapeMask, ColorIndex) pair in the input ShapeTile
  3. Looks up the actual color from the ColorIndexMap using the ColorIndex
  4. Panics if a ColorIndex is not found in the ColorIndexMap
  5. Sets the ShapeMask with the pixel color in the result ShapeTile
  6. Returns the completed ShapeTile<PixelType>
Template Parameters
PixelTypeThe pixel type of the output tile, must support transparency
Parameters
shape_tileThe ShapeTile<ColorIndex> to convert
color_index_mapThe ColorIndexMap providing index-to-color mappings
Precondition
All ColorIndex values in shape_tile must be present in color_index_map
Returns
A ShapeTile<PixelType> with the same masks but pixel colors instead of color indices

Definition at line 362 of file tile_converters.hpp.

◆ shuffle_strategy_from_str()

std::optional< ShuffleStrategy > porytiles::shuffle_strategy_from_str ( const std::string &  str)
inline

Parses a string into a ShuffleStrategy with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 60 of file shuffle_strategy.hpp.

◆ size_t_val_eight_or_twelve()

ChainableResult< ConfigValue< std::size_t > > porytiles::size_t_val_eight_or_twelve ( const ConfigValue< std::size_t > &  val)
inline

Validates that a size_t config value is either 8 or 12.

Parameters
valThe config value to validate
Returns
ChainableResult containing either the original value or a FormattableError if validation fails
Postcondition
If successful, the returned value is guaranteed to be greater than zero

Definition at line 127 of file xcut_config_validators.hpp.

◆ size_t_val_greater_than_zero()

ChainableResult< ConfigValue< std::size_t > > porytiles::size_t_val_greater_than_zero ( const ConfigValue< std::size_t > &  val)
inline

Validates that a size_t config value is greater than zero.

This validator checks that the provided size_t config value is non-zero. If the value is zero, it returns a detailed error message showing the field name and the invalid value along with its configuration source information.

Parameters
valThe config value to validate
Returns
ChainableResult containing either the original value or a FormattableError if validation fails
Postcondition
If successful, the returned value is guaranteed to be greater than zero

Definition at line 69 of file xcut_config_validators.hpp.

◆ size_t_val_two_or_four()

ChainableResult< ConfigValue< std::size_t > > porytiles::size_t_val_two_or_four ( const ConfigValue< std::size_t > &  val)
inline

Validates that a size_t config value is either 2 or 4.

Parameters
valThe config value to validate
Returns
ChainableResult containing either the original value or a FormattableError if validation fails
Postcondition
If successful, the returned value is guaranteed to be either 2 or 4

Definition at line 96 of file xcut_config_validators.hpp.

◆ split()

std::vector< std::string > porytiles::split ( std::string  input,
const std::string &  delimiter 
)
inline

Splits a string into tokens based on a delimiter.

This function splits the input string into a vector of substrings using the specified delimiter. The delimiter itself is not included in the resulting tokens. Empty tokens are preserved if consecutive delimiters are found.

Parameters
inputThe string to split
delimiterThe delimiter string to split on
Returns
A vector containing the split tokens

Definition at line 112 of file string_utils.hpp.

◆ standard_greyscale_pal()

std::vector< Rgba32 > porytiles::standard_greyscale_pal ( )
inline

Returns the standard 16-color greyscale palette used for indexed tile output.

This palette maps index 0 to pure white and index 15 to pure black, which matches vanilla game tilesets. The intermediate values are evenly spaced greyscale tones.

Returns
A vector of 16 Rgba32 colors representing the greyscale palette

Definition at line 152 of file rgba32.hpp.

◆ strip_all_extensions()

std::filesystem::path porytiles::strip_all_extensions ( const std::filesystem::path &  path)
inline

Strips all extensions from a path, returning the path with only the stem.

This function repeatedly removes extensions from the filename portion of a path until no extensions remain. This is useful for files with multiple extensions like "tiles.4bpp.smol" which should become "tiles". The directory portion of the path is preserved. Dot files (e.g., ".gitignore") are handled correctly - the leading dot is part of the filename, not an extension, so they are returned unchanged.

Parameters
pathThe path to strip extensions from.
Returns
A new path with all extensions removed from the filename.
Examples
  • "tiles.png" -> "tiles"
  • "tiles.4bpp.smol" -> "tiles"
  • "data/tiles.4bpp.smol" -> "data/tiles"
  • ".gitignore" -> ".gitignore"
  • "tiles" -> "tiles"

Definition at line 96 of file filesystem_utils.hpp.

◆ tile_sharing_alignment_from_str()

std::optional< TileSharingAlignment > porytiles::tile_sharing_alignment_from_str ( const std::string &  str)
inline

Parses a string into a TileSharingAlignment with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 60 of file tile_sharing_alignment.hpp.

◆ tile_sharing_packing_from_str()

std::optional< TileSharingPacking > porytiles::tile_sharing_packing_from_str ( const std::string &  str)
inline

Parses a string into a TileSharingPacking with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 60 of file tile_sharing_packing.hpp.

◆ tiles_pal_mode_from_str()

std::optional< TilesPalMode > porytiles::tiles_pal_mode_from_str ( const std::string &  str)
inline

Parses a string into a TilesPalMode with fuzzy matching.

Performs parsing in two phases:

  1. Exact match against C++ constant names (snake_case)
  2. Case-insensitive fuzzy match against configured fuzzy_names

This unified function is used by both CLI and YAML parsing. The fuzzy matching allows users to use various common formats (kebab-case, snake_case, etc.) while still getting good error messages through LazyLayeredConfig.

Parameters
strThe string to parse
Returns
The parsed value, or std::nullopt if the string is invalid

Definition at line 53 of file tiles_pal_mode.hpp.

◆ to_lower_str()

std::string porytiles::to_lower_str ( const std::string &  input)
inline

Converts all characters in a string to lowercase.

This function creates a new string where each character from the input is converted to its lowercase equivalent using std::tolower. Characters that are already lowercase or non-alphabetic remain unchanged. The function uses unsigned char casting internally to avoid undefined behavior with negative char values on platforms where char is signed.

Parameters
inputThe string to convert to lowercase
Returns
A new string with all alphabetic characters converted to lowercase
Examples
  • "Hello World" -> "hello world"
  • "UPPERCASE" -> "uppercase"
  • "MixedCase123" -> "mixedcase123"

Definition at line 380 of file string_utils.hpp.

◆ to_pascal_case()

std::string porytiles::to_pascal_case ( const std::string &  s)
inline

Converts a string to PascalCase format.

This function converts an input string to PascalCase by capitalizing the first letter of each word and removing separators. Words are identified by underscore ('_'), hyphen ('-'), or space (' ') delimiters. Characters following a delimiter are capitalized, and the delimiters themselves are removed from the output.

Parameters
sThe string to convert
Returns
A new string in PascalCase format
Examples
  • "hello_world" -> "HelloWorld"
  • "foo-bar" -> "FooBar"
  • "already PascalCase" -> "AlreadyPascalCase"

Definition at line 269 of file string_utils.hpp.

◆ to_snake_case()

std::string porytiles::to_snake_case ( const std::string &  s)
inline

Converts a string to snake_case format.

This function converts an input string to snake_case by inserting underscores before uppercase letters and converting all characters to lowercase. Existing separators (underscore, hyphen, space) are converted to underscores. Consecutive uppercase letters are treated as an acronym, with an underscore inserted before the last letter of the acronym when followed by lowercase letters (e.g., "XMLParser" becomes "xml_parser").

Parameters
sThe string to convert
Returns
A new string in snake_case format
Examples
  • "HelloWorld" -> "hello_world"
  • "camelCase" -> "camel_case"
  • "XMLParser" -> "xml_parser"
  • "already_snake" -> "already_snake"

Definition at line 315 of file string_utils.hpp.

◆ to_string() [1/25]

std::string porytiles::to_string ( BaseGame  game)
inline

Converts BaseGame to string representation.

Parameters
gameThe BaseGame to convert
Returns
String representation (e.g. "pokeemerald", "pokefirered", "pokeruby", "pokeemerald-expansion")

Definition at line 51 of file base_game.hpp.

◆ to_string() [2/25]

std::string porytiles::to_string ( bool  value)
inline

Converts a boolean to its string representation.

This overload is necessary because std::to_string() has no bool overload and implicitly converts bool to int, resulting in "1" or "0" instead of "true" or "false". This function provides human-readable boolean string representation for use in diagnostic messages and configuration value display.

Parameters
valueThe boolean value to convert.
Returns
"true" if value is true, "false" otherwise.

Definition at line 223 of file string_utils.hpp.

◆ to_string() [3/25]

std::string porytiles::to_string ( ConfigScopeType  type)
inline

Converts a ConfigScopeType enum value to its string representation.

This function provides a canonical string representation of the ConfigScopeType enum. Useful for logging, debugging, cache key generation, and serialization.

Parameters
typeThe ConfigScopeType value to convert
Returns
The string representation ("tileset" or "layout")
Note
This function always returns a valid string for any ConfigScopeType value.

Definition at line 54 of file config_scope_type.hpp.

◆ to_string() [4/25]

std::string porytiles::to_string ( const AnimKeyFrameResolutionStrategy  m)
inline

Converts a AnimKeyFrameResolutionStrategy to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 110 of file anim_key_frame_resolution_strategy.hpp.

◆ to_string() [5/25]

std::string porytiles::to_string ( const AnimMultiPalSubtileResolutionStrategy  m)
inline

Converts a AnimMultiPalSubtileResolutionStrategy to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 112 of file anim_multi_pal_subtile_resolution_strategy.hpp.

◆ to_string() [6/25]

std::string porytiles::to_string ( const AnimPalResolutionStrategy  m)
inline

Converts a AnimPalResolutionStrategy to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 643 of file anim_pal_resolution_strategy.hpp.

◆ to_string() [7/25]

std::string porytiles::to_string ( const ArtifactEditMode  m)
inline

Converts a ArtifactEditMode to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 105 of file artifact_edit_mode.hpp.

◆ to_string() [8/25]

std::string porytiles::to_string ( const DynamicCasedName value)

Converts a DynamicCasedName to its snake_case string representation.

Parameters
valueThe DynamicCasedName to convert.
Returns
The snake_case representation of the name.

Definition at line 283 of file dynamic_cased_name.cpp.

◆ to_string() [9/25]

std::string porytiles::to_string ( const FrameLinking  m)
inline

Converts a FrameLinking to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 106 of file frame_linking.hpp.

◆ to_string() [10/25]

std::string porytiles::to_string ( const PackableTile::Id id)
inline

Definition at line 236 of file packable_tile.hpp.

◆ to_string() [11/25]

std::string porytiles::to_string ( const PackingStrategyParams params)
inline

Converts a PackingStrategyParams to a human-readable string.

Parameters
paramsThe params to convert
Returns
A string representation of the params

Definition at line 82 of file packing_strategy_params.hpp.

◆ to_string() [12/25]

std::string porytiles::to_string ( const PackingStrategyType  m)
inline

Converts a PackingStrategyType to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 117 of file packing_strategy_type.hpp.

◆ to_string() [13/25]

std::string porytiles::to_string ( const PaletteHint hint)
inline

Converts a PaletteHint to its string representation.

Returns the name of the palette hint, which serves as its unique identifier.

Parameters
hintThe PaletteHint to convert
Returns
The name of the palette hint

Definition at line 56 of file palette_hint.hpp.

◆ to_string() [14/25]

std::string porytiles::to_string ( const PerAnimOverrides configs)
inline

Converts an PerAnimOverride map to a human-readable string.

Produces a brace-enclosed, comma-separated list of animation names. An empty map produces "{}".

Parameters
configsThe configs map to convert
Returns
A string representation of the map

Definition at line 31 of file per_anim_overrides.hpp.

◆ to_string() [15/25]

std::string porytiles::to_string ( const PrimaryPairingMode  m)
inline

Converts a PrimaryPairingMode to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 113 of file primary_pairing_mode.hpp.

◆ to_string() [16/25]

std::string porytiles::to_string ( const Rgba32 rgba)
inline

Definition at line 108 of file rgba32.hpp.

◆ to_string() [17/25]

std::string porytiles::to_string ( const SearchAlgorithm  m)
inline

Converts a SearchAlgorithm to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 111 of file search_algorithm.hpp.

◆ to_string() [18/25]

std::string porytiles::to_string ( const ShuffleStrategy  m)
inline

Converts a ShuffleStrategy to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 116 of file shuffle_strategy.hpp.

◆ to_string() [19/25]

std::string porytiles::to_string ( const std::string &  str)
inline

Identity function for to_string with std::string input.

This overload enables generic code that calls to_string() to work with std::string types. It simply returns the input string unchanged. This is needed because std::to_string() only works with numeric types, but generic templates (like config value caching) may need to convert any type to a string representation.

Parameters
strThe string to return
Returns
The input string unchanged

Definition at line 207 of file string_utils.hpp.

◆ to_string() [20/25]

template<typename T >
std::string porytiles::to_string ( const std::vector< T > &  vec)

Converts a vector to a string representation with curly brace delimiters.

This function formats a vector as a comma-separated list enclosed in curly braces. For example, to_string(std::vector<int>{1, 2, 3}) returns "{1, 2, 3}".

Template Parameters
TThe element type of the vector (must be formattable by fmt::format)
Parameters
vecThe vector to convert to a string
Returns
A string representation of the vector in the format "{elem1, elem2, ...}"

Definition at line 240 of file string_utils.hpp.

◆ to_string() [21/25]

std::string porytiles::to_string ( const TileSharingAlignment  m)
inline

Converts a TileSharingAlignment to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 104 of file tile_sharing_alignment.hpp.

◆ to_string() [22/25]

std::string porytiles::to_string ( const TileSharingPacking  m)
inline

Converts a TileSharingPacking to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 104 of file tile_sharing_packing.hpp.

◆ to_string() [23/25]

std::string porytiles::to_string ( const TilesPalMode  m)
inline

Converts a TilesPalMode to its canonical string representation.

Returns the C++ constant name (snake_case). This is the canonical form used for general purpose string conversion, logging, and error messages.

Parameters
mThe value to convert
Returns
The canonical snake_case string representation

Definition at line 108 of file tiles_pal_mode.hpp.

◆ to_string() [24/25]

std::string porytiles::to_string ( LayerMode  mode)
inline

Converts LayerMode to string representation.

Parameters
modeThe LayerMode to convert
Returns
String representation ("dual" or "triple")

Definition at line 66 of file layer.hpp.

◆ to_string() [25/25]

std::string porytiles::to_string ( LayerType  layer_type)
inline

Converts LayerType to string representation.

Parameters
layer_typeThe LayerType to convert
Returns
Human-readable string describing the layer type

Definition at line 105 of file layer.hpp.

◆ token_type_name()

std::string porytiles::token_type_name ( TokenType  type)

Returns a human-readable name for a token type.

Parameters
typeThe token type
Returns
A string describing the token type

Definition at line 61 of file lexer.cpp.

◆ transform() [1/4]

template<typename U , typename T >
requires std::constructible_from<U, T>
auto porytiles::transform ( const std::set< T > &  input) -> std::set<U>

Transforms a set of type T into a set of type U using direct type construction.

This convenience overload allows direct type conversion when U is constructible from T. The transformation is performed using C++23 ranges for optimal performance. Duplicate results from the transformation are automatically deduplicated since the result is a set.

Template Parameters
UThe target type for the output set elements
TThe type of elements in the input set (typically deduced)
Parameters
inputThe input set to transform
Returns
A new set containing the converted elements

Definition at line 85 of file transform.hpp.

◆ transform() [2/4]

template<typename T , typename F >
auto porytiles::transform ( const std::set< T > &  input,
F &&  func 
) -> std::set<std::invoke_result_t<F, const T &>>

Transforms a set of type T into a set of type U using a mapping function.

This function applies a transformation function to each element of the input set, producing a new set containing the transformed elements. The transformation is performed using C++23 ranges for optimal performance. Duplicate results from the transformation are automatically deduplicated since the result is a set.

Template Parameters
TThe type of elements in the input set
FThe type of the transformation function
Parameters
inputThe input set to transform
funcThe transformation function that maps T to U
Returns
A new set containing the transformed elements

Definition at line 65 of file transform.hpp.

◆ transform() [3/4]

template<typename U , typename T >
requires std::constructible_from<U, T>
auto porytiles::transform ( const std::vector< T > &  input) -> std::vector<U>

Transforms a vector of type T into a vector of type U using direct type construction.

This convenience overload allows direct type conversion when U is constructible from T. The transformation is performed using C++23 ranges for optimal performance. This is particularly useful for converting between related types like PixelTile and CanonicalPixelTile.

Template Parameters
UThe target type for the output vector elements
TThe type of elements in the input vector (typically deduced)
Parameters
inputThe input vector to transform
Returns
A new vector containing the converted elements

Definition at line 45 of file transform.hpp.

◆ transform() [4/4]

template<typename T , typename F >
auto porytiles::transform ( const std::vector< T > &  input,
F &&  func 
) -> std::vector<std::invoke_result_t<F, const T &>>

Transforms a vector of type T into a vector of type U using a mapping function.

This function applies a transformation function to each element of the input vector, producing a new vector containing the transformed elements. The transformation is performed using C++23 ranges for optimal performance. The function uses lazy evaluation via std::views::transform and efficiently materializes the result with std::ranges::to.

Template Parameters
TThe type of elements in the input vector
FThe type of the transformation function
Parameters
inputThe input vector to transform
funcThe transformation function that maps T to U
Returns
A new vector containing the transformed elements

Definition at line 25 of file transform.hpp.

◆ trim()

void porytiles::trim ( std::string &  string)
inline

Removes leading and trailing whitespace from a string in-place.

This function modifies the input string by removing all whitespace characters from the beginning and end of the string. The string is modified directly.

Parameters
stringThe string to trim (modified in-place)

Definition at line 88 of file string_utils.hpp.

◆ trim_line_ending() [1/2]

std::string porytiles::trim_line_ending ( const std::string &  line)
inline

Removes line ending characters from a string.

This function creates a copy of the input string and removes all trailing carriage return (\r) and newline (
) characters from the end. The original string is not modified.

Parameters
lineThe string to trim
Returns
A new string with line endings removed

Definition at line 153 of file string_utils.hpp.

◆ trim_line_ending() [2/2]

std::string & porytiles::trim_line_ending ( std::string &  line)
inline

Removes line ending characters from a string in-place.

This function removes all trailing carriage return (\r) and newline (
) characters from the end of the string. The string is modified directly.

Parameters
lineThe string to trim (modified in-place)
Returns
Reference to the modified string

Definition at line 135 of file string_utils.hpp.

◆ trim_prefix()

std::string porytiles::trim_prefix ( const std::string &  str,
const std::string &  prefix 
)
inline

Removes a prefix from a string if present.

This function checks if the input string starts with the specified prefix. If it does, the function returns a new string with the prefix removed. If the prefix is not present, the original string is returned unchanged.

Parameters
strThe string to potentially trim
prefixThe prefix to remove if present
Returns
A new string with the prefix removed, or the original string if prefix was not present
Examples
  • trim_prefix("hello_world", "hello_") -> "world"
  • trim_prefix("hello_world", "foo") -> "hello_world"
  • trim_prefix("hello", "hello") -> ""
  • trim_prefix("hello", "hello_world") -> "hello"

Definition at line 71 of file string_utils.hpp.

◆ union_size()

std::size_t porytiles::union_size ( const ColorSet a,
const ColorSet b 
)

Computes the union size of two ColorSets.

Returns the count of colors present in either set.

Parameters
aThe first ColorSet
bThe second ColorSet
Returns
The number of colors in the union

Definition at line 63 of file color_set.cpp.

◆ validate_alpha_channels()

ChainableResult< void > porytiles::validate_alpha_channels ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const std::vector< Metatile< Rgba32 > > &  metatiles,
const std::map< std::string, Animation< Rgba32 > > &  anims 
)
inline

Validates that all pixel alpha channels in provided input have valid values.

In Porytiles, only alpha values of 0 (fully transparent) or 255 (fully opaque) are valid. Any intermediate alpha value indicates partial transparency, which is not supported by the GBA hardware. This function iterates through all pixels in both metatiles and animation frames, reporting each invalid alpha channel with a visual highlight of the problematic pixel.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
metatilesThe metatiles to validate for alpha channel correctness.
animsThe animations to validate for alpha channel correctness.
Returns
Empty result on success, or FormattableError if any pixel has an invalid alpha value.

Definition at line 606 of file tileset_compile_validators.hpp.

◆ validate_anim_frames()

ChainableResult< void > porytiles::validate_anim_frames ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const std::map< std::string, Animation< Rgba32 > > &  anims 
)
inline

Validates animation frames for correctness according to tileset compilation constraints.

Performs three validation checks on animation frames:

  1. Transparent key frame check: Key frame tiles cannot be fully transparent, as this would make them indistinguishable from the actual transparent tile (tile 0) at runtime, preventing Porytiles from correctly indexing into animations from the layer sheet. All violations are collected before returning an error. This check only applies to animations with a key frame (key.png); animations without a key frame are skipped.
  2. Duplicate key frame check (error): The same tile content cannot appear as a key frame in multiple positions across all animations. Each key frame tile must be unique so the game engine can properly identify which animation a tile belongs to.
  3. Composite frame color count check (error): Each animation's composite frame (which aggregates all colors from all frames at each tile position) cannot exceed 15 unique colors per tile. This is because the palette index is fixed for the entire animation lifecycle, but the tile data changes dynamically.
Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
animsThe animations to validate.
Returns
Empty result on success, or FormattableError if any validation check fails.

Definition at line 1322 of file tileset_compile_validators.hpp.

◆ validate_global_color_count()

ChainableResult< void > porytiles::validate_global_color_count ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
bool  is_secondary,
const std::vector< Metatile< Rgba32 > > &  metatiles,
const std::map< std::string, Animation< Rgba32 > > &  anims,
const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &  porytiles_pals,
const std::vector< PaletteHint > &  hints 
)
inline

Validates that the total unique color count across all input does not exceed the global limit.

The global color limit is determined by the number of available palettes times 15 colors per palette (slot 0 is reserved for transparency). This function counts all unique colors across metatiles, animations, Porytiles override palettes, and palette hints. When the global limit is exceeded, an error is reported showing the pixel that triggered the violation, along with a complete color count summary.

Additionally, this function warns about unused colors in Porytiles override palettes and palette hints, helping users identify manual color specifications that don't correspond to any colors in the actual input assets.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
is_secondaryWhether this is a secondary tileset (determines which palette limit to use).
metatilesThe metatiles to include in global color counting.
animsThe animations to include in global color counting.
porytiles_palsUser-specified Porytiles override palettes (may contain wildcards).
hintsUser-specified palette hints for color grouping.
Returns
Empty result on success, or FormattableError if the global color limit is exceeded.
Note
Colors in Porytiles palettes and hints that don't appear in input assets trigger warnings.

Definition at line 970 of file tileset_compile_validators.hpp.

◆ validate_layer_mode()

ChainableResult< void > porytiles::validate_layer_mode ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const std::vector< Metatile< Rgba32 > > &  metatiles 
)
inline

Validates that metatiles conform to the configured layer mode.

Checks each metatile to ensure its implied layer mode matches the configured layer mode. The implied layer mode is determined by examining whether all three layers (bottom, middle, top) contain non-transparent content at any given subtile position. If a metatile requires triple-layer rendering but the configuration specifies dual-layer mode, an error is reported with visual highlights showing which subtile positions have content on all three layers.

This validation is skipped entirely if the configured layer mode is already triple, since triple-layer mode can accommodate any metatile configuration.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
metatilesThe metatiles to validate for layer mode compliance.
Returns
Empty result on success, or FormattableError if any metatile requires triple-layer mode in a dual-layer configuration.
Note
If validation fails, a note is emitted with instructions for enabling triple-layer mode.

Definition at line 725 of file tileset_compile_validators.hpp.

◆ validate_metatile_count()

ChainableResult< void > porytiles::validate_metatile_count ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
bool  is_secondary,
const std::vector< Metatile< Rgba32 > > &  metatiles 
)
inline

Validates that the metatile count does not exceed the configured limit.

Checks that the number of input metatiles does not exceed the configured limit for the tileset type. For primary tilesets, this checks against num_metatiles_in_primary. For secondary tilesets, this checks against num_metatiles_total - num_metatiles_in_primary. If validation fails, emits an error diagnostic with the actual count and limit, along with a note showing the relevant configuration source(s).

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
is_secondaryWhether this is a secondary tileset (determines which limit to use).
metatilesThe metatiles to validate.
Returns
Empty result on success, or FormattableError describing the violation.
See also
TilesetCompiler Main consumer of this validation function.

Definition at line 214 of file tileset_compile_validators.hpp.

◆ validate_pal_hint()

ChainableResult< void > porytiles::validate_pal_hint ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const PaletteHint hint 
)
inline

Validates a user-specified palette hint for correctness.

Performs three checks on a palette hint:

  1. Size check (error): Palette hints must have at most 15 colors (pal::max_size - 1), since slot 0 is reserved for transparency and hints don't include the transparency slot.
  2. Extrinsic transparency check (error): Palette hints must not contain the extrinsic transparency color at any position, as hints are meant to specify opaque colors that should be grouped together.
  3. Duplicate color check (error): Palette hints must not contain duplicate colors, as each color can only appear once in a palette.

Palette hints are user-provided color groupings that guide the palette assignment algorithm to place certain colors together in the same palette. Unlike full palettes, hints don't specify an index and may not include all 15 slots.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
hintThe palette hint to validate.
Returns
Empty result on success, or FormattableError if any validation check fails.

Definition at line 486 of file tileset_compile_validators.hpp.

◆ validate_porymap_pal()

ChainableResult< void > porytiles::validate_porymap_pal ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const Palette< Rgba32, pal::max_size > &  pal,
std::size_t  pal_index 
)
inline

Validates a Porymap palette for correctness according to GBA hardware constraints.

Performs two checks on an existing Porymap palette:

  1. Slot 0 transparency check (warning): Slot 0 should match the configured extrinsic transparency color, as it is typically reserved for transparent pixels. If slot 0 contains a different color, a warning is emitted (this may be intentional for .pla blend color usage).
  2. Non-slot-0 transparency check (error): Slots 1-15 must not contain the extrinsic transparency color, as this would cause rendering issues where non-transparent pixels become transparent.
Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
palThe Porymap palette to validate.
pal_indexThe index of this palette (0-12 typically), used for diagnostic messages.
Returns
Empty result on success, or FormattableError if extrinsic transparency appears in non-slot-0 positions.

Definition at line 278 of file tileset_compile_validators.hpp.

◆ validate_porytiles_pal()

ChainableResult< void > porytiles::validate_porytiles_pal ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const Palette< Rgba32, pal::max_size > &  pal,
std::size_t  pal_index 
)
inline

Validates a user-specified Porytiles override palette for correctness.

Performs two checks on a Porytiles override palette:

  1. Slot 0 transparency check (warning): If slot 0 is not a wildcard, it should match the configured extrinsic transparency color. A warning is emitted if it doesn't (this may be intentional for .pla blend color usage).
  2. Non-slot-0 transparency check (error): Non-wildcard slots 1-15 must not contain the extrinsic transparency color, as this would cause rendering issues.

Unlike Porymap palettes, Porytiles palettes may contain wildcards ('*' entries) that are filled in during the palette assignment process. Wildcard slots are skipped during validation.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
palThe Porytiles override palette to validate.
pal_indexThe index of this palette (0-12 typically), used for diagnostic messages.
Returns
Empty result on success, or FormattableError if extrinsic transparency appears in non-slot-0 positions.

Definition at line 381 of file tileset_compile_validators.hpp.

◆ validate_precision_loss()

ChainableResult< void > porytiles::validate_precision_loss ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const std::vector< Metatile< Rgba32 > > &  metatiles,
const std::map< std::string, Animation< Rgba32 > > &  anims,
const std::array< std::optional< Palette< Rgba32, pal::max_size > >, pal::num_pals > &  porytiles_pals,
const std::vector< PaletteHint > &  hints,
const std::optional< std::array< Palette< Rgba32, pal::max_size >, pal::num_pals > > &  porymap_pals 
)
inline

Validates that no colors will suffer unacceptable precision loss during GBA color conversion.

GBA hardware uses 15-bit color (5 bits per channel) rather than 24-bit color (8 bits per channel). When converting from 32-bit RGBA to GBA format, colors may be quantized in ways that cause visually different colors to become identical or similar colors to diverge. This validation checks for such precision loss scenarios and warns users about potential visual artifacts in the final output.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
metatilesThe metatiles to check for precision loss.
animsThe animations to check for precision loss.
porytiles_palsUser-specified Porytiles override palettes to check.
hintsUser-specified palette hints to check.
porymap_palsOptional existing Porymap palettes (relevant for pal:patch and pal:locked modes).
Returns
Empty result on success, or FormattableError if critical precision loss is detected.
Todo:
Implementation pending. Should check Porymap palettes in pal:patch and pal:locked modes.

Definition at line 1286 of file tileset_compile_validators.hpp.

◆ validate_tile_color_count()

ChainableResult< void > porytiles::validate_tile_color_count ( const TilesetCompileValidatorServices services,
const std::string &  tileset_name,
const std::vector< Metatile< Rgba32 > > &  metatiles,
const std::map< std::string, Animation< Rgba32 > > &  anims 
)
inline

Validates that each individual tile does not exceed the per-tile color limit.

Each 8x8 tile on GBA hardware can reference at most 16 palette slots, with slot 0 reserved for transparency. This means each tile can have at most 15 unique non-transparent colors. This function iterates through all tiles in both metatiles and animation frames, counting unique colors per tile. When a tile exceeds the limit, an error is reported showing the pixel that triggered the violation, along with a note listing all colors found in that tile.

Parameters
servicesCommon services parameter store.
tileset_nameThe name of the tileset being validated (used for config lookup).
metatilesThe metatiles to validate for per-tile color count compliance.
animsThe animations to validate for per-tile color count compliance.
Returns
Empty result on success, or FormattableError if any tile exceeds the color limit.
Note
Both extrinsic transparency and intrinsic transparency (alpha=0) are excluded from color counting.

Definition at line 833 of file tileset_compile_validators.hpp.

Variable Documentation

◆ colors_per_pal

constexpr std::size_t porytiles::colors_per_pal = 16
inlineconstexpr

Definition at line 12 of file palette_index.hpp.

◆ diagnostic_separator

constexpr std::string_view porytiles::diagnostic_separator = "--------"
constexpr

Definition at line 24 of file diagnostic_stencils.hpp.

◆ num_colors

constexpr std::size_t porytiles::num_colors = pal::max_size * pal::num_pals
inlineconstexpr

Maximum allowable color count for GBA hardware.

Definition at line 17 of file color_set.hpp.

◆ rgba_black

constexpr Rgba32 porytiles::rgba_black {0, 0, 0, Rgba32::alpha_opaque}
constexpr

Definition at line 131 of file rgba32.hpp.

◆ rgba_blue

constexpr Rgba32 porytiles::rgba_blue {0, 0, 255, Rgba32::alpha_opaque}
constexpr

Definition at line 136 of file rgba32.hpp.

◆ rgba_cyan

constexpr Rgba32 porytiles::rgba_cyan {0, 255, 255, Rgba32::alpha_opaque}
constexpr

Definition at line 139 of file rgba32.hpp.

◆ rgba_green

constexpr Rgba32 porytiles::rgba_green {0, 255, 0, Rgba32::alpha_opaque}
constexpr

Definition at line 135 of file rgba32.hpp.

◆ rgba_grey

constexpr Rgba32 porytiles::rgba_grey {128, 128, 128, Rgba32::alpha_opaque}
constexpr

Definition at line 133 of file rgba32.hpp.

◆ rgba_lime

constexpr Rgba32 porytiles::rgba_lime {128, 255, 128, Rgba32::alpha_opaque}
constexpr

Definition at line 141 of file rgba32.hpp.

◆ rgba_magenta

constexpr Rgba32 porytiles::rgba_magenta {255, 0, 255, Rgba32::alpha_opaque}
constexpr

Definition at line 138 of file rgba32.hpp.

◆ rgba_purple

constexpr Rgba32 porytiles::rgba_purple {128, 0, 255, Rgba32::alpha_opaque}
constexpr

Definition at line 140 of file rgba32.hpp.

◆ rgba_red

constexpr Rgba32 porytiles::rgba_red {255, 0, 0, Rgba32::alpha_opaque}
constexpr

Definition at line 134 of file rgba32.hpp.

◆ rgba_white

constexpr Rgba32 porytiles::rgba_white {255, 255, 255, Rgba32::alpha_opaque}
constexpr

Definition at line 132 of file rgba32.hpp.

◆ rgba_yellow

constexpr Rgba32 porytiles::rgba_yellow {255, 255, 0, Rgba32::alpha_opaque}
constexpr

Definition at line 137 of file rgba32.hpp.

◆ valid_yaml_map_prefixes

const std::unordered_set<std::string> porytiles::valid_yaml_map_prefixes
inline
Initial value:
= {
"tileset.animations.per_animation_overrides",
"tileset.palettes.packing.strategy_params",
}

Set of YAML path prefixes that represent map-type configuration values.

Map-type config values have dynamic children (e.g., animation names as keys). Paths that start with any of these prefixes followed by a dot should not trigger "unknown configuration key" warnings, since the children are user-defined keys rather than fixed config paths.

This is auto-generated from config_schema.yaml - do not edit directly.

Definition at line 88 of file valid_yaml_paths.hpp.

◆ valid_yaml_paths

const std::unordered_set<std::string> porytiles::valid_yaml_paths
inline

Set of valid YAML configuration paths.

This set contains all valid dot-separated paths that can appear in porytiles.yaml configuration files. Both leaf paths (e.g., "fieldmap.num_tiles_in_primary") and intermediate paths (e.g., "fieldmap") are included.

This is auto-generated from config_schema.yaml - do not edit directly.

Definition at line 24 of file valid_yaml_paths.hpp.