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
#![deny(rust_2018_idioms)]
#![allow(elided_lifetimes_in_paths)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

mod render_world;

pub mod encoder;

use bevy::{
    prelude::*,
    render::{
        camera::RenderTarget,
        render_asset::RenderAssetUsages,
        render_resource::{Extent3d, TextureDimension, TextureFormat, TextureUsages},
        texture::BevyDefault,
    },
    utils::all_tuples,
};
use std::sync::Mutex;

#[doc(inline)]
pub use encoder::Encoder;

type BoxedEncoder = Box<dyn Encoder + Send + Sync + 'static>;

/// A Bevy plugin for capturing frames.
pub struct CapturePlugin;

impl Plugin for CapturePlugin {
    fn build(&self, app: &mut App) {
        app.add_plugins(render_world::CaptureRenderWorldPlugin);
    }
}

/// Bundle for the capture plugin. This is usually attached to a camera.
#[derive(Default, Bundle)]
pub struct CaptureBundle {
    /// The capture component.
    pub capture: Capture,
    /// The source of the capture.
    pub camera_source: CaptureSource,
}

/// The capture component.
#[derive(Default, Component)]
pub struct Capture {
    state: CaptureState,
}

impl Capture {
    /// Starts capturing frames with the given encoders.
    pub fn start(&mut self, encoders: impl IntoEncoders) {
        self.state = CaptureState::Capturing {
            encoders: Mutex::new(Some(Encoders(encoders.into_encoders()))),
            paused: false,
        };
    }

    /// Pauses the capture.
    pub fn pause(&mut self) {
        if let CaptureState::Capturing { paused, .. } = &mut self.state {
            *paused = true;
        }
    }

    /// Resumes the capture.
    pub fn resume(&mut self) {
        if let CaptureState::Capturing { paused, .. } = &mut self.state {
            *paused = false;
        }
    }

    /// Stops the capture. This will drop the active encoders, which will call [`finish`](Encoder::finish)
    /// on them.
    pub fn stop(&mut self) {
        self.state = CaptureState::Idle;
    }

    /// Returns `true` if the capture is currently capturing frames.
    pub fn is_capturing(&self) -> bool {
        matches!(&self.state, CaptureState::Capturing { .. })
    }

    /// Returns `true` if the capture is currently paused.
    pub fn is_paused(&self) -> bool {
        matches!(&self.state, CaptureState::Capturing { paused: true, .. })
    }
}

#[derive(Default)]
enum CaptureState {
    #[default]
    Idle,
    Capturing {
        encoders: Mutex<Option<Encoders>>,
        paused: bool,
    },
}

struct Encoders(Vec<BoxedEncoder>);

impl Drop for Encoders {
    fn drop(&mut self) {
        for encoder in self.0.drain(..) {
            encoder.finish();
        }
    }
}

/// The source of the capture.
#[derive(Default, Clone, Copy, Component)]
#[non_exhaustive] // TODO: For windowed rendering: MainWindow, Window(Entity)
pub enum CaptureSource {
    /// Use the camera of the entity this component is attached to.
    #[default]
    ThisCamera,
    /// Use the camera with the given entity.
    Camera(Entity),
}

/// Extension trait for the camera to set the target to a headless image.
/// This is implemented for `Camera`, `Camera2dBundle`, and `Camera3dBundle`.
///
/// # Example
/// ```ignore
/// # use bevy::prelude::*;
/// # use bevy_capture::CameraTargetHeadless;
/// #
/// fn setup(mut commands: Commands, mut images: ResMut<Assets<Image>) {
///    commands.spawn(Camera2dBundle::default().target_headless(512, 512, &mut images));
/// }
/// ```
pub trait CameraTargetHeadless {
    /// Sets the target of the camera to a headless image with the given dimensions.
    fn target_headless(self, width: u32, height: u32, images: &mut Assets<Image>) -> Self;
}

impl CameraTargetHeadless for Camera {
    fn target_headless(mut self, width: u32, height: u32, images: &mut Assets<Image>) -> Self {
        let mut image = Image::new_fill(
            Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            TextureDimension::D2,
            &[0; 4],
            TextureFormat::bevy_default(),
            RenderAssetUsages::default(),
        );
        image.texture_descriptor.usage |= TextureUsages::COPY_SRC
            | TextureUsages::RENDER_ATTACHMENT
            | TextureUsages::TEXTURE_BINDING;

        self.target = RenderTarget::Image(images.add(image));

        self
    }
}

impl CameraTargetHeadless for Camera2dBundle {
    fn target_headless(mut self, width: u32, height: u32, images: &mut Assets<Image>) -> Self {
        self.camera = self.camera.target_headless(width, height, images);
        self
    }
}

impl CameraTargetHeadless for Camera3dBundle {
    fn target_headless(mut self, width: u32, height: u32, images: &mut Assets<Image>) -> Self {
        self.camera = self.camera.target_headless(width, height, images);
        self
    }
}

/// Convert a value into a sequence of encoders.
pub trait IntoEncoders {
    /// Converts the value into a sequence of encoders.
    fn into_encoders(self) -> Vec<BoxedEncoder>;
}

impl IntoEncoders for BoxedEncoder {
    fn into_encoders(self) -> Vec<BoxedEncoder> {
        vec![self]
    }
}

impl IntoEncoders for Vec<BoxedEncoder> {
    fn into_encoders(self) -> Vec<BoxedEncoder> {
        self
    }
}

impl<E> IntoEncoders for E
where
    E: Encoder + Send + Sync + 'static,
{
    fn into_encoders(self) -> Vec<BoxedEncoder> {
        vec![Box::new(self)]
    }
}

macro_rules! impl_into_encoders {
    ($(($E:ident, $e:ident)),*) => {
        impl<$($E),*> IntoEncoders for ($($E,)*)
        where
            $($E: Encoder + Send + Sync + 'static,)*
        {
            fn into_encoders(self) -> Vec<BoxedEncoder> {
                let ($($e,)*) = self;
                vec![$(Box::new($e),)*]
            }
        }
    };
}

all_tuples!(impl_into_encoders, 0, 15, E, e);