Skip to main content

alpha2_render/
generator.rs

1//! The internal generator behind fill sources: a color or gradient over the whole picture.
2//! Shapes use the vector pass ([`crate::vector`]) with the same paint code.
3
4use std::fmt::Write as _;
5
6use alpha2_gpu::CapabilityTier;
7
8use crate::{EffectDef, EffectKind, ParamSpec, ParamType, ParamUnit, ParamValue};
9
10/// Internal identifier of the generator pass.
11pub const GENERATOR_EFFECT_ID: &str = "alpha2.internal.generator";
12
13/// Most stops per paint.
14pub const MAX_GENERATOR_STOPS: usize = 16;
15
16/// The `vec4` parameters holding a paint's stop offsets, four each.
17pub const OFFSET_VECTORS: usize = MAX_GENERATOR_STOPS / 4;
18
19/// Enum values of a paint's `kind` parameter.
20pub const PAINT_KINDS: [&str; 5] = ["none", "solid", "linear", "radial", "conic"];
21
22/// Enum values of a paint's `spread` parameter.
23pub const PAINT_SPREADS: [&str; 3] = ["pad", "repeat", "reflect"];
24
25/// Parameter names of one paint in [`generator_definition`].
26#[derive(Copy, Clone, Debug, Eq, PartialEq)]
27pub struct PaintParams {
28    /// `{paint}_kind`.
29    pub kind: &'static str,
30    /// `{paint}_a`.
31    pub a: &'static str,
32    /// `{paint}_b`.
33    pub b: &'static str,
34    /// `{paint}_spread`.
35    pub spread: &'static str,
36    /// `{paint}_count`.
37    pub count: &'static str,
38    /// `{paint}_offsets0` to `{paint}_offsets3`, four stops each.
39    pub offsets: [&'static str; OFFSET_VECTORS],
40    /// `{paint}_c0` to `{paint}_c15`, by stop.
41    pub colors: [&'static str; MAX_GENERATOR_STOPS],
42}
43
44macro_rules! paint_params {
45    ($paint:literal) => {
46        PaintParams {
47            kind: concat!($paint, "_kind"),
48            a: concat!($paint, "_a"),
49            b: concat!($paint, "_b"),
50            spread: concat!($paint, "_spread"),
51            count: concat!($paint, "_count"),
52            offsets: [
53                concat!($paint, "_offsets0"),
54                concat!($paint, "_offsets1"),
55                concat!($paint, "_offsets2"),
56                concat!($paint, "_offsets3"),
57            ],
58            colors: [
59                concat!($paint, "_c0"),
60                concat!($paint, "_c1"),
61                concat!($paint, "_c2"),
62                concat!($paint, "_c3"),
63                concat!($paint, "_c4"),
64                concat!($paint, "_c5"),
65                concat!($paint, "_c6"),
66                concat!($paint, "_c7"),
67                concat!($paint, "_c8"),
68                concat!($paint, "_c9"),
69                concat!($paint, "_c10"),
70                concat!($paint, "_c11"),
71                concat!($paint, "_c12"),
72                concat!($paint, "_c13"),
73                concat!($paint, "_c14"),
74                concat!($paint, "_c15"),
75            ],
76        }
77    };
78}
79
80/// The fill paint's parameter names, static so callers need not format them.
81pub const FILL_PAINT_PARAMS: PaintParams = paint_params!("fill");
82
83fn param(name: String, param_type: ParamType, default: ParamValue) -> ParamSpec {
84    ParamSpec {
85        name,
86        param_type,
87        default,
88        min: None,
89        max: None,
90        step: None,
91        unit: ParamUnit::Normalized,
92        enum_values: Vec::new(),
93    }
94}
95
96fn enum_param(name: String, values: &[&str]) -> ParamSpec {
97    ParamSpec {
98        unit: ParamUnit::Enum,
99        enum_values: values.iter().map(|value| (*value).to_owned()).collect(),
100        ..param(name, ParamType::Enum, ParamValue::Enum(0))
101    }
102}
103
104/// The generator pass: the fill paint over the whole picture.
105///
106/// `fill_*` holds `kind`; points `a` and `b` (linear start and end; radial centre and radius
107/// in `b.x`; conic centre and start angle in `b.x`, radians clockwise from up); `spread`;
108/// stop `count`; offsets in `offsets0` to `offsets3`, four each; and straight sRGB colors
109/// `c0` to `c15`. Stops interpolate premultiplied in linear light; output is premultiplied sRGB.
110#[must_use]
111pub fn generator_definition() -> EffectDef {
112    let names = FILL_PAINT_PARAMS;
113    let mut params = vec![
114        enum_param(names.kind.into(), &PAINT_KINDS),
115        param(
116            names.a.into(),
117            ParamType::Vec2,
118            ParamValue::Vec2([0.0, 0.0]),
119        ),
120        param(
121            names.b.into(),
122            ParamType::Vec2,
123            ParamValue::Vec2([1.0, 0.0]),
124        ),
125        enum_param(names.spread.into(), &PAINT_SPREADS),
126        param(names.count.into(), ParamType::Float, ParamValue::Float(0.0)),
127    ];
128    params.extend(
129        names
130            .offsets
131            .map(|name| param(name.into(), ParamType::Vec4, ParamValue::Vec4([0.0; 4]))),
132    );
133    params.extend(names.colors.map(|name| ParamSpec {
134        unit: ParamUnit::Color,
135        ..param(name.into(), ParamType::Color, ParamValue::Color([0.0; 4]))
136    }));
137    EffectDef {
138        id: GENERATOR_EFFECT_ID.into(),
139        version: 1,
140        kind: EffectKind::Generator,
141        inputs: Vec::new(),
142        params,
143        resources: Vec::new(),
144        wgsl_body: generator_body(),
145        tier_min: CapabilityTier::TierB,
146        license: Some(crate::builtins::ALPHA2_EFFECT_LICENSE.into()),
147    }
148}
149
150fn paint_constructor(paint: &str) -> String {
151    let mut colors = String::new();
152    for stop in 0..MAX_GENERATOR_STOPS {
153        let separator = if stop + 1 == MAX_GENERATOR_STOPS {
154            ""
155        } else {
156            ", "
157        };
158        write!(colors, "params.{paint}_c{stop}{separator}")
159            .expect("writing to a String cannot fail");
160    }
161    let offsets = offset_list(|vector| format!("params.{paint}_offsets{vector}"));
162    format!(
163        "fn builtin_{paint}_paint() -> AlphaPaint {{
164    return AlphaPaint(
165        params.{paint}_kind,
166        params.{paint}_a,
167        params.{paint}_b,
168        params.{paint}_spread,
169        u32(clamp(params.{paint}_count, 0.0, {MAX_GENERATOR_STOPS}.0)),
170        array<f32, {MAX_GENERATOR_STOPS}>({offsets}),
171        array<vec4f, {MAX_GENERATOR_STOPS}>({colors}),
172    );
173}}
174"
175    )
176}
177
178pub(crate) fn offset_list(vector: impl Fn(usize) -> String) -> String {
179    (0..OFFSET_VECTORS)
180        .flat_map(|index| {
181            let name = vector(index);
182            ["x", "y", "z", "w"].map(|lane| format!("{name}.{lane}"))
183        })
184        .collect::<Vec<_>>()
185        .join(", ")
186}
187
188fn generator_body() -> String {
189    let paint = paint_constructor("fill");
190    format!(
191        r"{paint_wgsl}
192{paint}
193fn generate(uv: vec2f) -> vec4f {{
194    return builtin_generator_store(builtin_paint(builtin_fill_paint(), uv, resolution()));
195}}
196",
197        paint_wgsl = crate::paint_wgsl::paint_wgsl(),
198    )
199}
200
201#[cfg(test)]
202mod tests {
203    use super::{FILL_PAINT_PARAMS, generator_definition};
204
205    #[test]
206    fn the_paints_static_names_are_the_ones_the_pass_declares() {
207        let declared = generator_definition()
208            .params
209            .into_iter()
210            .map(|spec| spec.name)
211            .collect::<Vec<_>>();
212        let names = FILL_PAINT_PARAMS;
213        let mut expected = Vec::new();
214        let fields = [
215            ("kind", names.kind),
216            ("a", names.a),
217            ("b", names.b),
218            ("spread", names.spread),
219            ("count", names.count),
220            ("offsets0", names.offsets[0]),
221            ("offsets1", names.offsets[1]),
222            ("offsets2", names.offsets[2]),
223            ("offsets3", names.offsets[3]),
224        ];
225        let stops = names
226            .colors
227            .iter()
228            .enumerate()
229            .map(|(stop, name)| (format!("c{stop}"), *name));
230        for (field, name) in fields
231            .into_iter()
232            .map(|(field, name)| (field.to_owned(), name))
233            .chain(stops)
234        {
235            assert_eq!(name, format!("fill_{field}"));
236            expected.push(name.to_owned());
237        }
238        assert_eq!(declared, expected);
239    }
240}