diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0186c76f..1c7626aa 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1172,6 +1172,54 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() { } +/// ADR 0099: text with filters reaches the renderers as a filtered group like a movie clip's +/// (no pass changed), so the GPU stage draws it as the oracle does: static text with a bevel, +/// and a half-transparent dynamic field (box, clipped text and border) with a shadow and a +/// glow. +#[test] +fn gpu_matches_the_oracle_on_filtered_text() { + use anicraft_doc::{Filter as F, FilterSide, TextBlock, TextField, TextKind}; + let Some(g) = gpu() else { return }; + let mut glyphs = Path::ellipse(30.0, 22.0, 18.0, 14.0); + glyphs.cmds.extend(Path::rect(56.0, 8.0, 14.0, 30.0).cmds); + glyphs.cmds.extend(Path::rect(78.0, 8.0, 60.0, 9.0).cmds); + let block = |field: Option, filters: Vec| TextBlock { + text: "Hi".into(), + font: "Test".into(), + size: 30.0, + bold: false, + italic: false, + color: Rgba::new(0.1, 0.2, 0.5, 1.0), + align: Default::default(), + letter_spacing: 0.0, + line_spacing: 0.0, + width: None, + outline: Arc::new(glyphs.clone()), + box_width: 120.0, + box_height: 44.0, + field, + on_path: None, + filters: filters.into_iter().map(anicraft_doc::FilterEntry::from).collect(), + }; + let mut field = TextField::new(TextKind::Dynamic); + (field.border, field.background, field.background_color) = (true, true, Rgba::new(1.0, 0.95, 0.8, 1.0)); + let shadow = F::DropShadow { blur_x: 6.0, blur_y: 6.0, strength: 0.8, quality: 2, angle: 45.0, distance: 8.0, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false }; + let glow = F::Glow { blur_x: 10.0, blur_y: 10.0, strength: 1.5, quality: 2, color: Rgba::new(1.0, 0.3, 0.1, 1.0), inner: false, knockout: false }; + let bevel = F::Bevel { blur_x: 4.0, blur_y: 4.0, strength: 1.2, quality: 2, angle: 45.0, distance: 3.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: FilterSide::Inner, knockout: false }; + let mut doc = anicraft_doc::Document { stage: anicraft_doc::Stage { width: 220, height: 160, fps: 24.0, background: Rgba::new(0.9, 0.95, 1.0, 1.0) }, ..Default::default() }; + let text = |id: u64, at: (f32, f32), color: ColorEffect, block: TextBlock| Arc::new(anicraft_doc::Element { id: ElementId(id), name: String::new(), transform: Affine::translate(at.0, at.1).mul(&Affine::rotate(0.08)), color, kind: ElementKind::Text(Arc::new(block)) }); + let els = vec![text(1, (20.0, 12.0), ColorEffect::default(), block(None, vec![bevel])), text(2, (40.0, 84.0), ColorEffect::Alpha(0.5), block(Some(field), vec![shadow, glow]))]; + if let Some(k) = Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0) { + k.elements = els; + } + let dl = anicraft_doc::evaluate(&doc, 0); + assert_eq!(dl.groups.iter().map(|g| g.filters.len()).collect::>(), [1, 2], "each text is a filtered group"); + for s in [1.0f32, 0.5, 1.7] { + let d = assert_parity(g, "filtered text", &dl, &View::stage(&doc, s)); + eprintln!("filtered text at {s}: mean {:.5} / max {} / {} of {} px differ", d.mean, d.max, d.differing, d.pixels); + } +} + // ----- binning on the GPU (ADR 0048) ---------------------------------------------------------- /// Scenes the GPU bins (no fill in a mask or a group): the analytic ones, the sample, stress diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 7f05f22a..fdae1e74 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -102,6 +102,9 @@ pub struct HtmlExport { const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)"; const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)"; const NINE_SLICE: &str = "9-slice scaling (scaled as a whole)"; +/// An input field is a real form element over the canvas (ADR 0066): what is typed is the +/// browser's to draw, so the filters reach the field's box, border and authored text only. +const INPUT_FILTERS: &str = "filters on input text (typed text is drawn by the browser, without them)"; const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)"; const WARPED_BITMAPS: &str = "warped bitmaps (the image shows unbent inside its bent outline; warped shapes come across)"; const FIELD_FONTS: &str = "text fields (their authored text keeps its outlines; text a script or the viewer changes is drawn with the browser's fonts)"; @@ -200,6 +203,17 @@ fn filter_json(f: &anicraft_doc::Filter) -> Value { } } +/// An item's filters, on a symbol instance or on text (ADR 0099). Filters run in the page as +/// the renderer runs them (ADR 0072): `fx` the list, `fm` how far they reach together (stage +/// pixels). Filters switched off are left out, as the renderer leaves them (ADR 0091). +fn filters_json(filters: &[anicraft_doc::FilterEntry], item: &mut Map) { + let on = anicraft_doc::active_filters(filters); + if !on.is_empty() { + item.insert("fx".into(), Value::Array(on.iter().map(filter_json).collect())); + item.insert("fm".into(), exact(on.iter().map(anicraft_doc::Filter::margin).sum::())); + } +} + fn color(c: Rgba) -> Vec { let c = c.sanitized(); [c.r, c.g, c.b, c.a].into_iter().map(|v| num(v, 10_000.0)).collect() @@ -576,6 +590,10 @@ impl<'a> Bake<'a> { } let mut item = Map::new(); item.insert("tf".into(), o); + filters_json(&t.filters, &mut item); + if f.kind == anicraft_doc::TextKind::Input && anicraft_doc::any_active_filter(&t.filters) { + self.notes.entry(INPUT_FILTERS).or_default().insert(el.id.0); + } item.insert("id".into(), json!(el.id.0)); if !el.name.is_empty() { item.insert("n".into(), json!(el.name)); @@ -633,7 +651,12 @@ impl<'a> Bake<'a> { } None => { let fill = Paint::Solid(t.color); - out.push(self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero)); + let mut item = self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero); + // Static text with filters draws in a group of its own, as a field does. + if let Some(o) = item.as_object_mut() { + filters_json(&t.filters, o); + } + out.push(item); } }, ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => { @@ -674,14 +697,7 @@ impl<'a> Bake<'a> { if !blend.is_normal() { o.insert("bl".into(), json!(blend.key())); } - // Filters run in the page as the renderer runs them (ADR 0072): `fx` the list, - // `fm` how far they reach together (stage pixels). - // Filters switched off are left out, as the renderer leaves them (ADR 0091). - let on = anicraft_doc::active_filters(filters); - if !on.is_empty() { - o.insert("fx".into(), Value::Array(on.iter().map(filter_json).collect())); - o.insert("fm".into(), exact(on.iter().map(anicraft_doc::Filter::margin).sum::())); - } + filters_json(filters, &mut o); if !events.is_empty() { o.insert("ev".into(), Value::Array(events.iter().map(|h| json!([h.event.key(), actions(&h.actions)])).collect())); } diff --git a/crates/render/src/html/player.js b/crates/render/src/html/player.js index 439cf6b4..43d44c8a 100644 --- a/crates/render/src/html/player.js +++ b/crates/render/src/html/player.js @@ -363,11 +363,25 @@ var AniCraft = (function () { } } const xf = mul(cx.xf, m); - if (e.tf) return evalField(e.tf, e.n || "", xf, concat(cx.c, fx), cx.group, clip, masks, dl, child, v); - if (e.y === undefined) { - const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, k: e.k || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group }; - dl.items.push(it); - if (v) v.item(it); + if (e.tf || e.y === undefined) { + // Text with filters draws in a group of its own, as a movie clip does (eval.rs, ADR + // 0099): the group fades at the text's alpha and its items keep the rest of the effect. + // (Mask artwork takes neither.) + const filters = masks === null && Array.isArray(e.fx) && e.fx.length ? e.fx : null; + let color = concat(cx.c, fx), group = cx.group; + if (filters) { + group = dl.groups.length; + dl.groups.push({ parent: cx.group, alpha: fx[7] === 0 ? Math.min(Math.max(fx[3], 0), 1) : 1, blend: "normal", clip: clip, filters: filters, margin: e.fm || 0 }); + color = concat(cx.c, fx[7] === 0 ? [fx[0], fx[1], fx[2], 1, fx[4], fx[5], fx[6], 0] : fx); + if (v) v.groupBegin(group, dl.groups[group]); + } + if (e.tf) evalField(e.tf, e.n || "", xf, color, group, clip, masks, dl, child, v); + else { + const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, k: e.k || null, eo: !!e.eo, c: color, clip: clip, masks: masks, group: group }; + dl.items.push(it); + if (v) v.item(it); + } + if (filters && v) v.groupEnd(group, dl.groups[group]); return; } const sym = M.symbols[e.y]; diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 6ad13d2c..99aacb10 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -1031,6 +1031,75 @@ fn text_fields_export_as_named_instances_and_static_text_as_before() { // ----- filters and per-pixel blending in the page (ADR 0072) ------------------------------------ /// A JavaScript engine with the page's filters. +/// ADR 0099: filters on text reach the page as an instance's do (`fx`, `fm`), switched-off ones +/// left out; the page's player draws the text in a filtered group exactly as `evaluate` does, +/// static text and fields alike; and what an input field can't show is reported. +#[test] +fn filters_on_text_reach_the_page_and_group_as_in_the_renderer() { + use anicraft_doc::{Filter, FilterEntry, TextField, TextKind}; + let with = |e: Arc, filters: Vec, color: ColorEffect| { + let mut e = (*e).clone(); + if let Some(list) = e.kind.filters_mut() { + *list = filters; + } + e.color = color; + Arc::new(e) + }; + let shadow = FilterEntry::from(Filter::new("drop_shadow").unwrap()); + let glow = FilterEntry::from(Filter::Glow { blur_x: 6.0, blur_y: 6.0, strength: 2.0, quality: 2, color: Rgba::hex(0x00aaff), inner: false, knockout: false }); + let off = FilterEntry { filter: Filter::new("blur").unwrap(), enabled: false }; + let mut note = TextField::new(TextKind::Dynamic); + (note.background, note.border) = (true, true); + let mut doc = Document { stage: anicraft_doc::Stage { width: 200, height: 120, fps: 24.0, background: Rgba::hex(0xffffff) }, ..Document::default() }; + let els = vec![ + // Static text with a glow, half transparent: the group fades, after the filters. + with(field_el(60, "", Vec2::new(5.0, 5.0), (40.0, 16.0), "Hi", None), vec![glow.clone()], ColorEffect::Alpha(0.5)), + // A dynamic field with a shadow (and a filter switched off): box, text and border as one. + with(field_el(61, "note_txt", Vec2::new(5.0, 30.0), (150.0, 40.0), "Hello", Some(note)), vec![off.clone(), shadow.clone()], ColorEffect::default()), + // An input field with a glow: the page's form element draws what is typed. + with(field_el(62, "name_txt", Vec2::new(5.0, 80.0), (90.0, 18.0), "", Some(TextField::new(TextKind::Input))), vec![glow.clone()], ColorEffect::default()), + // Text whose only filter is off, and plain text: as before, no group. + with(field_el(63, "", Vec2::new(120.0, 5.0), (40.0, 16.0), "No", None), vec![off], ColorEffect::default()), + field_el(64, "", Vec2::new(160.0, 5.0), (30.0, 16.0), "Ok", None), + ]; + Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = els; + let m = movie(&doc, &HtmlOptions::default()); + let items = m.json["contents"][0]["l"][0]["e"].as_array().unwrap().clone(); + assert_eq!(items.iter().map(|e| e.get("fx").is_some()).collect::>(), [true, true, true, false, false]); + assert_eq!(items[0]["fx"].as_array().map(Vec::len), Some(1)); + assert_eq!(items[0]["fx"][0]["k"], "shadow", "a glow is the page's shadow kind"); + assert_eq!(items[0]["fm"].as_f64(), Some(f64::from(glow.filter.margin()))); + assert_eq!(items[1]["fx"].as_array().map(Vec::len), Some(1), "the filter that is off is left out: {}", items[1]["fx"]); + assert_eq!(items[1]["fm"].as_f64(), Some(f64::from(shadow.filter.margin()))); + assert!(items[1].get("tf").is_some() && items[0].get("tf").is_none()); + assert_eq!(m.report.get(INPUT_FILTERS), Some(&1), "{:?}", m.report); + // The page's display list is the renderer's: three filtered groups, their items in them. + let r = start(&doc, &mut NoScripts); + let mut js = Js::new(&m); + js.eval("P.start().output"); + same_display_list(&mut js, &m, &doc, &r.state, "start"); + let dl = evaluate_player(&doc, &r.state); + assert_eq!(dl.groups.iter().map(|g| (g.filters.len(), g.alpha)).collect::>(), [(1, 0.5), (1, 1.0), (1, 1.0)]); + // The page hears each group open and close around its text (canvas.js draws so). + let seen = js.eval("(function () { var out = []; P.evaluate({ item: function () { out.push('i'); }, field: function (f) { out.push('f' + f.group); }, clipBegin: function () {}, clipEnd: function () {}, maskBegin: function () {}, maskEnd: function () {}, groupBegin: function (g, grp) { out.push('<' + g + ':' + grp.filters.length + ':' + grp.margin); }, groupEnd: function (g) { out.push('>' + g); } }); return out.join(' '); })()"); + let want = format!("<0:1:{} i >0 <1:1:{} f1 >1 <2:1:{} f2 >2 i i", glow.filter.margin(), shadow.filter.margin(), glow.filter.margin()); + assert_eq!(seen, json!(want)); + // Mask artwork takes no filters: the text masks as it is. + let mut masked = doc.clone(); + let tl = masked.timeline_mut(0); + let mut below = Layer::new(LayerId(7), "below"); + below.keyframe_mut(0).unwrap().elements = vec![rect(70, 0.0, 0.0, 200.0, 120.0, 0x223344)]; + below.parent = Some(tl.layers[0].id); + Arc::make_mut(&mut tl.layers[0]).kind = LayerKind::Mask; + tl.layers.push(Arc::new(below)); + let m = movie(&masked, &HtmlOptions::default()); + let r = start(&masked, &mut NoScripts); + let mut js = Js::new(&m); + js.eval("P.start().output"); + same_display_list(&mut js, &m, &masked, &r.state, "masking"); + assert!(evaluate_player(&masked, &r.state).groups.is_empty()); +} + fn filters_js() -> Context { let mut ctx = Context::default(); ctx.eval(Source::from_bytes(FILTERS_JS)).unwrap_or_else(|e| panic!("filters.js: {e}")); diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 89c3acfb..c9eba82a 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -586,7 +586,10 @@ impl<'a> Builder<'a> { } /// A text field: one text element per block (`text::field`), placed by the field's matrix. + /// Its filters (the same `` records an instance holds) come in on each block, in + /// order, switched off where Animate had them off (ADR 0099). fn text_field(&mut self, el: &X, parent: &Affine, out: &mut Vec>) { + let filters = self.filters(el); let fonts: &'a Fonts = match self.fonts { Some(f) => f, None => Fonts::get(), @@ -595,7 +598,8 @@ impl<'a> Builder<'a> { let m = parent.mul(&matrix(el)); let name: String = el.attr("name").unwrap_or("").chars().take(256).collect(); for (i, p) in crate::text::field(el, fonts, &mut self.faces, &mut self.report).into_iter().enumerate() { - let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m.mul(&Affine::translate(p.offset.x, p.offset.y)), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(p.block)) }; + let block = anicraft_doc::TextBlock { filters: filters.clone(), ..p.block }; + let mut e = Element { id: ElementId(self.doc.alloc_id()), name: String::new(), transform: m.mul(&Affine::translate(p.offset.x, p.offset.y)), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }; // A dynamic or input field's instance name goes on it (its first block for static // text, which keeps the name for a later conversion). if i == 0 { diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index cd09a166..8f875c34 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -459,6 +459,39 @@ fn text_fields_become_blocks_with_this_computers_fonts() { assert_eq!(fields, [("score_txt".into(), Dynamic, 200.0, 28.0), ("name_txt".into(), Input, 200.0, 24.0), ("notes_txt".into(), Input, 140.0, 64.0), ("pw_txt".into(), Input, 120.0, 24.0)]); } +/// ADR 0099: a text field's `` (the records an instance holds) come in on the text, in +/// order, switched-off ones switched off; nothing about them is reported as skipped. +#[test] +fn filters_on_text_fields_come_in_on_the_text() { + let mut package = files("textfields"); + let xml = String::from_utf8(package["DOMDocument.xml"].clone()).unwrap(); + let field = ""; + assert!(xml.contains(field), "the fixture's dynamic field"); + let filters = ""; + package.insert("DOMDocument.xml".into(), xml.replace(field, &format!("{field}{filters}")).into_bytes()); + // Without fonts no text comes in; the import still reads the package, and says only that. + let (_, report) = import_files(&package, &Fonts::from_faces(Vec::new())).unwrap(); + assert!(!report.skipped.contains_key("filters on text"), "{:?}", report.skipped); + assert_eq!(report.skipped.get("unknown filters"), Some(&1), "a filter AniCraft doesn't know is reported: {:?}", report.skipped); + let fonts = Fonts::get(); + if fonts.resolve("").is_none() { + return; // A computer without fonts: nothing to hold the filters. + } + let (doc, report) = import_files(&package, fonts).unwrap(); + assert!(!report.skipped.contains_key("filters on text"), "{:?}", report.skipped); + let texts: Vec<(String, Vec)> = doc.timeline(0).layers[1].keyframes[0].elements.iter().filter_map(|e| if let ElementKind::Text(t) = &e.kind { Some((e.name.clone(), t.filters.clone())) } else { None }).collect(); + let (name, list) = &texts[0]; + assert_eq!(name, "score_txt"); + assert_eq!(list.len(), 2, "{list:?}"); + assert!(matches!(list[0], anicraft_doc::FilterEntry { filter: anicraft_doc::Filter::DropShadow { blur_x, distance, strength, color, .. }, enabled: true } if blur_x == 4.0 && distance == 6.0 && (strength - 0.6).abs() < 1e-6 && color == anicraft_doc::Rgba::hex(0x112233)), "{:?}", list[0]); + assert!(matches!(list[1], anicraft_doc::FilterEntry { filter: anicraft_doc::Filter::Glow { .. }, .. }), "{:?}", list[1]); + assert!(texts.iter().skip(1).all(|(_, f)| f.is_empty()), "the other fields have none"); + // And the text draws through them: one filtered group, the field's items in it. + let dl = anicraft_doc::evaluate(&doc, 0); + let g = dl.groups.iter().position(|g| !g.filters.is_empty()).expect("a filtered group") as u32; + assert!(dl.items.iter().filter(|i| i.group == Some(g)).count() >= 2); +} + /// A small deterministic generator (xorshift), so a failing variant can be found again. struct Rng(u64); impl Rng {