use indicatrix::{
optics::raytracer::EnvironmentSource,
renderer::env_map::{EnvironmentMap, HdrLimits, environment_from_hdr_bytes},
};
use indicatrix_net::{
SceneState,
messages::{ContentHash, hash_hex},
scene::HdrEnvironment,
};
use std::{
collections::VecDeque,
sync::{Arc, Mutex, PoisonError, Weak},
};
const RECENT_KEEP: usize = 2;
static REGISTERED: Mutex<Vec<(ContentHash, Weak<EnvironmentMap>)>> = Mutex::new(Vec::new());
static RECENT: Mutex<VecDeque<(ContentHash, Arc<EnvironmentMap>)>> = Mutex::new(VecDeque::new());
static DECODE_LOCK: Mutex<()> = Mutex::new(());
#[must_use]
pub fn lookup(hash: &ContentHash) -> Option<Arc<EnvironmentMap>> {
let found = REGISTERED
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.rev()
.filter(|(h, _)| h == hash)
.find_map(|(_, weak)| weak.upgrade());
if let Some(map) = &found {
remember_recent(hash, map);
}
found
}
pub fn decode_and_register(
expected: &HdrEnvironment,
bytes: &[u8],
) -> Result<Arc<EnvironmentMap>, String> {
let map = {
let _one_at_a_time = DECODE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
environment_from_hdr_bytes(bytes, HdrLimits::DEFAULT).map_err(|e| e.to_string())?
};
if (map.width(), map.height()) != (expected.width as usize, expected.height as usize) {
return Err(format!(
"the HDR map decodes to {}x{} texels but the scene declared {}x{}",
map.width(),
map.height(),
expected.width,
expected.height
));
}
let map = Arc::new(map);
let mut registered = REGISTERED.lock().unwrap_or_else(PoisonError::into_inner);
registered.retain(|(h, weak)| *h != expected.content_hash || weak.strong_count() > 0);
registered.push((expected.content_hash, Arc::downgrade(&map)));
drop(registered);
remember_recent(&expected.content_hash, &map);
Ok(map)
}
fn remember_recent(hash: &ContentHash, map: &Arc<EnvironmentMap>) {
push_recent(
&mut RECENT.lock().unwrap_or_else(PoisonError::into_inner),
hash,
map,
);
}
fn push_recent(
recent: &mut VecDeque<(ContentHash, Arc<EnvironmentMap>)>,
hash: &ContentHash,
map: &Arc<EnvironmentMap>,
) {
recent.retain(|(h, _)| h != hash);
recent.push_back((*hash, Arc::clone(map)));
while recent.len() > RECENT_KEEP {
recent.pop_front();
}
}
#[must_use]
pub fn resolved_hdr_map(scene: &SceneState) -> Option<Arc<EnvironmentMap>> {
let hdr = scene.hdr()?;
Some(lookup(&hdr.content_hash).unwrap_or_else(|| {
panic!(
"HDR environment {} was not resolved before tracing (the request path must fetch it first)",
hash_hex(&hdr.content_hash)
)
}))
}
#[must_use]
pub fn environment_source<'a>(
scene: &SceneState,
hdr_map: Option<&'a EnvironmentMap>,
) -> EnvironmentSource<'a> {
hdr_map.map_or_else(
|| {
scene
.lighting_preset
.studio(scene.exposure, scene.light_yaw, scene.light_pitch)
.with_backdrop(scene.backdrop)
.with_surface_glare(scene.surface_glare)
.with_head_shadow(scene.head_shadow_deg)
},
EnvironmentSource::HdrMap,
)
}