From 924d96139e9b02ccf7847b162f96f202941899f0 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 19:02:43 +0400 Subject: [PATCH 01/16] Rasterize SVG into Image with FreeType ImageLoad::fromSvg draws the shapes of LinesLoad::fromSvg with solid fill and stroke, fill rules and group opacity, fitting the view box into the given resolution. FreeType's outline renderer and stroker do the scan conversion, so MRIOExtras links FreeType together with tinyxml2. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/CMakeLists.txt | 7 +- source/MRIOExtras/MRIOExtrasConfig.cmake | 1 + source/MRIOExtras/MRSvg.cpp | 419 +++++++++++++++++++++++ source/MRIOExtras/MRSvg.h | 12 + source/MRTest/MRSvgTests.cpp | 48 +++ 5 files changed, 486 insertions(+), 1 deletion(-) diff --git a/source/MRIOExtras/CMakeLists.txt b/source/MRIOExtras/CMakeLists.txt index f5cc823523bc..7b94c0977224 100644 --- a/source/MRIOExtras/CMakeLists.txt +++ b/source/MRIOExtras/CMakeLists.txt @@ -34,7 +34,12 @@ target_link_libraries(${PROJECT_NAME} ) IF(NOT MRIOEXTRAS_NO_XML) - target_link_libraries(${PROJECT_NAME} PRIVATE tinyxml2) + # FreeType rasterizes SVG + IF(EMSCRIPTEN) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s USE_FREETYPE=1") + ENDIF() + find_package(Freetype REQUIRED) + target_link_libraries(${PROJECT_NAME} PRIVATE tinyxml2 Freetype::Freetype) ENDIF() IF(NOT MRIOEXTRAS_NO_CTM) diff --git a/source/MRIOExtras/MRIOExtrasConfig.cmake b/source/MRIOExtras/MRIOExtrasConfig.cmake index 6288fa1ba3d0..51ebef4a6038 100644 --- a/source/MRIOExtras/MRIOExtrasConfig.cmake +++ b/source/MRIOExtras/MRIOExtrasConfig.cmake @@ -5,6 +5,7 @@ if(EMSCRIPTEN) find_dependency(OpenCTM) find_dependency(draco) find_dependency(LAZPERF) + find_dependency(Freetype) endif() include("${CMAKE_CURRENT_LIST_DIR}/MRIOExtrasTargets.cmake") diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index a5aa39b084c3..308484d4fa7d 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -2,16 +2,26 @@ #ifndef MRIOEXTRAS_NO_XML #include "MRMesh/MRBezier.h" +#include "MRMesh/MRBox.h" +#include "MRMesh/MRFinally.h" #include "MRMesh/MRIOFormatsRegistry.h" #include "MRMesh/MRIOParsing.h" #include "MRMesh/MRMatrix2.h" +#include "MRMesh/MRString.h" #include "MRMesh/MRStringConvert.h" +#include "MRMesh/MRVector4.h" #include #include +#include +#include FT_FREETYPE_H +#include FT_OUTLINE_H +#include FT_STROKER_H + #include +#include #include #include @@ -294,6 +304,32 @@ Expected parseTransform( std::string_view str ) return result; } +// parses a number ignoring the units after it +Expected parseNumber( std::string_view str ) +{ + float result = 0.f; + if ( !phrase_parse( str.begin(), str.end(), float_, space, result ) ) + return unexpected( "Failed to parse number " + std::string( str ) ); + return result; +} + +Expected> parseNumbers( std::string_view str ) +{ + std::vector results; + if ( !phrase_parse( str.begin(), str.end(), float_ % -lit( ',' ), space, results ) ) + return unexpected( "Failed to parse numbers " + std::string( str ) ); + return results; +} + +// parses rgb(r, g, b) +Expected> parseRgb( std::string_view str ) +{ + std::vector results; + if ( !phrase_parse( str.begin(), str.end(), lit( "rgb" ) >> '(' >> ( uint_ % ',' ) >> ')', space, results ) || results.size() != 3 ) + return unexpected( "Failed to parse color " + std::string( str ) ); + return results; +} + Expected> parsePath( std::string_view str ) { #define _( ... ) ( [] ( auto& ctx ) { auto& cmd = _val( ctx ); [[maybe_unused]] auto& val = _attr( ctx ); __VA_ARGS__; } ) @@ -372,6 +408,256 @@ void close( Contour2f& contour ) contour.emplace_back( contour.front() ); } +// returns nullopt for none +Expected> parseColor( std::string_view str ) +{ + str = trim( str ); + if ( str == "none" ) + return std::optional{}; + if ( str == "black" ) + return Color::black(); + if ( str == "white" ) + return Color::white(); + if ( str.starts_with( '#' ) && ( str.size() == 4 || str.size() == 7 ) ) + { + unsigned v = 0; + const auto [end, ec] = std::from_chars( str.data() + 1, str.data() + str.size(), v, 16 ); + if ( ec == std::errc() && end == str.data() + str.size() ) + { + if ( str.size() == 4 ) + return Color( int( v >> 8 ) * 17, int( ( v >> 4 ) & 0xF ) * 17, int( v & 0xF ) * 17 ); + return Color( int( v >> 16 ), int( ( v >> 8 ) & 0xFF ), int( v & 0xFF ) ); + } + } + if ( const auto rgb = parser::parseRgb( str ) ) + return Color( int( std::min( ( *rgb )[0], 255u ) ), int( std::min( ( *rgb )[1], 255u ) ), int( std::min( ( *rgb )[2], 255u ) ) ); + return unexpected( "Unsupported paint " + std::string( str ) ); +} + +// inherited presentation properties +struct Style +{ + std::optional fill = Color::black(); + float fillOpacity = 1.f; + bool evenOdd = false; + std::optional stroke; + float strokeOpacity = 1.f; + float strokeWidth = 1.f; + FT_Stroker_LineCap lineCap = FT_STROKER_LINECAP_BUTT; + FT_Stroker_LineJoin lineJoin = FT_STROKER_LINEJOIN_MITER_FIXED; + float miterLimit = 4.f; +}; + +// applies a presentation attribute or a style declaration; opacity is not inherited so it is returned separately +Expected applyProperty( Style& style, float& opacity, std::string_view name, std::string_view value ) +{ + value = trim( value ); + const auto number = [value] ( float& target ) + { + return parser::parseNumber( value ).transform( [&target] ( float v ) { target = v; } ); + }; + const auto color = [value] ( std::optional& target ) + { + return parseColor( value ).transform( [&target] ( std::optional c ) { target = c; } ); + }; + if ( name == "fill" ) + return color( style.fill ); + if ( name == "stroke" ) + return color( style.stroke ); + if ( name == "fill-opacity" ) + return number( style.fillOpacity ); + if ( name == "stroke-opacity" ) + return number( style.strokeOpacity ); + if ( name == "opacity" ) + return number( opacity ); + if ( name == "stroke-width" ) + return number( style.strokeWidth ); + if ( name == "stroke-miterlimit" ) + return number( style.miterLimit ); + if ( name == "fill-rule" ) + style.evenOdd = value == "evenodd"; + else if ( name == "stroke-linecap" ) + style.lineCap = value == "round" ? FT_STROKER_LINECAP_ROUND : value == "square" ? FT_STROKER_LINECAP_SQUARE : FT_STROKER_LINECAP_BUTT; + else if ( name == "stroke-linejoin" ) + style.lineJoin = value == "round" ? FT_STROKER_LINEJOIN_ROUND : value == "bevel" ? FT_STROKER_LINEJOIN_BEVEL : FT_STROKER_LINEJOIN_MITER_FIXED; + return {}; +} + +Expected applyStyle( const tinyxml2::XMLElement* elem, Style& style, float& opacity ) +{ + for ( auto* attr = elem->FirstAttribute(); attr; attr = attr->Next() ) + if ( auto res = applyProperty( style, opacity, attr->Name(), attr->Value() ); !res ) + return res; + // style declarations take precedence over presentation attributes + if ( const char* declarations = elem->Attribute( "style" ) ) + { + for ( const auto& declaration : split( declarations, ";" ) ) + { + const std::string_view decl = declaration; + const auto colon = decl.find( ':' ); + if ( colon == decl.npos ) + continue; + if ( auto res = applyProperty( style, opacity, trim( decl.substr( 0, colon ) ), decl.substr( colon + 1 ) ); !res ) + return res; + } + } + return {}; +} + +// premultiplied colors, rows go from bottom to top as in Image +struct Canvas +{ + Vector2i resolution; + std::vector pixels; + + explicit Canvas( const Vector2i& res ) : resolution( res ), pixels( size_t( res.x ) * res.y ) {} + + void blend( const Canvas& layer, float opacity ) + { + for ( size_t i = 0; i < pixels.size(); ++i ) + { + const auto s = layer.pixels[i] * opacity; + pixels[i] = s + pixels[i] * ( 1.f - s.w ); + } + } +}; + +Vector4f premultiplied( const Color& color, float opacity ) +{ + const auto c = Vector4f( color ); + const auto a = c.w * std::clamp( opacity, 0.f, 1.f ); + return { c.x * a, c.y * a, c.z * a, a }; +} + +Image toImage( const Canvas& canvas ) +{ + const auto byte = [] ( float v ) { return std::clamp( int( std::lround( v * 255.f ) ), 0, 255 ); }; + Image image; + image.resolution = canvas.resolution; + image.pixels.reserve( canvas.pixels.size() ); + for ( const auto& p : canvas.pixels ) + image.pixels.push_back( p.w > 0.f ? Color( byte( p.x / p.w ), byte( p.y / p.w ), byte( p.z / p.w ), byte( p.w ) ) : Color( 0, 0, 0, 0 ) ); + return image; +} + +// point in 26.6 fixed-point format +FT_Vector toFt( const Vector2f& p ) +{ + return { FT_Pos( std::lround( p.x * 64.f ) ), FT_Pos( std::lround( p.y * 64.f ) ) }; +} + +// FreeType outline with own storage; the types of FT_Outline fields differ between FreeType versions +struct Outline +{ + std::vector points; + std::vector> tags; + std::vector> contours; + FT_Outline ft{}; + + Expected resize( size_t numPoints, size_t numContours ) + { + using PointCount = decltype( FT_Outline::n_points ); + using ContourCount = decltype( FT_Outline::n_contours ); + if ( numPoints > size_t( std::numeric_limits::max() ) || numContours > size_t( std::numeric_limits::max() ) ) + return unexpected( "Too many points in SVG shape" ); + points.resize( numPoints ); + tags.resize( numPoints, FT_CURVE_TAG_ON ); + contours.resize( numContours ); + ft.n_points = PointCount( numPoints ); + ft.n_contours = ContourCount( numContours ); + ft.points = points.data(); + ft.tags = tags.data(); + ft.contours = contours.data(); + return {}; + } +}; + +struct SpanPaint +{ + Canvas& canvas; + Vector4f color; +}; + +void blendSpans( int y, int count, const FT_Span* spans, void* user ) +{ + const auto& paint = *static_cast( user ); + auto* row = paint.canvas.pixels.data() + size_t( y ) * paint.canvas.resolution.x; + for ( int i = 0; i < count; ++i ) + { + const auto s = paint.color * ( float( spans[i].coverage ) / 255.f ); + for ( int x = spans[i].x; x < spans[i].x + spans[i].len; ++x ) + row[x] = s + row[x] * ( 1.f - s.w ); + } +} + +Expected render( FT_Library library, FT_Outline& outline, const Vector4f& color, Canvas& canvas ) +{ + SpanPaint paint{ canvas, color }; + FT_Raster_Params params{}; + params.flags = FT_RASTER_FLAG_AA | FT_RASTER_FLAG_DIRECT | FT_RASTER_FLAG_CLIP; + params.gray_spans = blendSpans; + params.user = &paint; + params.clip_box = { 0, 0, canvas.resolution.x, canvas.resolution.y }; + if ( const auto error = FT_Outline_Render( library, &outline, ¶ms ) ) + return unexpected( "FreeType rendering error " + std::to_string( error ) ); + return {}; +} + +Expected fill( FT_Library library, const Contours2f& contours, bool evenOdd, const Vector4f& color, Canvas& canvas ) +{ + size_t numPoints = 0; + for ( const auto& contour : contours ) + numPoints += contour.size(); + Outline outline; + if ( auto res = outline.resize( numPoints, contours.size() ); !res ) + return res; + size_t n = 0; + for ( size_t i = 0; i < contours.size(); ++i ) + { + for ( const auto& p : contours[i] ) + outline.points[n++] = toFt( p ); + outline.contours[i] = decltype( outline.contours )::value_type( n - 1 ); + } + outline.ft.flags = evenOdd ? FT_OUTLINE_EVEN_ODD_FILL : FT_OUTLINE_NONE; + return render( library, outline.ft, color, canvas ); +} + +// scale converts the stroke width to pixels +Expected stroke( FT_Library library, const Contours2f& contours, const Style& style, float scale, const Vector4f& color, Canvas& canvas ) +{ + FT_Stroker stroker = nullptr; + if ( FT_Stroker_New( library, &stroker ) ) + return unexpected( "Cannot create FreeType stroker" ); + MR_FINALLY { FT_Stroker_Done( stroker ); }; + // the radius is in 26.6 and the miter limit is in 16.16 fixed-point format + FT_Stroker_Set( stroker, FT_Fixed( std::lround( style.strokeWidth * scale * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( style.miterLimit * 65536.f ) ) ); + for ( const auto& contour : contours ) + { + // a closed contour repeats its first point in the end + const bool closed = contour.size() > 2 && contour.front() == contour.back(); + auto p = toFt( contour.front() ); + auto error = FT_Stroker_BeginSubPath( stroker, &p, !closed ); + for ( size_t i = 1; !error && i + size_t( closed ) < contour.size(); ++i ) + { + p = toFt( contour[i] ); + error = FT_Stroker_LineTo( stroker, &p ); + } + if ( error || FT_Stroker_EndSubPath( stroker ) ) + return unexpected( "FreeType stroking error" ); + } + FT_UInt numPoints = 0, numContours = 0; + if ( FT_Stroker_GetCounts( stroker, &numPoints, &numContours ) ) + return unexpected( "FreeType stroking error" ); + Outline outline; + if ( auto res = outline.resize( numPoints, numContours ); !res ) + return res; + // export appends to the outline + outline.ft.n_points = 0; + outline.ft.n_contours = 0; + FT_Stroker_Export( stroker, &outline.ft ); + return render( library, outline.ft, color, canvas ); +} + class SvgLoader { public: @@ -403,7 +689,115 @@ class SvgLoader } } + Expected rasterize( const Vector2i& resolution ) + { + assert( resolution.x > 0 && resolution.y > 0 ); + auto* svg = doc_.RootElement(); + if ( !svg || svg->Name() != std::string_view{ "svg" } ) + return unexpected( "Not an SVG document" ); + + Box2f viewBox; + if ( const char* attr = svg->Attribute( "viewBox" ) ) + { + const auto numbers = parser::parseNumbers( attr ); + if ( !numbers ) + return unexpected( numbers.error() ); + if ( numbers->size() != 4 ) + return unexpected( "Invalid viewBox " + std::string( attr ) ); + viewBox = Box2f::fromMinAndSize( { ( *numbers )[0], ( *numbers )[1] }, { ( *numbers )[2], ( *numbers )[3] } ); + } + else + { + const char* width = svg->Attribute( "width" ); + const char* height = svg->Attribute( "height" ); + if ( !width || !height ) + return unexpected( "SVG has neither viewBox nor width and height" ); + const auto w = parser::parseNumber( width ); + const auto h = parser::parseNumber( height ); + if ( !w || !h ) + return unexpected( !w ? w.error() : h.error() ); + viewBox = { Vector2f{}, Vector2f{ *w, *h } }; + } + const auto size = viewBox.size(); + if ( !( size.x > 0.f && size.y > 0.f ) ) + return unexpected( "Empty SVG view box" ); + + // fit the view box in the center keeping its aspect ratio; flip Y axis since image rows go from bottom to top + const auto scale = std::min( float( resolution.x ) / size.x, float( resolution.y ) / size.y ); + const auto xf = AffineXf2f::translation( Vector2f( resolution ) / 2.f ) * AffineXf2f::linear( Matrix2f::scale( scale, -scale ) ) + * AffineXf2f::translation( -viewBox.center() ); + + FT_Library library = nullptr; + if ( FT_Init_FreeType( &library ) ) + return unexpected( "Cannot initialize FreeType" ); + MR_FINALLY { FT_Done_FreeType( library ); }; + + Canvas canvas( resolution ); + if ( auto res = render_( library, svg, xf, {}, canvas ); !res ) + return unexpected( std::move( res.error() ) ); + return toImage( canvas ); + } + private: + // draws the element with its children over the canvas + Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) const + { + const bool group = elem == doc_.RootElement() || elem->Name() == std::string_view{ "g" }; + Contours2f contours; + if ( !group ) + { + auto shape = parseElement_( elem ); + if ( !shape ) + return unexpected( std::move( shape.error() ) ); + // omitting unknown elements and empty shapes + if ( shape->empty() ) + return {}; + contours = std::move( *shape ); + } + + if ( const auto* transform = elem->FindAttribute( "transform" ) ) + { + const auto elemXf = parser::parseTransform( transform->Value() ); + if ( !elemXf ) + return unexpected( std::move( elemXf.error() ) ); + xf = xf * *elemXf; + } + float opacity = 1.f; + if ( auto res = applyStyle( elem, style, opacity ); !res ) + return res; + + // an element with opacity is drawn in a separate layer + opacity = std::clamp( opacity, 0.f, 1.f ); + std::optional layer; + Canvas& target = opacity < 1.f ? layer.emplace( canvas.resolution ) : canvas; + if ( group ) + { + for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) + if ( auto res = render_( library, child, xf, style, target ); !res ) + return res; + } + else + { + for ( auto& contour : contours ) + for ( auto& p : contour ) + p = xf( p ); + if ( style.fill ) + { + if ( auto res = fill( library, contours, style.evenOdd, premultiplied( *style.fill, style.fillOpacity ), target ); !res ) + return res; + } + if ( style.stroke ) + { + const auto pixelScale = std::sqrt( std::abs( xf.A.det() ) ); + if ( auto res = stroke( library, contours, style, pixelScale, premultiplied( *style.stroke, style.strokeOpacity ), target ); !res ) + return res; + } + } + if ( layer ) + canvas.blend( *layer, opacity ); + return {}; + } + Expected parseChildren_( XMLElement* group ) const { Contours2f results; @@ -742,4 +1136,29 @@ Expected fromSvg( const char* data, size_t size, const LinesLoadSetti MR_ADD_LINES_LOADER(IOFilter( "SVG (.svg)", "*.svg" ), fromSvg) } // namespace MR::LinesLoad + +namespace MR::ImageLoad +{ + +Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ) +{ + std::ifstream in( file, std::ifstream::binary ); + if ( !in ) + return unexpected( std::string( "Cannot open file for reading " ) + utf8string( file ) ); + + return addFileNameInError( readCharBuffer( in ).and_then( [&] ( Buffer&& buf ) + { + return fromSvg( buf.data(), buf.size(), resolution ); + } ), file ); +} + +Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ) +{ + LinesLoad::SvgLoader loader( data, size ); + if ( !loader ) + return unexpected( loader.error() ); + return loader.rasterize( resolution ); +} + +} // namespace MR::ImageLoad #endif diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index f7d3776f2369..1187c8f06ba5 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -5,6 +5,7 @@ #include "exports.h" #include "MRMesh/MRExpected.h" +#include "MRMesh/MRImage.h" #include "MRMesh/MRLinesLoadSettings.h" #include @@ -18,4 +19,15 @@ MRIOEXTRAS_API Expected fromSvg( std::istream& in, const LinesLoadSet MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const LinesLoadSettings& settings = {} ); } // namespace MR::LinesLoad + +namespace MR::ImageLoad +{ + +/// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; +/// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, opacity, fill-rule, stroke width, caps, joins, miter limit), +/// group and element opacity; other elements and attributes are ignored, other paints (gradients, patterns) give an error +MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); +MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); + +} // namespace MR::ImageLoad #endif diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 4d0a8097cec2..cd6499848419 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -28,5 +28,53 @@ TEST( MRIOExtras, SvgUnicodeFileName ) EXPECT_TRUE( absent.error().starts_with( "Cannot open file for reading" ) ) << absent.error(); } +TEST( MRIOExtras, SvgRasterize ) +{ + // red top-left quadrant, and blue horizontal line 1 wide at y = 3 + const std::string svg = R"svg( + + +)svg"; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); + ASSERT_TRUE( image ) << image.error(); + ASSERT_EQ( image->resolution, Vector2i( 8, 8 ) ); + // image rows go from bottom to top + const Color transparent( 0, 0, 0, 0 ); + EXPECT_EQ( ( *image )[Vector2i( 1, 6 )], Color( 255, 0, 0 ) ); + EXPECT_EQ( ( *image )[Vector2i( 6, 6 )], transparent ); + EXPECT_EQ( ( *image )[Vector2i( 5, 3 )], transparent ); + EXPECT_EQ( ( *image )[Vector2i( 5, 2 )], Color( 0, 0, 255 ) ); + EXPECT_EQ( ( *image )[Vector2i( 5, 1 )], Color( 0, 0, 255 ) ); + EXPECT_EQ( ( *image )[Vector2i( 5, 0 )], transparent ); +} + +TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) +{ + const auto ring = [] ( const std::string& rule ) + { + const auto svg = R"()"; + return ImageLoad::fromSvg( svg.data(), svg.size(), { 4, 4 } ); + }; + const auto evenOdd = ring( "evenodd" ); + ASSERT_TRUE( evenOdd ) << evenOdd.error(); + EXPECT_EQ( ( *evenOdd )[Vector2i( 0, 0 )], Color::black() ); + EXPECT_EQ( ( *evenOdd )[Vector2i( 1, 1 )], Color( 0, 0, 0, 0 ) ); + const auto nonZero = ring( "nonzero" ); + ASSERT_TRUE( nonZero ) << nonZero.error(); + EXPECT_EQ( ( *nonZero )[Vector2i( 1, 1 )], Color::black() ); + + // group opacity applies to the group as a whole, so the overlap of its rectangles is not darker + const std::string group = R"()"; + const auto image = ImageLoad::fromSvg( group.data(), group.size(), { 2, 1 } ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color( 255, 255, 255, 128 ) ); + EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color( 255, 255, 255, 128 ) ); + + const std::string gradient = R"svg()svg"; + const auto unsupported = ImageLoad::fromSvg( gradient.data(), gradient.size(), { 1, 1 } ); + ASSERT_FALSE( unsupported ); + EXPECT_TRUE( unsupported.error().starts_with( "Unsupported paint" ) ) << unsupported.error(); +} + } // namespace MR #endif From 87a20969b43fb464cfb7bd749d19fc3f315ffe9c Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 19:05:43 +0400 Subject: [PATCH 02/16] Make drawn use, image and text elements an SVG rasterization error Skipping them silently gave wrong images, e.g. blank shapes drawn through use. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 6 +++++- source/MRIOExtras/MRSvg.h | 2 +- source/MRTest/MRSvgTests.cpp | 8 ++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 308484d4fa7d..2eec939a5982 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -742,10 +742,14 @@ class SvgLoader // draws the element with its children over the canvas Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) const { - const bool group = elem == doc_.RootElement() || elem->Name() == std::string_view{ "g" }; + const std::string_view name = elem->Name(); + const bool group = elem == doc_.RootElement() || name == "g"; Contours2f contours; if ( !group ) { + // drawing them is not supported, and omitting them would give a wrong image + if ( name == "use" || name == "image" || name == "text" ) + return unexpected( "Unsupported SVG element " + std::string( name ) ); auto shape = parseElement_( elem ); if ( !shape ) return unexpected( std::move( shape.error() ) ); diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 1187c8f06ba5..5ffe559b3fe8 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -25,7 +25,7 @@ namespace MR::ImageLoad /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, opacity, fill-rule, stroke width, caps, joins, miter limit), -/// group and element opacity; other elements and attributes are ignored, other paints (gradients, patterns) give an error +/// group and element opacity; other paints (gradients, patterns) and drawn use, image, text elements give an error, other elements and attributes are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index cd6499848419..11aceede8aba 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -74,6 +74,14 @@ TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) const auto unsupported = ImageLoad::fromSvg( gradient.data(), gradient.size(), { 1, 1 } ); ASSERT_FALSE( unsupported ); EXPECT_TRUE( unsupported.error().starts_with( "Unsupported paint" ) ) << unsupported.error(); + + // use in defs is not drawn by itself + const std::string useInDefs = R"()"; + EXPECT_TRUE( ImageLoad::fromSvg( useInDefs.data(), useInDefs.size(), { 1, 1 } ) ); + const std::string use = R"()"; + const auto unsupportedUse = ImageLoad::fromSvg( use.data(), use.size(), { 1, 1 } ); + ASSERT_FALSE( unsupportedUse ); + EXPECT_EQ( unsupportedUse.error(), "Unsupported SVG element use" ); } } // namespace MR From aba097e317a37cd04f87e97ab660eae0c657de63 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 19:48:42 +0400 Subject: [PATCH 03/16] Fix SVG arcs with the radius of half the chord and shapes without geometry Rounding made the squared center offset of such arcs slightly negative, which gave NaN points (an assert in Debug); path, polygon and polyline without d or points dereferenced a null attribute and now are empty shapes. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 16 +++++++++++----- source/MRTest/MRSvgTests.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 2eec939a5982..47e908dbbff8 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -188,8 +188,8 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) // https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter const auto rp_ = Vector2f { r.x * p0_.y, r.y * p0_.x }; assert( rp_.lengthSq() != 0.f ); - const auto k1Sq = sqr( r.x * r.y ) / rp_.lengthSq() - 1; - assert( k1Sq >= 0.f ); + // slightly negative from rounding errors if the radius is half of the chord + const auto k1Sq = std::max( 0.f, sqr( r.x * r.y ) / rp_.lengthSq() - 1 ); const auto k1 = std::sqrt( k1Sq ) * ( cmd.largeArc != cmd.sweep ? +1.f : -1.f ); assert( std::isfinite( k1 ) ); const auto c_ = k1 * Vector2f { rp_.x / r.y, -rp_.y / r.x }; @@ -859,7 +859,9 @@ class SvgLoader Expected parsePath_( XMLElement* elem ) const { - const std::string_view d = elem->Attribute( "d" ); + const char* d = elem->Attribute( "d" ); + if ( !d ) + return {}; const auto commands = parser::parsePath( d ); if ( !commands ) return unexpected( std::move( commands.error() ) ); @@ -1009,7 +1011,9 @@ class SvgLoader Expected parsePolygon_( XMLElement* elem ) const { - const std::string pointsStr = elem->Attribute( "points" ); + const char* pointsStr = elem->Attribute( "points" ); + if ( !pointsStr ) + return {}; auto points = parser::parsePoints( pointsStr ); if ( !points ) return unexpected( std::move( points.error() ) ); @@ -1019,7 +1023,9 @@ class SvgLoader Expected parsePolyline_( XMLElement* elem ) const { - const std::string pointsStr = elem->Attribute( "points" ); + const char* pointsStr = elem->Attribute( "points" ); + if ( !pointsStr ) + return {}; auto points = parser::parsePoints( pointsStr ); if ( !points ) return unexpected( std::move( points.error() ) ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 11aceede8aba..27431a34f2f5 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -28,6 +28,31 @@ TEST( MRIOExtras, SvgUnicodeFileName ) EXPECT_TRUE( absent.error().starts_with( "Cannot open file for reading" ) ) << absent.error(); } +// the radius of this arc is almost exactly half of its chord +TEST( MRIOExtras, SvgSemicircleArc ) +{ + const std::string svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), 33 ); + for ( const auto& p : loaded->points ) + EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ); + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); + EXPECT_TRUE( image ) << image.error(); +} + +// shapes without their geometry attributes are empty +TEST( MRIOExtras, SvgMissingAttributes ) +{ + const std::string svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), 0 ); + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 1, 1 } ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::transparent() ); +} + TEST( MRIOExtras, SvgRasterize ) { // red top-left quadrant, and blue horizontal line 1 wide at y = 3 From 5b1c2c57579ca3f16861f1edfdd110e48eea5dcb Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 19:51:59 +0400 Subject: [PATCH 04/16] Fix SVG stroking of collapsed subpaths and circles, reject more unsupported SVG Stroked contours are deduplicated in 26.6 points, so a subpath collapsed into one point draws its caps instead of crashing FreeType, and circles are closed with a join instead of two caps. Style sheets, mask, filter, stroke-dasharray, switch and nested svg give errors; a is drawn as a group, display none hides an element, currentColor is black. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 82 +++++++++++++++++++++++------------- source/MRIOExtras/MRSvg.h | 3 +- source/MRTest/MRSvgTests.cpp | 72 ++++++++++++++++++++++++++++--- 3 files changed, 122 insertions(+), 35 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 47e908dbbff8..50372e389282 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -313,14 +313,6 @@ Expected parseNumber( std::string_view str ) return result; } -Expected> parseNumbers( std::string_view str ) -{ - std::vector results; - if ( !phrase_parse( str.begin(), str.end(), float_ % -lit( ',' ), space, results ) ) - return unexpected( "Failed to parse numbers " + std::string( str ) ); - return results; -} - // parses rgb(r, g, b) Expected> parseRgb( std::string_view str ) { @@ -414,7 +406,8 @@ Expected> parseColor( std::string_view str ) str = trim( str ); if ( str == "none" ) return std::optional{}; - if ( str == "black" ) + // currentColor is the color property, which is black by default + if ( str == "black" || str == "currentColor" ) return Color::black(); if ( str == "white" ) return Color::white(); @@ -446,6 +439,8 @@ struct Style FT_Stroker_LineCap lineCap = FT_STROKER_LINECAP_BUTT; FT_Stroker_LineJoin lineJoin = FT_STROKER_LINEJOIN_MITER_FIXED; float miterLimit = 4.f; + // display none, which is not inherited, but children of a hidden element are not drawn either + bool hidden = false; }; // applies a presentation attribute or a style declaration; opacity is not inherited so it is returned separately @@ -460,6 +455,9 @@ Expected applyProperty( Style& style, float& opacity, std::string_view nam { return parseColor( value ).transform( [&target] ( std::optional c ) { target = c; } ); }; + // ignoring them would give a wrong image + if ( ( name == "mask" || name == "filter" || name == "stroke-dasharray" ) && value != "none" ) + return unexpected( "Unsupported SVG attribute " + std::string( name ) ); if ( name == "fill" ) return color( style.fill ); if ( name == "stroke" ) @@ -480,6 +478,8 @@ Expected applyProperty( Style& style, float& opacity, std::string_view nam style.lineCap = value == "round" ? FT_STROKER_LINECAP_ROUND : value == "square" ? FT_STROKER_LINECAP_SQUARE : FT_STROKER_LINECAP_BUTT; else if ( name == "stroke-linejoin" ) style.lineJoin = value == "round" ? FT_STROKER_LINEJOIN_ROUND : value == "bevel" ? FT_STROKER_LINEJOIN_BEVEL : FT_STROKER_LINEJOIN_MITER_FIXED; + else if ( name == "display" ) + style.hidden = value == "none"; return {}; } @@ -536,7 +536,7 @@ Image toImage( const Canvas& canvas ) image.resolution = canvas.resolution; image.pixels.reserve( canvas.pixels.size() ); for ( const auto& p : canvas.pixels ) - image.pixels.push_back( p.w > 0.f ? Color( byte( p.x / p.w ), byte( p.y / p.w ), byte( p.z / p.w ), byte( p.w ) ) : Color( 0, 0, 0, 0 ) ); + image.pixels.push_back( p.w > 0.f ? Color( byte( p.x / p.w ), byte( p.y / p.w ), byte( p.z / p.w ), byte( p.w ) ) : Color::transparent() ); return image; } @@ -559,7 +559,7 @@ struct Outline using PointCount = decltype( FT_Outline::n_points ); using ContourCount = decltype( FT_Outline::n_contours ); if ( numPoints > size_t( std::numeric_limits::max() ) || numContours > size_t( std::numeric_limits::max() ) ) - return unexpected( "Too many points in SVG shape" ); + return unexpected( "Too many points or contours in SVG shape" ); points.resize( numPoints ); tags.resize( numPoints, FT_CURVE_TAG_ON ); contours.resize( numContours ); @@ -631,17 +631,29 @@ Expected stroke( FT_Library library, const Contours2f& contours, const Sty MR_FINALLY { FT_Stroker_Done( stroker ); }; // the radius is in 26.6 and the miter limit is in 16.16 fixed-point format FT_Stroker_Set( stroker, FT_Fixed( std::lround( style.strokeWidth * scale * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( style.miterLimit * 65536.f ) ) ); + const auto same = [] ( const FT_Vector& a, const FT_Vector& b ) { return a.x == b.x && a.y == b.y; }; + std::vector points; for ( const auto& contour : contours ) { + // FreeType stroker crashes on a subpath without a segment of nonzero length + points.clear(); + for ( const auto& p : contour ) + if ( const auto q = toFt( p ); points.empty() || !same( q, points.back() ) ) + points.push_back( q ); // a closed contour repeats its first point in the end - const bool closed = contour.size() > 2 && contour.front() == contour.back(); - auto p = toFt( contour.front() ); - auto error = FT_Stroker_BeginSubPath( stroker, &p, !closed ); - for ( size_t i = 1; !error && i + size_t( closed ) < contour.size(); ++i ) + const bool closed = points.size() > 2 && same( points.front(), points.back() ); + if ( closed ) + points.pop_back(); + if ( points.size() < 2 ) { - p = toFt( contour[i] ); - error = FT_Stroker_LineTo( stroker, &p ); + // a zero-length subpath draws only its caps, nothing for butt caps + if ( style.lineCap == FT_STROKER_LINECAP_BUTT ) + continue; + points.push_back( { points[0].x + 1, points[0].y } ); } + auto error = FT_Stroker_BeginSubPath( stroker, &points[0], !closed ); + for ( size_t i = 1; !error && i < points.size(); ++i ) + error = FT_Stroker_LineTo( stroker, &points[i] ); if ( error || FT_Stroker_EndSubPath( stroker ) ) return unexpected( "FreeType stroking error" ); } @@ -691,20 +703,31 @@ class SvgLoader Expected rasterize( const Vector2i& resolution ) { - assert( resolution.x > 0 && resolution.y > 0 ); + // FT_Span.x is short in older FreeType versions + assert( resolution.x > 0 && resolution.y > 0 && resolution.x <= 32767 && resolution.y <= 32767 ); auto* svg = doc_.RootElement(); if ( !svg || svg->Name() != std::string_view{ "svg" } ) return unexpected( "Not an SVG document" ); + // style sheets restyle the drawn elements, so ignoring them would give a wrong image + const auto hasStyleSheet = [] ( const auto& self, const XMLElement* elem ) -> bool + { + for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) + if ( child->Name() == std::string_view{ "style" } || self( self, child ) ) + return true; + return false; + }; + if ( hasStyleSheet( hasStyleSheet, svg ) ) + return unexpected( "Unsupported SVG element style" ); + Box2f viewBox; if ( const char* attr = svg->Attribute( "viewBox" ) ) { - const auto numbers = parser::parseNumbers( attr ); - if ( !numbers ) - return unexpected( numbers.error() ); - if ( numbers->size() != 4 ) + // min and size + const auto points = parser::parsePoints( attr ); + if ( !points || points->size() != 2 ) return unexpected( "Invalid viewBox " + std::string( attr ) ); - viewBox = Box2f::fromMinAndSize( { ( *numbers )[0], ( *numbers )[1] }, { ( *numbers )[2], ( *numbers )[3] } ); + viewBox = Box2f::fromMinAndSize( ( *points )[0], ( *points )[1] ); } else { @@ -743,13 +766,12 @@ class SvgLoader Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) const { const std::string_view name = elem->Name(); - const bool group = elem == doc_.RootElement() || name == "g"; + const bool group = elem == doc_.RootElement() || name == "g" || name == "a"; + // drawing them is not supported, and omitting them would give a wrong image + const bool unsupported = !group && ( name == "use" || name == "image" || name == "text" || name == "svg" || name == "switch" ); Contours2f contours; - if ( !group ) + if ( !group && !unsupported ) { - // drawing them is not supported, and omitting them would give a wrong image - if ( name == "use" || name == "image" || name == "text" ) - return unexpected( "Unsupported SVG element " + std::string( name ) ); auto shape = parseElement_( elem ); if ( !shape ) return unexpected( std::move( shape.error() ) ); @@ -767,8 +789,10 @@ class SvgLoader xf = xf * *elemXf; } float opacity = 1.f; - if ( auto res = applyStyle( elem, style, opacity ); !res ) + if ( auto res = applyStyle( elem, style, opacity ); !res || style.hidden ) return res; + if ( unsupported ) + return unexpected( "Unsupported SVG element " + std::string( name ) ); // an element with opacity is drawn in a separate layer opacity = std::clamp( opacity, 0.f, 1.f ); diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 5ffe559b3fe8..5f94a62e7954 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -25,7 +25,8 @@ namespace MR::ImageLoad /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, opacity, fill-rule, stroke width, caps, joins, miter limit), -/// group and element opacity; other paints (gradients, patterns) and drawn use, image, text elements give an error, other elements and attributes are ignored +/// group and element opacity, display none; other paints (gradients, patterns), drawn use, image, text, switch, nested svg elements, style sheets, +/// mask, filter and stroke-dasharray give an error; other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 27431a34f2f5..c68083a5f76e 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -64,13 +65,12 @@ TEST( MRIOExtras, SvgRasterize ) ASSERT_TRUE( image ) << image.error(); ASSERT_EQ( image->resolution, Vector2i( 8, 8 ) ); // image rows go from bottom to top - const Color transparent( 0, 0, 0, 0 ); EXPECT_EQ( ( *image )[Vector2i( 1, 6 )], Color( 255, 0, 0 ) ); - EXPECT_EQ( ( *image )[Vector2i( 6, 6 )], transparent ); - EXPECT_EQ( ( *image )[Vector2i( 5, 3 )], transparent ); + EXPECT_EQ( ( *image )[Vector2i( 6, 6 )], Color::transparent() ); + EXPECT_EQ( ( *image )[Vector2i( 5, 3 )], Color::transparent() ); EXPECT_EQ( ( *image )[Vector2i( 5, 2 )], Color( 0, 0, 255 ) ); EXPECT_EQ( ( *image )[Vector2i( 5, 1 )], Color( 0, 0, 255 ) ); - EXPECT_EQ( ( *image )[Vector2i( 5, 0 )], transparent ); + EXPECT_EQ( ( *image )[Vector2i( 5, 0 )], Color::transparent() ); } TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) @@ -83,7 +83,7 @@ TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) const auto evenOdd = ring( "evenodd" ); ASSERT_TRUE( evenOdd ) << evenOdd.error(); EXPECT_EQ( ( *evenOdd )[Vector2i( 0, 0 )], Color::black() ); - EXPECT_EQ( ( *evenOdd )[Vector2i( 1, 1 )], Color( 0, 0, 0, 0 ) ); + EXPECT_EQ( ( *evenOdd )[Vector2i( 1, 1 )], Color::transparent() ); const auto nonZero = ring( "nonzero" ); ASSERT_TRUE( nonZero ) << nonZero.error(); EXPECT_EQ( ( *nonZero )[Vector2i( 1, 1 )], Color::black() ); @@ -109,5 +109,67 @@ TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) EXPECT_EQ( unsupportedUse.error(), "Unsupported SVG element use" ); } +// a zero-length subpath draws only its caps, which are nothing for butt caps +TEST( MRIOExtras, SvgRasterizeDot ) +{ + const auto dot = [] ( const std::string& cap ) + { + const auto svg = R"()"; + return ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); + }; + const auto round = dot( "round" ); + ASSERT_TRUE( round ) << round.error(); + EXPECT_EQ( ( *round )[Vector2i( 3, 3 )], Color::black() ); + EXPECT_EQ( ( *round )[Vector2i( 0, 0 )], Color::transparent() ); + const auto square = dot( "square" ); + ASSERT_TRUE( square ) << square.error(); + EXPECT_EQ( ( *square )[Vector2i( 2, 2 )], Color::black() ); + const auto butt = dot( "butt" ); + ASSERT_TRUE( butt ) << butt.error(); + EXPECT_EQ( std::count( butt->pixels.begin(), butt->pixels.end(), Color::transparent() ), 64 ); +} + +// a stroked circle is closed, so it has a join and no notch between two caps at its seam on the right +TEST( MRIOExtras, SvgRasterizeCircleSeam ) +{ + const std::string svg = R"()"; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 64, 64 } ); + ASSERT_TRUE( image ) << image.error(); + // 8 pixels outward from the seam, and from the opposite point + EXPECT_EQ( ( *image )[Vector2i( 56, 31 )], ( *image )[Vector2i( 7, 31 )] ); + EXPECT_EQ( ( *image )[Vector2i( 7, 31 )], Color::black() ); +} + +// elements and attributes that would be drawn wrong give errors +TEST( MRIOExtras, SvgRasterizeUnsupported ) +{ + const auto rasterize = [] ( const std::string& shapes ) + { + const auto svg = R"()" + shapes + ""; + return ImageLoad::fromSvg( svg.data(), svg.size(), { 2, 1 } ); + }; + const std::pair errors[] = { + { "", "Unsupported SVG element svg" }, + { "", "Unsupported SVG element switch" }, + { "", "Unsupported SVG element style" }, + { R"svg()svg", "Unsupported SVG attribute mask" }, + { R"svg()svg", "Unsupported SVG attribute filter" }, + { R"()", "Unsupported SVG attribute stroke-dasharray" }, + }; + for ( const auto& [shapes, error] : errors ) + { + const auto image = rasterize( shapes ); + ASSERT_FALSE( image ) << shapes; + EXPECT_EQ( image.error(), error ); + } + + // a is a group, currentColor is black, hidden elements are not drawn even if they are unsupported + const auto image = rasterize( R"()" + R"()" ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::black() ); + EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color::transparent() ); +} + } // namespace MR #endif From 604a5faf4aa7018982742994c049d9e1ab0a146e Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 20:41:22 +0400 Subject: [PATCH 05/16] Fix SVG compact arc flags, degenerate arcs and empty paths Arc flags are parsed as single characters, so compact arcs like "a9 9 0 11-18 0" no longer drop the rest of the path. Arcs with identical endpoints or one zero radius gave NaN points and now end in a straight line per the SVG spec, and an empty d is no path instead of an error. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 8 +++++--- source/MRTest/MRSvgTests.cpp | 32 +++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 50372e389282..9fc62b65d2e4 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -175,7 +175,7 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) // https://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii auto r = cmd.radii; - if ( r == Vector2f{} ) + if ( r.x == 0.f || r.y == 0.f || p1 == p2 ) return { p2 }; if ( r.x < 0.f ) r.x *= -1.f; @@ -353,8 +353,9 @@ Expected> parsePath( std::string_view str ) constexpr auto qscurveto = rule{ "qscurveto" } = eps[_( cmd.shorthand = true )] >> point[_( cmd.end = val )]; + // a flag is a single character, so "11" is two flags constexpr auto arc = rule{ "arc" } - = point[_( cmd.radii = val )] >> float_[_( cmd.xAxisRot = val )] >> int_[_( cmd.largeArc = (bool)val )] >> int_[_( cmd.sweep = (bool)val )] >> point[_( cmd.end = val )]; + = point[_( cmd.radii = val )] >> float_[_( cmd.xAxisRot = val )] >> char_( '0', '1' )[_( cmd.largeArc = val == '1' )] >> char_( '0', '1' )[_( cmd.sweep = val == '1' )] >> point[_( cmd.end = val )]; #undef _ @@ -883,8 +884,9 @@ class SvgLoader Expected parsePath_( XMLElement* elem ) const { + // an empty path is valid and draws nothing const char* d = elem->Attribute( "d" ); - if ( !d ) + if ( !d || trim( d ).empty() ) return {}; const auto commands = parser::parsePath( d ); if ( !commands ) diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index c68083a5f76e..cc5e8f59527a 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -42,10 +42,40 @@ TEST( MRIOExtras, SvgSemicircleArc ) EXPECT_TRUE( image ) << image.error(); } +// an arc with identical endpoints is omitted, and an arc with a zero radius is a straight line +TEST( MRIOExtras, SvgDegenerateArcs ) +{ + for ( const std::string d : { "M1 1 A1 1 0 0 1 1 1", "M0 0 A0 1 0 0 1 2 0" } ) + { + const auto svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + for ( const auto& p : loaded->points ) + EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ) << d; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 2, 2 } ); + EXPECT_TRUE( image ) << image.error(); + } +} + +// arc flags are single characters, so they need no separators +TEST( MRIOExtras, SvgArcFlags ) +{ + const std::string compact = R"()"; + const std::string spaced = R"()"; + const auto loaded = LinesLoad::fromSvg( compact.data(), compact.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + const auto expected = LinesLoad::fromSvg( spaced.data(), spaced.size() ); + ASSERT_TRUE( expected ) << expected.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), 68 ); + EXPECT_TRUE( loaded->points == expected->points ); + const auto image = ImageLoad::fromSvg( compact.data(), compact.size(), { 24, 24 } ); + EXPECT_TRUE( image ) << image.error(); +} + // shapes without their geometry attributes are empty TEST( MRIOExtras, SvgMissingAttributes ) { - const std::string svg = R"()"; + const std::string svg = R"()"; const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); ASSERT_TRUE( loaded ) << loaded.error(); EXPECT_EQ( loaded->topology.numValidVerts(), 0 ); From b5700a5dc95b9d9e8157b7ae90d3d4a3ad740f6f Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 20:43:45 +0400 Subject: [PATCH 06/16] Resolve SVG currentColor at drawing, reject markers and blend modes currentColor stays a keyword in inherited fill and stroke and takes the color property of the drawn element. Markers, vector-effect, mix-blend-mode, paint-order with stroke first and preserveAspectRatio other than xMidYMid meet give errors; outlines are allocated by FT_Outline_New, which checks their limits. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 91 ++++++++++++++++-------------------- source/MRIOExtras/MRSvg.h | 5 +- source/MRTest/MRSvgTests.cpp | 44 ++++++++++++++++- 3 files changed, 86 insertions(+), 54 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 9fc62b65d2e4..e17b503032b1 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -407,8 +407,7 @@ Expected> parseColor( std::string_view str ) str = trim( str ); if ( str == "none" ) return std::optional{}; - // currentColor is the color property, which is black by default - if ( str == "black" || str == "currentColor" ) + if ( str == "black" ) return Color::black(); if ( str == "white" ) return Color::white(); @@ -440,6 +439,9 @@ struct Style FT_Stroker_LineCap lineCap = FT_STROKER_LINECAP_BUTT; FT_Stroker_LineJoin lineJoin = FT_STROKER_LINEJOIN_MITER_FIXED; float miterLimit = 4.f; + // the color property, and whether fill and stroke are currentColor, which is resolved with the color of the drawn element + Color color = Color::black(); + bool currentFill = false, currentStroke = false; // display none, which is not inherited, but children of a hidden element are not drawn either bool hidden = false; }; @@ -452,17 +454,22 @@ Expected applyProperty( Style& style, float& opacity, std::string_view nam { return parser::parseNumber( value ).transform( [&target] ( float v ) { target = v; } ); }; - const auto color = [value] ( std::optional& target ) + const auto color = [value] ( std::optional& target, bool& current ) { - return parseColor( value ).transform( [&target] ( std::optional c ) { target = c; } ); + current = value == "currentColor"; + return current ? Expected{} : parseColor( value ).transform( [&target] ( std::optional c ) { target = c; } ); }; // ignoring them would give a wrong image - if ( ( name == "mask" || name == "filter" || name == "stroke-dasharray" ) && value != "none" ) + if ( ( ( name == "mask" || name == "filter" || name == "stroke-dasharray" || name == "marker" || name.starts_with( "marker-" ) || name == "vector-effect" ) && value != "none" ) + || ( name == "mix-blend-mode" && value != "normal" ) || ( name == "paint-order" && value != "normal" && !value.starts_with( "fill" ) ) ) return unexpected( "Unsupported SVG attribute " + std::string( name ) ); if ( name == "fill" ) - return color( style.fill ); + return color( style.fill, style.currentFill ); if ( name == "stroke" ) - return color( style.stroke ); + return color( style.stroke, style.currentStroke ); + // currentColor keeps the inherited color + if ( name == "color" && value != "currentColor" ) + return parseColor( value ).transform( [&style] ( std::optional c ) { style.color = c.value_or( style.color ); } ); if ( name == "fill-opacity" ) return number( style.fillOpacity ); if ( name == "stroke-opacity" ) @@ -547,32 +554,6 @@ FT_Vector toFt( const Vector2f& p ) return { FT_Pos( std::lround( p.x * 64.f ) ), FT_Pos( std::lround( p.y * 64.f ) ) }; } -// FreeType outline with own storage; the types of FT_Outline fields differ between FreeType versions -struct Outline -{ - std::vector points; - std::vector> tags; - std::vector> contours; - FT_Outline ft{}; - - Expected resize( size_t numPoints, size_t numContours ) - { - using PointCount = decltype( FT_Outline::n_points ); - using ContourCount = decltype( FT_Outline::n_contours ); - if ( numPoints > size_t( std::numeric_limits::max() ) || numContours > size_t( std::numeric_limits::max() ) ) - return unexpected( "Too many points or contours in SVG shape" ); - points.resize( numPoints ); - tags.resize( numPoints, FT_CURVE_TAG_ON ); - contours.resize( numContours ); - ft.n_points = PointCount( numPoints ); - ft.n_contours = ContourCount( numContours ); - ft.points = points.data(); - ft.tags = tags.data(); - ft.contours = contours.data(); - return {}; - } -}; - struct SpanPaint { Canvas& canvas; @@ -609,18 +590,24 @@ Expected fill( FT_Library library, const Contours2f& contours, bool evenOd size_t numPoints = 0; for ( const auto& contour : contours ) numPoints += contour.size(); - Outline outline; - if ( auto res = outline.resize( numPoints, contours.size() ); !res ) - return res; + // FreeType checks the limits of point and contour counts, whose types differ between its versions + FT_Outline outline; + if ( FT_Outline_New( library, FT_UInt( numPoints ), FT_Int( contours.size() ), &outline ) ) + return unexpected( "Too many points or contours in SVG shape" ); + MR_FINALLY { FT_Outline_Done( library, &outline ); }; size_t n = 0; for ( size_t i = 0; i < contours.size(); ++i ) { for ( const auto& p : contours[i] ) + { + // zero tags of a new outline are off-curve points + outline.tags[n] = FT_CURVE_TAG_ON; outline.points[n++] = toFt( p ); - outline.contours[i] = decltype( outline.contours )::value_type( n - 1 ); + } + outline.contours[i] = std::remove_pointer_t( n - 1 ); } - outline.ft.flags = evenOdd ? FT_OUTLINE_EVEN_ODD_FILL : FT_OUTLINE_NONE; - return render( library, outline.ft, color, canvas ); + outline.flags |= evenOdd ? FT_OUTLINE_EVEN_ODD_FILL : FT_OUTLINE_NONE; + return render( library, outline, color, canvas ); } // scale converts the stroke width to pixels @@ -661,14 +648,15 @@ Expected stroke( FT_Library library, const Contours2f& contours, const Sty FT_UInt numPoints = 0, numContours = 0; if ( FT_Stroker_GetCounts( stroker, &numPoints, &numContours ) ) return unexpected( "FreeType stroking error" ); - Outline outline; - if ( auto res = outline.resize( numPoints, numContours ); !res ) - return res; + FT_Outline outline; + if ( FT_Outline_New( library, numPoints, FT_Int( numContours ), &outline ) ) + return unexpected( "Too many points or contours in SVG shape" ); + MR_FINALLY { FT_Outline_Done( library, &outline ); }; // export appends to the outline - outline.ft.n_points = 0; - outline.ft.n_contours = 0; - FT_Stroker_Export( stroker, &outline.ft ); - return render( library, outline.ft, color, canvas ); + outline.n_points = 0; + outline.n_contours = 0; + FT_Stroker_Export( stroker, &outline ); + return render( library, outline, color, canvas ); } class SvgLoader @@ -720,6 +708,9 @@ class SvgLoader }; if ( hasStyleSheet( hasStyleSheet, svg ) ) return unexpected( "Unsupported SVG element style" ); + // the view box is always fitted uniformly in the center + if ( const char* aspect = svg->Attribute( "preserveAspectRatio" ); aspect && trim( aspect ) != "xMidYMid" && trim( aspect ) != "xMidYMid meet" ) + return unexpected( "Unsupported SVG attribute preserveAspectRatio" ); Box2f viewBox; if ( const char* attr = svg->Attribute( "viewBox" ) ) @@ -810,15 +801,15 @@ class SvgLoader for ( auto& contour : contours ) for ( auto& p : contour ) p = xf( p ); - if ( style.fill ) + if ( const auto color = style.currentFill ? style.color : style.fill ) { - if ( auto res = fill( library, contours, style.evenOdd, premultiplied( *style.fill, style.fillOpacity ), target ); !res ) + if ( auto res = fill( library, contours, style.evenOdd, premultiplied( *color, style.fillOpacity ), target ); !res ) return res; } - if ( style.stroke ) + if ( const auto color = style.currentStroke ? style.color : style.stroke ) { const auto pixelScale = std::sqrt( std::abs( xf.A.det() ) ); - if ( auto res = stroke( library, contours, style, pixelScale, premultiplied( *style.stroke, style.strokeOpacity ), target ); !res ) + if ( auto res = stroke( library, contours, style, pixelScale, premultiplied( *color, style.strokeOpacity ), target ); !res ) return res; } } diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 5f94a62e7954..507d789a7847 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -24,9 +24,10 @@ namespace MR::ImageLoad { /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; -/// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, opacity, fill-rule, stroke width, caps, joins, miter limit), +/// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit), /// group and element opacity, display none; other paints (gradients, patterns), drawn use, image, text, switch, nested svg elements, style sheets, -/// mask, filter and stroke-dasharray give an error; other elements and attributes (e.g. clip-path, visibility) are ignored +/// mask, filter, stroke-dasharray give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, preserveAspectRatio other than xMidYMid meet; +/// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index cc5e8f59527a..b2f14046ec8f 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -170,6 +170,33 @@ TEST( MRIOExtras, SvgRasterizeCircleSeam ) EXPECT_EQ( ( *image )[Vector2i( 7, 31 )], Color::black() ); } +// the view box is fitted uniformly in the center of a non-square image +TEST( MRIOExtras, SvgRasterizeAspectRatio ) +{ + const std::string svg = R"()"; + for ( const auto& res : { Vector2i( 4, 2 ), Vector2i( 2, 4 ) } ) + { + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), res ); + ASSERT_TRUE( image ) << image.error(); + // columns or rows 0 and 3 are empty + for ( int y = 0; y < res.y; ++y ) + for ( int x = 0; x < res.x; ++x ) + EXPECT_EQ( ( *image )[Vector2i( x, y )], ( res.x > res.y ? x : y ) % 3 == 0 ? Color::transparent() : Color::black() ) << x << ' ' << y; + } +} + +// currentColor is the color property of the drawn element even if it is inherited or set after it +TEST( MRIOExtras, SvgRasterizeCurrentColor ) +{ + const std::string svg = R"()" + R"()" + R"()"; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 9, 3 } ); + ASSERT_TRUE( image ) << image.error(); + for ( int x : { 1, 4, 7 } ) + EXPECT_EQ( ( *image )[Vector2i( x, 1 )], Color( 255, 0, 0 ) ) << x; +} + // elements and attributes that would be drawn wrong give errors TEST( MRIOExtras, SvgRasterizeUnsupported ) { @@ -185,6 +212,13 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) { R"svg()svg", "Unsupported SVG attribute mask" }, { R"svg()svg", "Unsupported SVG attribute filter" }, { R"()", "Unsupported SVG attribute stroke-dasharray" }, + { R"svg()svg", "Unsupported SVG attribute marker" }, + { R"svg()svg", "Unsupported SVG attribute marker-start" }, + { R"svg()svg", "Unsupported SVG attribute marker-mid" }, + { R"svg()svg", "Unsupported SVG attribute marker-end" }, + { R"()", "Unsupported SVG attribute vector-effect" }, + { R"()", "Unsupported SVG attribute mix-blend-mode" }, + { R"()", "Unsupported SVG attribute paint-order" }, }; for ( const auto& [shapes, error] : errors ) { @@ -193,8 +227,14 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) EXPECT_EQ( image.error(), error ); } - // a is a group, currentColor is black, hidden elements are not drawn even if they are unsupported - const auto image = rasterize( R"()" + const std::string stretched = R"()"; + const auto unsupportedAspect = ImageLoad::fromSvg( stretched.data(), stretched.size(), { 2, 2 } ); + ASSERT_FALSE( unsupportedAspect ); + EXPECT_EQ( unsupportedAspect.error(), "Unsupported SVG attribute preserveAspectRatio" ); + + // a is a group, currentColor is black, default values are supported, hidden elements are not drawn even if they are unsupported + const auto image = rasterize( R"()" R"()" ); ASSERT_TRUE( image ) << image.error(); EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::black() ); From dba3389a92429064f4a00bc3dc2339c16765d1e9 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 21:40:29 +0400 Subject: [PATCH 07/16] Omit SVG arcs with identical endpoints, accept empty points Such an arc added a zero-length edge, while the SVG spec omits it, and empty or whitespace-only points of polygon and polyline are no shape instead of an error, as for an empty d. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 9 ++++++--- source/MRTest/MRSvgTests.cpp | 8 +++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index e17b503032b1..44caafc9d0ef 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -175,7 +175,10 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) // https://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii auto r = cmd.radii; - if ( r.x == 0.f || r.y == 0.f || p1 == p2 ) + // an arc with identical endpoints is omitted, and an arc with a zero radius is a straight line + if ( p1 == p2 ) + return {}; + if ( r.x == 0.f || r.y == 0.f ) return { p2 }; if ( r.x < 0.f ) r.x *= -1.f; @@ -1029,7 +1032,7 @@ class SvgLoader Expected parsePolygon_( XMLElement* elem ) const { const char* pointsStr = elem->Attribute( "points" ); - if ( !pointsStr ) + if ( !pointsStr || trim( pointsStr ).empty() ) return {}; auto points = parser::parsePoints( pointsStr ); if ( !points ) @@ -1041,7 +1044,7 @@ class SvgLoader Expected parsePolyline_( XMLElement* elem ) const { const char* pointsStr = elem->Attribute( "points" ); - if ( !pointsStr ) + if ( !pointsStr || trim( pointsStr ).empty() ) return {}; auto points = parser::parsePoints( pointsStr ); if ( !points ) diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index b2f14046ec8f..0939d4bb7995 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -45,11 +45,13 @@ TEST( MRIOExtras, SvgSemicircleArc ) // an arc with identical endpoints is omitted, and an arc with a zero radius is a straight line TEST( MRIOExtras, SvgDegenerateArcs ) { - for ( const std::string d : { "M1 1 A1 1 0 0 1 1 1", "M0 0 A0 1 0 0 1 2 0" } ) + const std::pair paths[] = { { "M0 0 L1 1 A1 1 0 0 1 1 1 L2 0", 3 }, { "M0 0 A0 1 0 0 1 2 0", 2 } }; + for ( const auto& [d, numVerts] : paths ) { const auto svg = R"()"; const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), numVerts ) << d; for ( const auto& p : loaded->points ) EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ) << d; const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 2, 2 } ); @@ -72,10 +74,10 @@ TEST( MRIOExtras, SvgArcFlags ) EXPECT_TRUE( image ) << image.error(); } -// shapes without their geometry attributes are empty +// shapes without their geometry attributes or with empty ones are empty TEST( MRIOExtras, SvgMissingAttributes ) { - const std::string svg = R"()"; + const std::string svg = R"()"; const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); ASSERT_TRUE( loaded ) << loaded.error(); EXPECT_EQ( loaded->topology.numValidVerts(), 0 ); From 3fb4cb60e52f258b21350ec06283d8fba5af26ce Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Tue, 1 Dec 2026 21:43:15 +0400 Subject: [PATCH 08/16] Reject out-of-range SVG coordinates in rasterization Pixel coordinates and stroke widths that are not finite or exceed FreeType's limit of 262144 pixels overflowed the conversion to 26.6 and gave wrong images, so they give an error. New tests cover element opacity of fill and stroke, stroke width under a group transform and the file overload. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 13 ++++++++++++- source/MRIOExtras/MRSvg.h | 2 +- source/MRTest/MRSvgTests.cpp | 20 +++++++++++++++++++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 44caafc9d0ef..2a17985b7215 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -551,6 +551,9 @@ Image toImage( const Canvas& canvas ) return image; } +// FreeType's limit of coordinates in pixels, 0x1000000 in 26.6 fixed-point format +constexpr float cMaxPixelCoord = 262144.f; + // point in 26.6 fixed-point format FT_Vector toFt( const Vector2f& p ) { @@ -616,12 +619,15 @@ Expected fill( FT_Library library, const Contours2f& contours, bool evenOd // scale converts the stroke width to pixels Expected stroke( FT_Library library, const Contours2f& contours, const Style& style, float scale, const Vector4f& color, Canvas& canvas ) { + const auto width = style.strokeWidth * scale; + if ( !( std::abs( width ) <= cMaxPixelCoord ) ) + return unexpected( "SVG coordinates out of range" ); FT_Stroker stroker = nullptr; if ( FT_Stroker_New( library, &stroker ) ) return unexpected( "Cannot create FreeType stroker" ); MR_FINALLY { FT_Stroker_Done( stroker ); }; // the radius is in 26.6 and the miter limit is in 16.16 fixed-point format - FT_Stroker_Set( stroker, FT_Fixed( std::lround( style.strokeWidth * scale * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( style.miterLimit * 65536.f ) ) ); + FT_Stroker_Set( stroker, FT_Fixed( std::lround( width * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( style.miterLimit * 65536.f ) ) ); const auto same = [] ( const FT_Vector& a, const FT_Vector& b ) { return a.x == b.x && a.y == b.y; }; std::vector points; for ( const auto& contour : contours ) @@ -803,7 +809,12 @@ class SvgLoader { for ( auto& contour : contours ) for ( auto& p : contour ) + { p = xf( p ); + // NaN fails the check too + if ( !( std::abs( p.x ) <= cMaxPixelCoord && std::abs( p.y ) <= cMaxPixelCoord ) ) + return unexpected( "SVG coordinates out of range" ); + } if ( const auto color = style.currentFill ? style.color : style.fill ) { if ( auto res = fill( library, contours, style.evenOdd, premultiplied( *color, style.fillOpacity ), target ); !res ) diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 507d789a7847..61e9cc3789f6 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -25,7 +25,7 @@ namespace MR::ImageLoad /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit), -/// group and element opacity, display none; other paints (gradients, patterns), drawn use, image, text, switch, nested svg elements, style sheets, +/// group and element opacity, display none; other paints (gradients, patterns, named colors other than black and white), drawn use, image, text, switch, nested svg elements, style sheets, /// mask, filter, stroke-dasharray give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, preserveAspectRatio other than xMidYMid meet; /// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 0939d4bb7995..2a462e97fa34 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -18,11 +18,13 @@ TEST( MRIOExtras, SvgUnicodeFileName ) ASSERT_TRUE( bool( folder ) ); const auto path = folder / std::filesystem::path( u8"\u0442\u0435\u0441\u0442 \u6587\u4ef6 \u00e9.svg" ); std::ofstream( path, std::ofstream::binary ) - << R"()"; + << R"()"; const auto loaded = LinesLoad::fromSvg( path ); ASSERT_TRUE( loaded ) << loaded.error(); EXPECT_EQ( loaded->topology.numValidVerts(), 2 ); + const auto image = ImageLoad::fromSvg( path, { 10, 5 } ); + EXPECT_TRUE( image ) << image.error(); const auto absent = LinesLoad::fromSvg( folder / "absent.svg" ); ASSERT_FALSE( absent ); @@ -103,6 +105,13 @@ TEST( MRIOExtras, SvgRasterize ) EXPECT_EQ( ( *image )[Vector2i( 5, 2 )], Color( 0, 0, 255 ) ); EXPECT_EQ( ( *image )[Vector2i( 5, 1 )], Color( 0, 0, 255 ) ); EXPECT_EQ( ( *image )[Vector2i( 5, 0 )], Color::transparent() ); + + // the stroke width is scaled by the group transform, so the line at y = 4 is 2 pixels wide + const std::string scaled = R"svg()svg"; + const auto scaledImage = ImageLoad::fromSvg( scaled.data(), scaled.size(), { 8, 8 } ); + ASSERT_TRUE( scaledImage ) << scaledImage.error(); + for ( int y = 2; y <= 5; ++y ) + EXPECT_EQ( ( *scaledImage )[Vector2i( 4, y )], y == 3 || y == 4 ? Color::black() : Color::transparent() ) << y; } TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) @@ -127,6 +136,12 @@ TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color( 255, 255, 255, 128 ) ); EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color( 255, 255, 255, 128 ) ); + // element opacity applies to its fill and stroke together, so their overlap is not darker + const std::string element = R"()"; + const auto elementImage = ImageLoad::fromSvg( element.data(), element.size(), { 8, 8 } ); + ASSERT_TRUE( elementImage ) << elementImage.error(); + EXPECT_EQ( ( *elementImage )[Vector2i( 2, 4 )], Color( 255, 255, 255, 128 ) ); + const std::string gradient = R"svg()svg"; const auto unsupported = ImageLoad::fromSvg( gradient.data(), gradient.size(), { 1, 1 } ); ASSERT_FALSE( unsupported ); @@ -221,6 +236,9 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) { R"()", "Unsupported SVG attribute vector-effect" }, { R"()", "Unsupported SVG attribute mix-blend-mode" }, { R"()", "Unsupported SVG attribute paint-order" }, + { R"()", "SVG coordinates out of range" }, + { R"()", "SVG coordinates out of range" }, + { R"()", "SVG coordinates out of range" }, }; for ( const auto& [shapes, error] : errors ) { From c7a9784f66602d333a0f3023f760ab9b2a3e2e0b Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Wed, 2 Dec 2026 13:47:25 +0400 Subject: [PATCH 09/16] Support SVG stroke-dasharray and stroke-dashoffset in rasterization Dashes are cut from the flattened contours in pixels before stroking; patterns finer than FreeType's 1/64 px give an error. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 81 ++++++++++++++++++++++++++++++++++-- source/MRIOExtras/MRSvg.h | 4 +- source/MRTest/MRSvgTests.cpp | 32 +++++++++++++- 3 files changed, 111 insertions(+), 6 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 2a17985b7215..ff06b2c5b0c0 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -23,6 +23,7 @@ #include #include +#include #include @@ -316,6 +317,14 @@ Expected parseNumber( std::string_view str ) return result; } +Expected> parseNumbers( std::string_view str ) +{ + std::vector results; + if ( !phrase_parse( str.begin(), str.end(), float_ % -lit( ',' ), space, results ) ) + return unexpected( "Failed to parse numbers " + std::string( str ) ); + return results; +} + // parses rgb(r, g, b) Expected> parseRgb( std::string_view str ) { @@ -442,6 +451,9 @@ struct Style FT_Stroker_LineCap lineCap = FT_STROKER_LINECAP_BUTT; FT_Stroker_LineJoin lineJoin = FT_STROKER_LINEJOIN_MITER_FIXED; float miterLimit = 4.f; + // lengths of dashes and gaps, empty for a solid line + std::vector dashes; + float dashOffset = 0.f; // the color property, and whether fill and stroke are currentColor, which is resolved with the color of the drawn element Color color = Color::black(); bool currentFill = false, currentStroke = false; @@ -463,7 +475,7 @@ Expected applyProperty( Style& style, float& opacity, std::string_view nam return current ? Expected{} : parseColor( value ).transform( [&target] ( std::optional c ) { target = c; } ); }; // ignoring them would give a wrong image - if ( ( ( name == "mask" || name == "filter" || name == "stroke-dasharray" || name == "marker" || name.starts_with( "marker-" ) || name == "vector-effect" ) && value != "none" ) + if ( ( ( name == "mask" || name == "filter" || name == "marker" || name.starts_with( "marker-" ) || name == "vector-effect" ) && value != "none" ) || ( name == "mix-blend-mode" && value != "normal" ) || ( name == "paint-order" && value != "normal" && !value.starts_with( "fill" ) ) ) return unexpected( "Unsupported SVG attribute " + std::string( name ) ); if ( name == "fill" ) @@ -483,6 +495,25 @@ Expected applyProperty( Style& style, float& opacity, std::string_view nam return number( style.strokeWidth ); if ( name == "stroke-miterlimit" ) return number( style.miterLimit ); + if ( name == "stroke-dashoffset" ) + return number( style.dashOffset ); + if ( name == "stroke-dasharray" ) + { + style.dashes.clear(); + if ( value == "none" ) + return {}; + const auto dashes = parser::parseNumbers( value ); + if ( !dashes || std::any_of( dashes->begin(), dashes->end(), [] ( float d ) { return !( d >= 0.f ); } ) ) + return unexpected( "Invalid stroke-dasharray " + std::string( value ) ); + // all zeros give a solid line, and a list of odd length is repeated + if ( std::accumulate( dashes->begin(), dashes->end(), 0.f ) > 0.f ) + { + style.dashes = *dashes; + if ( dashes->size() % 2 == 1 ) + style.dashes.insert( style.dashes.end(), dashes->begin(), dashes->end() ); + } + return {}; + } if ( name == "fill-rule" ) style.evenOdd = value == "evenodd"; else if ( name == "stroke-linecap" ) @@ -616,12 +647,55 @@ Expected fill( FT_Library library, const Contours2f& contours, bool evenOd return render( library, outline, color, canvas ); } -// scale converts the stroke width to pixels +// splits the contours into dashes by the pattern of dash and gap lengths, multiplied by scale; each contour starts the pattern at the offset +Contours2f dash( const Contours2f& contours, const std::vector& pattern, float offset, float scale ) +{ + // in double, so that adding short dashes to long distances makes progress + const auto length = [&] ( size_t i ) { return double( pattern[i] ) * scale; }; + const auto period = std::accumulate( pattern.begin(), pattern.end(), 0. ) * scale; + Contours2f res; + for ( const auto& contour : contours ) + { + size_t i = 0; + auto pos = std::fmod( double( offset ) * scale, period ); + if ( pos < 0 ) + pos += period; + for ( ; pos >= length( i ); i = ( i + 1 ) % pattern.size() ) + pos -= length( i ); + // where the current dash or gap ends from the start of the current segment, dashes have even indices + auto end = length( i ) - pos; + if ( i % 2 == 0 ) + res.push_back( { contour.front() } ); + for ( size_t j = 1; j < contour.size(); ++j ) + { + const auto a = contour[j - 1], b = contour[j]; + const double segment = ( b - a ).length(); + for ( ; end <= segment; end += length( i ) ) + { + const auto p = a + ( b - a ) * float( segment > 0 ? end / segment : 0 ); + if ( i % 2 == 0 ) + res.back().push_back( p ); + i = ( i + 1 ) % pattern.size(); + if ( i % 2 == 0 ) + res.push_back( { p } ); + } + end -= segment; + if ( i % 2 == 0 ) + res.back().push_back( b ); + } + } + return res; +} + +// scale converts the stroke width and dash lengths to pixels Expected stroke( FT_Library library, const Contours2f& contours, const Style& style, float scale, const Vector4f& color, Canvas& canvas ) { const auto width = style.strokeWidth * scale; if ( !( std::abs( width ) <= cMaxPixelCoord ) ) return unexpected( "SVG coordinates out of range" ); + // FreeType does not resolve finer dash patterns, and there would be too many dashes + if ( !style.dashes.empty() && !( std::accumulate( style.dashes.begin(), style.dashes.end(), 0.f ) * scale >= 1.f / 64 ) ) + return unexpected( "SVG dash pattern is too fine" ); FT_Stroker stroker = nullptr; if ( FT_Stroker_New( library, &stroker ) ) return unexpected( "Cannot create FreeType stroker" ); @@ -630,7 +704,8 @@ Expected stroke( FT_Library library, const Contours2f& contours, const Sty FT_Stroker_Set( stroker, FT_Fixed( std::lround( width * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( style.miterLimit * 65536.f ) ) ); const auto same = [] ( const FT_Vector& a, const FT_Vector& b ) { return a.x == b.x && a.y == b.y; }; std::vector points; - for ( const auto& contour : contours ) + const auto dashed = style.dashes.empty() ? Contours2f{} : dash( contours, style.dashes, style.dashOffset, scale ); + for ( const auto& contour : style.dashes.empty() ? contours : dashed ) { // FreeType stroker crashes on a subpath without a segment of nonzero length points.clear(); diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 61e9cc3789f6..8940460c11f3 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -24,9 +24,9 @@ namespace MR::ImageLoad { /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; -/// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit), +/// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit, dashes), /// group and element opacity, display none; other paints (gradients, patterns, named colors other than black and white), drawn use, image, text, switch, nested svg elements, style sheets, -/// mask, filter, stroke-dasharray give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, preserveAspectRatio other than xMidYMid meet; +/// mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, preserveAspectRatio other than xMidYMid meet; /// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 2a462e97fa34..8fc943377521 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -228,7 +228,8 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) { "", "Unsupported SVG element style" }, { R"svg()svg", "Unsupported SVG attribute mask" }, { R"svg()svg", "Unsupported SVG attribute filter" }, - { R"()", "Unsupported SVG attribute stroke-dasharray" }, + { R"()", "Invalid stroke-dasharray 1 -1" }, + { R"()", "SVG dash pattern is too fine" }, { R"svg()svg", "Unsupported SVG attribute marker" }, { R"svg()svg", "Unsupported SVG attribute marker-start" }, { R"svg()svg", "Unsupported SVG attribute marker-mid" }, @@ -261,5 +262,34 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color::transparent() ); } +TEST( MRIOExtras, SvgRasterizeDashes ) +{ + // a line through the only row of pixels, with dash ends on pixel borders + const auto row = [] ( const std::string& dashes ) + { + const auto svg = R"svg("; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 1 } ); + if ( !image ) + return image.error(); + std::string res; + for ( const auto& c : image->pixels ) + res += c.a == 255 ? '#' : c.a == 0 ? '.' : '?'; + return res; + }; + EXPECT_EQ( row( R"(stroke-dasharray="2")" ), "##..##.." ); + EXPECT_EQ( row( R"(stroke-dasharray="2 2" stroke-dashoffset="1")" ), "#..##..#" ); + EXPECT_EQ( row( R"(stroke-dasharray="2,2" stroke-dashoffset="-1")" ), ".##..##." ); + EXPECT_EQ( row( R"(style="stroke-dasharray: 1, 2, 3")" ), "#..###.#" ); + EXPECT_EQ( row( R"(stroke-dasharray="0 0")" ), "########" ); + // the pattern goes on through the vertices of a polyline, and its lengths are transformed as the stroke width + const std::string polyline = R"svg()svg"; + const auto image = ImageLoad::fromSvg( polyline.data(), polyline.size(), { 16, 2 } ); + ASSERT_TRUE( image ) << image.error(); + for ( int x = 0; x < 16; ++x ) + { + EXPECT_EQ( ( *image )[Vector2i( x, 1 )].a, x % 4 < 2 ? 255 : 0 ) << x; + } +} + } // namespace MR #endif From fd0bffae9c9452dac01b43f0f03d9166655e6f22 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Wed, 2 Dec 2026 14:35:14 +0400 Subject: [PATCH 10/16] Start SVG rects at x + rx and go in +x direction as their SVG path Sharp rects ran in the opposite direction and rounded ones started at x + width - rx, so their dashes were mirrored or shifted compared with browsers; this reverses the point order of sharp rects loaded as lines. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 10 ++++++---- source/MRTest/MRSvgTests.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index ff06b2c5b0c0..412303f33bc1 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -1148,13 +1148,14 @@ class SvgLoader auto ry = elem->FloatAttribute( "ry", 0.f ); if ( width == 0.f || height == 0.f ) return {}; + // like its equivalent path in SVG, which sets the dash pattern, the rect starts at ( x + rx, y ) and goes in +x direction if ( rx == 0.f && ry == 0.f ) { Contour2f rect { { x, y }, - { x, y + height }, - { x + width, y + height }, { x + width, y }, + { x + width, y + height }, + { x, y + height }, { x, y }, }; return { { std::move( rect ) } }; @@ -1171,7 +1172,7 @@ class SvgLoader if ( height / 2.f < ry ) ry = height / 2.f; - Contour2f points; + Contour2f points{ Vector2f{ x + rx, y } }; for ( auto p : getEllipsePoints( { .cx = x + width - rx, .cy = y + ry, @@ -1208,7 +1209,8 @@ class SvgLoader .a1 = -PI2_F, } ) ) points.emplace_back( p ); - close( points ); + // the last arc ends at the start up to rounding errors + points.back() = points.front(); return { { std::move( points ) } }; } } diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 8fc943377521..61fb58949906 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -76,6 +76,35 @@ TEST( MRIOExtras, SvgArcFlags ) EXPECT_TRUE( image ) << image.error(); } +// a rect starts at ( x + rx, y ) and goes in +x direction as its equivalent path in SVG, which sets its dash pattern +TEST( MRIOExtras, SvgRectDirection ) +{ + const std::pair rects[] = { { "0", 1.f }, { "2", 3.f } }; + for ( const auto& [rx, startX] : rects ) + { + const auto svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_TRUE( loaded->topology.isClosed() ) << rx; + EXPECT_EQ( loaded->topology.numValidVerts(), rx == "0" ? 4 : 132 ) << rx; + // Y axis is flipped + EXPECT_EQ( loaded->points[0_v], Vector3f( startX, -1.f, 0.f ) ) << rx; + EXPECT_EQ( loaded->points[1_v].y, -1.f ) << rx; + EXPECT_GT( loaded->points[1_v].x, startX ) << rx; + } + + const auto draw = [] ( const std::string& shape ) + { + const auto svg = R"(<)" + shape + R"( fill="none" stroke="#000" stroke-width="2" stroke-dasharray="3 2"/>)"; + return ImageLoad::fromSvg( svg.data(), svg.size(), { 24, 16 } ); + }; + const auto rect = draw( R"(rect x="1" y="1" width="10" height="6")" ); + ASSERT_TRUE( rect ) << rect.error(); + const auto path = draw( R"(path d="M1 1H11V7H1Z")" ); + ASSERT_TRUE( path ) << path.error(); + EXPECT_TRUE( rect->pixels == path->pixels ); +} + // shapes without their geometry attributes or with empty ones are empty TEST( MRIOExtras, SvgMissingAttributes ) { From 335fc1b2c4a4f11385f8de224569c1d1bc89446a Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Wed, 2 Dec 2026 14:39:30 +0400 Subject: [PATCH 11/16] Fix SVG dash ends and joins, clamp miter limit, reject pathLength and foreignObject A zero-length dash at the offset is drawn, no dash starts at the end of a contour, and a dash through the start of a closed contour gets a join instead of two caps, as in Chromium. Patterns that would give more dashes than a FreeType outline holds fail before the dashes are built, miter limits are clamped to the 16.16 range, and dashed strokes with pathLength and foreignObject elements give errors. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 46 +++++++++++++++++++++++++++--------- source/MRIOExtras/MRSvg.h | 4 ++-- source/MRTest/MRSvgTests.cpp | 46 +++++++++++++++++++++++++++++++++++- 3 files changed, 82 insertions(+), 14 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 412303f33bc1..d8d560a2f502 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -3,6 +3,7 @@ #include "MRMesh/MRBezier.h" #include "MRMesh/MRBox.h" +#include "MRMesh/MRContour.h" #include "MRMesh/MRFinally.h" #include "MRMesh/MRIOFormatsRegistry.h" #include "MRMesh/MRIOParsing.h" @@ -591,6 +592,11 @@ FT_Vector toFt( const Vector2f& p ) return { FT_Pos( std::lround( p.x * 64.f ) ), FT_Pos( std::lround( p.y * 64.f ) ) }; } +bool same( const FT_Vector& a, const FT_Vector& b ) +{ + return a.x == b.x && a.y == b.y; +} + struct SpanPaint { Canvas& canvas; @@ -660,19 +666,23 @@ Contours2f dash( const Contours2f& contours, const std::vector& pattern, auto pos = std::fmod( double( offset ) * scale, period ); if ( pos < 0 ) pos += period; - for ( ; pos >= length( i ); i = ( i + 1 ) % pattern.size() ) + // a zero-length dash at the offset is not skipped + for ( ; pos > length( i ) || ( pos == length( i ) && pos > 0 ); i = ( i + 1 ) % pattern.size() ) pos -= length( i ); // where the current dash or gap ends from the start of the current segment, dashes have even indices auto end = length( i ) - pos; - if ( i % 2 == 0 ) + const auto first = res.size(); + const bool startsWithDash = i % 2 == 0; + if ( startsWithDash ) res.push_back( { contour.front() } ); for ( size_t j = 1; j < contour.size(); ++j ) { const auto a = contour[j - 1], b = contour[j]; const double segment = ( b - a ).length(); - for ( ; end <= segment; end += length( i ) ) + // what ends at b is cut at the start of the next segment, so no dash starts at the end of the contour + for ( ; end < segment; end += length( i ) ) { - const auto p = a + ( b - a ) * float( segment > 0 ? end / segment : 0 ); + const auto p = a + ( b - a ) * float( end / segment ); if ( i % 2 == 0 ) res.back().push_back( p ); i = ( i + 1 ) % pattern.size(); @@ -683,6 +693,12 @@ Contours2f dash( const Contours2f& contours, const std::vector& pattern, if ( i % 2 == 0 ) res.back().push_back( b ); } + // a dash through the start of a closed contour is one dash with a join there + if ( startsWithDash && i % 2 == 0 && res.size() > first + 1 && same( toFt( contour.front() ), toFt( contour.back() ) ) ) + { + res.back().insert( res.back().end(), res[first].begin() + 1, res[first].end() ); + res.erase( res.begin() + first ); + } } return res; } @@ -693,16 +709,21 @@ Expected stroke( FT_Library library, const Contours2f& contours, const Sty const auto width = style.strokeWidth * scale; if ( !( std::abs( width ) <= cMaxPixelCoord ) ) return unexpected( "SVG coordinates out of range" ); - // FreeType does not resolve finer dash patterns, and there would be too many dashes - if ( !style.dashes.empty() && !( std::accumulate( style.dashes.begin(), style.dashes.end(), 0.f ) * scale >= 1.f / 64 ) ) - return unexpected( "SVG dash pattern is too fine" ); + if ( !style.dashes.empty() ) + { + double length = 0; + for ( const auto& contour : contours ) + length += calcLength( contour ); + // fails early if the dashes would exceed 65535 outline points, estimating 4 points for each of length / period * size / 2 dashes + if ( !( length / ( std::accumulate( style.dashes.begin(), style.dashes.end(), 0. ) * scale ) * double( style.dashes.size() / 2 * 4 ) <= 65535 ) ) + return unexpected( "Too many points or contours in SVG shape" ); + } FT_Stroker stroker = nullptr; if ( FT_Stroker_New( library, &stroker ) ) return unexpected( "Cannot create FreeType stroker" ); MR_FINALLY { FT_Stroker_Done( stroker ); }; - // the radius is in 26.6 and the miter limit is in 16.16 fixed-point format - FT_Stroker_Set( stroker, FT_Fixed( std::lround( width * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( style.miterLimit * 65536.f ) ) ); - const auto same = [] ( const FT_Vector& a, const FT_Vector& b ) { return a.x == b.x && a.y == b.y; }; + // the radius is in 26.6 and the miter limit, which SVG requires to be at least 1, is in 16.16 fixed-point format of 32 bits + FT_Stroker_Set( stroker, FT_Fixed( std::lround( width * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( std::clamp( style.miterLimit, 1.f, 32767.f ) * 65536.f ) ) ); std::vector points; const auto dashed = style.dashes.empty() ? Contours2f{} : dash( contours, style.dashes, style.dashOffset, scale ); for ( const auto& contour : style.dashes.empty() ? contours : dashed ) @@ -844,7 +865,7 @@ class SvgLoader const std::string_view name = elem->Name(); const bool group = elem == doc_.RootElement() || name == "g" || name == "a"; // drawing them is not supported, and omitting them would give a wrong image - const bool unsupported = !group && ( name == "use" || name == "image" || name == "text" || name == "svg" || name == "switch" ); + const bool unsupported = !group && ( name == "use" || name == "image" || name == "text" || name == "svg" || name == "switch" || name == "foreignObject" ); Contours2f contours; if ( !group && !unsupported ) { @@ -897,6 +918,9 @@ class SvgLoader } if ( const auto color = style.currentStroke ? style.color : style.stroke ) { + // pathLength rescales the dashes + if ( !style.dashes.empty() && elem->Attribute( "pathLength" ) ) + return unexpected( "Unsupported SVG attribute pathLength" ); const auto pixelScale = std::sqrt( std::abs( xf.A.det() ) ); if ( auto res = stroke( library, contours, style, pixelScale, premultiplied( *color, style.strokeOpacity ), target ); !res ) return res; diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 8940460c11f3..834c5ad511a5 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -25,8 +25,8 @@ namespace MR::ImageLoad /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit, dashes), -/// group and element opacity, display none; other paints (gradients, patterns, named colors other than black and white), drawn use, image, text, switch, nested svg elements, style sheets, -/// mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, preserveAspectRatio other than xMidYMid meet; +/// group and element opacity, display none; other paints (gradients, patterns, named colors other than black and white), drawn use, image, text, switch, foreignObject, nested svg elements, +/// style sheets, mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, pathLength of dashed strokes, preserveAspectRatio other than xMidYMid meet; /// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 61fb58949906..9c472c09fa22 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -254,11 +254,13 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) const std::pair errors[] = { { "", "Unsupported SVG element svg" }, { "", "Unsupported SVG element switch" }, + { "", "Unsupported SVG element foreignObject" }, { "", "Unsupported SVG element style" }, { R"svg()svg", "Unsupported SVG attribute mask" }, { R"svg()svg", "Unsupported SVG attribute filter" }, { R"()", "Invalid stroke-dasharray 1 -1" }, - { R"()", "SVG dash pattern is too fine" }, + { R"()", "Too many points or contours in SVG shape" }, + { R"()", "Unsupported SVG attribute pathLength" }, { R"svg()svg", "Unsupported SVG attribute marker" }, { R"svg()svg", "Unsupported SVG attribute marker-start" }, { R"svg()svg", "Unsupported SVG attribute marker-mid" }, @@ -318,6 +320,48 @@ TEST( MRIOExtras, SvgRasterizeDashes ) { EXPECT_EQ( ( *image )[Vector2i( x, 1 )].a, x % 4 < 2 ? 255 : 0 ) << x; } + + // a zero-length dash at the start is a dot of round caps, and no dash starts at the end of a path + const auto roundRow = [] ( const std::string& d, const std::string& dashes ) + { + const auto svg = R"()"; + const auto roundImage = ImageLoad::fromSvg( svg.data(), svg.size(), { 10, 1 } ); + if ( !roundImage ) + return roundImage.error(); + std::string res; + for ( const auto& c : roundImage->pixels ) + res += c.a > 128 ? '#' : c.a < 16 ? '.' : '?'; + return res; + }; + EXPECT_EQ( roundRow( "M0.5 .5H9.5", "0 3" ), "#..#..#..." ); + EXPECT_EQ( roundRow( "M1 .5H9", "2" ), "?##??##?.." ); + + // a dash through the start of a closed path has a join there instead of two caps, so the outer corner is filled + const std::string closed = R"()"; + const auto closedImage = ImageLoad::fromSvg( closed.data(), closed.size(), { 12, 8 } ); + ASSERT_TRUE( closedImage ) << closedImage.error(); + EXPECT_EQ( ( *closedImage )[Vector2i( 0, 7 )], Color::black() ); +} + +// a miter limit beyond the range of FreeType's fixed-point format still gives miter joins +TEST( MRIOExtras, SvgRasterizeMiterLimit ) +{ + const std::string svg = R"()"; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); + ASSERT_TRUE( image ) << image.error(); + // the tip of the miter at the top-left corner + EXPECT_EQ( ( *image )[Vector2i( 0, 7 )], Color::black() ); +} + +// an icon as exported from Figma, whose clip path covers the whole icon +TEST( MRIOExtras, SvgRasterizeFigmaIcon ) +{ + const std::string svg = R"svg()svg" + R"()"; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 24, 24 } ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 12, 12 )], Color( 0x1C, 0x9C, 0x01 ) ); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::transparent() ); } } // namespace MR From d7b2379553142b3cd8a9048115eadfe1afc36f60 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Thu, 3 Dec 2026 18:08:00 +0400 Subject: [PATCH 12/16] Draw SVG use elements in rasterization A use draws the element it references by id as its child, moved by its x and y; references outside the document, symbol targets and cycles give errors. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 49 ++++++++++++++++++++++++++++-------- source/MRIOExtras/MRSvg.h | 3 ++- source/MRTest/MRSvgTests.cpp | 38 ++++++++++++++++++++++------ 3 files changed, 72 insertions(+), 18 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index d8d560a2f502..0cf82432c031 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -8,6 +8,7 @@ #include "MRMesh/MRIOFormatsRegistry.h" #include "MRMesh/MRIOParsing.h" #include "MRMesh/MRMatrix2.h" +#include "MRMesh/MRphmap.h" #include "MRMesh/MRString.h" #include "MRMesh/MRStringConvert.h" #include "MRMesh/MRVector4.h" @@ -803,15 +804,20 @@ class SvgLoader if ( !svg || svg->Name() != std::string_view{ "svg" } ) return unexpected( "Not an SVG document" ); - // style sheets restyle the drawn elements, so ignoring them would give a wrong image - const auto hasStyleSheet = [] ( const auto& self, const XMLElement* elem ) -> bool + // collects the elements that use can draw; style sheets restyle the drawn elements, so ignoring them would give a wrong image + bool styleSheet = false; + const auto collect = [&] ( const auto& self, XMLElement* elem ) -> void { for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) - if ( child->Name() == std::string_view{ "style" } || self( self, child ) ) - return true; - return false; + { + styleSheet = styleSheet || child->Name() == std::string_view{ "style" }; + if ( const char* id = child->Attribute( "id" ) ) + ids_.emplace( id, child ); + self( self, child ); + } }; - if ( hasStyleSheet( hasStyleSheet, svg ) ) + collect( collect, svg ); + if ( styleSheet ) return unexpected( "Unsupported SVG element style" ); // the view box is always fitted uniformly in the center if ( const char* aspect = svg->Attribute( "preserveAspectRatio" ); aspect && trim( aspect ) != "xMidYMid" && trim( aspect ) != "xMidYMid meet" ) @@ -860,12 +866,14 @@ class SvgLoader private: // draws the element with its children over the canvas - Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) const + Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) { const std::string_view name = elem->Name(); - const bool group = elem == doc_.RootElement() || name == "g" || name == "a"; + // use draws the element it references as its only child + const bool use = name == "use"; + const bool group = elem == doc_.RootElement() || name == "g" || name == "a" || use; // drawing them is not supported, and omitting them would give a wrong image - const bool unsupported = !group && ( name == "use" || name == "image" || name == "text" || name == "svg" || name == "switch" || name == "foreignObject" ); + const bool unsupported = !group && ( name == "image" || name == "text" || name == "svg" || name == "switch" || name == "foreignObject" || name == "symbol" ); Contours2f contours; if ( !group && !unsupported ) { @@ -885,6 +893,8 @@ class SvgLoader return unexpected( std::move( elemXf.error() ) ); xf = xf * *elemXf; } + if ( use ) + xf = xf * AffineXf2f::translation( { elem->FloatAttribute( "x" ), elem->FloatAttribute( "y" ) } ); float opacity = 1.f; if ( auto res = applyStyle( elem, style, opacity ); !res || style.hidden ) return res; @@ -895,7 +905,23 @@ class SvgLoader opacity = std::clamp( opacity, 0.f, 1.f ); std::optional layer; Canvas& target = opacity < 1.f ? layer.emplace( canvas.resolution ) : canvas; - if ( group ) + if ( use ) + { + const char* href = elem->Attribute( "href" ) ? elem->Attribute( "href" ) : elem->Attribute( "xlink:href" ); + if ( href && *href != '#' ) + return unexpected( "Unsupported SVG use reference " + std::string( href ) ); + // a reference to a missing element draws nothing, as in browsers + if ( const auto it = href ? ids_.find( href + 1 ) : ids_.end(); it != ids_.end() ) + { + if ( std::find( useTargets_.begin(), useTargets_.end(), it->second ) != useTargets_.end() ) + return unexpected( "SVG use references form a cycle" ); + useTargets_.push_back( it->second ); + MR_FINALLY { useTargets_.pop_back(); }; + if ( auto res = render_( library, it->second, xf, style, target ); !res ) + return res; + } + } + else if ( group ) { for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) if ( auto res = render_( library, child, xf, style, target ); !res ) @@ -1241,6 +1267,9 @@ class SvgLoader private: tinyxml2::XMLDocument doc_; + // elements by their ids, and the elements being drawn by use to detect cycles + HashMap ids_; + std::vector useTargets_; }; } // namespace diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 834c5ad511a5..7397126ec644 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -25,7 +25,8 @@ namespace MR::ImageLoad /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit, dashes), -/// group and element opacity, display none; other paints (gradients, patterns, named colors other than black and white), drawn use, image, text, switch, foreignObject, nested svg elements, +/// group and element opacity, display none, use of elements in the document; other paints (gradients, patterns, named colors other than black and white), +/// drawn image, text, switch, foreignObject, symbol, nested svg elements, /// style sheets, mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, pathLength of dashed strokes, preserveAspectRatio other than xMidYMid meet; /// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 9c472c09fa22..3d3e8e04fba3 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -176,13 +176,37 @@ TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) ASSERT_FALSE( unsupported ); EXPECT_TRUE( unsupported.error().starts_with( "Unsupported paint" ) ) << unsupported.error(); - // use in defs is not drawn by itself - const std::string useInDefs = R"()"; - EXPECT_TRUE( ImageLoad::fromSvg( useInDefs.data(), useInDefs.size(), { 1, 1 } ) ); - const std::string use = R"()"; - const auto unsupportedUse = ImageLoad::fromSvg( use.data(), use.size(), { 1, 1 } ); - ASSERT_FALSE( unsupportedUse ); - EXPECT_EQ( unsupportedUse.error(), "Unsupported SVG element use" ); +} + +TEST( MRIOExtras, SvgRasterizeUse ) +{ + const auto rasterize = [] ( const std::string& shapes ) + { + const auto svg = R"()" + shapes + ""; + return ImageLoad::fromSvg( svg.data(), svg.size(), { 4, 1 } ); + }; + // use draws the referenced element moved by x, y and its transform, which inherits the style of use but keeps its own; + // the elements in defs are not drawn by themselves, and a reference to a missing element draws nothing + const auto image = rasterize( R"svg()svg" + R"svg()svg" ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color( 255, 0, 0 ) ); + EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color( 0, 0, 255 ) ); + EXPECT_EQ( ( *image )[Vector2i( 2, 0 )], Color( 0, 255, 0 ) ); + EXPECT_EQ( ( *image )[Vector2i( 3, 0 )], Color::transparent() ); + + const std::pair errors[] = { + { R"svg()svg", "SVG use references form a cycle" }, + { R"svg()svg", "SVG use references form a cycle" }, + { R"svg()svg", "Unsupported SVG element symbol" }, + { R"svg()svg", "Unsupported SVG use reference other.svg#a" }, + }; + for ( const auto& [shapes, error] : errors ) + { + const auto res = rasterize( shapes ); + ASSERT_FALSE( res ) << shapes; + EXPECT_EQ( res.error(), error ); + } } // a zero-length subpath draws only its caps, which are nothing for butt caps From 7d0cc4cd61ba915042201781403e081a2c204fb0 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Thu, 3 Dec 2026 19:18:29 +0400 Subject: [PATCH 13/16] Fix SVG smooth curves after the other curve kind, scale arc endpoint asserts S reflected the control point of a preceding Q and T that of a preceding C, while SVG reflects it only after a curve of the same kind and uses the current point otherwise. The arc endpoint asserts had an absolute tolerance, which valid arcs far from the origin or with large radii exceeded in Debug; it now grows with the center and radii. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 13 ++++++++---- source/MRTest/MRSvgTests.cpp | 39 ++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 0cf82432c031..4c81da735655 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -223,8 +223,9 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) for ( auto& p : results ) p = ellXfInv( p ); } - assert( ( p1 - results.front() ).lengthSq() < 1e-6f ); - assert( ( p2 - results.back() ).lengthSq() < 1e-6f ); + // rounding errors grow with the magnitude of the center and the radii + assert( ( p1 - results.front() ).lengthSq() < 1e-6f + sqr( 1e-5f * ( c.length() + std::max( r.x, r.y ) ) ) ); + assert( ( p2 - results.back() ).lengthSq() < 1e-6f + sqr( 1e-5f * ( c.length() + std::max( r.x, r.y ) ) ) ); results.erase( results.begin() ); return results; } @@ -1024,7 +1025,9 @@ class SvgLoader Contours2f results; Vector2f pos{}; + // a smooth curve reflects the control point of the previous curve only if it is of the same kind std::optional nextCurveControlPoint{}; + bool cubicControlPoint = false; results.emplace_back(); for ( const auto& command : *commands ) { @@ -1079,8 +1082,9 @@ class SvgLoader if ( results.back().empty() ) results.back().emplace_back( pos ); - if ( !nextCurveControlPoint ) + if ( !nextCurveControlPoint || !cubicControlPoint ) nextCurveControlPoint = pos; + cubicControlPoint = true; for ( auto p : Path::getPoints( pos, *nextCurveControlPoint, cmd ) ) results.back().emplace_back( p ); @@ -1091,8 +1095,9 @@ class SvgLoader if ( results.back().empty() ) results.back().emplace_back( pos ); - if ( !nextCurveControlPoint ) + if ( !nextCurveControlPoint || cubicControlPoint ) nextCurveControlPoint = pos; + cubicControlPoint = false; for ( auto p : Path::getPoints( pos, *nextCurveControlPoint, cmd ) ) results.back().emplace_back( p ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 3d3e8e04fba3..52e64cd2643a 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -61,6 +61,45 @@ TEST( MRIOExtras, SvgDegenerateArcs ) } } +// rounding errors of arc points grow with the magnitude of coordinates or radii +TEST( MRIOExtras, SvgArcLargeCoordinates ) +{ + for ( const std::string d : { "M100000.3 100000.7 A5.3 4.1 20 0 1 100007.1 100006.2", "M0 0 A100000 100000 0 0 1 1 0" } ) + { + const auto svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), 33 ) << d; + for ( const auto& p : loaded->points ) + EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ) << d; + } +} + +// a smooth curve reflects the control point of the previous curve only if it is of the same kind, otherwise its control point is the current point +TEST( MRIOExtras, SvgSmoothCurves ) +{ + const auto load = [] ( const std::string& d ) + { + const auto svg = R"()"; + return LinesLoad::fromSvg( svg.data(), svg.size() ); + }; + // smooth and equivalent full commands + const std::pair paths[] = { + { "M0 0 Q5 10 10 0 S10 10 10 10", "M0 0 Q5 10 10 0 C10 0 10 10 10 10" }, + { "M0 0 C0 5 5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 Q5 0 10 0" }, + { "M0 0 C0 5 5 5 5 0 S10 -5 10 0", "M0 0 C0 5 5 5 5 0 C5 -5 10 -5 10 0" }, + { "M0 0 Q5 10 10 0 T20 0", "M0 0 Q5 10 10 0 Q15 -10 20 0" }, + }; + for ( const auto& [smooth, full] : paths ) + { + const auto loaded = load( smooth ); + ASSERT_TRUE( loaded ) << loaded.error(); + const auto expected = load( full ); + ASSERT_TRUE( expected ) << expected.error(); + EXPECT_TRUE( loaded->points == expected->points ) << smooth; + } +} + // arc flags are single characters, so they need no separators TEST( MRIOExtras, SvgArcFlags ) { From 69952f0fdab253ba601a213c02007a71fae2446b Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Thu, 3 Dec 2026 19:21:10 +0400 Subject: [PATCH 14/16] Bound SVG edge length and nesting depth in rasterization, allow empty text FreeType's rasterizer never ended on outline edges of 32768 pixels or longer, whose coordinate products overflow 32-bit long on Windows and wasm32, and chains of use overflowed the stack; both give errors now. Text without content and symbols outside use draw nothing instead of an error. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 21 +++++++++++-- source/MRIOExtras/MRSvg.h | 2 +- source/MRTest/MRSvgTests.cpp | 59 ++++++++++++++++++++++++++++-------- 3 files changed, 65 insertions(+), 17 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 4c81da735655..56aa2cd7a678 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -625,6 +626,11 @@ Expected render( FT_Library library, FT_Outline& outline, const Vector4f& params.gray_spans = blendSpans; params.user = &paint; params.clip_box = { 0, 0, canvas.resolution.x, canvas.resolution.y }; + // FreeType's rasterizer overflows 32-bit long on an edge of 32768 pixels or longer and never ends + FT_BBox box; + FT_Outline_Get_CBox( &outline, &box ); + if ( std::max( std::int64_t( box.xMax ) - box.xMin, std::int64_t( box.yMax ) - box.yMin ) >= 32768 * 64 ) + return unexpected( "SVG coordinates out of range" ); if ( const auto error = FT_Outline_Render( library, &outline, ¶ms ) ) return unexpected( "FreeType rendering error " + std::to_string( error ) ); return {}; @@ -869,12 +875,17 @@ class SvgLoader // draws the element with its children over the canvas Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) { + // use nests elements deeper than XML does, which would overflow the stack + ++depth_; + MR_FINALLY { --depth_; }; + if ( depth_ > 128 ) + return unexpected( "SVG nesting is too deep" ); const std::string_view name = elem->Name(); // use draws the element it references as its only child const bool use = name == "use"; const bool group = elem == doc_.RootElement() || name == "g" || name == "a" || use; - // drawing them is not supported, and omitting them would give a wrong image - const bool unsupported = !group && ( name == "image" || name == "text" || name == "svg" || name == "switch" || name == "foreignObject" || name == "symbol" ); + // drawing them is not supported, and omitting them would give a wrong image; text without content draws nothing + const bool unsupported = !group && ( name == "image" || ( name == "text" && elem->FirstChild() ) || name == "svg" || name == "switch" || name == "foreignObject" ); Contours2f contours; if ( !group && !unsupported ) { @@ -914,6 +925,9 @@ class SvgLoader // a reference to a missing element draws nothing, as in browsers if ( const auto it = href ? ids_.find( href + 1 ) : ids_.end(); it != ids_.end() ) { + // a symbol is drawn only by use, which is not supported for it + if ( it->second->Name() == std::string_view{ "symbol" } ) + return unexpected( "Unsupported SVG element symbol" ); if ( std::find( useTargets_.begin(), useTargets_.end(), it->second ) != useTargets_.end() ) return unexpected( "SVG use references form a cycle" ); useTargets_.push_back( it->second ); @@ -1272,9 +1286,10 @@ class SvgLoader private: tinyxml2::XMLDocument doc_; - // elements by their ids, and the elements being drawn by use to detect cycles + // elements by their ids, the elements being drawn by use to detect cycles, and the depth of the drawn element HashMap ids_; std::vector useTargets_; + int depth_ = 0; }; } // namespace diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 7397126ec644..4841f3dbac01 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -26,7 +26,7 @@ namespace MR::ImageLoad /// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit, dashes), /// group and element opacity, display none, use of elements in the document; other paints (gradients, patterns, named colors other than black and white), -/// drawn image, text, switch, foreignObject, symbol, nested svg elements, +/// drawn image, text with content, switch, foreignObject, nested svg elements, use of symbol, /// style sheets, mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, pathLength of dashed strokes, preserveAspectRatio other than xMidYMid meet; /// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 52e64cd2643a..ecccf33ebce8 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -221,18 +221,36 @@ TEST( MRIOExtras, SvgRasterizeUse ) { const auto rasterize = [] ( const std::string& shapes ) { - const auto svg = R"()" + shapes + ""; - return ImageLoad::fromSvg( svg.data(), svg.size(), { 4, 1 } ); + const auto svg = R"()" + shapes + ""; + return ImageLoad::fromSvg( svg.data(), svg.size(), { 7, 1 } ); }; - // use draws the referenced element moved by x, y and its transform, which inherits the style of use but keeps its own; - // the elements in defs are not drawn by themselves, and a reference to a missing element draws nothing - const auto image = rasterize( R"svg()svg" - R"svg()svg" ); + // use draws the referenced element moved by x, y and its transform, which inherits the style of use but keeps its own, also through a group or another use; + // opacity of use applies to the drawn element, the elements in defs are not drawn by themselves, and a reference to a missing element draws nothing + const auto image = rasterize( R"svg()svg" + R"svg()svg" + R"svg()svg" + R"svg()svg" ); ASSERT_TRUE( image ) << image.error(); - EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color( 255, 0, 0 ) ); - EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color( 0, 0, 255 ) ); - EXPECT_EQ( ( *image )[Vector2i( 2, 0 )], Color( 0, 255, 0 ) ); - EXPECT_EQ( ( *image )[Vector2i( 3, 0 )], Color::transparent() ); + const Color expected[] = { Color( 255, 0, 0 ), Color( 0, 0, 255 ), Color( 0, 255, 0 ), Color( 255, 0, 0 ), Color( 0, 0, 255 ), Color( 0, 0, 0, 128 ), Color::transparent() }; + for ( int x = 0; x < 7; ++x ) + { + EXPECT_EQ( ( *image )[Vector2i( x, 0 )], expected[x] ) << x; + } + + // use can nest elements deeper than XML does, so too deep nesting gives an error instead of overflowing the stack + const auto chain = [&] ( int length ) + { + std::string shapes = R"()"; + for ( int i = 1; i <= length; ++i ) + shapes += ""; + return rasterize( shapes + "" ); + }; + const auto deep = chain( 200 ); + ASSERT_FALSE( deep ); + EXPECT_EQ( deep.error(), "SVG nesting is too deep" ); + const auto shallow = chain( 50 ); + ASSERT_TRUE( shallow ) << shallow.error(); + EXPECT_EQ( ( *shallow )[Vector2i( 0, 0 )], Color::black() ); const std::pair errors[] = { { R"svg()svg", "SVG use references form a cycle" }, @@ -318,11 +336,12 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) { "", "Unsupported SVG element svg" }, { "", "Unsupported SVG element switch" }, { "", "Unsupported SVG element foreignObject" }, + { "a", "Unsupported SVG element text" }, { "", "Unsupported SVG element style" }, { R"svg()svg", "Unsupported SVG attribute mask" }, { R"svg()svg", "Unsupported SVG attribute filter" }, { R"()", "Invalid stroke-dasharray 1 -1" }, - { R"()", "Too many points or contours in SVG shape" }, + { R"()", "Too many points or contours in SVG shape" }, { R"()", "Unsupported SVG attribute pathLength" }, { R"svg()svg", "Unsupported SVG attribute marker" }, { R"svg()svg", "Unsupported SVG attribute marker-start" }, @@ -347,15 +366,29 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) ASSERT_FALSE( unsupportedAspect ); EXPECT_EQ( unsupportedAspect.error(), "Unsupported SVG attribute preserveAspectRatio" ); - // a is a group, currentColor is black, default values are supported, hidden elements are not drawn even if they are unsupported + // a is a group, currentColor is black, default values are supported, hidden elements are not drawn even if they are unsupported; + // text without content and a symbol not drawn by use draw nothing const auto image = rasterize( R"()" - R"()" ); + R"(a)" + R"()" ); ASSERT_TRUE( image ) << image.error(); EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::black() ); EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color::transparent() ); } +// FreeType's rasterizer never ends on an edge of 32768 pixels or longer, as in this fill or the caps of this stroke +TEST( MRIOExtras, SvgRasterizeLongEdges ) +{ + for ( const std::string shape : { R"()", R"()" } ) + { + const auto svg = R"()" + shape + ""; + const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 64, 64 } ); + ASSERT_FALSE( image ) << shape; + EXPECT_EQ( image.error(), "SVG coordinates out of range" ); + } +} + TEST( MRIOExtras, SvgRasterizeDashes ) { // a line through the only row of pixels, with dash ends on pixel borders From a72d31dec92e7da408e3a7d5f3cade1cfae5b963 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Thu, 3 Dec 2026 20:05:58 +0400 Subject: [PATCH 15/16] Simplify SVG rasterization code and tests Reuse existing helpers (split callback, parsePolyline_, accumulate, designated initializers) and check the root element once; merge overlapping SVG tests into tables without dropping any check. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 174 +++++++++---------------- source/MRTest/MRSvgTests.cpp | 237 +++++++++++------------------------ 2 files changed, 138 insertions(+), 273 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 56aa2cd7a678..196c8ab0f4ae 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include @@ -420,24 +421,18 @@ void close( Contour2f& contour ) // returns nullopt for none Expected> parseColor( std::string_view str ) { - str = trim( str ); if ( str == "none" ) return std::optional{}; if ( str == "black" ) return Color::black(); if ( str == "white" ) return Color::white(); - if ( str.starts_with( '#' ) && ( str.size() == 4 || str.size() == 7 ) ) - { - unsigned v = 0; - const auto [end, ec] = std::from_chars( str.data() + 1, str.data() + str.size(), v, 16 ); - if ( ec == std::errc() && end == str.data() + str.size() ) - { - if ( str.size() == 4 ) - return Color( int( v >> 8 ) * 17, int( ( v >> 4 ) & 0xF ) * 17, int( v & 0xF ) * 17 ); - return Color( int( v >> 16 ), int( ( v >> 8 ) & 0xFF ), int( v & 0xFF ) ); - } - } + // #rgb or #rrggbb, whose at most 6 hex digits cannot overflow + unsigned v = 0; + const auto end = str.data() + str.size(); + if ( str.starts_with( '#' ) && ( str.size() == 4 || str.size() == 7 ) && std::from_chars( str.data() + 1, end, v, 16 ).ptr == end ) + return str.size() == 4 ? Color( int( v >> 8 ) * 17, int( ( v >> 4 ) & 0xF ) * 17, int( v & 0xF ) * 17 ) + : Color( int( v >> 16 ), int( ( v >> 8 ) & 0xFF ), int( v & 0xFF ) ); if ( const auto rgb = parser::parseRgb( str ) ) return Color( int( std::min( ( *rgb )[0], 255u ) ), int( std::min( ( *rgb )[1], 255u ) ), int( std::min( ( *rgb )[2], 255u ) ) ); return unexpected( "Unsupported paint " + std::string( str ) ); @@ -469,10 +464,6 @@ struct Style Expected applyProperty( Style& style, float& opacity, std::string_view name, std::string_view value ) { value = trim( value ); - const auto number = [value] ( float& target ) - { - return parser::parseNumber( value ).transform( [&target] ( float v ) { target = v; } ); - }; const auto color = [value] ( std::optional& target, bool& current ) { current = value == "currentColor"; @@ -489,18 +480,11 @@ Expected applyProperty( Style& style, float& opacity, std::string_view nam // currentColor keeps the inherited color if ( name == "color" && value != "currentColor" ) return parseColor( value ).transform( [&style] ( std::optional c ) { style.color = c.value_or( style.color ); } ); - if ( name == "fill-opacity" ) - return number( style.fillOpacity ); - if ( name == "stroke-opacity" ) - return number( style.strokeOpacity ); - if ( name == "opacity" ) - return number( opacity ); - if ( name == "stroke-width" ) - return number( style.strokeWidth ); - if ( name == "stroke-miterlimit" ) - return number( style.miterLimit ); - if ( name == "stroke-dashoffset" ) - return number( style.dashOffset ); + const std::pair numbers[] = { { "opacity", &opacity }, { "fill-opacity", &style.fillOpacity }, { "stroke-opacity", &style.strokeOpacity }, + { "stroke-width", &style.strokeWidth }, { "stroke-miterlimit", &style.miterLimit }, { "stroke-dashoffset", &style.dashOffset } }; + for ( const auto& number : numbers ) + if ( name == number.first ) + return parser::parseNumber( value ).transform( [target = number.second] ( float v ) { *target = v; } ); if ( name == "stroke-dasharray" ) { style.dashes.clear(); @@ -535,19 +519,15 @@ Expected applyStyle( const tinyxml2::XMLElement* elem, Style& style, float if ( auto res = applyProperty( style, opacity, attr->Name(), attr->Value() ); !res ) return res; // style declarations take precedence over presentation attributes + Expected res; if ( const char* declarations = elem->Attribute( "style" ) ) - { - for ( const auto& declaration : split( declarations, ";" ) ) + split( declarations, ";", [&] ( std::string_view decl ) { - const std::string_view decl = declaration; - const auto colon = decl.find( ':' ); - if ( colon == decl.npos ) - continue; - if ( auto res = applyProperty( style, opacity, trim( decl.substr( 0, colon ) ), decl.substr( colon + 1 ) ); !res ) - return res; - } - } - return {}; + if ( const auto colon = decl.find( ':' ); colon != decl.npos ) + res = applyProperty( style, opacity, trim( decl.substr( 0, colon ) ), decl.substr( colon + 1 ) ); + return !res; + } ); + return res; } // premultiplied colors, rows go from bottom to top as in Image @@ -621,11 +601,8 @@ void blendSpans( int y, int count, const FT_Span* spans, void* user ) Expected render( FT_Library library, FT_Outline& outline, const Vector4f& color, Canvas& canvas ) { SpanPaint paint{ canvas, color }; - FT_Raster_Params params{}; - params.flags = FT_RASTER_FLAG_AA | FT_RASTER_FLAG_DIRECT | FT_RASTER_FLAG_CLIP; - params.gray_spans = blendSpans; - params.user = &paint; - params.clip_box = { 0, 0, canvas.resolution.x, canvas.resolution.y }; + FT_Raster_Params params{ .flags = FT_RASTER_FLAG_AA | FT_RASTER_FLAG_DIRECT | FT_RASTER_FLAG_CLIP, .gray_spans = blendSpans, .user = &paint, + .clip_box = { 0, 0, canvas.resolution.x, canvas.resolution.y } }; // FreeType's rasterizer overflows 32-bit long on an edge of 32768 pixels or longer and never ends FT_BBox box; FT_Outline_Get_CBox( &outline, &box ); @@ -638,23 +615,19 @@ Expected render( FT_Library library, FT_Outline& outline, const Vector4f& Expected fill( FT_Library library, const Contours2f& contours, bool evenOdd, const Vector4f& color, Canvas& canvas ) { - size_t numPoints = 0; - for ( const auto& contour : contours ) - numPoints += contour.size(); + const auto numPoints = std::accumulate( contours.begin(), contours.end(), size_t( 0 ), [] ( size_t s, const Contour2f& c ) { return s + c.size(); } ); // FreeType checks the limits of point and contour counts, whose types differ between its versions FT_Outline outline; if ( FT_Outline_New( library, FT_UInt( numPoints ), FT_Int( contours.size() ), &outline ) ) return unexpected( "Too many points or contours in SVG shape" ); MR_FINALLY { FT_Outline_Done( library, &outline ); }; + // zero tags of a new outline are off-curve points + std::memset( outline.tags, FT_CURVE_TAG_ON, numPoints ); size_t n = 0; for ( size_t i = 0; i < contours.size(); ++i ) { for ( const auto& p : contours[i] ) - { - // zero tags of a new outline are off-curve points - outline.tags[n] = FT_CURVE_TAG_ON; outline.points[n++] = toFt( p ); - } outline.contours[i] = std::remove_pointer_t( n - 1 ); } outline.flags |= evenOdd ? FT_OUTLINE_EVEN_ODD_FILL : FT_OUTLINE_NONE; @@ -719,9 +692,7 @@ Expected stroke( FT_Library library, const Contours2f& contours, const Sty return unexpected( "SVG coordinates out of range" ); if ( !style.dashes.empty() ) { - double length = 0; - for ( const auto& contour : contours ) - length += calcLength( contour ); + const auto length = std::accumulate( contours.begin(), contours.end(), 0., [] ( double s, const Contour2f& c ) { return s + calcLength( c ); } ); // fails early if the dashes would exceed 65535 outline points, estimating 4 points for each of length / period * size / 2 dashes if ( !( length / ( std::accumulate( style.dashes.begin(), style.dashes.end(), 0. ) * scale ) * double( style.dashes.size() / 2 * 4 ) <= 65535 ) ) return unexpected( "Too many points or contours in SVG shape" ); @@ -777,19 +748,16 @@ class SvgLoader public: explicit SvgLoader( const char* data, size_t size ) { - doc_.Parse( data, size ); + if ( doc_.Parse( data, size ) == XML_SUCCESS && doc_.RootElement() && doc_.RootElement()->Name() == std::string_view{ "svg" } ) + svg_ = doc_.RootElement(); } - explicit operator bool () const { return !doc_.Error(); } - std::string error() const { return doc_.ErrorStr(); } + explicit operator bool () const { return svg_ != nullptr; } + std::string error() const { return doc_.Error() ? doc_.ErrorStr() : "Not an SVG document"; } Expected parse() { - auto* svg = doc_.RootElement(); - if ( !svg || svg->Name() != std::string_view{ "svg" } ) - return unexpected( "Not an SVG document" ); - - if ( auto contours = parseChildren_( svg ) ) + if ( auto contours = parseChildren_( svg_ ) ) { Polyline2 result{ *contours }; // flip Y axis @@ -807,10 +775,6 @@ class SvgLoader { // FT_Span.x is short in older FreeType versions assert( resolution.x > 0 && resolution.y > 0 && resolution.x <= 32767 && resolution.y <= 32767 ); - auto* svg = doc_.RootElement(); - if ( !svg || svg->Name() != std::string_view{ "svg" } ) - return unexpected( "Not an SVG document" ); - // collects the elements that use can draw; style sheets restyle the drawn elements, so ignoring them would give a wrong image bool styleSheet = false; const auto collect = [&] ( const auto& self, XMLElement* elem ) -> void @@ -823,15 +787,15 @@ class SvgLoader self( self, child ); } }; - collect( collect, svg ); + collect( collect, svg_ ); if ( styleSheet ) return unexpected( "Unsupported SVG element style" ); // the view box is always fitted uniformly in the center - if ( const char* aspect = svg->Attribute( "preserveAspectRatio" ); aspect && trim( aspect ) != "xMidYMid" && trim( aspect ) != "xMidYMid meet" ) + if ( const char* aspect = svg_->Attribute( "preserveAspectRatio" ); aspect && trim( aspect ) != "xMidYMid" && trim( aspect ) != "xMidYMid meet" ) return unexpected( "Unsupported SVG attribute preserveAspectRatio" ); Box2f viewBox; - if ( const char* attr = svg->Attribute( "viewBox" ) ) + if ( const char* attr = svg_->Attribute( "viewBox" ) ) { // min and size const auto points = parser::parsePoints( attr ); @@ -841,8 +805,8 @@ class SvgLoader } else { - const char* width = svg->Attribute( "width" ); - const char* height = svg->Attribute( "height" ); + const char* width = svg_->Attribute( "width" ); + const char* height = svg_->Attribute( "height" ); if ( !width || !height ) return unexpected( "SVG has neither viewBox nor width and height" ); const auto w = parser::parseNumber( width ); @@ -866,45 +830,35 @@ class SvgLoader MR_FINALLY { FT_Done_FreeType( library ); }; Canvas canvas( resolution ); - if ( auto res = render_( library, svg, xf, {}, canvas ); !res ) - return unexpected( std::move( res.error() ) ); - return toImage( canvas ); + return render_( library, svg_, xf, {}, canvas, 0 ).transform( [&] { return toImage( canvas ); } ); } private: // draws the element with its children over the canvas - Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas ) + Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas, int depth ) { // use nests elements deeper than XML does, which would overflow the stack - ++depth_; - MR_FINALLY { --depth_; }; - if ( depth_ > 128 ) + if ( depth >= 128 ) return unexpected( "SVG nesting is too deep" ); const std::string_view name = elem->Name(); // use draws the element it references as its only child const bool use = name == "use"; - const bool group = elem == doc_.RootElement() || name == "g" || name == "a" || use; + const bool group = elem == svg_ || name == "g" || name == "a" || use; // drawing them is not supported, and omitting them would give a wrong image; text without content draws nothing const bool unsupported = !group && ( name == "image" || ( name == "text" && elem->FirstChild() ) || name == "svg" || name == "switch" || name == "foreignObject" ); - Contours2f contours; - if ( !group && !unsupported ) - { - auto shape = parseElement_( elem ); - if ( !shape ) - return unexpected( std::move( shape.error() ) ); - // omitting unknown elements and empty shapes - if ( shape->empty() ) - return {}; - contours = std::move( *shape ); - } + const bool shape = !group && !unsupported; + auto contours = shape ? parseElement_( elem ) : Expected{}; + if ( !contours ) + return unexpected( std::move( contours.error() ) ); + // omitting unknown elements and empty shapes + if ( shape && contours->empty() ) + return {}; - if ( const auto* transform = elem->FindAttribute( "transform" ) ) - { - const auto elemXf = parser::parseTransform( transform->Value() ); - if ( !elemXf ) - return unexpected( std::move( elemXf.error() ) ); - xf = xf * *elemXf; - } + const char* t = elem->Attribute( "transform" ); + const auto elemXf = t ? parser::parseTransform( t ) : AffineXf2f{}; + if ( !elemXf ) + return unexpected( std::move( elemXf.error() ) ); + xf = xf * *elemXf; if ( use ) xf = xf * AffineXf2f::translation( { elem->FloatAttribute( "x" ), elem->FloatAttribute( "y" ) } ); float opacity = 1.f; @@ -932,19 +886,19 @@ class SvgLoader return unexpected( "SVG use references form a cycle" ); useTargets_.push_back( it->second ); MR_FINALLY { useTargets_.pop_back(); }; - if ( auto res = render_( library, it->second, xf, style, target ); !res ) + if ( auto res = render_( library, it->second, xf, style, target, depth + 1 ); !res ) return res; } } else if ( group ) { for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) - if ( auto res = render_( library, child, xf, style, target ); !res ) + if ( auto res = render_( library, child, xf, style, target, depth + 1 ); !res ) return res; } else { - for ( auto& contour : contours ) + for ( auto& contour : *contours ) for ( auto& p : contour ) { p = xf( p ); @@ -954,7 +908,7 @@ class SvgLoader } if ( const auto color = style.currentFill ? style.color : style.fill ) { - if ( auto res = fill( library, contours, style.evenOdd, premultiplied( *color, style.fillOpacity ), target ); !res ) + if ( auto res = fill( library, *contours, style.evenOdd, premultiplied( *color, style.fillOpacity ), target ); !res ) return res; } if ( const auto color = style.currentStroke ? style.color : style.stroke ) @@ -963,7 +917,7 @@ class SvgLoader if ( !style.dashes.empty() && elem->Attribute( "pathLength" ) ) return unexpected( "Unsupported SVG attribute pathLength" ); const auto pixelScale = std::sqrt( std::abs( xf.A.det() ) ); - if ( auto res = stroke( library, contours, style, pixelScale, premultiplied( *color, style.strokeOpacity ), target ); !res ) + if ( auto res = stroke( library, *contours, style, pixelScale, premultiplied( *color, style.strokeOpacity ), target ); !res ) return res; } } @@ -1186,14 +1140,10 @@ class SvgLoader Expected parsePolygon_( XMLElement* elem ) const { - const char* pointsStr = elem->Attribute( "points" ); - if ( !pointsStr || trim( pointsStr ).empty() ) - return {}; - auto points = parser::parsePoints( pointsStr ); - if ( !points ) - return unexpected( std::move( points.error() ) ); - close( *points ); - return { { std::move( *points ) } }; + auto res = parsePolyline_( elem ); + if ( res && !res->empty() ) + close( res->front() ); + return res; } Expected parsePolyline_( XMLElement* elem ) const @@ -1286,10 +1236,10 @@ class SvgLoader private: tinyxml2::XMLDocument doc_; - // elements by their ids, the elements being drawn by use to detect cycles, and the depth of the drawn element + // the root element if it is svg, elements by their ids, and the elements being drawn by use to detect cycles + XMLElement* svg_ = nullptr; HashMap ids_; std::vector useTargets_; - int depth_ = 0; }; } // namespace diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index ecccf33ebce8..f2b27ba95a23 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -11,6 +11,11 @@ namespace MR { +static Expected rasterize( const std::string& svg, const Vector2i& res ) +{ + return ImageLoad::fromSvg( svg.data(), svg.size(), res ); +} + // a file with symbols outside of any single code page in its name must be opened on Windows as well TEST( MRIOExtras, SvgUnicodeFileName ) { @@ -31,51 +36,33 @@ TEST( MRIOExtras, SvgUnicodeFileName ) EXPECT_TRUE( absent.error().starts_with( "Cannot open file for reading" ) ) << absent.error(); } -// the radius of this arc is almost exactly half of its chord -TEST( MRIOExtras, SvgSemicircleArc ) -{ - const std::string svg = R"()"; - const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); - ASSERT_TRUE( loaded ) << loaded.error(); - EXPECT_EQ( loaded->topology.numValidVerts(), 33 ); - for ( const auto& p : loaded->points ) - EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ); - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); - EXPECT_TRUE( image ) << image.error(); -} - -// an arc with identical endpoints is omitted, and an arc with a zero radius is a straight line -TEST( MRIOExtras, SvgDegenerateArcs ) +// arcs with the radius almost exactly half of the chord, with identical endpoints, which are omitted, with a zero radius, which are straight lines, +// with flags without separators, and with large coordinates or radii, whose rounding errors grow with the magnitude +TEST( MRIOExtras, SvgArcs ) { - const std::pair paths[] = { { "M0 0 L1 1 A1 1 0 0 1 1 1 L2 0", 3 }, { "M0 0 A0 1 0 0 1 2 0", 2 } }; + const std::pair paths[] = { + { "M2.37 3.29 A2.6 2.6 0 0 1 6.5 6.46", 33 }, + { "M0 0 L1 1 A1 1 0 0 1 1 1 L2 0", 3 }, + { "M0 0 A0 1 0 0 1 2 0", 2 }, + { "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z", 68 }, + { "M100000.3 100000.7 A5.3 4.1 20 0 1 100007.1 100006.2", 33 }, + { "M0 0 A100000 100000 0 0 1 1 0", 33 }, + }; for ( const auto& [d, numVerts] : paths ) { - const auto svg = R"()"; + const auto svg = R"()"; const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); ASSERT_TRUE( loaded ) << loaded.error(); EXPECT_EQ( loaded->topology.numValidVerts(), numVerts ) << d; for ( const auto& p : loaded->points ) EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ) << d; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 2, 2 } ); - EXPECT_TRUE( image ) << image.error(); + const auto image = rasterize( svg, { 24, 24 } ); + EXPECT_TRUE( image ) << d << ": " << image.error(); } } -// rounding errors of arc points grow with the magnitude of coordinates or radii -TEST( MRIOExtras, SvgArcLargeCoordinates ) -{ - for ( const std::string d : { "M100000.3 100000.7 A5.3 4.1 20 0 1 100007.1 100006.2", "M0 0 A100000 100000 0 0 1 1 0" } ) - { - const auto svg = R"()"; - const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); - ASSERT_TRUE( loaded ) << loaded.error(); - EXPECT_EQ( loaded->topology.numValidVerts(), 33 ) << d; - for ( const auto& p : loaded->points ) - EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ) << d; - } -} - -// a smooth curve reflects the control point of the previous curve only if it is of the same kind, otherwise its control point is the current point +// a smooth curve reflects the control point of the previous curve only if it is of the same kind, otherwise its control point is the current point; +// arc flags are single characters, so they need no separators TEST( MRIOExtras, SvgSmoothCurves ) { const auto load = [] ( const std::string& d ) @@ -83,12 +70,13 @@ TEST( MRIOExtras, SvgSmoothCurves ) const auto svg = R"()"; return LinesLoad::fromSvg( svg.data(), svg.size() ); }; - // smooth and equivalent full commands + // smooth and equivalent full commands, compact and spaced arc flags const std::pair paths[] = { { "M0 0 Q5 10 10 0 S10 10 10 10", "M0 0 Q5 10 10 0 C10 0 10 10 10 10" }, { "M0 0 C0 5 5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 Q5 0 10 0" }, { "M0 0 C0 5 5 5 5 0 S10 -5 10 0", "M0 0 C0 5 5 5 5 0 C5 -5 10 -5 10 0" }, { "M0 0 Q5 10 10 0 T20 0", "M0 0 Q5 10 10 0 Q15 -10 20 0" }, + { "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z", "M9 12l2 2 4-4m6 2a9 9 0 1 1-18 0 9 9 0 0,1 18 0z" }, }; for ( const auto& [smooth, full] : paths ) { @@ -100,21 +88,6 @@ TEST( MRIOExtras, SvgSmoothCurves ) } } -// arc flags are single characters, so they need no separators -TEST( MRIOExtras, SvgArcFlags ) -{ - const std::string compact = R"()"; - const std::string spaced = R"()"; - const auto loaded = LinesLoad::fromSvg( compact.data(), compact.size() ); - ASSERT_TRUE( loaded ) << loaded.error(); - const auto expected = LinesLoad::fromSvg( spaced.data(), spaced.size() ); - ASSERT_TRUE( expected ) << expected.error(); - EXPECT_EQ( loaded->topology.numValidVerts(), 68 ); - EXPECT_TRUE( loaded->points == expected->points ); - const auto image = ImageLoad::fromSvg( compact.data(), compact.size(), { 24, 24 } ); - EXPECT_TRUE( image ) << image.error(); -} - // a rect starts at ( x + rx, y ) and goes in +x direction as its equivalent path in SVG, which sets its dash pattern TEST( MRIOExtras, SvgRectDirection ) { @@ -134,14 +107,15 @@ TEST( MRIOExtras, SvgRectDirection ) const auto draw = [] ( const std::string& shape ) { - const auto svg = R"(<)" + shape + R"( fill="none" stroke="#000" stroke-width="2" stroke-dasharray="3 2"/>)"; - return ImageLoad::fromSvg( svg.data(), svg.size(), { 24, 16 } ); + return rasterize( R"(<)" + shape + R"( fill="none" stroke="#000" stroke-width="2" stroke-dasharray="3 2"/>)", { 24, 16 } ); }; const auto rect = draw( R"(rect x="1" y="1" width="10" height="6")" ); ASSERT_TRUE( rect ) << rect.error(); const auto path = draw( R"(path d="M1 1H11V7H1Z")" ); ASSERT_TRUE( path ) << path.error(); EXPECT_TRUE( rect->pixels == path->pixels ); + // a dash through the start of a closed path has a join there instead of two caps, so the outer corner is filled + EXPECT_EQ( ( *path )[Vector2i( 0, 15 )], Color::black() ); } // shapes without their geometry attributes or with empty ones are empty @@ -151,7 +125,7 @@ TEST( MRIOExtras, SvgMissingAttributes ) const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); ASSERT_TRUE( loaded ) << loaded.error(); EXPECT_EQ( loaded->topology.numValidVerts(), 0 ); - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 1, 1 } ); + const auto image = rasterize( svg, { 1, 1 } ); ASSERT_TRUE( image ) << image.error(); EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::transparent() ); } @@ -159,11 +133,10 @@ TEST( MRIOExtras, SvgMissingAttributes ) TEST( MRIOExtras, SvgRasterize ) { // red top-left quadrant, and blue horizontal line 1 wide at y = 3 - const std::string svg = R"svg( + const auto image = rasterize( R"svg( -)svg"; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); +)svg", { 8, 8 } ); ASSERT_TRUE( image ) << image.error(); ASSERT_EQ( image->resolution, Vector2i( 8, 8 ) ); // image rows go from bottom to top @@ -175,19 +148,17 @@ TEST( MRIOExtras, SvgRasterize ) EXPECT_EQ( ( *image )[Vector2i( 5, 0 )], Color::transparent() ); // the stroke width is scaled by the group transform, so the line at y = 4 is 2 pixels wide - const std::string scaled = R"svg()svg"; - const auto scaledImage = ImageLoad::fromSvg( scaled.data(), scaled.size(), { 8, 8 } ); - ASSERT_TRUE( scaledImage ) << scaledImage.error(); + const auto scaled = rasterize( R"svg()svg", { 8, 8 } ); + ASSERT_TRUE( scaled ) << scaled.error(); for ( int y = 2; y <= 5; ++y ) - EXPECT_EQ( ( *scaledImage )[Vector2i( 4, y )], y == 3 || y == 4 ? Color::black() : Color::transparent() ) << y; + EXPECT_EQ( ( *scaled )[Vector2i( 4, y )], y == 3 || y == 4 ? Color::black() : Color::transparent() ) << y; } TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) { const auto ring = [] ( const std::string& rule ) { - const auto svg = R"()"; - return ImageLoad::fromSvg( svg.data(), svg.size(), { 4, 4 } ); + return rasterize( R"()", { 4, 4 } ); }; const auto evenOdd = ring( "evenodd" ); ASSERT_TRUE( evenOdd ) << evenOdd.error(); @@ -198,44 +169,33 @@ TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) EXPECT_EQ( ( *nonZero )[Vector2i( 1, 1 )], Color::black() ); // group opacity applies to the group as a whole, so the overlap of its rectangles is not darker - const std::string group = R"()"; - const auto image = ImageLoad::fromSvg( group.data(), group.size(), { 2, 1 } ); + const auto image = rasterize( R"()", { 2, 1 } ); ASSERT_TRUE( image ) << image.error(); EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color( 255, 255, 255, 128 ) ); EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color( 255, 255, 255, 128 ) ); // element opacity applies to its fill and stroke together, so their overlap is not darker - const std::string element = R"()"; - const auto elementImage = ImageLoad::fromSvg( element.data(), element.size(), { 8, 8 } ); - ASSERT_TRUE( elementImage ) << elementImage.error(); - EXPECT_EQ( ( *elementImage )[Vector2i( 2, 4 )], Color( 255, 255, 255, 128 ) ); - - const std::string gradient = R"svg()svg"; - const auto unsupported = ImageLoad::fromSvg( gradient.data(), gradient.size(), { 1, 1 } ); - ASSERT_FALSE( unsupported ); - EXPECT_TRUE( unsupported.error().starts_with( "Unsupported paint" ) ) << unsupported.error(); - + const auto element = rasterize( R"()", { 8, 8 } ); + ASSERT_TRUE( element ) << element.error(); + EXPECT_EQ( ( *element )[Vector2i( 2, 4 )], Color( 255, 255, 255, 128 ) ); } TEST( MRIOExtras, SvgRasterizeUse ) { - const auto rasterize = [] ( const std::string& shapes ) + const auto draw = [] ( const std::string& shapes ) { - const auto svg = R"()" + shapes + ""; - return ImageLoad::fromSvg( svg.data(), svg.size(), { 7, 1 } ); + return rasterize( R"()" + shapes + "", { 7, 1 } ); }; // use draws the referenced element moved by x, y and its transform, which inherits the style of use but keeps its own, also through a group or another use; // opacity of use applies to the drawn element, the elements in defs are not drawn by themselves, and a reference to a missing element draws nothing - const auto image = rasterize( R"svg()svg" + const auto image = draw( R"svg()svg" R"svg()svg" R"svg()svg" R"svg()svg" ); ASSERT_TRUE( image ) << image.error(); const Color expected[] = { Color( 255, 0, 0 ), Color( 0, 0, 255 ), Color( 0, 255, 0 ), Color( 255, 0, 0 ), Color( 0, 0, 255 ), Color( 0, 0, 0, 128 ), Color::transparent() }; for ( int x = 0; x < 7; ++x ) - { EXPECT_EQ( ( *image )[Vector2i( x, 0 )], expected[x] ) << x; - } // use can nest elements deeper than XML does, so too deep nesting gives an error instead of overflowing the stack const auto chain = [&] ( int length ) @@ -243,7 +203,7 @@ TEST( MRIOExtras, SvgRasterizeUse ) std::string shapes = R"()"; for ( int i = 1; i <= length; ++i ) shapes += ""; - return rasterize( shapes + "" ); + return draw( shapes + "" ); }; const auto deep = chain( 200 ); ASSERT_FALSE( deep ); @@ -251,19 +211,6 @@ TEST( MRIOExtras, SvgRasterizeUse ) const auto shallow = chain( 50 ); ASSERT_TRUE( shallow ) << shallow.error(); EXPECT_EQ( ( *shallow )[Vector2i( 0, 0 )], Color::black() ); - - const std::pair errors[] = { - { R"svg()svg", "SVG use references form a cycle" }, - { R"svg()svg", "SVG use references form a cycle" }, - { R"svg()svg", "Unsupported SVG element symbol" }, - { R"svg()svg", "Unsupported SVG use reference other.svg#a" }, - }; - for ( const auto& [shapes, error] : errors ) - { - const auto res = rasterize( shapes ); - ASSERT_FALSE( res ) << shapes; - EXPECT_EQ( res.error(), error ); - } } // a zero-length subpath draws only its caps, which are nothing for butt caps @@ -271,8 +218,7 @@ TEST( MRIOExtras, SvgRasterizeDot ) { const auto dot = [] ( const std::string& cap ) { - const auto svg = R"()"; - return ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); + return rasterize( R"()", { 8, 8 } ); }; const auto round = dot( "round" ); ASSERT_TRUE( round ) << round.error(); @@ -289,8 +235,7 @@ TEST( MRIOExtras, SvgRasterizeDot ) // a stroked circle is closed, so it has a join and no notch between two caps at its seam on the right TEST( MRIOExtras, SvgRasterizeCircleSeam ) { - const std::string svg = R"()"; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 64, 64 } ); + const auto image = rasterize( R"()", { 64, 64 } ); ASSERT_TRUE( image ) << image.error(); // 8 pixels outward from the seam, and from the opposite point EXPECT_EQ( ( *image )[Vector2i( 56, 31 )], ( *image )[Vector2i( 7, 31 )] ); @@ -303,7 +248,7 @@ TEST( MRIOExtras, SvgRasterizeAspectRatio ) const std::string svg = R"()"; for ( const auto& res : { Vector2i( 4, 2 ), Vector2i( 2, 4 ) } ) { - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), res ); + const auto image = rasterize( svg, res ); ASSERT_TRUE( image ) << image.error(); // columns or rows 0 and 3 are empty for ( int y = 0; y < res.y; ++y ) @@ -315,10 +260,9 @@ TEST( MRIOExtras, SvgRasterizeAspectRatio ) // currentColor is the color property of the drawn element even if it is inherited or set after it TEST( MRIOExtras, SvgRasterizeCurrentColor ) { - const std::string svg = R"()" + const auto image = rasterize( R"()" R"()" - R"()"; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 9, 3 } ); + R"()", { 9, 3 } ); ASSERT_TRUE( image ) << image.error(); for ( int x : { 1, 4, 7 } ) EXPECT_EQ( ( *image )[Vector2i( x, 1 )], Color( 255, 0, 0 ) ) << x; @@ -327,10 +271,9 @@ TEST( MRIOExtras, SvgRasterizeCurrentColor ) // elements and attributes that would be drawn wrong give errors TEST( MRIOExtras, SvgRasterizeUnsupported ) { - const auto rasterize = [] ( const std::string& shapes ) + const auto draw = [] ( const std::string& shapes ) { - const auto svg = R"()" + shapes + ""; - return ImageLoad::fromSvg( svg.data(), svg.size(), { 2, 1 } ); + return rasterize( R"()" + shapes + "", { 2, 1 } ); }; const std::pair errors[] = { { "", "Unsupported SVG element svg" }, @@ -338,6 +281,7 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) { "", "Unsupported SVG element foreignObject" }, { "a", "Unsupported SVG element text" }, { "", "Unsupported SVG element style" }, + { R"svg()svg", "Unsupported paint url(#g)" }, { R"svg()svg", "Unsupported SVG attribute mask" }, { R"svg()svg", "Unsupported SVG attribute filter" }, { R"()", "Invalid stroke-dasharray 1 -1" }, @@ -350,25 +294,31 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) { R"()", "Unsupported SVG attribute vector-effect" }, { R"()", "Unsupported SVG attribute mix-blend-mode" }, { R"()", "Unsupported SVG attribute paint-order" }, + { R"svg()svg", "SVG use references form a cycle" }, + { R"svg()svg", "SVG use references form a cycle" }, + { R"svg()svg", "Unsupported SVG element symbol" }, + { R"svg()svg", "Unsupported SVG use reference other.svg#a" }, { R"()", "SVG coordinates out of range" }, { R"()", "SVG coordinates out of range" }, { R"()", "SVG coordinates out of range" }, + // FreeType's rasterizer never ends on an edge of 32768 pixels or longer, as in this fill or the caps of this stroke + { R"()", "SVG coordinates out of range" }, + { R"()", "SVG coordinates out of range" }, }; for ( const auto& [shapes, error] : errors ) { - const auto image = rasterize( shapes ); + const auto image = draw( shapes ); ASSERT_FALSE( image ) << shapes; EXPECT_EQ( image.error(), error ); } - const std::string stretched = R"()"; - const auto unsupportedAspect = ImageLoad::fromSvg( stretched.data(), stretched.size(), { 2, 2 } ); + const auto unsupportedAspect = rasterize( R"()", { 2, 2 } ); ASSERT_FALSE( unsupportedAspect ); EXPECT_EQ( unsupportedAspect.error(), "Unsupported SVG attribute preserveAspectRatio" ); // a is a group, currentColor is black, default values are supported, hidden elements are not drawn even if they are unsupported; // text without content and a symbol not drawn by use draw nothing - const auto image = rasterize( R"()" R"(a)" R"()" ); @@ -377,73 +327,39 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color::transparent() ); } -// FreeType's rasterizer never ends on an edge of 32768 pixels or longer, as in this fill or the caps of this stroke -TEST( MRIOExtras, SvgRasterizeLongEdges ) -{ - for ( const std::string shape : { R"()", R"()" } ) - { - const auto svg = R"()" + shape + ""; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 64, 64 } ); - ASSERT_FALSE( image ) << shape; - EXPECT_EQ( image.error(), "SVG coordinates out of range" ); - } -} - TEST( MRIOExtras, SvgRasterizeDashes ) { - // a line through the only row of pixels, with dash ends on pixel borders - const auto row = [] ( const std::string& dashes ) + // a stroke through the only row of pixels, dash ends are on pixel borders; alpha of at least hi is '#', at most lo is '.', otherwise '?' + const auto row = [] ( const std::string& stroke, int lo = 0, int hi = 255 ) { - const auto svg = R"svg("; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 1 } ); + const auto image = rasterize( R"svg(", { 10, 1 } ); if ( !image ) return image.error(); std::string res; for ( const auto& c : image->pixels ) - res += c.a == 255 ? '#' : c.a == 0 ? '.' : '?'; + res += c.a >= hi ? '#' : c.a <= lo ? '.' : '?'; return res; }; - EXPECT_EQ( row( R"(stroke-dasharray="2")" ), "##..##.." ); - EXPECT_EQ( row( R"(stroke-dasharray="2 2" stroke-dashoffset="1")" ), "#..##..#" ); - EXPECT_EQ( row( R"(stroke-dasharray="2,2" stroke-dashoffset="-1")" ), ".##..##." ); - EXPECT_EQ( row( R"(style="stroke-dasharray: 1, 2, 3")" ), "#..###.#" ); - EXPECT_EQ( row( R"(stroke-dasharray="0 0")" ), "########" ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="2")" ), "##..##...." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="2 2" stroke-dashoffset="1")" ), "#..##..#.." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="2,2" stroke-dashoffset="-1")" ), ".##..##..." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" style="stroke-dasharray: 1, 2, 3")" ), "#..###.#.." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="0 0")" ), "########.." ); + // a zero-length dash at the start is a dot of round caps, and no dash starts at the end of a path + EXPECT_EQ( row( R"(d="M0.5 .5H9.5" stroke-linecap="round" stroke-dasharray="0 3")", 15, 129 ), "#..#..#..." ); + EXPECT_EQ( row( R"(d="M1 .5H9" stroke-linecap="round" stroke-dasharray="2")", 15, 129 ), "?##??##?.." ); + // the pattern goes on through the vertices of a polyline, and its lengths are transformed as the stroke width - const std::string polyline = R"svg()svg"; - const auto image = ImageLoad::fromSvg( polyline.data(), polyline.size(), { 16, 2 } ); + const auto image = rasterize( R"svg()svg", { 16, 2 } ); ASSERT_TRUE( image ) << image.error(); for ( int x = 0; x < 16; ++x ) - { EXPECT_EQ( ( *image )[Vector2i( x, 1 )].a, x % 4 < 2 ? 255 : 0 ) << x; - } - - // a zero-length dash at the start is a dot of round caps, and no dash starts at the end of a path - const auto roundRow = [] ( const std::string& d, const std::string& dashes ) - { - const auto svg = R"()"; - const auto roundImage = ImageLoad::fromSvg( svg.data(), svg.size(), { 10, 1 } ); - if ( !roundImage ) - return roundImage.error(); - std::string res; - for ( const auto& c : roundImage->pixels ) - res += c.a > 128 ? '#' : c.a < 16 ? '.' : '?'; - return res; - }; - EXPECT_EQ( roundRow( "M0.5 .5H9.5", "0 3" ), "#..#..#..." ); - EXPECT_EQ( roundRow( "M1 .5H9", "2" ), "?##??##?.." ); - - // a dash through the start of a closed path has a join there instead of two caps, so the outer corner is filled - const std::string closed = R"()"; - const auto closedImage = ImageLoad::fromSvg( closed.data(), closed.size(), { 12, 8 } ); - ASSERT_TRUE( closedImage ) << closedImage.error(); - EXPECT_EQ( ( *closedImage )[Vector2i( 0, 7 )], Color::black() ); } // a miter limit beyond the range of FreeType's fixed-point format still gives miter joins TEST( MRIOExtras, SvgRasterizeMiterLimit ) { - const std::string svg = R"()"; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 8, 8 } ); + const auto image = rasterize( R"()", { 8, 8 } ); ASSERT_TRUE( image ) << image.error(); // the tip of the miter at the top-left corner EXPECT_EQ( ( *image )[Vector2i( 0, 7 )], Color::black() ); @@ -452,9 +368,8 @@ TEST( MRIOExtras, SvgRasterizeMiterLimit ) // an icon as exported from Figma, whose clip path covers the whole icon TEST( MRIOExtras, SvgRasterizeFigmaIcon ) { - const std::string svg = R"svg()svg" - R"()"; - const auto image = ImageLoad::fromSvg( svg.data(), svg.size(), { 24, 24 } ); + const auto image = rasterize( R"svg()svg" + R"()", { 24, 24 } ); ASSERT_TRUE( image ) << image.error(); EXPECT_EQ( ( *image )[Vector2i( 12, 12 )], Color( 0x1C, 0x9C, 0x01 ) ); EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::transparent() ); From 5d98c84680d728d6f72a5ee631aab9b799d2cf90 Mon Sep 17 00:00:00 2001 From: Grant Karapetyan Date: Thu, 3 Dec 2026 21:08:04 +0400 Subject: [PATCH 16/16] Return SVG rasterization errors for skewed strokes, units, bad resolutions and fan-out Strokes under non-uniform scale or skew, units other than px, a resolution out of 1..32767 and more than 100000 drawn elements give errors; the header says the function is meant for small images. Co-Authored-By: Claude Opus 5.5 --- source/MRIOExtras/MRSvg.cpp | 22 ++++++++++++++++------ source/MRIOExtras/MRSvg.h | 5 +++-- source/MRTest/MRSvgTests.cpp | 31 ++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 11 deletions(-) diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index 196c8ab0f4ae..ddf6b6edcea0 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -313,11 +313,12 @@ Expected parseTransform( std::string_view str ) return result; } -// parses a number ignoring the units after it +// parses a number with an optional px unit; other units would be ignored, which gives wrong values Expected parseNumber( std::string_view str ) { float result = 0.f; - if ( !phrase_parse( str.begin(), str.end(), float_, space, result ) ) + auto it = str.begin(); + if ( !phrase_parse( it, str.end(), float_ >> -lit( "px" ), space, result ) || it != str.end() ) return unexpected( "Failed to parse number " + std::string( str ) ); return result; } @@ -325,7 +326,8 @@ Expected parseNumber( std::string_view str ) Expected> parseNumbers( std::string_view str ) { std::vector results; - if ( !phrase_parse( str.begin(), str.end(), float_ % -lit( ',' ), space, results ) ) + auto it = str.begin(); + if ( !phrase_parse( it, str.end(), ( float_ >> -lit( "px" ) ) % -lit( ',' ), space, results ) || it != str.end() ) return unexpected( "Failed to parse numbers " + std::string( str ) ); return results; } @@ -774,7 +776,8 @@ class SvgLoader Expected rasterize( const Vector2i& resolution ) { // FT_Span.x is short in older FreeType versions - assert( resolution.x > 0 && resolution.y > 0 && resolution.x <= 32767 && resolution.y <= 32767 ); + if ( !( resolution.x > 0 && resolution.y > 0 && resolution.x <= 32767 && resolution.y <= 32767 ) ) + return unexpected( "Invalid image resolution" ); // collects the elements that use can draw; style sheets restyle the drawn elements, so ignoring them would give a wrong image bool styleSheet = false; const auto collect = [&] ( const auto& self, XMLElement* elem ) -> void @@ -837,9 +840,11 @@ class SvgLoader // draws the element with its children over the canvas Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas, int depth ) { - // use nests elements deeper than XML does, which would overflow the stack + // use nests elements deeper than XML does, which would overflow the stack, and can multiply them without bound if ( depth >= 128 ) return unexpected( "SVG nesting is too deep" ); + if ( ++numDrawn_ > 100000 ) + return unexpected( "SVG has too many elements to draw" ); const std::string_view name = elem->Name(); // use draws the element it references as its only child const bool use = name == "use"; @@ -916,6 +921,10 @@ class SvgLoader // pathLength rescales the dashes if ( !style.dashes.empty() && elem->Attribute( "pathLength" ) ) return unexpected( "Unsupported SVG attribute pathLength" ); + // the stroke is drawn with a round pen in pixels, which is right only if the transform keeps circles + const auto n = xf.A.x.lengthSq() + xf.A.y.lengthSq(); + if ( std::abs( xf.A.x.lengthSq() - xf.A.y.lengthSq() ) > 1e-4f * n || std::abs( dot( xf.A.x, xf.A.y ) ) > 1e-4f * n ) + return unexpected( "Unsupported SVG stroke under non-uniform scale or skew" ); const auto pixelScale = std::sqrt( std::abs( xf.A.det() ) ); if ( auto res = stroke( library, *contours, style, pixelScale, premultiplied( *color, style.strokeOpacity ), target ); !res ) return res; @@ -1236,10 +1245,11 @@ class SvgLoader private: tinyxml2::XMLDocument doc_; - // the root element if it is svg, elements by their ids, and the elements being drawn by use to detect cycles + // the root element if it is svg, elements by their ids, the elements being drawn by use to detect cycles, and the number of drawn elements XMLElement* svg_ = nullptr; HashMap ids_; std::vector useTargets_; + size_t numDrawn_ = 0; }; } // namespace diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index 4841f3dbac01..0fb2ae4f8a4c 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -23,10 +23,11 @@ MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const namespace MR::ImageLoad { -/// rasterizes .SVG file into an image of given resolution, the view box is fitted in the center keeping its aspect ratio; +/// rasterizes .SVG file into an image of given resolution (from 1 to 32767 in each dimension), the view box is fitted in the center keeping its aspect ratio; +/// meant for small images like icons, since curves are flattened into 32 segments each whatever the resolution; /// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit, dashes), /// group and element opacity, display none, use of elements in the document; other paints (gradients, patterns, named colors other than black and white), -/// drawn image, text with content, switch, foreignObject, nested svg elements, use of symbol, +/// drawn image, text with content, switch, foreignObject, nested svg elements, use of symbol, strokes under non-uniform scale or skew, units other than px, /// style sheets, mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, pathLength of dashed strokes, preserveAspectRatio other than xMidYMid meet; /// other elements and attributes (e.g. clip-path, visibility) are ignored MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index f2b27ba95a23..bd406aedaa80 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -304,6 +304,11 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) // FreeType's rasterizer never ends on an edge of 32768 pixels or longer, as in this fill or the caps of this stroke { R"()", "SVG coordinates out of range" }, { R"()", "SVG coordinates out of range" }, + { R"svg()svg", "Unsupported SVG stroke under non-uniform scale or skew" }, + { R"svg()svg", "Unsupported SVG stroke under non-uniform scale or skew" }, + { R"()", "Failed to parse number 0.5mm" }, + { R"()", "Failed to parse number 50%" }, + { R"()", "Invalid stroke-dasharray 1px 2em" }, }; for ( const auto& [shapes, error] : errors ) { @@ -316,9 +321,29 @@ TEST( MRIOExtras, SvgRasterizeUnsupported ) ASSERT_FALSE( unsupportedAspect ); EXPECT_EQ( unsupportedAspect.error(), "Unsupported SVG attribute preserveAspectRatio" ); - // a is a group, currentColor is black, default values are supported, hidden elements are not drawn even if they are unsupported; - // text without content and a symbol not drawn by use draw nothing - const auto image = draw( R"()", res ); + ASSERT_FALSE( invalid ) << res.x << " " << res.y; + EXPECT_EQ( invalid.error(), "Invalid image resolution" ); + } + + // use can multiply the drawn elements beyond any limit: here 10^6 empty groups + std::string fanOut = R"()"; + for ( int i = 1; i <= 6; ++i ) + { + fanOut += ""; + for ( int j = 0; j < 10; ++j ) + fanOut += ""; + fanOut += ""; + } + const auto tooMany = draw( fanOut + R"()" ); + ASSERT_FALSE( tooMany ); + EXPECT_EQ( tooMany.error(), "SVG has too many elements to draw" ); + + // a is a group, currentColor is black, default values and px are supported, hidden elements are not drawn even if they are unsupported; + // text without content and a symbol not drawn by use draw nothing; a fill is right under any transform + const auto image = draw( R"svg()" R"(a)" R"()" );