Skip to main content

alpha2_engine/
capabilities.rs

1//! What a runtime can do, in one shape shared by the native host and the browser bridge.
2
3use std::collections::BTreeMap;
4
5use alpha2_gpu::CapabilityTier;
6use alpha2_render::Renderer;
7use serde::Serialize;
8
9use crate::PlaybackPolicy;
10
11/// The report's schema name.
12pub const CAPABILITY_SCHEMA: &str = "alpha2-capabilities";
13/// The report's schema version.
14pub const CAPABILITY_VERSION: u32 = 3;
15
16const RELEASE: &str = env!("CARGO_PKG_VERSION");
17
18/// Where the engine runs.
19#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)]
20#[serde(rename_all = "snake_case")]
21pub enum Runtime {
22    /// A native host process.
23    Native,
24    /// A browser page.
25    Browser,
26}
27
28/// What a runtime can do.
29#[derive(Clone, Debug, PartialEq, Serialize)]
30#[serde(rename_all = "camelCase")]
31pub struct CapabilityReport {
32    /// [`CAPABILITY_SCHEMA`].
33    pub schema: &'static str,
34    /// [`CAPABILITY_VERSION`].
35    pub version: u32,
36    /// The alpha2 release this engine is. Clients and hosts work together only within one release.
37    pub release: &'static str,
38    /// The project `schema_version` this engine reads and writes
39    /// ([`alpha2_model::CURRENT_SCHEMA_VERSION`]). Before v1 the release, not this number, decides
40    /// which fields a document may hold.
41    pub project_schema_version: u32,
42    /// Where the engine runs.
43    pub runtime: Runtime,
44    /// The GPU it renders with.
45    pub gpu: GpuReport,
46    /// How it handles color.
47    pub color: ColorReport,
48    /// How its real-time playback behaves.
49    pub playback: PlaybackReport,
50    /// Host-specific video decode description, or `null` when the browser page decodes.
51    pub decode: serde_json::Value,
52    /// Containers, codecs and encoders; `null` when only known at export.
53    pub encode: serde_json::Value,
54    /// Named features, each available or not, with why not.
55    pub features: BTreeMap<String, Feature>,
56    /// Host-specific adapter choice under `ALPHA2_GPU_ADAPTER` and what each candidate supports;
57    /// `null` where no choice was made (browser, CPU renderer).
58    pub adapters: serde_json::Value,
59    /// Host-specific machine and process memory; `null` where not read (browser).
60    pub memory: serde_json::Value,
61}
62
63/// The GPU the renderer drives.
64#[derive(Clone, Debug, PartialEq, Serialize)]
65#[serde(rename_all = "camelCase")]
66pub struct GpuReport {
67    /// The adapter's name.
68    pub adapter: String,
69    /// Whether the adapter rasterizes in software (lavapipe, llvmpipe, WARP, `SwiftShader`).
70    pub software_adapter: bool,
71    /// The graphics backend.
72    pub backend: String,
73    /// The driver's name.
74    pub driver: String,
75    /// The driver's version and details, where the platform gives them.
76    pub driver_info: String,
77    /// The DX12 shader compiler (`FXC`, `DXC <path>`, ...); empty elsewhere.
78    pub shader_compiler: String,
79    /// `a` (an adapter meeting all of WebGPU) or `b` (a downlevel one).
80    pub tier: &'static str,
81    /// Intermediate texture format, independent of tier: `rgba16float` where the adapter
82    /// renders, filters and copies it, else `rgba8unorm`.
83    pub intermediate_format: &'static str,
84    /// The largest 2D texture side.
85    pub max_texture_dimension_2d: u32,
86    /// Whether passes are timed on the GPU.
87    pub timestamp_queries: bool,
88    /// The idle-texture pool's byte budget.
89    pub texture_budget_bytes: u64,
90    /// The adapter's device memory.
91    pub memory: GpuMemoryReport,
92}
93
94/// The device memory the adapter may use.
95#[derive(Clone, Debug, Default, PartialEq, Serialize)]
96#[serde(rename_all = "camelCase")]
97pub struct GpuMemoryReport {
98    /// The budget the graphics API reports (DXGI local segment, Vulkan `VK_EXT_memory_budget`
99    /// device-local heaps, Metal recommended working set), or `None`. Idle pools use a quarter.
100    pub budget_bytes: Option<u64>,
101}
102
103/// How color is handled.
104#[derive(Clone, Debug, PartialEq, Serialize)]
105#[serde(rename_all = "camelCase")]
106pub struct ColorReport {
107    /// The working space: display-referred linear BT.709, 1.0 at SDR white.
108    pub working_space: &'static str,
109    /// Whether PQ and HLG sources are tone-mapped into it.
110    pub hdr_sources: bool,
111    /// Whether output can be HDR (always false; exports are SDR BT.709).
112    pub hdr_output: bool,
113    /// Whether linear float sources (`OpenEXR`) keep values beyond SDR until compositing, which
114    /// needs a half-float intermediate.
115    pub extended_range_sources: bool,
116}
117
118/// How real-time playback behaves.
119#[derive(Clone, Debug, PartialEq, Serialize)]
120#[serde(rename_all = "camelCase")]
121pub struct PlaybackReport {
122    /// The policies it runs.
123    pub policies: Vec<PlaybackPolicy>,
124    /// The one it runs unless asked otherwise.
125    pub default_policy: PlaybackPolicy,
126    /// Whether sound plays at rates other than 1x (always false).
127    pub audio_at_non_unit_rate: bool,
128}
129
130/// One feature: whether it is available, and why not.
131#[derive(Clone, Debug, PartialEq, Serialize)]
132pub struct Feature {
133    /// Whether the feature works here.
134    pub available: bool,
135    /// Why not, when it does not.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub reason: Option<String>,
138}
139
140impl Feature {
141    /// An available feature.
142    #[must_use]
143    pub const fn available() -> Self {
144        Self {
145            available: true,
146            reason: None,
147        }
148    }
149
150    /// A feature that is not available, and why.
151    #[must_use]
152    pub fn unavailable(reason: impl Into<String>) -> Self {
153        Self {
154            available: false,
155            reason: Some(reason.into()),
156        }
157    }
158}
159
160impl CapabilityReport {
161    /// The report of `renderer` on `runtime`, with decode, encode and features left to the host.
162    #[must_use]
163    pub fn new(runtime: Runtime, renderer: &Renderer) -> Self {
164        let capabilities = renderer.gpu_capabilities();
165        let half = matches!(
166            capabilities.intermediate_format,
167            alpha2_gpu::IntermediateFormat::Rgba16Float
168        );
169        Self {
170            schema: CAPABILITY_SCHEMA,
171            version: CAPABILITY_VERSION,
172            release: RELEASE,
173            project_schema_version: alpha2_model::CURRENT_SCHEMA_VERSION,
174            runtime,
175            gpu: GpuReport {
176                adapter: capabilities.adapter_name.clone(),
177                software_adapter: capabilities.software_rasterizer,
178                backend: capabilities.backend.clone(),
179                driver: capabilities.driver.clone(),
180                driver_info: capabilities.driver_info.clone(),
181                shader_compiler: capabilities.shader_compiler.clone(),
182                tier: match capabilities.tier {
183                    CapabilityTier::TierA => "a",
184                    CapabilityTier::TierB => "b",
185                    _ => "unknown",
186                },
187                intermediate_format: if half { "rgba16float" } else { "rgba8unorm" },
188                max_texture_dimension_2d: capabilities.max_texture_dimension_2d,
189                timestamp_queries: capabilities.timestamp_queries,
190                texture_budget_bytes: renderer.diagnostics().textures.budget_bytes,
191                memory: GpuMemoryReport {
192                    budget_bytes: renderer.gpu_memory_budget(),
193                },
194            },
195            color: ColorReport {
196                working_space: "linear_bt709_sdr",
197                hdr_sources: true,
198                hdr_output: false,
199                extended_range_sources: half,
200            },
201            playback: PlaybackReport {
202                policies: PlaybackPolicy::ALL.to_vec(),
203                default_policy: PlaybackPolicy::default(),
204                audio_at_non_unit_rate: false,
205            },
206            decode: serde_json::Value::Null,
207            encode: serde_json::Value::Null,
208            features: BTreeMap::new(),
209            adapters: serde_json::Value::Null,
210            memory: serde_json::Value::Null,
211        }
212    }
213
214    /// The report for the CPU renderer on `runtime`: tier A with a half-float intermediate.
215    #[must_use]
216    pub fn cpu(runtime: Runtime, renderer: &alpha2_render::CpuRenderer) -> Self {
217        Self {
218            schema: CAPABILITY_SCHEMA,
219            version: CAPABILITY_VERSION,
220            release: RELEASE,
221            project_schema_version: alpha2_model::CURRENT_SCHEMA_VERSION,
222            runtime,
223            gpu: GpuReport {
224                adapter: format!("alpha2 CPU renderer ({} threads)", renderer.threads()),
225                software_adapter: false,
226                backend: "cpu".to_owned(),
227                driver: "alpha2".to_owned(),
228                driver_info: env!("CARGO_PKG_VERSION").to_owned(),
229                shader_compiler: String::new(),
230                tier: "a",
231                intermediate_format: "rgba16float",
232                max_texture_dimension_2d: alpha2_render::RenderSize::MAX_DIMENSION,
233                timestamp_queries: false,
234                texture_budget_bytes: 0,
235                memory: GpuMemoryReport::default(),
236            },
237            color: ColorReport {
238                working_space: "linear_bt709_sdr",
239                hdr_sources: true,
240                hdr_output: false,
241                extended_range_sources: true,
242            },
243            playback: PlaybackReport {
244                policies: PlaybackPolicy::ALL.to_vec(),
245                default_policy: PlaybackPolicy::default(),
246                audio_at_non_unit_rate: false,
247            },
248            decode: serde_json::Value::Null,
249            encode: serde_json::Value::Null,
250            features: BTreeMap::new(),
251            adapters: serde_json::Value::Null,
252            memory: serde_json::Value::Null,
253        }
254    }
255
256    /// Records a feature.
257    #[must_use]
258    pub fn with_feature(mut self, name: &str, feature: Feature) -> Self {
259        self.features.insert(name.to_owned(), feature);
260        self
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::{CAPABILITY_VERSION, CapabilityReport, Runtime};
267
268    #[test]
269    fn the_report_names_its_release_and_the_project_schema_it_reads() {
270        let renderer = alpha2_render::CpuRenderer::new(1);
271        for runtime in [Runtime::Native, Runtime::Browser] {
272            let report =
273                serde_json::to_value(CapabilityReport::cpu(runtime, &renderer)).expect("a report");
274            assert_eq!(report["version"], serde_json::json!(3), "{report}");
275            assert_eq!(CAPABILITY_VERSION, 3);
276            assert_eq!(
277                report["release"],
278                serde_json::json!(env!("CARGO_PKG_VERSION")),
279                "{report}"
280            );
281            assert_eq!(
282                report["projectSchemaVersion"],
283                serde_json::json!(alpha2_model::CURRENT_SCHEMA_VERSION),
284                "{report}"
285            );
286        }
287    }
288}