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
use super::*;
use rafx_api::{RafxExtents3D, RafxFormat, RafxResourceType, RafxSampleCount, RafxTextureBindType};

/// Unique ID for a particular usage (read or write) of a specific image
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct RenderGraphImageUsageId(pub(super) usize);

/// An ID for an image used within the graph between passes
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct VirtualImageId(pub(super) usize);

/// An ID for an image allocation (possibly reused)
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct PhysicalImageId(pub(super) usize);

/// An ID for an image view allocation (possibly reused)
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct PhysicalImageViewId(pub(super) usize);

/// Unique ID provided for any image registered as an external image
#[derive(Debug, Copy, Clone)]
pub struct RenderGraphExternalImageId(pub(super) usize);

/// Unique ID for a particular version of an image. Any time an image is modified, a new version is
/// produced
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct RenderGraphImageVersionId {
    pub(super) index: usize,
    pub(super) version: usize,
}

/// A "virtual" image that the render graph knows about. The render graph will allocate images as
/// needed, but can reuse the same image for multiple resources if the lifetimes of those images
/// don't overlap
#[derive(Debug)]
pub struct RenderGraphImageResource {
    pub(super) name: Option<RenderGraphResourceName>,

    pub(super) versions: Vec<RenderGraphImageResourceVersionInfo>,
}

impl RenderGraphImageResource {
    pub(super) fn new() -> Self {
        RenderGraphImageResource {
            name: None,
            versions: Default::default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RenderGraphImageView {
    pub(super) physical_image: PhysicalImageId,
    pub(super) format: RafxFormat,
    pub(super) view_options: RenderGraphImageViewOptions,
}

/// Defines what created a RenderGraphImageUsage
#[derive(Debug, Clone, Copy)]
pub enum RenderGraphImageUser {
    Node(RenderGraphNodeId),
    Input(RenderGraphExternalImageId),
    Output(RenderGraphExternalImageId),
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum RenderGraphImageExtents {
    MatchSurface,
    // (width, height, depth)
    Custom(RafxExtents3D),
}

impl RenderGraphImageExtents {
    pub fn into_rafx_extents(
        self,
        swapchain_surface_info: &SwapchainSurfaceInfo,
    ) -> RafxExtents3D {
        match self {
            RenderGraphImageExtents::MatchSurface => RafxExtents3D {
                width: swapchain_surface_info.extents.width,
                height: swapchain_surface_info.extents.height,
                depth: 1,
            },
            RenderGraphImageExtents::Custom(extents) => extents,
        }
    }
}

impl Default for RenderGraphImageExtents {
    fn default() -> Self {
        RenderGraphImageExtents::MatchSurface
    }
}

#[derive(Default, Clone, Debug, PartialEq, Eq, Hash)]
pub struct RenderGraphImageViewOptions {
    pub texture_bind_type: Option<RafxTextureBindType>,
    pub array_slice: Option<u16>,
    pub mip_slice: Option<u8>,
}

impl RenderGraphImageViewOptions {
    pub fn array_slice(array_slice: u16) -> Self {
        RenderGraphImageViewOptions {
            texture_bind_type: None,
            array_slice: Some(array_slice),
            mip_slice: None,
        }
    }

    pub fn mip_slice(mip_slice: u8) -> Self {
        RenderGraphImageViewOptions {
            texture_bind_type: None,
            array_slice: None,
            mip_slice: Some(mip_slice),
        }
    }
}

/// A usage of a particular image
#[derive(Debug)]
pub struct RenderGraphImageUsage {
    pub(super) user: RenderGraphImageUser,
    pub(super) usage_type: RenderGraphImageUsageType,
    pub(super) version: RenderGraphImageVersionId,

    pub(super) view_options: RenderGraphImageViewOptions,
}

/// Immutable, fully-specified attributes of an image. A *constraint* is partially specified and
/// the graph will use constraints to solve for the specification
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RenderGraphImageSpecification {
    // Rename to RenderGraphImageUsageSpecification?
    pub samples: RafxSampleCount,
    pub format: RafxFormat,
    pub resource_type: RafxResourceType,
    pub extents: RafxExtents3D,
    pub layer_count: u32,
    pub mip_count: u32,
    // image type - always 2D
}

impl RenderGraphImageSpecification {
    /// Returns true if no fields in the two constraints are conflicting
    pub fn can_merge(
        &self,
        other: &RenderGraphImageSpecification,
    ) -> bool {
        if self.samples != other.samples {
            return false;
        }
        if self.format != other.format {
            return false;
        }
        if self.mip_count != other.mip_count {
            return false;
        }
        if self.layer_count != other.layer_count {
            return false;
        }
        if self.extents != other.extents {
            return false;
        }

        true
    }

    /// Merge other's constraints into self, but only if there are no conflicts. No modification
    /// occurs if any conflict exists
    pub fn try_merge(
        &mut self,
        other: &RenderGraphImageSpecification,
    ) -> bool {
        if !self.can_merge(other) {
            return false;
        }

        self.resource_type |= other.resource_type;

        true
    }

    pub fn specifications_are_compatible(
        written: &RenderGraphImageSpecification,
        read: &RenderGraphImageSpecification,
    ) -> bool {
        if written.samples != read.samples {
            return false;
        }
        if written.format != read.format {
            return false;
        }
        if written.mip_count != read.mip_count {
            return false;
        }
        if written.layer_count != read.layer_count {
            return false;
        }
        if written.extents != read.extents {
            return false;
        }
        if (written.resource_type | read.resource_type) != written.resource_type {
            return false;
        }
        return true;
    }
}

/// Constraints on an image. Constraints are set per-field and start out None (i.e. unconstrained)
/// The rendergraph will derive specifications from the constraints
#[derive(Default, Clone, Debug)]
pub struct RenderGraphImageConstraint {
    // Rename to RenderGraphImageUsageConstraint?
    pub samples: Option<RafxSampleCount>,
    pub format: Option<RafxFormat>,
    pub resource_type: RafxResourceType,
    pub extents: Option<RenderGraphImageExtents>,
    pub layer_count: Option<u32>,
    pub mip_count: Option<u32>,
}

impl From<RenderGraphImageSpecification> for RenderGraphImageConstraint {
    fn from(specification: RenderGraphImageSpecification) -> Self {
        RenderGraphImageConstraint {
            samples: Some(specification.samples),
            format: Some(specification.format),
            resource_type: specification.resource_type,
            layer_count: Some(specification.layer_count),
            mip_count: Some(specification.mip_count),
            extents: Some(RenderGraphImageExtents::Custom(specification.extents)),
        }
    }
}

impl RenderGraphImageConstraint {
    pub fn try_convert_to_specification(
        self,
        swapchain_surface_info: &SwapchainSurfaceInfo,
    ) -> Option<RenderGraphImageSpecification> {
        // Format is the only thing we can't default sensibly
        if self.format.is_none() {
            None
        } else {
            Some(RenderGraphImageSpecification {
                samples: self.samples.unwrap_or(RafxSampleCount::SampleCount1),
                format: self.format.unwrap(),
                layer_count: self.layer_count.unwrap_or(1),
                mip_count: self.mip_count.unwrap_or(1),
                extents: self
                    .extents
                    .unwrap_or(RenderGraphImageExtents::MatchSurface)
                    .into_rafx_extents(swapchain_surface_info),
                resource_type: self.resource_type,
            })
        }
    }
}

impl RenderGraphImageConstraint {
    /// Returns true if no fields in the two constraints are conflicting
    pub fn can_merge(
        &self,
        other: &RenderGraphImageConstraint,
    ) -> bool {
        if self.samples.is_some() && other.samples.is_some() && self.samples != other.samples {
            return false;
        }
        if self.format.is_some() && other.format.is_some() && self.format != other.format {
            return false;
        }
        if self.layer_count.is_some()
            && other.layer_count.is_some()
            && self.layer_count != other.layer_count
        {
            return false;
        }
        if self.mip_count.is_some()
            && other.mip_count.is_some()
            && self.mip_count != other.mip_count
        {
            return false;
        }
        if self.extents.is_some() && other.extents.is_some() && self.extents != other.extents {
            return false;
        }

        true
    }

    /// Merge other's constraints into self, but only if there are no conflicts. No modification
    /// occurs if any conflict exists
    pub fn try_merge(
        &mut self,
        other: &RenderGraphImageConstraint,
    ) -> bool {
        if !self.can_merge(other) {
            return false;
        }

        if self.samples.is_none() && other.samples.is_some() {
            self.samples = other.samples;
        }
        if self.format.is_none() && other.format.is_some() {
            self.format = other.format;
        }
        if self.layer_count.is_none() && other.layer_count.is_some() {
            self.layer_count = other.layer_count;
        }
        if self.mip_count.is_none() && other.mip_count.is_some() {
            self.mip_count = other.mip_count;
        }
        if self.extents.is_none() && other.extents.is_some() {
            self.extents = other.extents;
        }

        self.resource_type |= other.resource_type;

        true
    }

    /// Merge other's constraints into self. We will merge fields where we can and skip fields with
    /// conflicts
    pub fn partial_merge(
        &mut self,
        other: &RenderGraphImageConstraint,
    ) -> bool {
        let mut complete_merge = true;

        if self.samples.is_some() && other.samples.is_some() && self.samples != other.samples {
            complete_merge = false;
        } else if other.samples.is_some() {
            self.samples = other.samples;
        }

        if self.format.is_some() && other.format.is_some() && self.format != other.format {
            complete_merge = false;
        } else if other.format.is_some() {
            self.format = other.format;
        }

        if self.layer_count.is_some()
            && other.layer_count.is_some()
            && self.layer_count != other.layer_count
        {
            complete_merge = false;
        } else if other.layer_count.is_some() {
            self.layer_count = other.layer_count;
        }

        if self.mip_count.is_some()
            && other.mip_count.is_some()
            && self.mip_count != other.mip_count
        {
            complete_merge = false;
        } else if other.mip_count.is_some() {
            self.mip_count = other.mip_count;
        }

        if self.extents.is_some() && other.extents.is_some() && self.extents != other.extents {
            complete_merge = false;
        } else if other.extents.is_some() {
            self.extents = other.extents;
        }

        self.resource_type |= other.resource_type;

        complete_merge
    }

    /// Sets the constraints based on the given specification
    pub fn set(
        &mut self,
        other: &RenderGraphImageSpecification,
    ) {
        *self = other.clone().into();
    }
}

/// How an image is being used
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum RenderGraphImageUsageType {
    Create,
    Input,
    Read,
    ModifyRead,
    ModifyWrite,
    Output,
}

impl RenderGraphImageUsageType {
    //TODO: Add support to see if multiple writes actually overlap
    pub fn is_read_only(&self) -> bool {
        match self {
            RenderGraphImageUsageType::Read => true,
            RenderGraphImageUsageType::Output => true,
            RenderGraphImageUsageType::ModifyRead => false,
            RenderGraphImageUsageType::Create => false,
            RenderGraphImageUsageType::Input => false,
            RenderGraphImageUsageType::ModifyWrite => false,
        }
    }
}

/// Information about a specific version of the image.
#[derive(Debug)]
pub struct RenderGraphImageResourceVersionInfo {
    /// What node created the image (keep in mind these are virtual images, not images provided
    /// from outside the graph. So every image will have a creator node)
    pub(super) creator_node: RenderGraphNodeId,

    pub(super) create_usage: RenderGraphImageUsageId,
    pub(super) read_usages: Vec<RenderGraphImageUsageId>,
}

impl RenderGraphImageResourceVersionInfo {
    pub(super) fn new(
        creator: RenderGraphNodeId,
        create_usage: RenderGraphImageUsageId,
    ) -> Self {
        RenderGraphImageResourceVersionInfo {
            creator_node: creator,
            create_usage,
            read_usages: Default::default(),
        }
    }

    // for redirect_image_usage
    pub(super) fn remove_read_usage(
        &mut self,
        usage: RenderGraphImageUsageId,
    ) {
        if let Some(position) = self.read_usages.iter().position(|x| *x == usage) {
            self.read_usages.swap_remove(position);
        }
    }

    pub(super) fn add_read_usage(
        &mut self,
        usage: RenderGraphImageUsageId,
    ) {
        self.read_usages.push(usage);
    }
}