Skip to content

programmatic video rendering framework that is actually fast

fix(svgr): draw a numeric font-weight expression at its weight (#204)

Ian Tomkins23e607e4dd4b
diff --git a/AGENTS.md b/AGENTS.md
index 5e823458..b8cca4fe 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -427,8 +427,8 @@ let paragraph = frame.text_break_lines(ctx, self.description, BreakLinesOpts {
```
Use the same `FontQuery` values in the `<text>` attributes (`font-family`, `font-size`,
-`font-weight`) so what is measured is what is drawn. `font-weight` must be numeric or
-`normal`/`bold`.
+`font-weight`) so what is measured is what is drawn. `font-weight` is a number from 1 to
+1000, written or as `{expr}`, or `normal`/`bold`; a number outside that range is ignored.
### 6. Scenes (optional)
diff --git a/fframes-test-utils/_svgr_snapshots/$numeric_expressions.snapshot.txt b/fframes-test-utils/_svgr_snapshots/$numeric_expressions.snapshot.txt
new file mode 100644
index 00000000..a1b0dbde
--- /dev/null
+++ b/fframes-test-utils/_svgr_snapshots/$numeric_expressions.snapshot.txt
@@ -0,0 +1,11 @@
+(Compile-time)
+<svg width="400" height="300" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg">
+ <defs/>
+ <g>
+ <text xml:space="preserve"><tspan x="10" y="50"><tspan font-family="DM Sans" font-size="40" fill="#000000" stroke="none">Literal</tspan></tspan></text>
+ <text xml:space="preserve"><tspan x="10" y="100"><tspan font-family="DM Sans" font-weight="700" font-size="40" fill="#000000" stroke="none">u16</tspan></tspan></text>
+ <text xml:space="preserve"><tspan x="10" y="150"><tspan font-family="DM Sans" font-weight="650" font-size="40" fill="#000000" stroke="none">650</tspan></tspan></text>
+ <text xml:space="preserve"><tspan x="10" y="200"><tspan font-family="DM Sans" font-weight="551" font-size="40" fill="#000000" stroke="none">f32</tspan></tspan></text>
+ <text xml:space="preserve" rotate="20 20 20 20"><tspan x="10" y="250"><tspan font-family="DM Sans" font-weight="650" font-size="40" fill="#000000" stroke="none">Text</tspan></tspan></text>
+ </g>
+</svg>
diff --git a/fframes-test-utils/src/lib.rs b/fframes-test-utils/src/lib.rs
index 92034147..9677c7d9 100644
--- a/fframes-test-utils/src/lib.rs
+++ b/fframes-test-utils/src/lib.rs
@@ -27,12 +27,23 @@ fn read_snapshot(path: &std::path::Path) -> io::Result<String> {
})
}
+/// DM Sans Regular and Medium. usvgr drops text in a font it cannot find, so snapshots keep
+/// only the text in DM Sans.
+pub fn dm_sans() -> usvgr::fontdb::Database {
+ let mut fontdb = usvgr::fontdb::Database::default();
+ fontdb.load_font_data(include_bytes!("../../examples/beta/media/DMSans-Regular.ttf").to_vec());
+ fontdb.load_font_data(
+ include_bytes!("../../examples/hello-world/media/DMSans-Medium.ttf").to_vec(),
+ );
+ fontdb
+}
+
pub fn assert_compile_time_svgr_eq_runtime(name: &str, svgr: Svgr) {
let svgtree = svgr
.into_svg_tree(
&usvgr::Options::default(),
&mut usvgr::Cache::default(),
- &usvgr::fontdb::Database::default(),
+ &dm_sans(),
)
.unwrap();
diff --git a/fframes-test-utils/src/svgr_spec.rs b/fframes-test-utils/src/svgr_spec.rs
index cf721094..db803d1f 100644
--- a/fframes-test-utils/src/svgr_spec.rs
+++ b/fframes-test-utils/src/svgr_spec.rs
@@ -415,3 +415,155 @@ pub fn string_attributes_that_look_like_colors() {
),
);
}
+
+/// Converts with DM Sans Regular and Medium and writes the tree twice, with text kept and as
+/// paths, so both the resolved values and the face the text is drawn in are compared.
+fn written_with_fonts(svgr: fframes::Svgr) -> String {
+ let tree = svgr
+ .into_svg_tree(
+ &fframes::usvgr::Options::default(),
+ &mut fframes::usvgr::Cache::default(),
+ &crate::dm_sans(),
+ )
+ .unwrap();
+ let mut out = tree.to_string(&fframes::usvgr::WriteOptions {
+ preserve_text: true,
+ ..Default::default()
+ });
+ out.push_str(&tree.to_string(&fframes::usvgr::WriteOptions::default()));
+ out
+}
+
+/// A number from an expression renders like the same number written in the markup. In
+/// compile-time trees the expression is a number without text, in runtime ones it is text.
+#[test]
+pub fn numeric_expressions_render_like_literals() {
+ let (w700, w650, w1500): (u16, u16, u16) = (700, 650, 1500);
+ let w550 = 550.5_f32;
+ let (angle, origin, order) = (20.0_f32, 40_i32, 2_u8);
+
+ macro_rules! label {
+ ($($attr:tt)*) => {
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="400" height="100">
+ <text x="10" y="60" font-family="DM Sans" font-size="40" $($attr)*>"Ab"</text>
+ </svg>
+ )
+ };
+ }
+
+ let cases = [
+ (
+ "font-weight u16",
+ label!(font - weight = { w700 }),
+ label!(font - weight = "700"),
+ ),
+ (
+ "font-weight 650",
+ label!(font - weight = { w650 }),
+ label!(font - weight = "650"),
+ ),
+ (
+ "font-weight f32",
+ label!(font - weight = { w550 }),
+ label!(font - weight = "550.5"),
+ ),
+ (
+ "font-weight str",
+ label!(font - weight = { "bold" }),
+ label!(font - weight = "bold"),
+ ),
+ (
+ "font-weight String",
+ label!(font - weight = { w650.to_string() }),
+ label!(font - weight = "650"),
+ ),
+ (
+ "font-weight out of range",
+ label!(font - weight = { w1500 }),
+ label!(),
+ ),
+ (
+ "font-weight literal out of range",
+ label!(font - weight = "1500"),
+ label!(),
+ ),
+ ("rotate", label!(rotate = { angle }), label!(rotate = "20")),
+ (
+ "inherited font-weight",
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="400" height="100">
+ <g font-weight={w700}><text x="10" y="60" font-family="DM Sans" font-size="40">"Ab"</text></g>
+ </svg>
+ ),
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="400" height="100">
+ <g font-weight="700"><text x="10" y="60" font-family="DM Sans" font-size="40">"Ab"</text></g>
+ </svg>
+ ),
+ ),
+ (
+ "transform-origin",
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
+ <rect width="60" height="40" transform="rotate(30)" transform-origin={origin} />
+ </svg>
+ ),
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
+ <rect width="60" height="40" transform="rotate(30)" transform-origin="40" />
+ </svg>
+ ),
+ ),
+ (
+ "feConvolveMatrix order",
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
+ <filter id="f"><feConvolveMatrix order={order} kernelMatrix="1 0 0 1" /></filter>
+ <rect width="50" height="50" fill="red" filter="url(#f)" />
+ </svg>
+ ),
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
+ <filter id="f"><feConvolveMatrix order="2" kernelMatrix="1 0 0 1" /></filter>
+ <rect width="50" height="50" fill="red" filter="url(#f)" />
+ </svg>
+ ),
+ ),
+ ];
+ for (case, expression, literal) in cases {
+ assert_eq!(
+ written_with_fonts(expression),
+ written_with_fonts(literal),
+ "{case}"
+ );
+ }
+
+ // The weights have an effect: 650 is drawn in Medium, not in Regular.
+ assert_ne!(
+ written_with_fonts(label!(font - weight = { w650 })),
+ written_with_fonts(label!())
+ );
+}
+
+/// Numeric expressions give the same tree in compile-time and runtime mode.
+#[test]
+pub fn numeric_expressions() {
+ let (w700, w650, angle) = (700_u16, 650_u16, 20.0_f32);
+ let w550 = 550.5_f32;
+
+ assert_compile_time_svgr_eq_runtime(
+ "numeric_expressions",
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="400" height="300">
+ <g font-family="DM Sans" font-size="40">
+ <text x="10" y="50">"Literal"</text>
+ <text x="10" y="100" font-weight={w700}>"u16"</text>
+ <text x="10" y="150" font-weight={w650}>"650"</text>
+ <text x="10" y="200" font-weight={w550}>"f32"</text>
+ <text x="10" y="250" font-weight={w650.to_string()} rotate={angle}>"Text"</text>
+ </g>
+ </svg>
+ ),
+ );
+}
diff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.md
index 9ca552c8..67644c91 100644
--- a/skills/fframes-video/references/api.md
+++ b/skills/fframes-video/references/api.md
@@ -290,8 +290,9 @@ fframes::cli::new(&video, options)
- Zero width/height rects and zero radius circles are invalid SVG and are skipped (inspect
reports them): animate from `0.5`, not `0`.
- A panic in `render_frame` stops the render; the error names frame, second and scene.
-- `font-weight` must be numeric (`600`) or `normal`/`bold`. Unknown families fall back
- silently in the renderer, `inspect` reports "No match for ... font-family".
+- `font-weight` is a number from 1 to 1000 (`600`, `{weight}`) or `normal`/`bold`; a number
+ outside that range is ignored. Unknown families fall back silently in the renderer,
+ `inspect` reports "No match for ... font-family".
- `Color::TRANSPARENT` backgrounds need an alpha capable encoder and pixel format.
- Heavy filters (`feGaussianBlur`, `feDropShadow`) on animated subtrees are slow on the CPU
backend: keep them static or use Skia.
diff --git a/svgr-macro/src/nodes_to_svgtree.rs b/svgr-macro/src/nodes_to_svgtree.rs
index 427cc77c..f6aec018 100644
--- a/svgr-macro/src/nodes_to_svgtree.rs
+++ b/svgr-macro/src/nodes_to_svgtree.rs
@@ -179,6 +179,15 @@ fn accepts_color(aid: AId) -> bool {
)
}
+/// Attributes usvgr reads as a transform. A literal of any other attribute stays text, even
+/// when it parses as one: an empty value parses as the identity transform.
+fn accepts_transform(aid: AId) -> bool {
+ matches!(
+ aid,
+ AId::Transform | AId::GradientTransform | AId::PatternTransform
+ )
+}
+
fn inline_attribute_value(value: &str, aid: AId, element: EId) -> TokenStream {
// Special handling for path data - parse at compile time
if aid == AId::D {
@@ -225,7 +234,10 @@ fn inline_attribute_value(value: &str, aid: AId, element: EId) -> TokenStream {
quote! {
SvgAttributeValue::Length(#length)
}
- } else if let Ok(transform) = svgtree::svgrtypes::Transform::from_str(value) {
+ } else if let Some(transform) = accepts_transform(aid)
+ .then(|| svgtree::svgrtypes::Transform::from_str(value).ok())
+ .flatten()
+ {
quote! {
SvgAttributeValue::Transform(#transform)
}
@@ -999,3 +1011,21 @@ pub fn nodes_to_svgtree(
Ok(output_tree)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_transform_attributes_get_a_transform() {
+ let tokens = |value, aid| inline_attribute_value(value, aid, EId::Rect).to_string();
+ assert!(tokens("rotate(30)", AId::Transform).contains("Transform"));
+ assert!(tokens("rotate(30)", AId::GradientTransform).contains("Transform"));
+ // An empty value parses as the identity transform but is text for usvgr.
+ for aid in [AId::FontFamily, AId::Class, AId::D, AId::TransformOrigin] {
+ let value = tokens("", aid);
+ assert!(!value.contains("Transform"), "{:?}: {}", aid, value);
+ assert!(value.contains("StringStorage"), "{:?}: {}", aid, value);
+ }
+ }
+}