use crate::render_core::hybrid::JobKey;
use std::{
collections::BTreeMap,
sync::{LazyLock, Mutex},
time::Duration,
};
pub(super) const TARGET_SUBBATCH: Duration = Duration::from_millis(100);
pub(super) const MAX_SUBBATCH: u32 = 2048;
#[must_use]
pub(super) fn next_batch_size(prev: u32, elapsed: Duration) -> u32 {
if elapsed.is_zero() {
return prev.saturating_mul(4).clamp(1, MAX_SUBBATCH);
}
let ratio = TARGET_SUBBATCH.as_secs_f64() / elapsed.as_secs_f64();
let scaled = f64::from(prev) * ratio;
let max_growth = f64::from(prev.saturating_mul(4).clamp(1, MAX_SUBBATCH));
scaled.clamp(1.0, max_growth).round() as u32
}
static CONVERGED_SUBBATCH: LazyLock<Mutex<BTreeMap<JobKey, u32>>> =
LazyLock::new(|| Mutex::new(BTreeMap::new()));
#[must_use]
pub(super) fn seeded_batch_size(key: JobKey) -> u32 {
CONVERGED_SUBBATCH
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(&key)
.copied()
.unwrap_or(1)
}
pub(super) fn remember_converged_subbatch(key: JobKey, size: u32) {
CONVERGED_SUBBATCH
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(key, size);
}
#[cfg(test)]
mod cache_tests {
use super::*;
use crate::{cli::ComputeMode, render_core::hybrid::job_key};
use indicatrix::{
geometry::cuts::StandardGemCuts,
optics::{materials::GemMaterial, raytracer::LightingPreset},
renderer::gpu_backend::GpuBackend,
};
use indicatrix_net::SceneState;
fn tiny_scene() -> SceneState {
SceneState {
width: 8,
height: 8,
yaw: 0.4,
pitch: 0.3,
distance: 3.0,
light_yaw: 0.85,
light_pitch: 0.95,
exposure: 1.0,
max_bounces: 4,
lighting_preset: LightingPreset::Daylight,
material: GemMaterial::diamond(),
planes: StandardGemCuts::standard_round_brilliant(),
girdle_frosted: false,
backdrop: 0.0,
environment: indicatrix_net::scene::SceneEnvironment::Studio,
surface_glare: 1.0,
tools: Vec::new(),
fluorescence: indicatrix::optics::fluorescence::Fluorescence::default(),
head_shadow_deg: 16.0,
}
}
#[test]
fn seeded_batch_size_defaults_to_one_before_anything_is_recorded() {
let gpu = GpuBackend::disabled();
let key = job_key(&gpu, &tiny_scene(), 11, ComputeMode::Hybrid);
assert_eq!(seeded_batch_size(key), 1);
}
#[test]
fn remember_then_seed_round_trips_the_converged_size() {
let gpu = GpuBackend::disabled();
let key = job_key(&gpu, &tiny_scene(), 12, ComputeMode::Hybrid);
remember_converged_subbatch(key, 512);
assert_eq!(seeded_batch_size(key), 512);
remember_converged_subbatch(key, 640);
assert_eq!(seeded_batch_size(key), 640);
}
#[test]
fn different_keys_never_share_a_converged_size() {
let gpu = GpuBackend::disabled();
let scene = tiny_scene();
let a = job_key(&gpu, &scene, 13, ComputeMode::Hybrid);
let b = job_key(&gpu, &scene, 14, ComputeMode::Hybrid);
remember_converged_subbatch(a, 900);
assert_eq!(
seeded_batch_size(b),
1,
"an unrelated key must not see `a`'s size"
);
assert_eq!(seeded_batch_size(a), 900);
}
}