raden 2026.1.1

2D Vector Graphics Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/// グリフアウトライン → Path 変換。
///
/// glyf テーブルからグリフデータを読み出し、TrueType の 2 次ベジェアウトラインを
/// Path に変換する。Simple Glyph と Compound Glyph の両方に対応。
use crate::api::path::Path;
use crate::font::FontError;
use crate::font::tables::{ParsedTables, be_i8, be_i16, be_u8, be_u16};

/// Compound Glyph の最大再帰深度。
const MAX_COMPOUND_DEPTH: u32 = 16;

// glyf フラグビット
const ON_CURVE: u8 = 0x01;
const X_SHORT: u8 = 0x02;
const Y_SHORT: u8 = 0x04;
const REPEAT_FLAG: u8 = 0x08;
const X_SAME_OR_POS: u8 = 0x10;
const Y_SAME_OR_POS: u8 = 0x20;

// Compound フラグビット
const ARG_1_AND_2_ARE_WORDS: u16 = 0x0001;
const ARGS_ARE_XY_VALUES: u16 = 0x0002;
const WE_HAVE_A_SCALE: u16 = 0x0008;
const MORE_COMPONENTS: u16 = 0x0020;
const WE_HAVE_AN_X_AND_Y_SCALE: u16 = 0x0040;
const WE_HAVE_A_TWO_BY_TWO: u16 = 0x0080;

/// design units → pixel 変換パラメータ。
#[derive(Clone, Copy)]
struct GlyphTransform {
    offset_x: f64,
    offset_y: f64,
    scale: f64,
    m00: f64,
    m01: f64,
    m10: f64,
    m11: f64,
}

impl GlyphTransform {
    fn new(offset_x: f64, offset_y: f64, scale: f64) -> Self {
        Self {
            offset_x,
            offset_y,
            scale,
            m00: 1.0,
            m01: 0.0,
            m10: 0.0,
            m11: 1.0,
        }
    }

    /// design units 座標をピクセル座標に変換する。
    #[inline]
    fn apply(&self, x_design: i32, y_design: i32) -> (f64, f64) {
        let xd = x_design as f64;
        let yd = y_design as f64;
        let tx = xd * self.m00 + yd * self.m01;
        let ty = xd * self.m10 + yd * self.m11;
        (
            tx * self.scale + self.offset_x,
            -ty * self.scale + self.offset_y,
        )
    }
}

/// グリフアウトラインを Path に追加する。
pub(crate) fn append_glyph_outline(
    glyph_id: u16,
    offset_x: f64,
    offset_y: f64,
    scale: f64,
    tables: &ParsedTables,
    data: &[u8],
    path: &mut Path,
) -> Result<(), FontError> {
    let xform = GlyphTransform::new(offset_x, offset_y, scale);
    append_glyph_recursive(glyph_id, xform, tables, data, path, 0)
}

/// 再帰的にグリフアウトラインを追加する (Compound 対応)。
fn append_glyph_recursive(
    glyph_id: u16,
    xform: GlyphTransform,
    tables: &ParsedTables,
    data: &[u8],
    path: &mut Path,
    depth: u32,
) -> Result<(), FontError> {
    if depth > MAX_COMPOUND_DEPTH {
        return Err(FontError::InvalidData("compound glyph recursion too deep"));
    }

    let gid = glyph_id as usize;
    if gid + 1 >= tables.loca_offsets.len() {
        return Err(FontError::InvalidData("glyph id out of range"));
    }

    let glyf_start = tables.loca_offsets[gid];
    let glyf_end = tables.loca_offsets[gid + 1];

    // Empty glyph (スペース等)
    if glyf_start == glyf_end {
        return Ok(());
    }

    let abs_start = tables.glyf_offset as usize + glyf_start as usize;
    let abs_end = tables.glyf_offset as usize + glyf_end as usize;

    if abs_end > data.len() || abs_start >= abs_end {
        return Err(FontError::InvalidData("glyph data out of range"));
    }

    let glyph_data = &data[abs_start..abs_end];

    if glyph_data.len() < 10 {
        return Err(FontError::InvalidData("glyph header too short"));
    }

    let number_of_contours = be_i16(glyph_data, 0)?;

    if number_of_contours >= 0 {
        parse_simple_glyph(glyph_data, number_of_contours as usize, xform, path)
    } else {
        parse_compound_glyph(glyph_data, xform, tables, data, path, depth)
    }
}

/// Simple Glyph をパースして Path に変換する。
fn parse_simple_glyph(
    glyph_data: &[u8],
    number_of_contours: usize,
    xform: GlyphTransform,
    path: &mut Path,
) -> Result<(), FontError> {
    if number_of_contours == 0 {
        return Ok(());
    }

    // ヘッダ: number_of_contours(2) + xMin(2) + yMin(2) + xMax(2) + yMax(2) = 10 bytes
    let end_pts_off = 10;
    let end_pts_end = end_pts_off + number_of_contours * 2;

    if end_pts_end + 2 > glyph_data.len() {
        return Err(FontError::InvalidData(
            "simple glyph contour data too short",
        ));
    }

    // end_pts_of_contours を読み出す
    let mut end_pts = Vec::with_capacity(number_of_contours);
    for i in 0..number_of_contours {
        end_pts.push(be_u16(glyph_data, end_pts_off + i * 2)? as usize);
    }

    let num_points = end_pts.last().map_or(0, |&e| e + 1);
    if num_points == 0 {
        return Ok(());
    }

    // instruction_length + instructions をスキップ
    let instr_len = be_u16(glyph_data, end_pts_end)? as usize;
    let flags_off = end_pts_end + 2 + instr_len;

    if flags_off > glyph_data.len() {
        return Err(FontError::InvalidData(
            "simple glyph instructions exceed data",
        ));
    }

    // フラグのデコード (repeat 対応)
    let mut flags = Vec::with_capacity(num_points);
    let mut cursor = flags_off;
    while flags.len() < num_points {
        if cursor >= glyph_data.len() {
            return Err(FontError::InvalidData("simple glyph flags truncated"));
        }
        let flag = glyph_data[cursor];
        cursor += 1;
        flags.push(flag);

        if flag & REPEAT_FLAG != 0 {
            if cursor >= glyph_data.len() {
                return Err(FontError::InvalidData(
                    "simple glyph repeat count truncated",
                ));
            }
            let repeat_count = glyph_data[cursor] as usize;
            cursor += 1;
            for _ in 0..repeat_count {
                if flags.len() >= num_points {
                    break;
                }
                flags.push(flag);
            }
        }
    }

    // X 座標のデコード (delta → 累積)
    let mut x_coords = Vec::with_capacity(num_points);
    let mut x: i32 = 0;
    for &flag in &flags {
        if flag & X_SHORT != 0 {
            if cursor >= glyph_data.len() {
                return Err(FontError::InvalidData("simple glyph x data truncated"));
            }
            let dx = glyph_data[cursor] as i32;
            cursor += 1;
            if flag & X_SAME_OR_POS != 0 {
                x += dx;
            } else {
                x -= dx;
            }
        } else if flag & X_SAME_OR_POS == 0 {
            if cursor + 1 >= glyph_data.len() {
                return Err(FontError::InvalidData("simple glyph x data truncated"));
            }
            let dx = i16::from_be_bytes([glyph_data[cursor], glyph_data[cursor + 1]]) as i32;
            cursor += 2;
            x += dx;
        }
        // X_SAME_OR_POS && !X_SHORT → delta = 0, x unchanged
        x_coords.push(x);
    }

    // Y 座標のデコード (delta → 累積)
    let mut y_coords = Vec::with_capacity(num_points);
    let mut y: i32 = 0;
    for &flag in &flags {
        if flag & Y_SHORT != 0 {
            if cursor >= glyph_data.len() {
                return Err(FontError::InvalidData("simple glyph y data truncated"));
            }
            let dy = glyph_data[cursor] as i32;
            cursor += 1;
            if flag & Y_SAME_OR_POS != 0 {
                y += dy;
            } else {
                y -= dy;
            }
        } else if flag & Y_SAME_OR_POS == 0 {
            if cursor + 1 >= glyph_data.len() {
                return Err(FontError::InvalidData("simple glyph y data truncated"));
            }
            let dy = i16::from_be_bytes([glyph_data[cursor], glyph_data[cursor + 1]]) as i32;
            cursor += 2;
            y += dy;
        }
        y_coords.push(y);
    }

    // contour ごとにパスを生成
    let mut contour_start = 0;
    for &end_pt in &end_pts {
        let contour_end = end_pt + 1;
        if contour_end > num_points || contour_start >= contour_end {
            contour_start = contour_end;
            continue;
        }

        emit_contour(
            &flags[contour_start..contour_end],
            &x_coords[contour_start..contour_end],
            &y_coords[contour_start..contour_end],
            xform,
            path,
        );

        contour_start = contour_end;
    }

    Ok(())
}

/// 1 つの contour を Path に変換する。
///
/// TrueType の 2 次ベジェ規則:
/// - on → on: line_to
/// - on → off → on: quad_to(off, on)
/// - off → off: 暗黙の on-curve (2 つの off-curve の中点) を挿入
fn emit_contour(
    flags: &[u8],
    x_coords: &[i32],
    y_coords: &[i32],
    xform: GlyphTransform,
    path: &mut Path,
) {
    let n = flags.len();
    if n == 0 {
        return;
    }

    let tx = |i: usize| -> (f64, f64) { xform.apply(x_coords[i], y_coords[i]) };

    let on_curve = |i: usize| -> bool { flags[i] & ON_CURVE != 0 };

    // 最初の on-curve 点を探す
    // すべて off-curve の場合は最初の 2 点の中点を開始点とする
    let (start_x, start_y, first_idx);
    if on_curve(0) {
        let (sx, sy) = tx(0);
        start_x = sx;
        start_y = sy;
        first_idx = 1;
    } else if on_curve(n - 1) {
        let (sx, sy) = tx(n - 1);
        start_x = sx;
        start_y = sy;
        first_idx = 0;
    } else {
        // 最初の 2 つの off-curve 点の中点
        let (x0, y0) = tx(0);
        let (x1, y1) = tx(n - 1);
        start_x = (x0 + x1) * 0.5;
        start_y = (y0 + y1) * 0.5;
        first_idx = 0;
    };

    path.move_to(start_x, start_y);

    let mut i = first_idx;
    while i < n {
        if on_curve(i) {
            let (px, py) = tx(i);
            path.line_to(px, py);
            i += 1;
        } else {
            // off-curve 点
            let (cpx, cpy) = tx(i);
            let next = (i + 1) % n;

            if next == first_idx && first_idx == 0 && !on_curve(0) && !on_curve(n - 1) {
                // contour の終端に戻る (暗黙 on-curve = start)
                path.quad_to(cpx, cpy, start_x, start_y);
                i += 1;
            } else if next < n && on_curve(next) {
                // off → on
                let (ex, ey) = tx(next);
                path.quad_to(cpx, cpy, ex, ey);
                i += 2;
            } else {
                // off → off: 暗黙 on-curve (中点)
                let (nx, ny) = tx(next);
                let mid_x = (cpx + nx) * 0.5;
                let mid_y = (cpy + ny) * 0.5;
                path.quad_to(cpx, cpy, mid_x, mid_y);
                i += 1;
            }
        }
    }

    // contour を閉じる
    path.close();
}

/// Compound Glyph をパースする。
fn parse_compound_glyph(
    glyph_data: &[u8],
    xform: GlyphTransform,
    tables: &ParsedTables,
    data: &[u8],
    path: &mut Path,
    depth: u32,
) -> Result<(), FontError> {
    // ヘッダ 10 bytes をスキップ
    let mut cursor = 10usize;

    loop {
        if cursor + 4 > glyph_data.len() {
            return Err(FontError::InvalidData("compound glyph truncated"));
        }

        let comp_flags = be_u16(glyph_data, cursor)?;
        let glyph_index = be_u16(glyph_data, cursor + 2)?;
        cursor += 4;

        // 引数 (オフセット)
        let (arg1, arg2);
        if comp_flags & ARG_1_AND_2_ARE_WORDS != 0 {
            if cursor + 4 > glyph_data.len() {
                return Err(FontError::InvalidData("compound args truncated"));
            }
            if comp_flags & ARGS_ARE_XY_VALUES != 0 {
                arg1 = be_i16(glyph_data, cursor)? as f64;
                arg2 = be_i16(glyph_data, cursor + 2)? as f64;
            } else {
                arg1 = be_u16(glyph_data, cursor)? as f64;
                arg2 = be_u16(glyph_data, cursor + 2)? as f64;
            }
            cursor += 4;
        } else {
            if cursor + 2 > glyph_data.len() {
                return Err(FontError::InvalidData("compound args truncated"));
            }
            if comp_flags & ARGS_ARE_XY_VALUES != 0 {
                arg1 = be_i8(glyph_data, cursor)? as f64;
                arg2 = be_i8(glyph_data, cursor + 1)? as f64;
            } else {
                arg1 = be_u8(glyph_data, cursor)? as f64;
                arg2 = be_u8(glyph_data, cursor + 1)? as f64;
            }
            cursor += 2;
        }

        // 変換行列
        let (mut cm00, mut cm01, mut cm10, mut cm11) = (1.0f64, 0.0f64, 0.0f64, 1.0f64);

        if comp_flags & WE_HAVE_A_SCALE != 0 {
            if cursor + 2 > glyph_data.len() {
                return Err(FontError::InvalidData("compound scale truncated"));
            }
            let s = f2dot14(be_i16(glyph_data, cursor)?);
            cursor += 2;
            cm00 = s;
            cm11 = s;
        } else if comp_flags & WE_HAVE_AN_X_AND_Y_SCALE != 0 {
            if cursor + 4 > glyph_data.len() {
                return Err(FontError::InvalidData("compound xy scale truncated"));
            }
            cm00 = f2dot14(be_i16(glyph_data, cursor)?);
            cm11 = f2dot14(be_i16(glyph_data, cursor + 2)?);
            cursor += 4;
        } else if comp_flags & WE_HAVE_A_TWO_BY_TWO != 0 {
            if cursor + 8 > glyph_data.len() {
                return Err(FontError::InvalidData("compound 2x2 matrix truncated"));
            }
            cm00 = f2dot14(be_i16(glyph_data, cursor)?);
            cm01 = f2dot14(be_i16(glyph_data, cursor + 2)?);
            cm10 = f2dot14(be_i16(glyph_data, cursor + 4)?);
            cm11 = f2dot14(be_i16(glyph_data, cursor + 6)?);
            cursor += 8;
        }

        // 親の変換行列と合成
        let new_m00 = xform.m00 * cm00 + xform.m01 * cm10;
        let new_m01 = xform.m00 * cm01 + xform.m01 * cm11;
        let new_m10 = xform.m10 * cm00 + xform.m11 * cm10;
        let new_m11 = xform.m10 * cm01 + xform.m11 * cm11;

        // XY オフセットを親の変換行列でピクセル空間に変換
        let dx = if comp_flags & ARGS_ARE_XY_VALUES != 0 {
            arg1
        } else {
            0.0
        };
        let dy = if comp_flags & ARGS_ARE_XY_VALUES != 0 {
            arg2
        } else {
            0.0
        };

        let child_xform = GlyphTransform {
            offset_x: xform.offset_x + (dx * xform.m00 + dy * xform.m01) * xform.scale,
            offset_y: xform.offset_y - (dx * xform.m10 + dy * xform.m11) * xform.scale,
            scale: xform.scale,
            m00: new_m00,
            m01: new_m01,
            m10: new_m10,
            m11: new_m11,
        };

        append_glyph_recursive(glyph_index, child_xform, tables, data, path, depth + 1)?;

        if comp_flags & MORE_COMPONENTS == 0 {
            break;
        }
    }

    Ok(())
}

/// F2Dot14 固定小数点数を f64 に変換する。
fn f2dot14(value: i16) -> f64 {
    value as f64 / 16384.0
}