logo
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
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! Configures how the color output of the fragment shader is written to the attachment.
//!
//! # Blending in details
//!
//! There are three kinds of color attachments for the purpose of blending:
//!
//! - Attachments with a floating-point or fixed point format.
//! - Attachments with a (non-normalized) integer format.
//! - Attachments with a normalized integer format.
//!
//! For floating-point and fixed-point formats, the blending operation is applied. For integer
//! formats, the logic operation is applied. For normalized integer formats, the logic operation
//! will take precedence if it is activated, otherwise the blending operation is applied.

use crate::{
    macros::{vulkan_bitflags, vulkan_enum},
    pipeline::StateMode,
};

/// Describes how the color output of the fragment shader is written to the attachment. See the
/// documentation of the `blend` module for more info.
#[derive(Clone, Debug)]
pub struct ColorBlendState {
    /// Sets the logical operation to perform between the incoming fragment color and the existing
    /// fragment in the framebuffer attachment.
    ///
    /// If set to `Some`, the [`logic_op`](crate::device::Features::logic_op) feature must be
    /// enabled on the device. If set to `Some(Dynamic)`, then the
    /// [`extended_dynamic_state2_logic_op`](crate::device::Features::extended_dynamic_state2_logic_op)
    /// feature must also be enabled on the device.
    pub logic_op: Option<StateMode<LogicOp>>,

    /// Sets the blend and output state for each color attachment. The number of elements must match
    /// the number of color attachments in the framebuffer.
    ///
    /// If there are multiple elements, and the `blend` and `color_write_mask` members of each
    /// element differ, then the [`independent_blend`](crate::device::Features::independent_blend)
    /// feature must be enabled on the device.
    pub attachments: Vec<ColorBlendAttachmentState>,

    /// The constant color to use for some of the `BlendFactor` variants.
    pub blend_constants: StateMode<[f32; 4]>,
}

impl ColorBlendState {
    /// Creates a `ColorBlendState` with logical operations disabled, blend constants set to zero,
    /// and `num` attachment entries that have blending disabled, and color write and all color
    /// components enabled.
    #[inline]
    pub fn new(num: u32) -> Self {
        Self {
            logic_op: None,
            attachments: (0..num)
                .map(|_| ColorBlendAttachmentState {
                    blend: None,
                    color_write_mask: ColorComponents::all(),
                    color_write_enable: StateMode::Fixed(true),
                })
                .collect(),
            blend_constants: StateMode::Fixed([0.0, 0.0, 0.0, 0.0]),
        }
    }

    /// Enables logical operations with the given logical operation.
    #[inline]
    pub fn logic_op(mut self, logic_op: LogicOp) -> Self {
        self.logic_op = Some(StateMode::Fixed(logic_op));
        self
    }

    /// Enables logical operations with a dynamic logical operation.
    #[inline]
    pub fn logic_op_dynamic(mut self) -> Self {
        self.logic_op = Some(StateMode::Dynamic);
        self
    }

    /// Enables blending for all attachments, with the given parameters.
    #[inline]
    pub fn blend(mut self, blend: AttachmentBlend) -> Self {
        self.attachments
            .iter_mut()
            .for_each(|attachment_state| attachment_state.blend = Some(blend));
        self
    }

    /// Enables blending for all attachments, with alpha blending.
    #[inline]
    pub fn blend_alpha(mut self) -> Self {
        self.attachments
            .iter_mut()
            .for_each(|attachment_state| attachment_state.blend = Some(AttachmentBlend::alpha()));
        self
    }

    /// Enables blending for all attachments, with additive blending.
    #[inline]
    pub fn blend_additive(mut self) -> Self {
        self.attachments.iter_mut().for_each(|attachment_state| {
            attachment_state.blend = Some(AttachmentBlend::additive())
        });
        self
    }

    /// Sets the color write mask for all attachments.
    #[inline]
    pub fn color_write_mask(mut self, color_write_mask: ColorComponents) -> Self {
        self.attachments
            .iter_mut()
            .for_each(|attachment_state| attachment_state.color_write_mask = color_write_mask);
        self
    }

    /// Sets the blend constants.
    #[inline]
    pub fn blend_constants(mut self, constants: [f32; 4]) -> Self {
        self.blend_constants = StateMode::Fixed(constants);
        self
    }

    /// Sets the blend constants as dynamic.
    #[inline]
    pub fn blend_constants_dynamic(mut self) -> Self {
        self.blend_constants = StateMode::Dynamic;
        self
    }
}

impl Default for ColorBlendState {
    /// Returns [`ColorBlendState::new(1)`].
    #[inline]
    fn default() -> Self {
        Self::new(1)
    }
}

vulkan_enum! {
    /// Which logical operation to apply to the output values.
    ///
    /// The operation is applied individually for each channel (red, green, blue and alpha).
    ///
    /// Only relevant for integer or unsigned attachments.
    ///
    /// Also note that some implementations don't support logic operations.
    #[non_exhaustive]
    LogicOp = LogicOp(i32);

    /// Returns `0`.
    Clear = CLEAR,

    /// Returns `source & destination`.
    And = AND,

    /// Returns `source & !destination`.
    AndReverse = AND_REVERSE,

    /// Returns `source`.
    Copy = COPY,

    /// Returns `!source & destination`.
    AndInverted = AND_INVERTED,

    /// Returns `destination`.
    Noop = NO_OP,

    /// Returns `source ^ destination`.
    Xor = XOR,

    /// Returns `source | destination`.
    Or = OR,

    /// Returns `!(source | destination)`.
    Nor = NOR,

    /// Returns `!(source ^ destination)`.
    Equivalent = EQUIVALENT,

    /// Returns `!destination`.
    Invert = INVERT,

    /// Returns `source | !destination.
    OrReverse = OR_REVERSE,

    /// Returns `!source`.
    CopyInverted = COPY_INVERTED,

    /// Returns `!source | destination`.
    OrInverted = OR_INVERTED,

    /// Returns `!(source & destination)`.
    Nand = NAND,

    /// Returns `!0` (all bits set to 1).
    Set = SET,

}

impl Default for LogicOp {
    #[inline]
    fn default() -> LogicOp {
        LogicOp::Noop
    }
}

/// Describes how a framebuffer color attachment is handled in the pipeline during the color
/// blend stage.
#[derive(Clone, Debug)]
pub struct ColorBlendAttachmentState {
    /// The blend parameters for the attachment.
    ///
    /// If set to `None`, blending is disabled, and all incoming pixels will be used directly.
    pub blend: Option<AttachmentBlend>,

    /// Sets which components of the final pixel value are written to the attachment.
    pub color_write_mask: ColorComponents,

    /// Sets whether anything at all is written to the attachment. If enabled, the pixel data
    /// that is written is determined by the `color_write_mask`. If disabled, the mask is ignored
    /// and nothing is written.
    ///
    /// If set to anything other than `Fixed(true)`, the
    /// [`color_write_enable`](crate::device::Features::color_write_enable) feature must be enabled
    /// on the device.
    pub color_write_enable: StateMode<bool>,
}

/// Describes how the blending system should behave for an attachment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AttachmentBlend {
    /// The operation to apply between the color components of the source and destination pixels,
    /// to produce the final pixel value.
    pub color_op: BlendOp,

    /// The operation to apply to the source color component before applying `color_op`.
    pub color_source: BlendFactor,

    /// The operation to apply to the destination color component before applying `color_op`.
    pub color_destination: BlendFactor,

    /// The operation to apply between the alpha component of the source and destination pixels,
    /// to produce the final pixel value.
    pub alpha_op: BlendOp,

    /// The operation to apply to the source alpha component before applying `alpha_op`.
    pub alpha_source: BlendFactor,

    /// The operation to apply to the destination alpha component before applying `alpha_op`.
    pub alpha_destination: BlendFactor,
}

impl AttachmentBlend {
    /// Builds an `AttachmentBlend` where the output of the fragment shader is ignored and the
    /// destination is untouched.
    #[inline]
    pub fn ignore_source() -> Self {
        Self {
            color_op: BlendOp::Add,
            color_source: BlendFactor::Zero,
            color_destination: BlendFactor::DstColor,
            alpha_op: BlendOp::Add,
            alpha_source: BlendFactor::Zero,
            alpha_destination: BlendFactor::DstColor,
        }
    }

    /// Builds an `AttachmentBlend` where the output will be merged with the existing value
    /// based on the alpha of the source.
    #[inline]
    pub fn alpha() -> Self {
        Self {
            color_op: BlendOp::Add,
            color_source: BlendFactor::SrcAlpha,
            color_destination: BlendFactor::OneMinusSrcAlpha,
            alpha_op: BlendOp::Add,
            alpha_source: BlendFactor::SrcAlpha,
            alpha_destination: BlendFactor::OneMinusSrcAlpha,
        }
    }

    /// Builds an `AttachmentBlend` where the colors are added, and alpha is set to the maximum of
    /// the two.
    #[inline]
    pub fn additive() -> Self {
        Self {
            color_op: BlendOp::Add,
            color_source: BlendFactor::One,
            color_destination: BlendFactor::One,
            alpha_op: BlendOp::Max,
            alpha_source: BlendFactor::One,
            alpha_destination: BlendFactor::One,
        }
    }
}

impl From<AttachmentBlend> for ash::vk::PipelineColorBlendAttachmentState {
    #[inline]
    fn from(val: AttachmentBlend) -> Self {
        ash::vk::PipelineColorBlendAttachmentState {
            blend_enable: ash::vk::TRUE,
            src_color_blend_factor: val.color_source.into(),
            dst_color_blend_factor: val.color_destination.into(),
            color_blend_op: val.color_op.into(),
            src_alpha_blend_factor: val.alpha_source.into(),
            dst_alpha_blend_factor: val.alpha_destination.into(),
            alpha_blend_op: val.alpha_op.into(),
            color_write_mask: ash::vk::ColorComponentFlags::empty(), // Overwritten by GraphicsPipelineBuilder
        }
    }
}

vulkan_enum! {
    /// The operation that takes `source` (output from the fragment shader), `destination` (value
    /// currently in the framebuffer attachment) and `blend_constant` input values,
    /// and produces new inputs to be fed to `BlendOp`.
    ///
    /// Some operations take `source1` as an input, representing the second source value. The
    /// [`dual_src_blend`](crate::device::Features::dual_src_blend) feature must be enabled on the
    /// device when these are used.
    #[non_exhaustive]
    BlendFactor = BlendFactor(i32);

    /// Always `0`.
    Zero = ZERO,

    /// Always `1`.
    One = ONE,

    /// `source` component-wise.
    SrcColor = SRC_COLOR,

    /// `1 - source` component-wise.
    OneMinusSrcColor = ONE_MINUS_SRC_COLOR,

    /// `destination` component-wise.
    DstColor = DST_COLOR,

    /// `1 - destination` component-wise.
    OneMinusDstColor = ONE_MINUS_DST_COLOR,

    /// `source.a` for all components.
    SrcAlpha = SRC_ALPHA,

    /// `1 - source.a` for all components.
    OneMinusSrcAlpha = ONE_MINUS_SRC_ALPHA,

    /// `destination.a` for all components.
    DstAlpha = DST_ALPHA,

    /// `1 - destination.a` for all components.
    OneMinusDstAlpha = ONE_MINUS_DST_ALPHA,

    /// `blend_constants` component-wise.
    ConstantColor = CONSTANT_COLOR,

    /// `1 - blend_constants` component-wise.
    OneMinusConstantColor = ONE_MINUS_CONSTANT_COLOR,

    /// `blend_constants.a` for all components.
    ConstantAlpha = CONSTANT_ALPHA,

    /// `1 - blend_constants.a` for all components.
    OneMinusConstantAlpha = ONE_MINUS_CONSTANT_ALPHA,

    /// For the alpha component, always `1`. For the color components,
    /// `min(source.a, 1 - destination.a)` for all components.
    SrcAlphaSaturate = SRC_ALPHA_SATURATE,

    /// `source1` component-wise.
    Src1Color = SRC1_COLOR,

    /// `1 - source1` component-wise.
    OneMinusSrc1Color = ONE_MINUS_SRC1_COLOR,

    /// `source1.a` for all components.
    Src1Alpha = SRC1_ALPHA,

    /// `1 - source1.a` for all components.
    OneMinusSrc1Alpha = ONE_MINUS_SRC1_ALPHA,
}

vulkan_enum! {
    /// The arithmetic operation that is applied between the `source` and `destination` component
    /// values, after the appropriate `BlendFactor` is applied to both.
    #[non_exhaustive]
    BlendOp = BlendOp(i32);

    /// `source + destination`.
    Add = ADD,

    /// `source - destination`.
    Subtract = SUBTRACT,

    /// `destination - source`.
    ReverseSubtract = REVERSE_SUBTRACT,

    /// `min(source, destination)`.
    Min = MIN,

    /// `max(source, destination)`.
    Max = MAX,

    /*
    // TODO: document
    Zero = ZERO_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Src = SRC_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Dst = DST_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    SrcOver = SRC_OVER_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    DstOver = DST_OVER_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    SrcIn = SRC_IN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    DstIn = DST_IN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    SrcOut = SRC_OUT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    DstOut = DST_OUT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    SrcAtop = SRC_ATOP_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    DstAtop = DST_ATOP_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Xor = XOR_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Multiply = MULTIPLY_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Screen = SCREEN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Overlay = OVERLAY_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Darken = DARKEN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Lighten = LIGHTEN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Colordodge = COLORDODGE_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Colorburn = COLORBURN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Hardlight = HARDLIGHT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Softlight = SOFTLIGHT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Difference = DIFFERENCE_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Exclusion = EXCLUSION_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Invert = INVERT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    InvertRgb = INVERT_RGB_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Lineardodge = LINEARDODGE_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Linearburn = LINEARBURN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Vividlight = VIVIDLIGHT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Linearlight = LINEARLIGHT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Pinlight = PINLIGHT_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Hardmix = HARDMIX_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    HslHue = HSL_HUE_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    HslSaturation = HSL_SATURATION_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    HslColor = HSL_COLOR_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    HslLuminosity = HSL_LUMINOSITY_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Plus = PLUS_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    PlusClamped = PLUS_CLAMPED_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    PlusClampedAlpha = PLUS_CLAMPED_ALPHA_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    PlusDarker = PLUS_DARKER_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Minus = MINUS_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    MinusClamped = MINUS_CLAMPED_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Contrast = CONTRAST_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    InvertOvg = INVERT_OVG_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Red = RED_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Green = GREEN_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },

    // TODO: document
    Blue = BLUE_EXT {
        device_extensions: [ext_blend_operation_advanced],
    },
     */
}

vulkan_bitflags! {
    /// A mask specifying color components that can be written to a framebuffer attachment.
    ColorComponents = ColorComponentFlags(u32);

    /// The red component.
    r = R,

    /// The green component.
    g = G,

    /// The blue component.
    b = B,

    /// The alpha component.
    a = A,
}