svg
Garnet SVG
garnet-svg is an optional format adapter over garnet-vector. It loads a bounded SVG document profile into immutable Graphics::Drawing objects, and parses standalone path data into Vector::Path. It does not initialize a renderer or require ECS.
Documents
require "garnet-svg"
document = Garnet::SVG::Document.parse(File.read("icon.svg"))
texture = renderer.render(document.drawing, document.target)
# Or place it in a scene when garnet-scene is installed:
entity << Garnet::Graphics::Components::Picture.new(document.drawing)
The document loader uses Crystal's standard XML module backed by libxml2. Its initial profile supports:
- Root and nested
svg, nestedg, andpath,rect,circle,ellipse,line,polyline,polygon. Rectangle corners can have distinctrx/ryvalues. Zero-sized shapes emit no geometry. - Local
<defs>and<use href="#id">instances of shapes, groups, other instances, nested SVGs and<symbol>definitions, including forward references. Each instance inherits its own styles; explicit styles on the referenced elements override them. Definition ancestors do not supply instance inheritance. Instance x/y translation follows its transform, and opacity applies after composing the referenced content. Width/height override an SVG or symbol instance's viewport and are only validated for other targets. Legacyxlink:hrefis accepted; unnamespacedhreftakes precedence. Missing references, duplicate IDs, external references and recursive instances raise. - Root and nested
viewBoxandpreserveAspectRatio:noneor all nine alignments withmeet/slice. Nested SVG and symbol viewports clip overflowing content. Nested x/y/width/height and viewport-instance x/y/width/height accept percentages relative to the enclosing user viewport as well as unitless orpxvalues. Omitted nested extents use the enclosing viewport; zero extents suppress the subtree and negative extents raise. Root width/height default to viewBox dimensions when available, otherwise 300×150. Positive root viewport extents up to 16384 are accepted;targetrounds fractional pixel dimensions up. - SVG transform lists: matrix, translate, scale, rotate (including pivot), skewX and skewY. Angles are degrees.
Garnet::SVG.parse_transformexposes this separately. Root transforms apply outside the viewBox transform. - Inherited fill, stroke, color, fill-rule, fill/stroke opacity, stroke width/caps/joins/miter limit/dashes/offset. Presentation attributes and supported inline
styledeclarations are accepted; inline declarations take precedence.inheritis supported for these inherited properties. Dashes follow the vector profile's strictly-positive entry restriction. - Solid paints:
none,currentColor,#RGB,#RGBA,#RRGGBB,#RRGGBBAA; named black, white, red, green, blue, yellow, cyan, magenta, gray/grey and transparent. sRGB channels are converted to the graphics core's linear colors. Other color syntaxes raise. - Linear and two-circle radial gradient paint servers for fills/strokes via local
url(#id)references (optionally quoted). Radial gradients support independentfx,fy, and SVG 2frfocal circles. BothobjectBoundingBoxanduserSpaceOnUseunits, gradient transforms, pad/repeat/reflect spread, numeric/percentage coordinates and offsets, stop color/opacity, and local href/xlink templates are supported. Object bounds use analytic path extrema and exclude stroke expansion. Definition styles inherit from XML ancestors, independently of the painted element; template stop content inherits from the requesting gradient. Gradient colors interpolate with straight alpha in sRGB by default, or linear RGB viacolor-interpolation="linearRGB"(autochooses sRGB). - Local vector
<pattern>paint servers for fills and strokes. Tile and content coordinates independently supportobjectBoundingBoxanduserSpaceOnUse; x/y/width/height,patternTransform, inherited href/xlink templates, nested drawing content, paint opacity, and transparent tile space lower to the generic retained drawing-pattern operation. A finite tile target is selected from its transformed local size, capped at 16384 pixels per axis, then each renderer keeps the result in its ordinary GPU output path. - Raster
<image>elements supplied through an explicitImageResolverproc. The resolver maps each href to a genericGraphics::Texture; the loader caches that result for the rest of the parse and never opens a URL or selects an image decoder itself. Image x/y/width/height support viewport percentages, omitted dimensions preserve the texture's intrinsic aspect,preserveAspectRatiouses the same meet/slice mapping as nested viewports, overflow is clipped to the declared image rectangle, and sampling is linear. Legacyxlink:hrefis accepted. - Local
filterresources containing a single sequential chain offeGaussianBlurandfeColorMatrix. Matrix, saturate, hue-rotation and luminance-to-alpha color matrices lower to generic linear-RGB effects. Blur supports one or two deviations, transparent edges,userSpaceOnUseorobjectBoundingBoxprimitive units, document/scene scaling and uniform rotation. Filter regions support user/object coordinates and clip the final result before the element's clip, mask and opacity. - Local
clip-pathandmaskreferences on shapes, groups and instances, lowered to the shared drawing layers. Clip paths combine raw child geometry usingclip-rule, independent of paint, stroke and opacity. Masks render their contents normally and then use alpha or luminance coverage. Both support user-space and object-relative coordinates, including analytic bounds of transformed group geometry. - Group/element
opacityas a composition layer after children (or fill and stroke) are composed.display="none"suppresses a subtree; visibility inherits and can be overridden by children.title,desc,metadata, comments, IDs/classes and data/ARIA attributes do not create drawing operations.
Viewport mapping follows the SVG viewport transform algorithm. The immutable drawing retains no XML nodes or document source text. Use recorder.draw(document.drawing) to compose it into another drawing, or a scene Picture component for ordinary entity placement. Gradient loading follows the SVG paint-server semantics. Existing masks, clipping, pattern tiles and render-to-texture remain available to callers.
This is an explicit subset. Unsupported elements, rendering attributes and styles raise ArgumentError; malformed XML raises a wrapped ArgumentError. Automatic external-resource loading, DTDs, processing instructions, percentage shape lengths and physical lengths, CSS stylesheets/selectors, pattern viewBox/preserveAspectRatio, symbol refX/refY, viewport overflow overrides, CSS basic-shape clips, mask image lists, text and animation are not loaded yet. Input is UTF-8 XML; only an application-provided image resolver can interpret an image href. Paint URL fallbacks remain unsupported. Singular paint-server transforms raise. Empty gradients and zero-sized patterns paint nothing; one-stop and zero outer-radius gradients paint the final stop color; coincident focal/end circles paint nothing; negative radii or pattern extents raise. Stop offsets clamp to 0–1 and cannot decrease. Object-relative paints on zero-width/height geometry paint nothing, including strokes. The renderer limit of 16 gradient stops still applies. color-interpolation is supported for gradient stops and mask luminance; scene compositing remains the graphics core's linear-premultiplied profile. Zero/negative viewBox or root viewport extents are rejected by this profile rather than producing disabled rendering.
The filter profile deliberately rejects arbitrary result graphs, non-SourceGraphic inputs, primitive subregions, nontransparent blur edge modes, rotated anisotropic kernels and filter color spaces other than linear RGB. Other SVG filter primitives remain unsupported. Empty filters pass the source through the declared filter region; zero blur deviations are pass-through. Filter and geometry expansion share the document limits.
Document.load(source) reads a Garnet::Content::Source (at most max_bytes plus one byte) and accepts the same limits and image_resolver: as parse. Alternatively pass resolve: Proc(String, Garnet::Content::Source) with decoder: Graphics::ImageDecoder, the same keywords as Garnet::GLTF.load, to load each image href as a texture. Requiring the shard registers a default "svg" importer for .svg (see content).
Document.parse accepts max_bytes: 1_048_576, max_elements: 10_000, and max_depth: 64. Limits must be positive. An initial index bounds all XML elements, including definitions and metadata, and rejects duplicate IDs. Drawing expansion separately uses the same element and depth budgets, including each instance, gradient template, stop, effect resource and geometry-bounds expansion; root depth is zero. Definitions do not render directly, and their descendants are interpreted only when instantiated. Unsupported rendering features inside unused definitions are therefore not evaluated. Existing path parsing and tessellation limits also apply. Retain a parsed document/drawing for reuse; loading does not introduce a hidden global cache.
Clipping and masks
This profile implements local SVG resources using the CSS Masking composition model. The limits below remain explicit.
document = Garnet::SVG::Document.parse(<<-SVG)
<svg width="64" height="64">
<defs>
<clipPath id="round"><circle cx="32" cy="32" r="28"/></clipPath>
<mask id="fade" maskContentUnits="objectBoundingBox" mask-type="alpha">
<rect width="1" height="1" fill="white" opacity=".6"/>
</mask>
</defs>
<g clip-path="url(#round)" mask="url(#fade)">
<rect width="64" height="64" fill="blue"/>
</g>
</svg>
SVG
clipPathUnits defaults to userSpaceOnUse. Clips accept paths/basic shapes and <use> that directly references a shape; group or indirect-use clip children raise. Child silhouettes form a union, nested clips intersect, and invisible children do not contribute. clip-rule inherits from the definition tree, independently of the referencing element. An empty clip hides all content.
maskUnits defaults to objectBoundingBox; maskContentUnits defaults to userSpaceOnUse. The mask region uses numeric/percentage x/y/width/height, defaulting to -10%, -10%, 120%, 120%. It clips mask content independently of content coordinates. Zero extents hide content; negative extents raise. Object-relative effects with zero-area geometry hide content. Bounds exclude stroke expansion and display:none subtrees, but include unpainted or visibility:hidden geometry and ignore clipping/masking. Geometry walks share the expansion budget.
mask-type accepts alpha or luminance (default). Luminance uses sRGB unless the mask's inherited color-interpolation is linearRGB; intermediate drawing composition still follows Garnet's linear-premultiplied profile. Mask content can contain supported groups, instances, gradients, clips and masks. Effects apply after composing children: clip, mask, then element opacity. Resource styles come from definition ancestors. Display on the mask/clipPath resource itself does not disable references; mask-resource opacity is ignored. Child display/opacity follow their normal rules (clip geometry ignores opacity).
References accept none or one local url(#id) (optionally quoted). Missing/wrong-kind/external references and expanded cycles raise. CSS-wide effect keywords, mask-mode overrides, mask lists and URL fallbacks are not implemented.
Path data
Use require "garnet-svg/path" when only path-data parsing is needed; that export does not require libxml2.
require "garnet-svg/path"
path = Garnet::SVG.parse_path("M8 8h24v24H8z m6 6v12h12V14z")
drawing = Garnet::Graphics::Drawing.record do |canvas|
canvas.fill(path, Garnet::Color::WHITE, rule: :even_odd)
end
The parser supports all ten SVG path commands: M, L, H, V, C, S, Q, T, A, Z, including lowercase relative forms. It handles implicit repeated argument groups, implicit lines after moveto, compact signs/decimal points/exponents, adjacent arc flags, and reflected controls for smooth curves. Arc rotation uses degrees; endpoint geometry and radius correction delegate to the vector shard's analytic arc implementation.
parse_path(data, max_segments: 65_536, max_bytes: 1_048_576) returns a complete immutable path or raises Garnet::SVG::ParseError, with a zero-based byte offset. Invalid data does not return partial geometry. Empty/whitespace-only data produces an empty path. Nonfinite numbers and unsupported numeric ranges are rejected. The segment budget counts every explicit or implicit command group, including moves and closes. This API accepts a d attribute's contents, not XML or a CSS path(...) expression.
From this shard, run shards install then crystal spec (libxml2 is required for document tests). crystal spec spec/path_data_spec.cr verifies the path-only export. Workspace checks use scripts/check-composition unit and its gl, gles, metal, vulkan modes for parsed-geometry and document rendering.
svg
- 0
- 0
- 0
- 1
- 2
- 1 day ago
- November 30, 2026
MIT License
Wed, 02 Dec 2026 02:09:32 GMT