use serde::{Deserialize, Serialize};
use crate::effects::{Antialiasing, RenderEffects};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ShadowsPass {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AmbientOcclusionPass {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReflectionsPass {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BloomPass {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AntialiasingPass {
pub tier: Antialiasing,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VolumetricFogPass {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AutoExposurePass {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContactShadowsPass {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CameraStack {
#[serde(default)]
pub shadows: Option<ShadowsPass>,
#[serde(default)]
pub ambient_occlusion: Option<AmbientOcclusionPass>,
#[serde(default)]
pub reflections: Option<ReflectionsPass>,
#[serde(default)]
pub bloom: Option<BloomPass>,
#[serde(default)]
pub antialiasing: Option<AntialiasingPass>,
#[serde(default)]
pub volumetric_fog: Option<VolumetricFogPass>,
#[serde(default)]
pub auto_exposure: Option<AutoExposurePass>,
#[serde(default)]
pub contact_shadows: Option<ContactShadowsPass>,
}
impl Default for CameraStack {
fn default() -> Self {
Self::default_stack()
}
}
impl CameraStack {
#[must_use]
pub const fn empty() -> Self {
Self {
shadows: None,
ambient_occlusion: None,
reflections: None,
bloom: None,
antialiasing: None,
volumetric_fog: None,
auto_exposure: None,
contact_shadows: None,
}
}
#[must_use]
pub const fn default_stack() -> Self {
Self {
shadows: Some(ShadowsPass {}),
ambient_occlusion: Some(AmbientOcclusionPass {}),
reflections: Some(ReflectionsPass {}),
antialiasing: Some(AntialiasingPass {
tier: Antialiasing::Cmaa2,
}),
..Self::empty()
}
}
#[must_use]
pub const fn compile(&self) -> RenderEffects {
let mut effects = RenderEffects::empty();
if self.shadows.is_some() {
effects = effects.union(RenderEffects::SHADOWS);
}
if self.ambient_occlusion.is_some() {
effects = effects.union(RenderEffects::AMBIENT_OCCLUSION);
}
if self.reflections.is_some() {
effects = effects.union(RenderEffects::REFLECTIONS);
}
if self.bloom.is_some() {
effects = effects.union(RenderEffects::BLOOM);
}
if let Some(pass) = self.antialiasing {
effects = effects.union(pass.tier.bits());
}
if self.volumetric_fog.is_some() {
effects = effects.union(RenderEffects::VOLUMETRIC_FOG);
}
if self.auto_exposure.is_some() {
effects = effects.union(RenderEffects::AUTO_EXPOSURE);
}
if self.contact_shadows.is_some() {
effects = effects.union(RenderEffects::CONTACT_SHADOWS);
}
effects
}
pub fn from_ron(text: &str) -> Result<Self, StackError> {
ron::from_str(text).map_err(StackError::from_spanned)
}
#[must_use]
pub fn to_ron(&self) -> String {
ron::ser::to_string_pretty(self, Self::pretty())
.expect("a CameraStack has no serializer path that can fail")
}
fn pretty() -> ron::ser::PrettyConfig {
ron::ser::PrettyConfig::new()
.new_line("\n")
.indentor(" ")
.struct_names(true)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("line {line}, column {column}: {message}")]
pub struct StackError {
line: usize,
column: usize,
message: String,
}
impl StackError {
#[must_use]
pub const fn line(&self) -> usize {
self.line
}
#[must_use]
pub const fn column(&self) -> usize {
self.column
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
fn from_spanned(error: ron::error::SpannedError) -> Self {
Self {
line: error.span.start.line,
column: error.span.start.col,
message: error.code.to_string(),
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn every_field_survives_the_round_trip_and_the_writer_repeats_itself() {
let full = CameraStack {
shadows: Some(ShadowsPass {}),
ambient_occlusion: Some(AmbientOcclusionPass {}),
reflections: Some(ReflectionsPass {}),
bloom: Some(BloomPass {}),
antialiasing: Some(AntialiasingPass {
tier: Antialiasing::Cmaa2,
}),
volumetric_fog: Some(VolumetricFogPass {}),
auto_exposure: Some(AutoExposurePass {}),
contact_shadows: Some(ContactShadowsPass {}),
};
let text = full.to_ron();
assert_eq!(
CameraStack::from_ron(&text).expect("what to_ron wrote has to parse"),
full,
"{text}"
);
assert_eq!(text, full.to_ron(), "the writer is not deterministic");
assert!(
!text.contains('\r'),
"the newline is pinned to \\n, so a Windows host writes the same bytes: {text:?}"
);
let empty = CameraStack::empty();
assert_eq!(
CameraStack::from_ron(&empty.to_ron()).expect("an empty stack parses"),
empty
);
assert_eq!(empty.compile(), RenderEffects::empty());
}
#[test]
fn an_unknown_field_is_refused_by_line_column_and_name() {
let error = CameraStack::from_ron("(\n shadows: Some(()),\n smaa: Some(()),\n)")
.expect_err("`smaa` is not a field of CameraStack");
assert_eq!(error.line(), 3, "{error}");
assert_eq!(error.column(), 5, "{error}");
assert!(
error.message().contains("smaa"),
"the message has to name the field: {error}"
);
assert!(
error.to_string().contains("line 3, column 5"),
"the Display has to carry the position: {error}"
);
assert!(CameraStack::from_ron("(antialiasing: Some((tier: taa)))").is_err());
assert!(CameraStack::from_ron("not ron").is_err());
}
#[test]
fn the_default_stack_compiles_to_the_default_stack() {
assert_eq!(
CameraStack::default_stack().compile(),
RenderEffects::DEFAULT_STACK
);
assert_eq!(CameraStack::default(), CameraStack::default_stack());
}
#[test]
fn a_field_sets_its_own_bit_and_the_fields_cover_every_bit() {
let one = |stack: CameraStack| stack.compile();
for (stack, bit) in [
(
CameraStack {
shadows: Some(ShadowsPass {}),
..CameraStack::empty()
},
RenderEffects::SHADOWS,
),
(
CameraStack {
ambient_occlusion: Some(AmbientOcclusionPass {}),
..CameraStack::empty()
},
RenderEffects::AMBIENT_OCCLUSION,
),
(
CameraStack {
reflections: Some(ReflectionsPass {}),
..CameraStack::empty()
},
RenderEffects::REFLECTIONS,
),
(
CameraStack {
bloom: Some(BloomPass {}),
..CameraStack::empty()
},
RenderEffects::BLOOM,
),
(
CameraStack {
volumetric_fog: Some(VolumetricFogPass {}),
..CameraStack::empty()
},
RenderEffects::VOLUMETRIC_FOG,
),
(
CameraStack {
auto_exposure: Some(AutoExposurePass {}),
..CameraStack::empty()
},
RenderEffects::AUTO_EXPOSURE,
),
(
CameraStack {
contact_shadows: Some(ContactShadowsPass {}),
..CameraStack::empty()
},
RenderEffects::CONTACT_SHADOWS,
),
] {
assert_eq!(one(stack), bit, "{stack:?}");
}
let mut covered = RenderEffects::empty();
for tier in Antialiasing::ALL {
let stack = CameraStack {
antialiasing: Some(AntialiasingPass { tier }),
..CameraStack::empty()
};
assert_eq!(stack.compile(), tier.bits(), "{tier:?}");
assert_eq!(
Antialiasing::from_effects(stack.compile()),
tier,
"{tier:?} did not survive its own stack"
);
covered = covered.union(tier.bits());
}
let mut all = CameraStack {
shadows: Some(ShadowsPass {}),
ambient_occlusion: Some(AmbientOcclusionPass {}),
reflections: Some(ReflectionsPass {}),
bloom: Some(BloomPass {}),
antialiasing: None,
volumetric_fog: Some(VolumetricFogPass {}),
auto_exposure: Some(AutoExposurePass {}),
contact_shadows: Some(ContactShadowsPass {}),
};
covered = covered.union(all.compile());
all.antialiasing = Some(AntialiasingPass {
tier: Antialiasing::Fxaa,
});
covered = covered.union(all.compile());
assert_eq!(
covered,
RenderEffects::all(),
"an effect bit no field of CameraStack names",
);
}
#[test]
fn a_tier_is_spelled_the_way_the_settings_seam_spells_it() {
for tier in Antialiasing::ALL {
let stack = CameraStack {
antialiasing: Some(AntialiasingPass { tier }),
..CameraStack::empty()
};
let text = stack.to_ron();
assert!(
text.contains(&format!("tier: {}", tier.name())),
"{tier:?} is spelled {:?} by the settings seam and {text:?} by this writer",
tier.name(),
);
assert_eq!(
CameraStack::from_ron(&text).expect("a tier round-trips"),
stack
);
}
}
#[test]
fn setting_a_camera_stack_leaves_the_other_three_layers_alone() {
use crcbl_hal::null::NullInstance;
use crcbl_hal::{AdapterId, DeviceDesc, Format, Instance, QueueKind};
use crate::effects::{EffectOverride, EffectRequest};
let instance = NullInstance::gpu_driven();
let device = instance
.create_device(&DeviceDesc {
label: Some("camera stack"),
..DeviceDesc::for_adapter(AdapterId(0))
})
.expect("the null backend always opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
let mut renderer =
crate::ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
.expect("the null backend accepts every descriptor");
let elsewhere = EffectRequest {
camera: RenderEffects::empty(),
video: RenderEffects::all().difference(RenderEffects::BLOOM),
antialiasing: Some(Antialiasing::Cmaa2),
programmatic: EffectOverride::none().force(RenderEffects::CONTACT_SHADOWS, Some(true)),
};
renderer.set_effect_request(elsewhere);
let stack =
CameraStack::from_ron("(shadows: Some(()), bloom: Some(()))").expect("that is a stack");
renderer.set_camera_stack(&stack);
let after = renderer.effect_request();
assert_eq!(
after.camera,
RenderEffects::SHADOWS.union(RenderEffects::BLOOM),
"the camera layer is the file's",
);
assert_eq!(after.video, elsewhere.video, "the video clamp moved");
assert_eq!(
after.antialiasing, elsewhere.antialiasing,
"the player's tier moved",
);
assert_eq!(
after.programmatic, elsewhere.programmatic,
"the programmatic override moved",
);
renderer.destroy(device.as_ref());
}
}