### Install msdfgen with vcpkg Source: https://github.com/chlumsky/msdfgen/blob/master/README.md Install the msdfgen library using the vcpkg package manager. This command fetches and builds the library along with its dependencies. ```bash vcpkg install msdfgen ``` -------------------------------- ### Install msdfgen Configuration Files Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Installs the msdfgen configuration files (Config.cmake and ConfigVersion.cmake) to the specified destination path. ```cmake install( FILES "${CMAKE_CURRENT_BINARY_DIR}/${MSDFGEN_CONFIG_PATH}/msdfgenConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/msdfgenConfigVersion.cmake" DESTINATION ${MSDFGEN_CONFIG_PATH} ) ``` -------------------------------- ### GeneratorConfig Usage Examples Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Demonstrates creating and using GeneratorConfig. The first example uses the default configuration, while the second optimizes for non-overlapping shapes by disabling overlap support. ```cpp #include using namespace msdfgen; // Default config with overlap support Bitmap sdf(32, 32); generateSDF(sdf, shape, transform, GeneratorConfig()); // Optimize for non-overlapping shapes GeneratorConfig config(false); // Disable overlap support generateSDF(sdf, shape, transform, config); ``` -------------------------------- ### SDFTransformation Example with Projection and DistanceMapping Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-transformations.md Demonstrates creating an SDFTransformation object using a Projection and DistanceMapping, then using it to generate an MSDF bitmap. ```cpp Projection proj(Vector2(32.0, 32.0), Vector2(0.5, 0.5)); DistanceMapping mapping(Range(0.25)); SDFTransformation transform(proj, mapping); Bitmap msdf(32, 32); generateMSDF(msdf, shape, transform); ``` -------------------------------- ### Load Glyph Example (by GlyphIndex) Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Demonstrates loading a glyph's geometry using its index and normalizing the shape. Requires a prior call to getGlyphIndex. ```cpp GlyphIndex idx; getGlyphIndex(idx, font, 'M'); Shape shape; double advance = 0; if (loadGlyph(shape, font, idx, FONT_SCALING_EM_NORMALIZED, &advance)) { shape.normalize(); } ``` -------------------------------- ### Basic SDFTransformation Setup Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-transformations.md Sets up a basic SDFTransformation for a 32x32 output with a 0.5 em margin. This involves creating a Projection and a DistanceMapping, then combining them into an SDFTransformation. ```cpp #include using namespace msdfgen; // For a 32x32 output with 0.5 em margin Projection proj(32.0, Vector2(0.5, 0.5)); DistanceMapping mapping(Range(0.25)); SDFTransformation transform(proj, mapping); Bitmap msdf(32, 32); generateMSDF(msdf, shape, transform); ``` -------------------------------- ### MSDFGeneratorConfig Usage Example Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Shows how to create an MSDFGeneratorConfig with custom error correction settings and use it for generating an MSDF. ```cpp // MSDF with custom error correction ErrorCorrectionConfig errorCfg( ErrorCorrectionConfig::EDGE_PRIORITY, ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE ); MSDFGeneratorConfig msdfConfig(true, errorCfg); Bitmap msdf(32, 32); generateMSDF(msdf, shape, transform, msdfConfig); ``` -------------------------------- ### Install msdfgen-ext Target Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Installs the msdfgen-ext target, including runtime, library, archive, framework, and public header destinations. This snippet is conditional on MSDFGEN_CORE_ONLY not being set. ```cmake if(NOT MSDFGEN_CORE_ONLY) install(TARGETS msdfgen-ext EXPORT msdfgenTargets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} FRAMEWORK DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen ) install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen-ext.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/msdfgen) if (NOT MSDFGEN_INSTALL_NO_GLOBAL_INCLUDE) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/msdfgen-ext.h" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) endif() if(MSVC AND BUILD_SHARED_LIBS) install(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL) endif() install(TARGETS msdfgen-full EXPORT msdfgenTargets) endif() ``` -------------------------------- ### Render MSDF to Image Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-rendering.md This example demonstrates loading an MSDF bitmap and rendering it to an RGB image with anti-aliasing. It also shows how to simulate 8-bit quantization for the output image. ```cpp #include using namespace msdfgen; // Load MSDF from file Bitmap msdf(32, 32); // ... msdf populated ... // Render to RGB image (256x256 for 8x magnification) Bitmap rendered(256, 256); Range pxRange(4); // 4 pixel range was used during generation renderSDF(rendered, msdf, pxRange); // Optional: simulate 8-bit quantization simulate8bit(rendered); savePng(rendered, "rendered.png"); ``` -------------------------------- ### Load Glyph Example (by Unicode) Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Demonstrates loading a glyph's geometry directly by its Unicode character and normalizing the shape. The advance width is also retrieved. ```cpp Shape shape; double advance = 0; if (loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED, &advance)) { // Glyph 'A' loaded successfully shape.normalize(); } ``` -------------------------------- ### msdfgen Example: Generating MSDF for a Font Glyph Source: https://github.com/chlumsky/msdfgen/blob/master/README.md This example demonstrates generating a multi-channel signed distance field for a specific font glyph. It specifies output dimensions, distance range, auto-framing, and creates a test render. ```bash msdfgen msdf -font C:\\Windows\\Fonts\\arialbd.ttf 'M' -o msdf.png -dimensions 32 32 -pxrange 4 -autoframe -testrender render.png 1024 1024 ``` -------------------------------- ### Install msdfgen Standalone Target Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Installs the msdfgen standalone target and its associated PDB file if using MSVC. This is conditional on MSDFGEN_BUILD_STANDALONE being set. ```cmake if(MSDFGEN_BUILD_STANDALONE) install(TARGETS msdfgen EXPORT msdfgenBinaryTargets DESTINATION ${CMAKE_INSTALL_BINDIR}) if(MSVC) install(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR} OPTIONAL) endif() export(EXPORT msdfgenBinaryTargets NAMESPACE msdfgen-standalone:: FILE "${CMAKE_CURRENT_BINARY_DIR}/msdfgenBinaryTargets.cmake") install(EXPORT msdfgenBinaryTargets FILE msdfgenBinaryTargets.cmake NAMESPACE msdfgen-standalone:: DESTINATION ${MSDFGEN_CONFIG_PATH}) endif() ``` -------------------------------- ### Example Usage of msdfFastEdgeErrorCorrection Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-rendering.md Demonstrates a basic call to the msdfFastEdgeErrorCorrection function with SDF and transformation parameters. ```cpp msdfFastEdgeErrorCorrection(msdf, transform); ``` -------------------------------- ### Generation & Core API Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/README.md Documentation for SDF, MSDF, and MTSDF generation functions, including signatures, parameters, return types, legacy overloads, and typical workflow examples. ```APIDOC ## Generation & Core API ### Description This section details all SDF, MSDF, and MTSDF generation functions available in the msdfgen library. It includes function signatures, parameter descriptions, return types, information on legacy overloads for backward compatibility, and practical workflow examples. ### API Reference Files - **[api-reference-generation-functions.md](api-reference-generation-functions.md)**: Covers SDF/MSDF/MTSDF generation functions, signatures, parameters, return types, legacy overloads, and typical workflow examples. - **[api-reference-shape.md](api-reference-shape.md)**: Details the Shape class structure and methods, including contour and edge management, normalization, validation, and bounding box operations. - **[api-reference-bitmap.md](api-reference-bitmap.md)**: Describes the Bitmap template class, BitmapRef and BitmapSection references, pixel access patterns, and Y-axis orientation handling. ``` -------------------------------- ### Balanced Error Correction Configuration (Recommended) Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Example of a balanced error correction configuration, recommended for general use. It uses default settings for mode and distance checking. ```cpp ErrorCorrectionConfig config( ErrorCorrectionConfig::EDGE_PRIORITY, ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE ); // Uses defaults ``` -------------------------------- ### Set msdfgen-core Include Directories Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Configures include directories for the msdfgen-core library. It specifies installation paths for installed targets and build paths for targets being built. ```cmake target_include_directories(msdfgen-core INTERFACE $ $ ) ``` -------------------------------- ### Error Correction Configuration with Pre-allocated Buffer Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Example of configuring error correction with a pre-allocated buffer. The buffer size must be at least the bitmap pixel count. ```cpp byte buffer[32 * 32]; // Must be at least bitmap size ErrorCorrectionConfig config( ErrorCorrectionConfig::EDGE_PRIORITY, ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE, 1.12, // defaultMinDeviationRatio 1.001, // defaultMinImproveRatio buffer ); ``` -------------------------------- ### Create Distance Mapping Range Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/types.md Shows how to initialize Range objects for distance mapping, both with a single value for symmetric range and with explicit start and end values for asymmetric ranges. ```cpp Range range(0.25); // -0.125 to +0.125 Range asymmetric(-0.1, 0.3); ``` -------------------------------- ### Complete MSDF Generation Example Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md This C++ snippet shows the full workflow for generating an MSDF for a font glyph. It includes FreeType initialization, font loading, glyph loading, MSDF generation with transformations, and saving the output. Ensure you have 'arial.ttf' in the same directory or provide a valid path. ```cpp #include #include #include using namespace msdfgen; int main() { // Initialize FreeType FreetypeHandle *ft = initializeFreetype(); if (!ft) return 1; // Load font FontHandle *font = loadFont(ft, "arial.ttf"); if (!font) return 1; // Get metrics FontMetrics metrics; getFontMetrics(metrics, font, FONT_SCALING_EM_NORMALIZED); std::cout << "EM Size: " << metrics.emSize << std::endl; // Load glyph for 'A' Shape shape; double advance = 0; if (loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED, &advance)) { std::cout << "Glyph 'A' advance: " << advance << std::endl; // Generate MSDF shape.normalize(); edgeColoringSimple(shape, 3.0); Bitmap msdf(32, 32); SDFTransformation transform( Projection(32.0, Vector2(0.125, 0.125)), DistanceMapping(Range(0.125)) ); generateMSDF(msdf, shape, transform); savePng(msdf, "glyph_a.png"); } // Cleanup destroyFont(font); deinitializeFreetype(ft); return 0; } ``` -------------------------------- ### No Error Correction Configuration Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Example of disabling error correction entirely for maximum performance. This is suitable when quality is already acceptable. ```cpp ErrorCorrectionConfig config( ErrorCorrectionConfig::DISABLED ); ``` -------------------------------- ### Basic MSDF Generation from Font Glyph Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/INDEX.md This snippet demonstrates the core workflow for generating an MSDF from a font glyph. It covers initializing FreeType, loading a font and glyph, preparing the shape, setting up the transformation, generating the MSDF, and saving the result. Ensure you have FreeType installed and a font file (e.g., arial.ttf) available. ```cpp #include #include using namespace msdfgen; int main() { // 1. Initialize FreeType FreetypeHandle *ft = initializeFreetype(); FontHandle *font = loadFont(ft, "arial.ttf"); // 2. Load glyph Shape shape; loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED); // 3. Prepare shape shape.normalize(); edgeColoringSimple(shape, 3.0); // 4. Set up transformation Bitmap msdf(32, 32); SDFTransformation transform( Projection(32.0, Vector2(0.125, 0.125)), DistanceMapping(Range(0.125)) ); // 5. Generate MSDF generateMSDF(msdf, shape, transform); // 6. Save result savePng(msdf, "output.png"); // 7. Cleanup destroyFont(font); deinitializeFreetype(ft); return 0; } ``` -------------------------------- ### Bitmap Constructor with Dimensions Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Creates a bitmap with specified dimensions and Y-axis orientation. Memory is allocated for all pixels. Example shows creating a 32x32 float bitmap with Y upwards. ```cpp Bitmap(int width, int height, YAxisOrientation yOrientation = MSDFGEN_Y_AXIS_DEFAULT_ORIENTATION); ``` ```cpp Bitmap msdf(32, 32, Y_UPWARD); ``` -------------------------------- ### Create Bitmaps Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/types.md Demonstrates the initialization of Bitmap objects with specified dimensions and data types for rendering. ```cpp Bitmap msdf(32, 32); Bitmap rgba(256, 256); ``` -------------------------------- ### Create and Generate MSDF Bitmap Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Demonstrates creating a 3-channel float bitmap for MSDF output, generating the MSDF data, and converting it to a byte format for saving as a PNG. ```cpp #include using namespace msdfgen; // Create 3-channel bitmap for MSDF output Bitmap msdf(32, 32); // Use in generation SDFTransformation transform(projection, mapping); generateMSDF(msdf, shape, transform); // Convert to save Bitmap msdfByte = msdf; // Convert float to byte savePng(msdfByte, "output.png"); ``` -------------------------------- ### Get Constant Bitmap Subsection Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Returns a constant reference to a rectangular subsection of the bitmap. ```cpp BitmapConstSection getConstSection(int xMin, int yMin, int xMax, int yMax) const; ``` -------------------------------- ### Using msdfgen Namespace Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/INDEX.md Demonstrates how to use the msdfgen namespace, either by a common using directive or by qualifying names. ```cpp using namespace msdfgen; // Common pattern // Or use qualified names msdfgen::Bitmap msdf(32, 32); msdfgen::generateMSDF(msdf, shape, transform); ``` -------------------------------- ### Get Bitmap Subsection Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Returns a reference to a rectangular subsection of the bitmap. The returned section does not own memory. ```cpp BitmapSection getSection(int xMin, int yMin, int xMax, int yMax); ``` ```cpp BitmapSection topLeft = msdf.getSection(0, 0, 16, 16); ``` -------------------------------- ### Create Transformations Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/types.md Illustrates the creation of Projection, DistanceMapping, and SDFTransformation objects for applying transformations to shapes. ```cpp Projection proj(32.0, Vector2(0.5, 0.5)); DistanceMapping mapping(Range(0.25)); SDFTransformation transform(proj, mapping); ``` -------------------------------- ### Get Bitmap Height Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Retrieves the height of the bitmap in pixels. Used to determine the vertical dimension of the image data. ```cpp int height() const; ``` -------------------------------- ### Create Bitmap from Custom Buffer Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Demonstrates creating a BitmapRef from an existing raw pixel data buffer, specifying the pixel format, dimensions, and row stride. ```cpp // If you have your own pixel buffer float pixelData[32 * 32 * 3]; BitmapRef ref(pixelData, 32, 32); ``` -------------------------------- ### Get Bitmap Width Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Retrieves the width of the bitmap in pixels. Used to determine the horizontal dimension of the image data. ```cpp int width() const; ``` ```cpp Bitmap sdf(64, 32); int w = sdf.width(); // Returns 64 ``` -------------------------------- ### Get Glyph Count Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Retrieves the total number of glyphs available in the font. Ensure a valid FontHandle is provided. ```cpp bool getGlyphCount(unsigned &output, FontHandle *font); ``` -------------------------------- ### Export msdfgen Targets Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Exports msdfgen targets for use by other CMake projects. This ensures that the installed targets are correctly recognized. ```cmake export(EXPORT msdfgenTargets NAMESPACE msdfgen:: FILE "${CMAKE_CURRENT_BINARY_DIR}/msdfgenTargets.cmake") install(EXPORT msdfgenTargets FILE msdfgenTargets.cmake NAMESPACE msdfgen:: DESTINATION ${MSDFGEN_CONFIG_PATH}) ``` -------------------------------- ### Set Visual Studio Startup Project Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Sets the default startup project in Visual Studio solutions. This ensures that 'msdfgen-core' is the project launched when debugging. ```cmake set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT msdfgen-core) ``` -------------------------------- ### Default Constructor Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Creates an empty bitmap with zero dimensions. ```APIDOC ## Default Constructor ### Description Creates an empty bitmap with zero dimensions. ### Method Constructor ### Endpoint Bitmap() ### Parameters None ### Response #### Success Response - Bitmap object with zero dimensions. ``` -------------------------------- ### Get Y-Axis Orientation Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-shape.md Returns the orientation of the shape's Y-axis. Most graphics systems use Y_UPWARD where positive Y goes up. ```cpp YAxisOrientation getYAxisOrientation() const; ``` ```cpp YAxisOrientation yAxis = shape.getYAxisOrientation(); ``` -------------------------------- ### Create Shape Coordinates Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/types.md Demonstrates the creation of Point2 objects and Vector2 objects, including normalization. ```cpp Point2 p0(0.0, 0.0); Vector2 direction(1.0, 1.0); Vector2 normalized = direction.normalize(); ``` -------------------------------- ### Initialize FreeType Library Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Initializes the FreeType library. Must be called before any font operations. Returns an opaque handle or NULL on failure. ```cpp #include #include using namespace msdfgen; FreetypeHandle *ft = initializeFreetype(); if (!ft) { // FreeType initialization failed return; } ``` -------------------------------- ### Create and Generate MTSDF Bitmap Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Shows how to create a 4-channel float bitmap for MTSDF output and generate the data using the provided shape and transformation. ```cpp Bitmap mtsdf(32, 32); generateMTSDF(mtsdf, shape, transform); ``` -------------------------------- ### Square Shape Example Source: https://github.com/chlumsky/msdfgen/blob/master/README.md Describes a square shape with magenta and yellow edges. The '#' symbol represents the first point to close the contour. ```text { -1, -1; m; -1, +1; y; +1, +1; m; +1, -1; y; # } ``` -------------------------------- ### Get Edge Count Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-shape.md Returns the total number of edge segments across all contours in the shape. Useful for analyzing shape complexity. ```cpp int edgeCount() const; ``` ```cpp int totalEdges = shape.edgeCount(); ``` -------------------------------- ### Load Font from File Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Loads a font from a specified file path. Returns an opaque font handle or NULL on failure. ```cpp FontHandle *font = loadFont(ft, "C:\\Windows\\Fonts\\arial.ttf"); if (!font) { // Font loading failed return; } ``` -------------------------------- ### Example Usage of distanceSignCorrection Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-rendering.md Demonstrates how to call the distanceSignCorrection function with specific parameters for the distance field, shape, projection, zero value, and fill rule. ```cpp distanceSignCorrection(sdf, shape, projection, 0.5f, FILL_NONZERO); ``` -------------------------------- ### SDFTransformation Constructors Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-transformations.md Documentation for the constructors of the SDFTransformation class, including the default constructor and a full constructor that takes projection and distance mapping. ```APIDOC ## SDFTransformation() ### Description Creates an identity transformation. ### Method Signature SDFTransformation(); ### Parameters None ### Example ```cpp SDFTransformation transform; ``` ``` ```APIDOC ## SDFTransformation(const Projection &projection, const DistanceMapping &distanceMapping) ### Description Creates a transformation with the specified projection and distance mapping. ### Method Signature SDFTransformation(const Projection &projection, const DistanceMapping &distanceMapping); ### Parameters * **projection** (Projection) - Required - The spatial transformation to apply. * **distanceMapping** (DistanceMapping) - Required - The distance scaling to apply. ### Example ```cpp Projection proj(Vector2(32.0, 32.0), Vector2(0.5, 0.5)); DistanceMapping mapping(Range(0.25)); SDFTransformation transform(proj, mapping); ``` ``` -------------------------------- ### Fast Error Correction Configuration Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Example of a fast error correction configuration that only corrects artifacts at edges and disables distance checking. This prioritizes performance. ```cpp ErrorCorrectionConfig config( ErrorCorrectionConfig::EDGE_ONLY, ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE ); ``` -------------------------------- ### Conservative Error Correction Configuration Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Example of a conservative error correction configuration that corrects all distance discontinuities. It sets deviation and improvement ratios to their minimum values. ```cpp ErrorCorrectionConfig config( ErrorCorrectionConfig::INDISCRIMINATE, ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE, 1.0, // minDeviationRatio 1.0 // minImproveRatio ); ``` -------------------------------- ### Error Handling with Font Loading Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/INDEX.md Shows how to check for errors when loading a font and loading a glyph. Ensure to check return values before proceeding. ```cpp FontHandle *font = loadFont(ft, "path.ttf"); if (!font) { // Handle error } Shape shape; if (!loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED)) { // Glyph not found } ``` -------------------------------- ### Teardrop Shape Example with Cubic Bézier Curve Source: https://github.com/chlumsky/msdfgen/blob/master/README.md Defines a teardrop shape using a single cubic Bézier curve. Control points are specified within parentheses. ```text { 0, 1; (+1.6, -0.8; -1.6, -0.8); # } ``` -------------------------------- ### Complete Shape Creation Workflow Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-shape.md Demonstrates the full process of creating a square shape, adding contours and edges, validating, normalizing, setting Y-axis orientation, and retrieving the shape's bounds. ```cpp #include using namespace msdfgen; // Create a square shape Shape shape; Contour &contour = shape.addContour(); // Add edges forming a square double size = 1.0; contour.addEdge(EdgeHolder(new LinearSegment(Point2(-size, -size), Point2(size, -size)))); contour.addEdge(EdgeHolder(new LinearSegment(Point2(size, -size), Point2(size, size)))); contour.addEdge(EdgeHolder(new LinearSegment(Point2(size, size), Point2(-size, size)))); contour.addEdge(EdgeHolder(new LinearSegment(Point2(-size, size), Point2(-size, -size)))); // Validate and normalize if (!shape.validate()) { // Handle error } shape.normalize(); shape.setYAxisOrientation(Y_UPWARD); // Get bounds Shape::Bounds bounds = shape.getBounds(); ``` -------------------------------- ### SDFTransformation Full Constructor Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-transformations.md Creates a transformation with specified projection and distance mapping. The projection defines the spatial transformation, and distanceMapping defines the distance scaling. ```cpp SDFTransformation(const Projection &projection, const DistanceMapping &distanceMapping); ``` -------------------------------- ### Manual Shape Construction and MSDF Generation Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-edge-coloring.md A typical workflow demonstrating how to manually construct a square shape, assign edge colors, and generate an MSDF bitmap using msdfgen. ```cpp #include using namespace msdfgen; int main() { // Create shape Shape shape; // Add contours and edges Contour &contour = shape.addContour(); // Create a square using factory methods Point2 p0(0, 0), p1(1, 0), p2(1, 1), p3(0, 1); contour.addEdge(EdgeSegment::create(p0, p1)); contour.addEdge(EdgeSegment::create(p1, p2)); contour.addEdge(EdgeSegment::create(p2, p3)); contour.addEdge(EdgeSegment::create(p3, p0)); // Validate and normalize if (!shape.validate()) { return 1; // Error } shape.normalize(); // Assign edge colors for MSDF edgeColoringSimple(shape, 3.0); // Generate MSDF Bitmap msdf(32, 32); SDFTransformation transform( Projection(32.0, Vector2(0.5, 0.5)), DistanceMapping(Range(0.25)) ); generateMSDF(msdf, shape, transform); // Save savePng(msdf, "square_msdf.png"); return 0; } ``` -------------------------------- ### Get Glyph Index by Unicode Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Looks up the glyph index for a given Unicode character. Returns true if a glyph exists for the character, false otherwise. The output GlyphIndex object will be populated on success. ```cpp bool getGlyphIndex(GlyphIndex &glyphIndex, FontHandle *font, unicode_t unicode); ``` -------------------------------- ### Basic MSDF Generation and Rendering Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-rendering.md Generates an MSDF from a shape, applies error correction, renders it to a larger bitmap, and saves it as a PNG. Ensure the shape is loaded and populated before use. ```cpp #include using namespace msdfgen; // Generate MSDF Shape shape; // ... load and populate shape ... shape.normalize(); edgeColoringSimple(shape, 3.0); Bitmap msdf(32, 32); SDFTransformation transform( Projection(32.0, Vector2(0.125, 0.125)), DistanceMapping(Range(0.125)) ); generateMSDF(msdf, shape, transform); // Apply error correction MSDFGeneratorConfig config; config.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY; msdfErrorCorrection(msdf, shape, transform, config); // Render to image (magnified 4x) Bitmap rendered(128, 128); renderSDF(rendered, msdf, Range(0.125 * 4)); // Save simulate8bit(rendered); savePng(rendered, "output.png"); ``` -------------------------------- ### Get Kerning Adjustment Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-font.md Retrieves the kerning adjustment between two glyphs or characters. Returns true if a kerning pair exists. A positive value moves the second glyph right, negative moves it left. ```cpp bool getKerning(double &output, FontHandle *font, GlyphIndex glyphIndex0, GlyphIndex glyphIndex1, FontCoordinateScaling coordinateScaling = FONT_SCALING_LEGACY); bool getKerning(double &output, FontHandle *font, unicode_t unicode0, unicode_t unicode1, FontCoordinateScaling coordinateScaling = FONT_SCALING_LEGACY); ``` ```cpp double kerning = 0; if (getKerning(kerning, font, 'A', 'V', FONT_SCALING_EM_NORMALIZED)) { // Apply kerning adjustment } ``` -------------------------------- ### Get Shape Bounds Structure Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-shape.md Returns a Bounds structure containing the shape's bounding box (l, b, r, t). Optional parameters allow for border, miter limit, and polarity adjustments. ```cpp Shape::Bounds bounds = shape.getBounds(); double width = bounds.r - bounds.l; double height = bounds.t - bounds.b; ``` -------------------------------- ### Configure msdfgen Extensions Library Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Configures the msdfgen-ext library, finding necessary packages like FreeType, tinyxml2, and PNG. It sets up compile definitions and links against core and extension libraries. ```cmake if(NOT MSDFGEN_CORE_ONLY) if(NOT TARGET Freetype::Freetype) find_package(Freetype REQUIRED) endif() if(NOT MSDFGEN_DISABLE_SVG AND NOT TARGET tinyxml2::tinyxml2) find_package(tinyxml2 REQUIRED) endif() if(NOT MSDFGEN_DISABLE_PNG AND NOT TARGET PNG::PNG) find_package(PNG REQUIRED) endif() add_library(msdfgen-ext "${CMAKE_CURRENT_SOURCE_DIR}/msdfgen-ext.h" ${MSDFGEN_EXT_HEADERS} ${MSDFGEN_EXT_SOURCES}) add_library(msdfgen::msdfgen-ext ALIAS msdfgen-ext) set_target_properties(msdfgen-ext PROPERTIES PUBLIC_HEADER "${MSDFGEN_EXT_HEADERS}") set_property(TARGET msdfgen-ext PROPERTY MSVC_RUNTIME_LIBRARY "${MSDFGEN_MSVC_RUNTIME}") target_compile_definitions(msdfgen-ext INTERFACE MSDFGEN_EXTENSIONS) if(NOT MSDFGEN_DISABLE_SVG) target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_USE_TINYXML2) target_link_libraries(msdfgen-ext PRIVATE tinyxml2::tinyxml2) else() target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_DISABLE_SVG) endif() if(NOT MSDFGEN_DISABLE_PNG) target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_USE_LIBPNG) target_link_libraries(msdfgen-ext PRIVATE PNG::PNG) else() target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_DISABLE_PNG) endif() if(MSDFGEN_DISABLE_VARIABLE_FONTS) target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_DISABLE_VARIABLE_FONTS) endif() target_link_libraries(msdfgen-ext PRIVATE Freetype::Freetype msdfgen::msdfgen-core) target_include_directories(msdfgen-ext PUBLIC $ $ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ) set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT msdfgen-ext) if(MSDFGEN_USE_SKIA) set(MSDFGEN_SKIA_LIB skia) set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads REQUIRED) if(NOT TARGET skia) if(MSDFGEN_USE_VCPKG) find_package(unofficial-skia REQUIRED) set(MSDFGEN_SKIA_LIB unofficial::skia::skia) else() find_package(skia REQUIRED) endif() endif() target_compile_features(msdfgen-ext PUBLIC cxx_std_17) target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_USE_SKIA) target_link_libraries(msdfgen-ext PRIVATE Threads::Threads ${MSDFGEN_SKIA_LIB}) endif() if(BUILD_SHARED_LIBS AND WIN32) target_compile_definitions(msdfgen-ext PRIVATE "MSDFGEN_EXT_PUBLIC=__declspec(dllexport)") target_compile_definitions(msdfgen-ext INTERFACE "MSDFGEN_EXT_PUBLIC=__declspec(dllimport)") else() target_compile_definitions(msdfgen-ext PUBLIC MSDFGEN_EXT_PUBLIC=) endif() add_library(msdfgen-full INTERFACE) add_library(msdfgen::msdfgen ALIAS msdfgen-full) target_link_libraries(msdfgen-full INTERFACE msdfgen::msdfgen-core msdfgen::msdfgen-ext) else() add_library(msdfgen::msdfgen ALIAS msdfgen-core) endif() ``` -------------------------------- ### GLSL Fragment Shader for MSDF Rendering with Anti-Aliasing Source: https://github.com/chlumsky/msdfgen/blob/master/README.md This shader samples a multi-channel distance field, computes the median of its channels to get the signed distance, and then calculates opacity for anti-aliased rendering. It assumes a uniform `screenPxRange()` function is available. ```glsl in vec2 texCoord; out vec4 color; uniform sampler2D msdf; uniform vec4 bgColor; uniform vec4 fgColor; float median(float r, float g, float b) { return max(min(r, g), min(max(r, g), b)); } void main() { vec3 msd = texture(msdf, texCoord).rgb; float sd = median(msd.r, msd.g, msd.b); float screenPxDistance = screenPxRange()*(sd - 0.5); float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0); color = mix(bgColor, fgColor, opacity); } ``` -------------------------------- ### Create Edge Segments Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-edge-coloring.md Static factory methods for creating linear, quadratic, and cubic Bézier edge segments with optional custom colors. ```cpp static EdgeSegment *create(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE); static EdgeSegment *create(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE); static EdgeSegment *create(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE); ``` ```cpp // Create different edge types EdgeSegment *line = EdgeSegment::create(Point2(0, 0), Point2(1, 0)); EdgeSegment *quad = EdgeSegment::create(Point2(0, 0), Point2(0.5, 1), Point2(1, 0)); EdgeSegment *cubic = EdgeSegment::create(Point2(0, 0), Point2(0.3, 1), Point2(0.7, 1), Point2(1, 0)); // With custom color EdgeSegment *redEdge = EdgeSegment::create(Point2(0, 0), Point2(1, 0), RED); ``` -------------------------------- ### Get Shape Bounding Box Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-edge-coloring.md Returns the bounding box of the shape. Can optionally include a border width, miter limit for strokes, and specify winding polarity. The result contains l, b, r, t members representing left, bottom, right, and top bounds. ```cpp Shape::Bounds getBounds(double border = 0, double miterLimit = 0, int polarity = 0) const; ``` ```cpp Shape::Bounds bounds = shape.getBounds(); double width = bounds.r - bounds.l; double height = bounds.t - bounds.b; // With border for strokes Shape::Bounds strokeBounds = shape.getBounds(0.1, 1.0, 1); ``` -------------------------------- ### Copy Constructor from Section Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Creates a new bitmap as a copy of the data in a BitmapConstSection. ```APIDOC ## Copy Constructor from Section ### Description Creates a new bitmap as a copy of the data in a BitmapConstSection. ### Method Constructor ### Endpoint explicit Bitmap(const BitmapConstSection &orig) ### Parameters #### Path Parameters - **orig** (const BitmapConstSection&) - Required - The constant reference to the original bitmap section. ### Response #### Success Response - A new Bitmap object that is a deep copy of the data in the `orig` section. ``` -------------------------------- ### EdgeSegment::create() Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-edge-coloring.md Static factory methods for creating various types of edge segments, including linear, quadratic Bézier, and cubic Bézier segments, with an option to specify edge color. ```APIDOC ## EdgeSegment::create() ### Description Static factory methods for creating edge segments. Supports linear, quadratic Bézier, and cubic Bézier segments, with an optional edge color parameter. ### Method ```cpp static EdgeSegment *create(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE); static EdgeSegment *create(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE); static EdgeSegment *create(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE); ``` ### Parameters #### Input Points - **p0** (Point2) - The starting point of the edge. - **p1** (Point2) - The ending point of the edge for linear segments, or the first endpoint for Bézier curves. - **p2** (Point2) - The second control point for quadratic and cubic Bézier curves. - **p3** (Point2) - The third control point for cubic Bézier curves. #### Optional Parameter - **edgeColor** (EdgeColor) - The color of the edge. Defaults to WHITE. ### Segment Types | Parameter Signature | Segment Type | Description | |---------------------|------------------|------------------------------| | (p0, p1) | LinearSegment | Line from p0 to p1 | | (p0, p1, p2) | QuadraticSegment | Quadratic Bézier (3 points) | | (p0, p1, p2, p3) | CubicSegment | Cubic Bézier (4 points) | ### Return Type EdgeSegment* ### Example ```cpp // Create different edge types EdgeSegment *line = EdgeSegment::create(Point2(0, 0), Point2(1, 0)); EdgeSegment *quad = EdgeSegment::create(Point2(0, 0), Point2(0.5, 1), Point2(1, 0)); EdgeSegment *cubic = EdgeSegment::create(Point2(0, 0), Point2(0.3, 1), Point2(0.7, 1), Point2(1, 0)); // With custom color EdgeSegment *redEdge = EdgeSegment::create(Point2(0, 0), Point2(1, 0), RED); ``` ``` -------------------------------- ### Generate and Save MSDF from Font Glyph Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-file-io.md Demonstrates a typical workflow for generating MSDF from a font glyph, saving it in multiple formats, and exporting the shape outline. Includes Freetype initialization and cleanup. ```cpp #include #include using namespace msdfgen; int main() { // Load font FreetypeHandle *ft = initializeFreetype(); FontHandle *font = loadFont(ft, "arial.ttf"); // Load glyph Shape shape; loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED); shape.normalize(); edgeColoringSimple(shape, 3.0); // Generate MSDF Bitmap msdf(32, 32); SDFTransformation transform( Projection(32.0, Vector2(0.125, 0.125)), DistanceMapping(Range(0.125)) ); generateMSDF(msdf, shape, transform); // Save in multiple formats savePng(msdf, "glyph.png"); saveTiff(msdf, "glyph.tiff"); saveFl32<3>(msdf, "glyph.fl32"); // Export shape for debugging saveSvgShape(shape, "glyph_outline.svg"); // Cleanup destroyFont(font); deinitializeFreetype(ft); return 0; } ``` -------------------------------- ### Reference Documentation Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/README.md Comprehensive reference for all exported type definitions, including enums, structures, and template classes, as well as configuration options for the generator. ```APIDOC ## Reference Documentation ### Description This section provides detailed reference information for the types and configurations used within the msdfgen library. ### Reference Files - **[types.md](types.md)**: Lists all exported type definitions, including enums (EdgeColor, FillRule, YAxisOrientation, FontCoordinateScaling), structures (Vector2, Range, SignedDistance, FontMetrics), and template classes (Bitmap, BitmapRef, BitmapSection), with detailed field descriptions. - **[configuration.md](configuration.md)**: Describes GeneratorConfig options, MSDFGeneratorConfig settings, ErrorCorrectionConfig modes and parameters, and provides configuration examples for various scenarios. ``` -------------------------------- ### Copy Constructor from Reference Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Creates a new bitmap as a copy of the data referenced by a BitmapConstRef. ```APIDOC ## Copy Constructor from Reference ### Description Creates a new bitmap as a copy of the data referenced by a BitmapConstRef. ### Method Constructor ### Endpoint explicit Bitmap(const BitmapConstRef &orig) ### Parameters #### Path Parameters - **orig** (const BitmapConstRef&) - Required - The constant reference to the original bitmap data. ### Response #### Success Response - A new Bitmap object that is a deep copy of the data referenced by `orig`. ``` -------------------------------- ### Discover Source and Header Files Source: https://github.com/chlumsky/msdfgen/blob/master/CMakeLists.txt Uses GLOB_RECURSE to find all header and source files within specified directories. This is useful for automatically including all project files in the build. ```cmake file(GLOB_RECURSE MSDFGEN_CORE_HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "core/*.h" "core/*.hpp") file(GLOB_RECURSE MSDFGEN_CORE_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "core/*.cpp") file(GLOB_RECURSE MSDFGEN_EXT_HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "ext/*.h" "ext/*.hpp") file(GLOB_RECURSE MSDFGEN_EXT_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "ext/*.cpp" "lib/*.cpp") ``` -------------------------------- ### Generate MSDF for a Glyph Source: https://github.com/chlumsky/msdfgen/blob/master/README.md This snippet demonstrates how to load a font, extract a glyph, normalize its shape, apply simple edge coloring, generate an MSDF bitmap, and save it as a PNG. Ensure you have FreeType and msdfgen libraries initialized. ```c++ #include #include using namespace msdfgen; int main() { if (FreetypeHandle *ft = initializeFreetype()) { if (FontHandle *font = loadFont(ft, "C:\\Windows\\Fonts\\arialbd.ttf")) { Shape shape; if (loadGlyph(shape, font, 'A', FONT_SCALING_EM_NORMALIZED)) { shape.normalize(); // max. angle edgeColoringSimple(shape, 3.0); // output width, height Bitmap msdf(32, 32); // scale, translation (in em's) SDFTransformation t(Projection(32.0, Vector2(0.125, 0.125)), Range(0.125)); generateMSDF(msdf, shape, t); savePng(msdf, "output.png"); } destroyFont(font); } deinitializeFreetype(ft); } return 0; } ``` -------------------------------- ### Default Bitmap Constructor Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Creates an empty bitmap with zero dimensions. Use when initializing a bitmap that will be populated later. ```cpp Bitmap(); ``` -------------------------------- ### Copy Constructor Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Creates a new bitmap as a deep copy of another bitmap. ```APIDOC ## Copy Constructor ### Description Creates a new bitmap as a deep copy of another bitmap. ### Method Constructor ### Endpoint Bitmap(const Bitmap &orig) ### Parameters #### Path Parameters - **orig** (const Bitmap&) - Required - The original bitmap to copy. ### Response #### Success Response - A new Bitmap object that is a deep copy of the `orig` bitmap. ``` -------------------------------- ### msdfgen Basic Command Structure Source: https://github.com/chlumsky/msdfgen/blob/master/README.md The fundamental structure for executing the msdfgen standalone program. The input specification is the only mandatory argument. ```bash msdfgen ``` -------------------------------- ### Move Constructor Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-bitmap.md Moves data from another bitmap, avoiding copy overhead. ```APIDOC ## Move Constructor (C++11) ### Description Moves data from another bitmap, avoiding copy overhead. ### Method Constructor ### Endpoint Bitmap(Bitmap &&orig) ### Parameters #### Path Parameters - **orig** (Bitmap&&) - Required - The bitmap to move data from. ### Response #### Success Response - A new Bitmap object with data moved from `orig`. The `orig` bitmap will be in a valid but unspecified state. ``` -------------------------------- ### Minimal MSDF Generation Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/configuration.md Use default settings for basic MSDF generation. This is suitable for simple cases where advanced features are not required. ```cpp Bitmap msdf(32, 32); generateMSDF(msdf, shape, transform); // Uses all defaults ``` -------------------------------- ### Simulate 8-bit Quantization Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-rendering.md Snaps floating-point pixel values into 256 discrete values. Use this to simulate precision loss when converting float to uint8 for storage. ```cpp void simulate8bit(const BitmapSection &bitmap); void simulate8bit(const BitmapSection &bitmap); void simulate8bit(const BitmapSection &bitmap); ``` ```cpp Bitmap msdf(32, 32); // ... generate or load msdf ... // Simulate storing as 8-bit PNG simulate8bit(msdf); savePng(msdf, "output_8bit.png"); ``` -------------------------------- ### Static inverse() Source: https://github.com/chlumsky/msdfgen/blob/master/_autodocs/api-reference-transformations.md Static method to create the inverse of a range-based mapping directly. ```APIDOC ## static inverse(Range range) ### Description Static method to create the inverse of a range-based mapping directly. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **range** (Range) - Required - Distance range ### Response - **return value** (DistanceMapping) - The inverse mapping. ### Example ```cpp DistanceMapping invMapping = DistanceMapping::inverse(Range(0.25)); ``` ```