summaryrefslogtreecommitdiff
path: root/rsvg_internals/src/filters/component_transfer.rs
blob: d21d6b84b330a5b9b8d8d3f6c1e4ae06a2552710 (plain)
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
use std::cell::{Cell, Ref, RefCell};
use std::cmp::min;

use cairo::{self, ImageSurface};

use attributes::Attribute;
use error::NodeError;
use handle::RsvgHandle;
use node::{NodeResult, NodeTrait, NodeType, RsvgCNodeImpl, RsvgNode};
use parsers::{self, ListLength, NumberListError, ParseError};
use property_bag::PropertyBag;
use srgb::{linearize_surface, unlinearize_surface};
use state::ColorInterpolationFilters;
use surface_utils::{
    iterators::Pixels,
    shared_surface::SharedImageSurface,
    ImageSurfaceDataExt,
    Pixel,
};
use util::clamp;

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::{make_result, Filter, FilterError, PrimitiveWithInput};

/// The `feComponentTransfer` filter primitive.
pub struct ComponentTransfer {
    base: PrimitiveWithInput,
}

/// Pixel components that can be influenced by `feComponentTransfer`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Channel {
    R,
    G,
    B,
    A,
}

/// Component transfer function types.
#[derive(Debug, Clone, Copy)]
enum FunctionType {
    Identity,
    Table,
    Discrete,
    Linear,
    Gamma,
}

/// The `<feFuncX>` element (X is R, G, B or A).
pub struct FuncX {
    channel: Channel,
    function_type: Cell<FunctionType>,
    table_values: RefCell<Vec<f64>>,
    slope: Cell<f64>,
    intercept: Cell<f64>,
    amplitude: Cell<f64>,
    exponent: Cell<f64>,
    offset: Cell<f64>,
}

/// The compute function parameters.
struct FunctionParameters<'a> {
    table_values: Ref<'a, Vec<f64>>,
    slope: f64,
    intercept: f64,
    amplitude: f64,
    exponent: f64,
    offset: f64,
}

/// The compute function type.
type Function = fn(&FunctionParameters, f64) -> f64;

/// The identity component transfer function.
fn identity(_: &FunctionParameters, value: f64) -> f64 {
    value
}

/// The table component transfer function.
fn table(params: &FunctionParameters, value: f64) -> f64 {
    let n = params.table_values.len() - 1;
    let k = (value * (n as f64)).floor() as usize;

    let k = min(k, n); // Just in case.

    if k == n {
        return params.table_values[k];
    }

    let vk = params.table_values[k];
    let vk1 = params.table_values[k + 1];
    let k = k as f64;
    let n = n as f64;

    vk + (value - k / n) * n * (vk1 - vk)
}

/// The discrete component transfer function.
fn discrete(params: &FunctionParameters, value: f64) -> f64 {
    let n = params.table_values.len();
    let k = (value * (n as f64)).floor() as usize;

    params.table_values[min(k, n - 1)]
}

/// The linear component transfer function.
fn linear(params: &FunctionParameters, value: f64) -> f64 {
    params.slope * value + params.intercept
}

/// The gamma component transfer function.
fn gamma(params: &FunctionParameters, value: f64) -> f64 {
    params.amplitude * value.powf(params.exponent) + params.offset
}

impl ComponentTransfer {
    /// Constructs a new `ComponentTransfer` with empty properties.
    #[inline]
    pub fn new() -> ComponentTransfer {
        ComponentTransfer {
            base: PrimitiveWithInput::new::<Self>(),
        }
    }
}

impl Default for FuncX {
    #[inline]
    fn default() -> Self {
        Self {
            channel: Channel::R,
            function_type: Cell::new(FunctionType::Identity),
            table_values: RefCell::new(Vec::new()),
            slope: Cell::new(1f64),
            intercept: Cell::new(0f64),
            amplitude: Cell::new(1f64),
            exponent: Cell::new(1f64),
            offset: Cell::new(0f64),
        }
    }
}

impl FuncX {
    /// Constructs a new `FuncR` with empty properties.
    #[inline]
    pub fn new_r() -> Self {
        Self {
            channel: Channel::R,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncG` with empty properties.
    #[inline]
    pub fn new_g() -> Self {
        Self {
            channel: Channel::G,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncB` with empty properties.
    #[inline]
    pub fn new_b() -> Self {
        Self {
            channel: Channel::B,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncA` with empty properties.
    #[inline]
    pub fn new_a() -> Self {
        Self {
            channel: Channel::A,
            ..Default::default()
        }
    }

    /// Returns the component transfer function parameters.
    #[inline]
    fn function_parameters(&self) -> FunctionParameters {
        FunctionParameters {
            table_values: self.table_values.borrow(),
            slope: self.slope.get(),
            intercept: self.intercept.get(),
            amplitude: self.amplitude.get(),
            exponent: self.exponent.get(),
            offset: self.offset.get(),
        }
    }

    /// Returns the component transfer function.
    #[inline]
    fn function(&self) -> Function {
        match self.function_type.get() {
            FunctionType::Identity => identity,
            FunctionType::Table => table,
            FunctionType::Discrete => discrete,
            FunctionType::Linear => linear,
            FunctionType::Gamma => gamma,
        }
    }
}

impl NodeTrait for ComponentTransfer {
    #[inline]
    fn set_atts(
        &self,
        node: &RsvgNode,
        handle: *const RsvgHandle,
        pbag: &PropertyBag,
    ) -> NodeResult {
        self.base.set_atts(node, handle, pbag)
    }

    #[inline]
    fn get_c_impl(&self) -> *const RsvgCNodeImpl {
        self.base.get_c_impl()
    }
}

impl NodeTrait for FuncX {
    #[inline]
    fn set_atts(
        &self,
        _node: &RsvgNode,
        _handle: *const RsvgHandle,
        pbag: &PropertyBag,
    ) -> NodeResult {
        for (_key, attr, value) in pbag.iter() {
            match attr {
                Attribute::Type => self.function_type.set(FunctionType::parse(attr, value)?),
                Attribute::TableValues => {
                    self.table_values.replace(
                        parsers::number_list_from_str(value, ListLength::Unbounded).map_err(
                            |err| {
                                if let NumberListError::Parse(err) = err {
                                    NodeError::parse_error(attr, err)
                                } else {
                                    panic!("unexpected number list error");
                                }
                            },
                        )?,
                    );
                }
                Attribute::Slope => self
                    .slope
                    .set(parsers::number(value).map_err(|err| NodeError::parse_error(attr, err))?),
                Attribute::Intercept => self
                    .intercept
                    .set(parsers::number(value).map_err(|err| NodeError::parse_error(attr, err))?),
                Attribute::Amplitude => self
                    .amplitude
                    .set(parsers::number(value).map_err(|err| NodeError::parse_error(attr, err))?),
                Attribute::Exponent => self
                    .exponent
                    .set(parsers::number(value).map_err(|err| NodeError::parse_error(attr, err))?),
                Attribute::Offset => self
                    .offset
                    .set(parsers::number(value).map_err(|err| NodeError::parse_error(attr, err))?),
                _ => (),
            }
        }

        // The table function type with empty table_values is considered an identity
        // function.
        match self.function_type.get() {
            FunctionType::Table | FunctionType::Discrete => {
                if self.table_values.borrow().is_empty() {
                    self.function_type.set(FunctionType::Identity);
                }
            }
            _ => (),
        }

        Ok(())
    }
}

impl Filter for ComponentTransfer {
    fn render(&self, node: &RsvgNode, ctx: &FilterContext) -> Result<FilterResult, FilterError> {
        let input = make_result(self.base.get_input(ctx))?;
        let bounds = self.base.get_bounds(ctx).add_input(&input).into_irect();

        let cascaded = node.get_cascaded_values();
        let values = cascaded.get();

        let input_surface =
            if values.color_interpolation_filters == ColorInterpolationFilters::LinearRgb {
                SharedImageSurface::new(
                    linearize_surface(input.surface(), bounds)
                        .map_err(FilterError::BadInputSurfaceStatus)?,
                ).unwrap()
            } else {
                input.surface().clone()
            };

        // Create the output surface.
        let mut output_surface = ImageSurface::create(
            cairo::Format::ARgb32,
            ctx.source_graphic().width(),
            ctx.source_graphic().height(),
        ).map_err(FilterError::OutputSurfaceCreation)?;

        // Enumerate all child <feFuncX> nodes.
        let functions = node
            .children()
            .rev()
            .filter(|c| c.get_type() == NodeType::ComponentTransferFunction);

        // Get a node for every pixel component.
        let get_node = |channel| {
            functions
                .clone()
                .find(|c| c.get_impl::<FuncX>().unwrap().channel == channel)
        };
        let func_r = get_node(Channel::R);
        let func_g = get_node(Channel::G);
        let func_b = get_node(Channel::B);
        let func_a = get_node(Channel::A);

        // This is the default node that performs an identity transformation.
        let func_default = FuncX::default();

        // Retrieve the compute function and parameters for each pixel component.
        // Can't make this a closure without hacks since it's not currently possible to
        // cleanly describe |&'a T| -> &'a U to the type system.
        #[inline]
        fn func_or_default<'a>(func: &'a Option<RsvgNode>, default: &'a FuncX) -> &'a FuncX {
            func.as_ref()
                .map(|c| c.get_impl::<FuncX>().unwrap())
                .unwrap_or(default)
        }

        #[inline]
        fn compute_func<'a>(func: &'a FuncX) -> impl Fn(u8, f64, f64) -> u8 + 'a {
            let compute = func.function();
            let params = func.function_parameters();

            move |value, alpha, new_alpha| {
                let value = f64::from(value) / 255f64;

                let unpremultiplied = if alpha == 0f64 { 0f64 } else { value / alpha };

                let new_value = compute(&params, unpremultiplied);
                let new_value = clamp(new_value, 0f64, 1f64);

                (new_value * new_alpha * 255f64).round() as u8
            }
        }

        let compute_r = compute_func(func_or_default(&func_r, &func_default));
        let compute_g = compute_func(func_or_default(&func_g, &func_default));
        let compute_b = compute_func(func_or_default(&func_b, &func_default));

        // Alpha gets special handling since everything else depends on it.
        let func_a = func_or_default(&func_a, &func_default);
        let compute_a = func_a.function();
        let params_a = func_a.function_parameters();
        let compute_a = |alpha| compute_a(&params_a, alpha);

        // Do the actual processing.
        let output_stride = output_surface.get_stride() as usize;
        {
            let mut output_data = output_surface.get_data().unwrap();

            for (x, y, pixel) in Pixels::new(&input_surface, bounds) {
                let alpha = f64::from(pixel.a) / 255f64;
                let new_alpha = compute_a(alpha);

                let output_pixel = Pixel {
                    r: compute_r(pixel.r, alpha, new_alpha),
                    g: compute_g(pixel.g, alpha, new_alpha),
                    b: compute_b(pixel.b, alpha, new_alpha),
                    a: (new_alpha * 255f64).round() as u8,
                };

                output_data.set_pixel(output_stride, output_pixel, x, y);
            }
        }

        let output_surface =
            if values.color_interpolation_filters == ColorInterpolationFilters::LinearRgb {
                unlinearize_surface(&SharedImageSurface::new(output_surface).unwrap(), bounds)
                    .map_err(FilterError::OutputSurfaceCreation)?
            } else {
                output_surface
            };

        Ok(FilterResult {
            name: self.base.result.borrow().clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface).unwrap(),
                bounds,
            },
        })
    }
}

impl FunctionType {
    fn parse(attr: Attribute, s: &str) -> Result<Self, NodeError> {
        match s {
            "identity" => Ok(FunctionType::Identity),
            "table" => Ok(FunctionType::Table),
            "discrete" => Ok(FunctionType::Discrete),
            "linear" => Ok(FunctionType::Linear),
            "gamma" => Ok(FunctionType::Gamma),
            _ => Err(NodeError::parse_error(
                attr,
                ParseError::new("invalid value"),
            )),
        }
    }
}