thorvg 0.4.2

Safe Rust bindings to the ThorVG 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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Scenes: grouping paints and applying post-processing effects.
//!
//! Wraps the [`ThorVG` C API](https://www.thorvg.org/c-native).

use crate::color::{Rgb, Rgba};
use crate::error::{Error, Result};
use crate::paint::Paint;
use thorvg_sys as sys;

/// Axis along which a [`Scene::add_gaussian_blur_effect`] blur is applied.
///
/// Maps to the raw `int direction` parameter of the underlying C call
/// `tvg_scene_add_effect_gaussian_blur`, whose documented values are:
///
/// | C value | Variant                          |
/// |---------|----------------------------------|
/// | `0`     | [`Both`](Self::Both)             |
/// | `1`     | [`Horizontal`](Self::Horizontal) |
/// | `2`     | [`Vertical`](Self::Vertical)     |
///
/// `ThorVG`'s C API takes a bare `int` here — there is no `Tvg_*`
/// typedef — so the wrapper carries the encoding rather than
/// re-exporting a C enum. The header documents the full set, so this
/// enum mirrors it exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum BlurDirection {
    /// Blur on both axes.
    Both = 0,
    /// Blur along the horizontal axis only.
    Horizontal = 1,
    /// Blur along the vertical axis only.
    Vertical = 2,
}

impl BlurDirection {
    fn to_raw(self) -> core::ffi::c_int {
        self as core::ffi::c_int
    }
}

/// Edge-sampling behavior for [`Scene::add_gaussian_blur_effect`].
///
/// Maps to the raw `int border` parameter of the underlying C call
/// `tvg_scene_add_effect_gaussian_blur`:
///
/// | C value | Variant                        |
/// |---------|--------------------------------|
/// | `0`     | [`Duplicate`](Self::Duplicate) |
/// | `1`     | [`Wrap`](Self::Wrap)           |
///
/// The C header documents both values, so this enum mirrors it exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum BlurBorder {
    /// Replicates the edge pixel when the kernel reaches outside the
    /// scene bounds.
    Duplicate = 0,
    /// Wraps the sampling window around to the opposite edge.
    Wrap = 1,
}

impl BlurBorder {
    fn to_raw(self) -> core::ffi::c_int {
        self as core::ffi::c_int
    }
}

/// Parameters for [`Scene::add_gaussian_blur_effect`].
///
/// Mirrors the layout of
/// `tvg_scene_add_effect_gaussian_blur(scene, sigma, direction, border, quality)`,
/// bundling the four arguments into one value with the same builder
/// ergonomics as [`DropShadow`].
///
/// The same three construction styles as [`DropShadow`] are supported
/// (struct literal, `..Default::default()`, builder).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GaussianBlur {
    /// Blur radius (sigma). Must be `> 0` or the engine rejects the
    /// effect with [`Error::InvalidArguments`].
    pub sigma: f64,
    /// Axis (or axes) the kernel sweeps.
    pub direction: BlurDirection,
    /// Edge-sampling behavior outside the scene bounds.
    pub border: BlurBorder,
    /// Blur quality level, in `0..=100`.
    pub quality: u8,
}

impl GaussianBlur {
    /// Returns a blur with sensible defaults that render.
    ///
    /// | Field       | Value                     |
    /// |-------------|---------------------------|
    /// | `sigma`     | `2.0`                     |
    /// | `direction` | [`BlurDirection::Both`]   |
    /// | `border`    | [`BlurBorder::Duplicate`] |
    /// | `quality`   | `50`                      |
    ///
    /// `sigma` is non-zero so the effect actually renders (the engine
    /// rejects `sigma <= 0`).
    #[must_use]
    pub const fn new() -> Self {
        Self {
            sigma: 2.0,
            direction: BlurDirection::Both,
            border: BlurBorder::Duplicate,
            quality: 50,
        }
    }

    /// Sets the blur radius (sigma). Must be `> 0`.
    #[must_use]
    pub const fn sigma(mut self, sigma: f64) -> Self {
        self.sigma = sigma;
        self
    }

    /// Sets the axis (or axes) the blur sweeps.
    #[must_use]
    pub const fn direction(mut self, direction: BlurDirection) -> Self {
        self.direction = direction;
        self
    }

    /// Sets the edge-sampling behavior.
    #[must_use]
    pub const fn border(mut self, border: BlurBorder) -> Self {
        self.border = border;
        self
    }

    /// Sets the blur quality level, in `0..=100`.
    #[must_use]
    pub const fn quality(mut self, quality: u8) -> Self {
        self.quality = quality;
        self
    }
}

impl Default for GaussianBlur {
    fn default() -> Self {
        Self::new()
    }
}

/// Parameters for [`Scene::add_drop_shadow_effect`].
///
/// Mirrors the layout of
/// `tvg_scene_add_effect_drop_shadow(scene, r, g, b, a, angle, distance, sigma, quality)`,
/// grouping the four RGBA ints into a single [`Rgba`] so the call
/// site no longer needs eight positional arguments.
///
/// Three construction styles are supported:
///
/// ```ignore
/// // 1. Struct literal (all fields explicit):
/// DropShadow {
///     color: Rgba::new(0, 0, 0, 150),
///     angle: 135.0,
///     distance: 8.0,
///     sigma: 4.0,
///     quality: 80,
/// }
///
/// // 2. Default + field override:
/// DropShadow { angle: 135.0, ..Default::default() }
///
/// // 3. Builder:
/// DropShadow::new().angle(135.0).distance(8.0)
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DropShadow {
    /// Shadow color, `0..=255` per channel. The alpha channel acts as
    /// the shadow opacity.
    pub color: Rgba,
    /// Shadow direction in degrees, in `0.0..=360.0`.
    pub angle: f64,
    /// Distance of the shadow from the original object, in user units.
    pub distance: f64,
    /// Gaussian blur sigma for the shadow. Must be `> 0`.
    pub sigma: f64,
    /// Blur quality level, in `0..=100`.
    pub quality: u8,
}

impl DropShadow {
    /// Returns a shadow with sensible defaults that the engine
    /// accepts (opaque black, modest offset and blur).
    ///
    /// | Field      | Value                                    |
    /// |------------|------------------------------------------|
    /// | `color`    | `Rgba::new(0, 0, 0, 255)` (opaque black) |
    /// | `angle`    | `0.0`                                    |
    /// | `distance` | `4.0`                                    |
    /// | `sigma`    | `2.0`                                    |
    /// | `quality`  | `50`                                     |
    ///
    /// `sigma` is non-zero so the effect actually renders (the engine
    /// rejects `sigma <= 0`).
    #[must_use]
    pub const fn new() -> Self {
        Self {
            color: Rgba::new(0, 0, 0, 255),
            angle: 0.0,
            distance: 4.0,
            sigma: 2.0,
            quality: 50,
        }
    }

    /// Sets the shadow color.
    #[must_use]
    pub const fn color(mut self, color: Rgba) -> Self {
        self.color = color;
        self
    }

    /// Sets the shadow direction in degrees, in `0.0..=360.0`.
    #[must_use]
    pub const fn angle(mut self, angle: f64) -> Self {
        self.angle = angle;
        self
    }

    /// Sets the distance of the shadow from the source object.
    #[must_use]
    pub const fn distance(mut self, distance: f64) -> Self {
        self.distance = distance;
        self
    }

    /// Sets the Gaussian blur sigma. Must be `> 0`.
    #[must_use]
    pub const fn sigma(mut self, sigma: f64) -> Self {
        self.sigma = sigma;
        self
    }

    /// Sets the blur quality level, in `0..=100`.
    #[must_use]
    pub const fn quality(mut self, quality: u8) -> Self {
        self.quality = quality;
        self
    }
}

impl Default for DropShadow {
    fn default() -> Self {
        Self::new()
    }
}

/// Parameters for [`Scene::add_tritone_effect`].
///
/// Mirrors the layout of
/// `tvg_scene_add_effect_tritone(scene, shadow_r, shadow_g, shadow_b, midtone_r, midtone_g, midtone_b, highlight_r, highlight_g, highlight_b, blend)`,
/// grouping the three RGB triplets into named [`Rgb`] fields.
///
/// The same three construction styles as [`DropShadow`] are supported
/// (struct literal, `..Default::default()`, builder).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Tritone {
    /// Color the darkest scene pixels map to.
    pub shadow: Rgb,
    /// Color the mid-brightness scene pixels map to.
    pub midtone: Rgb,
    /// Color the brightest scene pixels map to.
    pub highlight: Rgb,
    /// Blend factor between the original color and the tritone
    /// palette, in `0..=255`.
    pub blend: u8,
}

impl Tritone {
    /// Returns a neutral tritone palette:
    ///
    /// | Field       | Value                            |
    /// |-------------|----------------------------------|
    /// | `shadow`    | `Rgb::new(0, 0, 0)` (black)      |
    /// | `midtone`   | `Rgb::new(128, 128, 128)` (gray) |
    /// | `highlight` | `Rgb::new(255, 255, 255)` (white)|
    /// | `blend`     | `128`                            |
    #[must_use]
    pub const fn new() -> Self {
        Self {
            shadow: Rgb::new(0, 0, 0),
            midtone: Rgb::new(128, 128, 128),
            highlight: Rgb::new(255, 255, 255),
            blend: 128,
        }
    }

    /// Sets the shadow tone.
    #[must_use]
    pub const fn shadow(mut self, shadow: Rgb) -> Self {
        self.shadow = shadow;
        self
    }

    /// Sets the midtone.
    #[must_use]
    pub const fn midtone(mut self, midtone: Rgb) -> Self {
        self.midtone = midtone;
        self
    }

    /// Sets the highlight tone.
    #[must_use]
    pub const fn highlight(mut self, highlight: Rgb) -> Self {
        self.highlight = highlight;
        self
    }

    /// Sets the blend factor between the original color and the
    /// tritone palette, in `0..=255`.
    #[must_use]
    pub const fn blend(mut self, blend: u8) -> Self {
        self.blend = blend;
        self
    }
}

impl Default for Tritone {
    fn default() -> Self {
        Self::new()
    }
}

/// Parameters for [`Scene::add_tint_effect`].
///
/// Mirrors the layout of
/// `tvg_scene_add_effect_tint(scene, black_r, black_g, black_b, white_r, white_g, white_b, intensity)`,
/// grouping the two RGB endpoints into named [`Rgb`] fields.
///
/// The same three construction styles as [`DropShadow`] are supported
/// (struct literal, `..Default::default()`, builder).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Tint {
    /// Color the darkest scene pixels map to.
    pub black: Rgb,
    /// Color the brightest scene pixels map to.
    pub white: Rgb,
    /// Tint intensity, in `0.0..=100.0`. `0.0` leaves the original
    /// colors untouched; `100.0` is full tint.
    pub intensity: f64,
}

impl Tint {
    /// Returns a neutral grayscale tint:
    ///
    /// | Field       | Value                            |
    /// |-------------|----------------------------------|
    /// | `black`     | `Rgb::new(0, 0, 0)` (black)      |
    /// | `white`     | `Rgb::new(255, 255, 255)` (white)|
    /// | `intensity` | `50.0`                           |
    #[must_use]
    pub const fn new() -> Self {
        Self {
            black: Rgb::new(0, 0, 0),
            white: Rgb::new(255, 255, 255),
            intensity: 50.0,
        }
    }

    /// Sets the color the darkest scene pixels map to.
    #[must_use]
    pub const fn black(mut self, black: Rgb) -> Self {
        self.black = black;
        self
    }

    /// Sets the color the brightest scene pixels map to.
    #[must_use]
    pub const fn white(mut self, white: Rgb) -> Self {
        self.white = white;
        self
    }

    /// Sets the tint intensity, in `0.0..=100.0`.
    #[must_use]
    pub const fn intensity(mut self, intensity: f64) -> Self {
        self.intensity = intensity;
        self
    }
}

impl Default for Tint {
    fn default() -> Self {
        Self::new()
    }
}

/// A scene that groups multiple paint objects.
///
/// Paints are rendered in the order they are added; add them
/// back-to-front for the intended layering.
///
/// Post-processing effects (Gaussian blur, drop shadow, fill, tint,
/// tritone) are applied after the scene is rendered, cumulatively and
/// in the order they are added. [`clear_effects`](Self::clear_effects)
/// removes them all.
///
/// The lifetime `'eng` ties this scene to a [`Thorvg`](crate::Thorvg) engine
/// instance. Create scenes via [`Thorvg::scene()`](crate::Thorvg::scene).
pub struct Scene<'eng> {
    raw: sys::Tvg_Paint,
    owned: bool,
    _engine: core::marker::PhantomData<&'eng ()>,
}

// SAFETY: Same rationale as other `ThorVG` handle types — exclusive
// ownership of a C heap object; global state is mutex-protected.
unsafe impl Send for Scene<'_> {}

impl Scene<'_> {
    /// Creates a new Scene object.
    pub(crate) fn new() -> Result<Self> {
        let raw = unsafe { sys::tvg_scene_new() };
        if raw.is_null() {
            return Err(Error::FailedAllocation);
        }
        Ok(Self {
            raw,
            owned: true,
            _engine: core::marker::PhantomData,
        })
    }

    /// Appends a paint object to the end of the scene.
    ///
    /// Ownership of `paint` is transferred to the scene.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// paint handle.
    pub fn add<P: Paint>(&mut self, paint: P) -> Result<()> {
        Error::from_raw(unsafe { sys::tvg_scene_add(self.raw, paint.into_raw()) })
    }

    /// Inserts a paint object immediately before another paint already
    /// in the scene.
    ///
    /// Ownership of `target` is transferred to the scene. `at` must be
    /// a paint that is already part of this scene.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects either
    /// handle (for example, if `at` is not present in the scene).
    pub fn insert<P: Paint, Q: Paint>(&mut self, target: P, at: &Q) -> Result<()> {
        Error::from_raw(unsafe { sys::tvg_scene_insert(self.raw, target.into_raw(), at.raw()) })
    }

    /// Removes a single paint from the scene.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// paint handle.
    pub fn remove<P: Paint>(&mut self, paint: &P) -> Result<()> {
        Error::from_raw(unsafe { sys::tvg_scene_remove(self.raw, paint.raw()) })
    }

    /// Removes all paints from the scene.
    ///
    /// Wraps `tvg_scene_remove` with a null paint, which the C API
    /// interprets as "remove every paint".
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// request.
    pub fn clear(&mut self) -> Result<()> {
        Error::from_raw(unsafe { sys::tvg_scene_remove(self.raw, core::ptr::null_mut()) })
    }

    /// Removes all previously added scene effects.
    ///
    /// Restores the scene to its un-post-processed state.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// request.
    pub fn clear_effects(&mut self) -> Result<()> {
        Error::from_raw(unsafe { sys::tvg_scene_clear_effects(self.raw) })
    }

    /// Adds a Gaussian blur effect to the scene's effect pipeline.
    ///
    /// See [`GaussianBlur`] for the parameter layout. The effect is
    /// applied after the scene is rendered.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// parameters (notably `sigma <= 0`).
    pub fn add_gaussian_blur_effect(&mut self, params: GaussianBlur) -> Result<()> {
        let GaussianBlur {
            sigma,
            direction,
            border,
            quality,
        } = params;
        Error::from_raw(unsafe {
            sys::tvg_scene_add_effect_gaussian_blur(
                self.raw,
                sigma,
                direction.to_raw(),
                border.to_raw(),
                i32::from(quality),
            )
        })
    }

    /// Adds a drop shadow effect to the scene's effect pipeline.
    ///
    /// See [`DropShadow`] for the parameter layout. The effect is
    /// applied after the scene is rendered.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// parameters (notably `sigma <= 0`).
    pub fn add_drop_shadow_effect(&mut self, params: DropShadow) -> Result<()> {
        let DropShadow {
            color: Rgba { r, g, b, a },
            angle,
            distance,
            sigma,
            quality,
        } = params;
        Error::from_raw(unsafe {
            sys::tvg_scene_add_effect_drop_shadow(
                self.raw,
                i32::from(r),
                i32::from(g),
                i32::from(b),
                i32::from(a),
                angle,
                distance,
                sigma,
                i32::from(quality),
            )
        })
    }

    /// Adds a fill color effect, overriding the scene's content color.
    ///
    /// Each channel of `color` is in `0..=255`; the alpha channel acts
    /// as the fill opacity. The effect is applied after the scene is
    /// rendered.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// parameters.
    pub fn add_fill_effect(&mut self, color: Rgba) -> Result<()> {
        let Rgba { r, g, b, a } = color;
        Error::from_raw(unsafe {
            sys::tvg_scene_add_effect_fill(
                self.raw,
                i32::from(r),
                i32::from(g),
                i32::from(b),
                i32::from(a),
            )
        })
    }

    /// Adds a tint effect to the scene's effect pipeline.
    ///
    /// See [`Tint`] for the parameter layout. The effect is applied
    /// after the scene is rendered.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// parameters.
    pub fn add_tint_effect(&mut self, params: Tint) -> Result<()> {
        let Tint {
            black,
            white,
            intensity,
        } = params;
        Error::from_raw(unsafe {
            sys::tvg_scene_add_effect_tint(
                self.raw,
                i32::from(black.r),
                i32::from(black.g),
                i32::from(black.b),
                i32::from(white.r),
                i32::from(white.g),
                i32::from(white.b),
                intensity,
            )
        })
    }

    /// Adds a tritone color effect to the scene's effect pipeline.
    ///
    /// See [`Tritone`] for the parameter layout. The effect is applied
    /// after the scene is rendered.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidArguments`] if the engine rejects the
    /// parameters.
    pub fn add_tritone_effect(&mut self, params: Tritone) -> Result<()> {
        let Tritone {
            shadow,
            midtone,
            highlight,
            blend,
        } = params;
        Error::from_raw(unsafe {
            sys::tvg_scene_add_effect_tritone(
                self.raw,
                i32::from(shadow.r),
                i32::from(shadow.g),
                i32::from(shadow.b),
                i32::from(midtone.r),
                i32::from(midtone.g),
                i32::from(midtone.b),
                i32::from(highlight.r),
                i32::from(highlight.g),
                i32::from(highlight.b),
                i32::from(blend),
            )
        })
    }
}

impl crate::paint::sealed::Sealed for Scene<'_> {}

impl Paint for Scene<'_> {
    fn raw(&self) -> sys::Tvg_Paint {
        self.raw
    }

    fn into_raw(mut self) -> sys::Tvg_Paint {
        self.owned = false;
        self.raw
    }

    unsafe fn from_raw_paint(raw: sys::Tvg_Paint) -> Self {
        Self {
            raw,
            owned: true,
            _engine: core::marker::PhantomData,
        }
    }
}

impl Drop for Scene<'_> {
    fn drop(&mut self) {
        if self.owned {
            unsafe {
                sys::tvg_paint_rel(self.raw);
            }
        }
    }
}

impl core::fmt::Debug for Scene<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Scene").finish_non_exhaustive()
    }
}