Skip to main content

read_fonts/tables/
avar.rs

1//! The [Axis Variations](https://docs.microsoft.com/en-us/typography/opentype/spec/avar) table
2
3use super::variations::{DeltaSetIndexMap, ItemVariationStore};
4
5include!("../../generated/generated_avar.rs");
6
7impl SegmentMaps<'_> {
8    /// Applies the piecewise linear mapping to the specified coordinate,
9    /// matching HarfBuzz's extended avar behavior.
10    pub fn apply(&self, coord: Fixed) -> Fixed {
11        let maps = self.axis_value_maps();
12        let len = maps.len();
13
14        // Helpers
15        #[inline]
16        fn from(m: &AxisValueMap) -> Fixed {
17            m.from_coordinate().to_fixed()
18        }
19        #[inline]
20        fn to_(m: &AxisValueMap) -> Fixed {
21            m.to_coordinate().to_fixed()
22        }
23
24        // Special-cases (error-recovery / robustness), as in HB:
25        if len < 2 {
26            return if len == 0 {
27                coord
28            } else {
29                // len == 1: shift by the single mapping delta
30                coord - from(&maps[0]) + to_(&maps[0])
31            };
32        }
33
34        // Now we have at least two mappings.
35        // Trim "duplicate" -1/+1 caps in the wild (CoreText quirks), like HB:
36        let neg1 = Fixed::from_i32(-1);
37        let pos1 = Fixed::from_i32(1);
38
39        let mut start = 0usize;
40        let mut end = len;
41
42        if from(&maps[start]) == neg1 && to_(&maps[start]) == neg1 && from(&maps[start + 1]) == neg1
43        {
44            start += 1;
45        }
46
47        if from(&maps[end - 1]) == pos1
48            && to_(&maps[end - 1]) == pos1
49            && from(&maps[end - 2]) == pos1
50        {
51            end -= 1;
52        }
53
54        // Look for exact match first; handle multiple identical "from" entries.
55        let mut i = start;
56        while i < end {
57            if coord == from(&maps[i]) {
58                break;
59            }
60            i += 1;
61        }
62
63        if i < end {
64            // Found at least one exact match; check if there are consecutive equals.
65            let mut j = i;
66            while j + 1 < end && coord == from(&maps[j + 1]) {
67                j += 1;
68            }
69
70            // [i, j] inclusive are exact matches.
71
72            // Spec-compliant case: exactly one -> return its 'to'.
73            if i == j {
74                return to_(&maps[i]);
75            }
76
77            // Exactly three -> return the middle one.
78            if i + 2 == j {
79                return to_(&maps[i + 1]);
80            }
81
82            // Otherwise, ignore the middle ones.
83            // Return the mapping closer to 0 on the *from* side, following HB:
84            if coord < Fixed::ZERO {
85                return to_(&maps[j]);
86            }
87            if coord > Fixed::ZERO {
88                return to_(&maps[i]);
89            }
90
91            // coord == 0: choose the one with smaller |to|.
92            let ti = to_(&maps[i]);
93            let tj = to_(&maps[j]);
94            return if ti.abs() < tj.abs() { ti } else { tj };
95        }
96
97        // Not an exact match: find the segment for interpolation.
98        let mut k = start;
99        while k < end {
100            if coord < from(&maps[k]) {
101                break;
102            }
103            k += 1;
104        }
105
106        if k == start {
107            // Before all segments: shift by first mapping delta
108            return coord - from(&maps[start]) + to_(&maps[start]);
109        }
110        if k == end {
111            // After all segments: shift by last mapping delta
112            return coord - from(&maps[end - 1]) + to_(&maps[end - 1]);
113        }
114
115        // Interpolate between maps[k-1] and maps[k].
116        let before = &maps[k - 1];
117        let after = &maps[k];
118
119        let bf = from(before);
120        let bt = to_(before);
121        let af = from(after);
122        let at = to_(after);
123
124        let denom = af - bf; // guaranteed non-zero by construction
125        bt + (at - bt).mul_div(coord - bf, denom)
126    }
127}
128
129impl VarSize for SegmentMaps<'_> {
130    type Size = u16;
131
132    fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
133        Some(
134            data.read_at::<u16>(pos).ok()? as usize * AxisValueMap::RAW_BYTE_LEN
135                + u16::RAW_BYTE_LEN,
136        )
137    }
138}
139
140impl ReadArgs for SegmentMaps<'_> {
141    type Args = ();
142}
143
144impl<'a> FontRead<'a> for SegmentMaps<'a> {
145    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
146        let mut cursor = data.cursor();
147        let position_map_count: BigEndian<u16> = cursor.read_be()?;
148        let axis_value_maps = cursor.read_array(position_map_count.get() as _)?;
149        Ok(SegmentMaps {
150            position_map_count,
151            axis_value_maps,
152        })
153    }
154}
155
156#[cfg(test)]
157mod tests {
158
159    use font_test_data::bebuffer::BeBuffer;
160
161    use super::*;
162    use crate::{FontRef, TableProvider};
163
164    fn value_map(from: f32, to: f32) -> [F2Dot14; 2] {
165        [F2Dot14::from_f32(from), F2Dot14::from_f32(to)]
166    }
167
168    // for the purpose of testing it is easier for us to use an array
169    // instead of a concrete type, since we can write that into BeBuffer
170    impl PartialEq<[F2Dot14; 2]> for AxisValueMap {
171        fn eq(&self, other: &[F2Dot14; 2]) -> bool {
172            self.from_coordinate == other[0] && self.to_coordinate == other[1]
173        }
174    }
175
176    #[test]
177    fn segment_maps() {
178        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
179        let avar = font.avar().unwrap();
180        assert_eq!(avar.axis_count(), 1);
181        let expected_segment_maps = &[vec![
182            value_map(-1.0, -1.0),
183            value_map(-0.6667, -0.5),
184            value_map(-0.3333, -0.25),
185            value_map(0.0, 0.0),
186            value_map(0.2, 0.3674),
187            value_map(0.4, 0.52246),
188            value_map(0.6, 0.67755),
189            value_map(0.8, 0.83875),
190            value_map(1.0, 1.0),
191        ]];
192        let segment_maps = avar
193            .axis_segment_maps()
194            .iter()
195            .map(|segment_map| segment_map.unwrap().axis_value_maps().to_owned())
196            .collect::<Vec<_>>();
197        assert_eq!(segment_maps, expected_segment_maps);
198    }
199
200    #[test]
201    fn segment_maps_multi_axis() {
202        let segment_one_maps = [
203            value_map(-1.0, -1.0),
204            value_map(-0.6667, -0.5),
205            value_map(-0.3333, -0.25),
206        ];
207        let segment_two_maps = [value_map(0.8, 0.83875), value_map(1.0, 1.0)];
208
209        let data = BeBuffer::new()
210            .push(MajorMinor::VERSION_1_0)
211            .push(0u16) // reserved
212            .push(2u16) // axis count
213            // segment map one
214            .push(3u16) // position count
215            .extend(segment_one_maps[0])
216            .extend(segment_one_maps[1])
217            .extend(segment_one_maps[2])
218            // segment map two
219            .push(2u16) // position count
220            .extend(segment_two_maps[0])
221            .extend(segment_two_maps[1]);
222
223        let avar = super::Avar::read(data.data().into()).unwrap();
224        assert_eq!(avar.axis_segment_maps().iter().count(), 2);
225        assert_eq!(
226            avar.axis_segment_maps()
227                .get(0)
228                .unwrap()
229                .unwrap()
230                .axis_value_maps,
231            segment_one_maps,
232        );
233        assert_eq!(
234            avar.axis_segment_maps()
235                .get(1)
236                .unwrap()
237                .unwrap()
238                .axis_value_maps,
239            segment_two_maps,
240        );
241    }
242
243    #[test]
244    fn piecewise_linear() {
245        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
246        let avar = font.avar().unwrap();
247        let segment_map = avar.axis_segment_maps().get(0).unwrap().unwrap();
248        let coords = [-1.0, -0.5, 0.0, 0.5, 1.0];
249        let expected_result = [-1.0, -0.375, 0.0, 0.600006103515625, 1.0];
250        assert_eq!(
251            &expected_result[..],
252            &coords
253                .iter()
254                .map(|coord| segment_map.apply(Fixed::from_f64(*coord)).to_f64())
255                .collect::<Vec<_>>()
256        );
257    }
258
259    #[test]
260    fn avar2() {
261        let font = FontRef::new(font_test_data::AVAR2_CHECKER).unwrap();
262        let avar = font.avar().unwrap();
263        assert_eq!(avar.version(), MajorMinor::VERSION_2_0);
264        assert!(avar.axis_index_map_offset().is_some());
265        assert!(avar.var_store_offset().is_some());
266        assert!(avar.var_store().is_some());
267    }
268
269    #[test]
270    fn piecewise_linear_zero_tie_break_matches_harfbuzz() {
271        let maps = [
272            AxisValueMap {
273                from_coordinate: F2Dot14::NEG_ONE.into(),
274                to_coordinate: F2Dot14::NEG_ONE.into(),
275            },
276            AxisValueMap {
277                from_coordinate: F2Dot14::ZERO.into(),
278                to_coordinate: F2Dot14::from_f32(-0.25).into(),
279            },
280            AxisValueMap {
281                from_coordinate: F2Dot14::ZERO.into(),
282                to_coordinate: F2Dot14::from_f32(0.25).into(),
283            },
284            AxisValueMap {
285                from_coordinate: F2Dot14::ONE.into(),
286                to_coordinate: F2Dot14::ONE.into(),
287            },
288        ];
289        let segment_map = SegmentMaps {
290            position_map_count: (maps.len() as u16).into(),
291            axis_value_maps: &maps,
292        };
293        assert_eq!(segment_map.apply(Fixed::ZERO), Fixed::from_f64(0.25));
294    }
295
296    #[test]
297    fn piecewise_linear_before_start_after_leading_duplicate_cap() {
298        let maps = [
299            AxisValueMap {
300                from_coordinate: F2Dot14::NEG_ONE.into(),
301                to_coordinate: F2Dot14::NEG_ONE.into(),
302            },
303            AxisValueMap {
304                from_coordinate: F2Dot14::NEG_ONE.into(),
305                to_coordinate: F2Dot14::NEG_ONE.into(),
306            },
307            AxisValueMap {
308                from_coordinate: F2Dot14::from_f32(-0.5).into(),
309                to_coordinate: F2Dot14::from_f32(-0.5).into(),
310            },
311            AxisValueMap {
312                from_coordinate: F2Dot14::ZERO.into(),
313                to_coordinate: F2Dot14::ZERO.into(),
314            },
315            AxisValueMap {
316                from_coordinate: F2Dot14::ONE.into(),
317                to_coordinate: F2Dot14::ONE.into(),
318            },
319        ];
320        let segment_map = SegmentMaps {
321            position_map_count: (maps.len() as u16).into(),
322            axis_value_maps: &maps,
323        };
324        assert_eq!(
325            segment_map.apply(Fixed::from_f64(-2.0)),
326            Fixed::from_f64(-2.0)
327        );
328    }
329}