use crate::activity::{Activity, Catalog, MotionKind, builtin_catalog, int_weight};
use crate::archetype::{ARCHETYPE_INFO, ArchetypeInfo};
use crate::palette::{Theme, families_for};
use crate::recipe::{
Aspect, CONTRASTS, Composition, ContentContext, GENERATOR_VERSION, LOOKS, PalettePick,
SceneRecipe, TimeOfDay, ZOOMS,
};
use crate::rng::Rng;
pub fn compose(seed: u64, aspect: Aspect, ctx: &ContentContext) -> SceneRecipe {
compose_with(builtin_catalog(), seed, aspect, ctx)
}
pub fn compose_with(
catalog: &Catalog,
seed: u64,
aspect: Aspect,
ctx: &ContentContext,
) -> SceneRecipe {
let archetypes: Vec<&'static ArchetypeInfo> = ARCHETYPE_INFO
.iter()
.filter(|a| a.implemented && ctx.enabled_archetypes.iter().any(|e| e == a.id))
.collect();
let eligible: Vec<(&Activity, Vec<&'static ArchetypeInfo>)> = catalog
.activities
.iter()
.filter(|a| ctx.enabled_activities.contains(&a.id))
.filter(|a| match ctx.theme {
Some(Theme::Light) => !a.times_in(&TimeOfDay::LIGHT).is_empty(),
Some(Theme::Dark) => !a.times_in(&TimeOfDay::DARK).is_empty(),
None => true,
})
.filter_map(|a| {
let fits: Vec<_> = archetypes
.iter()
.copied()
.filter(|ar| a.fits(ar, &ctx.enabled_weather))
.collect();
(!fits.is_empty()).then_some((a, fits))
})
.collect();
tracing::debug!(
target: "clairlune_scene::compose",
seed,
candidates = ?eligible.iter().map(|(a, f)| (a.id.as_str(), f.len())).collect::<Vec<_>>(),
"activity candidates (id, fitting archetypes)"
);
let picked = pick_activity(seed, &eligible, ctx);
if picked.is_none() {
tracing::warn!(
target: "clairlune_scene::compose",
seed,
"no eligible activity; archetype-first fallback without a character"
);
}
let fallback = [&ARCHETYPE_INFO[0]];
let candidates: &[&ArchetypeInfo] = match picked {
Some((_, fits)) => fits,
None if !archetypes.is_empty() => &archetypes,
None => &fallback,
};
let archetype = pick_archetype(seed, candidates, &eligible, ctx);
let mut tod = Rng::stream(seed, "time_of_day");
let (light_tod, dark_tod) = match picked {
Some((a, _)) => (
pick_opt(&mut tod, &a.times_in(&TimeOfDay::LIGHT)),
pick_opt(&mut tod, &a.times_in(&TimeOfDay::DARK)),
),
None => (
Some(*tod.choose(&TimeOfDay::LIGHT)),
Some(*tod.choose(&TimeOfDay::DARK)),
),
};
let mut wx = Rng::stream(seed, "weather");
let weather = match picked {
Some((a, _)) => {
pick_opt(&mut wx, &a.weathers_in(archetype, &ctx.enabled_weather)).unwrap_or("none")
}
None => "none",
};
let mut platform_rng = Rng::stream(seed, "platform");
let platform = *platform_rng.choose(archetype.platforms);
let mut comp = Rng::stream(seed, "composition");
let portrait = aspect.w < aspect.h;
let horizon_pm = comp.range_u32(560, 700);
let lines: [u32; 3] = if portrait {
[420, 500, 580]
} else {
[333, 500, 667]
};
let focus_base = lines[comp.weighted_index(&[2, 1, 2])];
let focus_x_pm = (focus_base as i32 + comp.range_i32(-30, 30)) as u32;
let gap_pm = comp.range_u32(200, 340);
let shape_pow_pm = comp.range_u32(450, 850);
let platform_margin_pm = comp.range_u32(12, 40);
let mut props_rng = Rng::stream(seed, "props");
let prop_left = props_rng.chance(1, 2);
let mut motion = Rng::stream(seed, "motion");
let (motion_speed_cc, pace_half_pm, fly_lift_pm) =
match picked.map(|(a, _)| (&a.motion.kind, a.motion.speed_cells_per_s)) {
Some((MotionKind::Pace, Some([lo, hi]))) => {
let (lo, hi) = ((lo * 100.0).round() as u32, (hi * 100.0).round() as u32);
(
motion.range_u32(lo, hi.max(lo)),
motion.range_u32(60, 140),
0,
)
}
Some((MotionKind::Bob, Some([lo, hi]))) => {
let (lo, hi) = ((lo * 100.0).round() as u32, (hi * 100.0).round() as u32);
(motion.range_u32(lo, hi.max(lo)), 0, 0)
}
Some((MotionKind::Fly, Some([lo, hi]))) => {
let (lo, hi) = ((lo * 100.0).round() as u32, (hi * 100.0).round() as u32);
(
motion.range_u32(lo, hi.max(lo)),
0,
motion.range_u32(170, 270),
)
}
_ => (0, 0, 0),
};
let journey_pace_c = match picked.map(|(a, _)| (&a.motion.kind, a.motion.speed_cells_per_s)) {
Some((MotionKind::Journey, Some([lo, hi]))) => {
let (lo, hi) = ((lo * 100.0).round() as u32, (hi * 100.0).round() as u32);
motion.range_u32(lo, hi.max(lo))
}
_ => 0,
};
let landmark = if journey_pace_c > 0 {
let options = crate::terrain::landmark::options(archetype.id);
let mut lm = Rng::stream(seed, "landmark");
if !options.is_empty() && lm.chance(5, 6) {
lm.choose(options).to_string()
} else {
String::new()
}
} else {
String::new()
};
let mut look_rng = Rng::stream(seed, "look");
let looks: Vec<&str> = LOOKS
.iter()
.copied()
.filter(|l| ctx.enabled_looks.iter().any(|e| e == l))
.collect();
let look = if looks.is_empty() {
"line"
} else {
*look_rng.choose(&looks)
};
let zooms: Vec<&str> = ZOOMS
.iter()
.copied()
.filter(|z| ctx.enabled_zooms.iter().any(|e| e == z))
.collect();
let zoom = match zooms.as_slice() {
[] => "close",
[only] => only,
_ => *Rng::stream(seed, "zoom").choose(&zooms),
};
let contrast = match ctx.contrast.as_str() {
"vary" => *look_rng.choose(&CONTRASTS),
c if CONTRASTS.contains(&c) => c,
_ => "normal",
};
let mut pal = Rng::stream(seed, "palette");
let light: Vec<_> = families_for(Theme::Light).collect();
let dark: Vec<_> = families_for(Theme::Dark).collect();
let light_family = pal.choose(&light).id.to_string();
let dark_family = pal.choose(&dark).id.to_string();
let recipe = SceneRecipe {
generator_version: GENERATOR_VERSION,
seed,
aspect,
content_ctx_hash: format!("{:016x}", ctx.hash()),
activity: picked.map(|(a, _)| a.id.clone()),
archetype: archetype.id.to_string(),
light_tod,
dark_tod,
platform: platform.to_string(),
props: picked
.map(|(a, _)| a.props.keys().cloned().collect())
.unwrap_or_default(),
weather: weather.to_string(),
composition: Composition {
horizon_pm,
focus_x_pm,
gap_pm,
shape_pow_pm,
platform_margin_pm,
cliff_layers: 3,
prop_left,
motion_speed_cc,
pace_half_pm,
fly_lift_pm,
journey_ms: 0,
journey_pace_c,
landmark,
},
palette: PalettePick {
light: light_family,
dark: dark_family,
},
look: look.to_string(),
contrast: contrast.to_string(),
zoom: zoom.to_string(),
};
log_composed(&recipe, eligible.len());
recipe
}
fn log_composed(r: &SceneRecipe, eligible: usize) {
if tracing::enabled!(target: "clairlune_scene::compose", tracing::Level::INFO) {
tracing::info!(
target: "clairlune_scene::compose",
seed = r.seed,
recipe_hash = %r.hash_hex(),
generator_version = r.generator_version,
activity = r.activity.as_deref().unwrap_or("-"),
archetype = %r.archetype,
light_tod = ?r.light_tod,
dark_tod = ?r.dark_tod,
eligible,
"scene composed"
);
}
}
fn pick_opt<T: Copy>(rng: &mut Rng, items: &[T]) -> Option<T> {
(!items.is_empty()).then(|| *rng.choose(items))
}
fn pick_activity<'a, 'b>(
seed: u64,
eligible: &'b [(&'a Activity, Vec<&'static ArchetypeInfo>)],
ctx: &ContentContext,
) -> Option<&'b (&'a Activity, Vec<&'static ArchetypeInfo>)> {
if eligible.is_empty() {
return None;
}
let last = ctx.recent.last().and_then(|h| h.activity.as_deref());
let spread = spread(eligible);
let weights: Vec<u32> = eligible
.iter()
.zip(&spread)
.map(|((a, _), &s)| {
if eligible.len() > 1 && Some(a.id.as_str()) == last {
return 0;
}
let uses = ctx
.recent
.iter()
.filter(|h| h.activity.as_deref() == Some(a.id.as_str()))
.count() as u32;
let w = int_weight(a.weight).saturating_mul(4) / (4 + uses);
((f64::from(w) * s).round() as u32).max(1)
})
.collect();
let mut rng = Rng::stream(seed, "activity");
Some(&eligible[rng.weighted_index(&weights)])
}
fn spread(eligible: &[(&Activity, Vec<&'static ArchetypeInfo>)]) -> Vec<f64> {
let hosted = |id: &str| -> f64 {
eligible
.iter()
.filter(|(_, fits)| fits.iter().any(|f| f.id == id))
.map(|(a, _)| f64::from(int_weight(a.weight)))
.sum::<f64>()
.max(1.0)
};
let splits: Vec<Vec<(&str, f64)>> = eligible
.iter()
.map(|(_, fits)| {
let inv: Vec<f64> = fits.iter().map(|f| 1.0 / hosted(f.id)).collect();
let total: f64 = inv.iter().sum();
fits.iter()
.zip(inv)
.map(|(f, i)| (f.id, i / total))
.collect()
})
.collect();
let mut load: Vec<(&str, f64)> = Vec::new();
for ((a, _), split) in eligible.iter().zip(&splits) {
let w = f64::from(int_weight(a.weight));
for &(id, share) in split {
match load.iter_mut().find(|(l, _)| *l == id) {
Some((_, v)) => *v += w * share,
None => load.push((id, w * share)),
}
}
}
if load.is_empty() {
return vec![1.0; eligible.len()];
}
let fair = load.iter().map(|(_, v)| v).sum::<f64>() / load.len() as f64;
splits
.iter()
.map(|split| {
let f: f64 = split
.iter()
.map(|&(id, share)| {
let l = load
.iter()
.find(|(l, _)| *l == id)
.map_or(fair, |(_, v)| *v);
share * (fair / l).min(1.0)
})
.sum();
f.sqrt().max(0.5)
})
.collect()
}
fn pick_archetype(
seed: u64,
candidates: &[&'static ArchetypeInfo],
eligible: &[(&Activity, Vec<&'static ArchetypeInfo>)],
ctx: &ContentContext,
) -> &'static ArchetypeInfo {
let last = ctx.recent.last().map(|h| h.archetype.as_str());
let hosted = |id: &str| -> u64 {
eligible
.iter()
.filter(|(_, fits)| fits.iter().any(|f| f.id == id))
.map(|(a, _)| u64::from(int_weight(a.weight)))
.sum::<u64>()
.max(1)
};
let weights: Vec<u32> = candidates
.iter()
.map(|a| {
let base: u64 = if candidates.len() > 1 && Some(a.id) == last {
1
} else {
4
};
(base * 1_000_000 / hosted(a.id)).max(1) as u32
})
.collect();
let mut rng = Rng::stream(seed, "archetype");
candidates[rng.weighted_index(&weights)]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::recipe::HistoryEntry;
#[test]
fn a_known_theme_only_gets_scenes_that_have_it() {
for theme in [Theme::Light, Theme::Dark] {
let ctx = ContentContext {
theme: Some(theme),
..ContentContext::default()
};
for seed in 0..300 {
let r = compose(seed, Aspect::from_size(1920, 1080), &ctx);
assert!(
r.tod_for(theme).is_some(),
"seed {seed}: {:?} has no {theme:?} variant",
r.activity
);
}
}
let any = ContentContext::default();
assert!(
(0..300).any(|s| compose(s, Aspect::from_size(1920, 1080), &any).is_theme_locked())
);
}
#[test]
fn compose_is_deterministic() {
let ctx = ContentContext::default();
let a = compose(7, Aspect::from_size(3840, 2160), &ctx);
let b = compose(7, Aspect::from_size(3840, 2160), &ctx);
assert_eq!(a.to_json(), b.to_json());
assert_eq!(a.aspect, Aspect { w: 16, h: 9 });
assert!(a.activity.is_some());
}
#[test]
fn recipe_round_trips_through_json() {
let r = compose(
123,
Aspect::from_size(1920, 1080),
&ContentContext::default(),
);
let back = SceneRecipe::from_json(&r.to_json()).unwrap();
assert_eq!(r, back);
}
#[test]
fn different_seeds_differ() {
let ctx = ContentContext::default();
let a = compose(1, Aspect::from_size(16, 9), &ctx);
let b = compose(2, Aspect::from_size(16, 9), &ctx);
assert_ne!(a.composition, b.composition);
}
#[test]
fn night_only_activities_are_theme_locked() {
let ctx = ContentContext {
enabled_activities: vec!["stargaze".into()],
..ContentContext::default()
};
let r = compose(5, Aspect::from_size(16, 9), &ctx);
assert_eq!(r.activity.as_deref(), Some("stargaze"));
assert!(r.light_tod.is_none() && r.dark_tod.is_some());
assert!(r.is_theme_locked());
}
#[test]
fn never_repeats_the_last_activity_when_there_is_a_choice() {
for seed in 0..200 {
let mut ctx = ContentContext::default();
ctx.recent.push(HistoryEntry {
activity: Some("warm_hands".into()),
archetype: "canyon".into(),
platform: "rock_ledge".into(),
prop: None,
});
assert_ne!(
compose(seed, Aspect::from_size(16, 9), &ctx)
.activity
.as_deref(),
Some("warm_hands")
);
}
}
#[test]
fn falls_back_when_nothing_is_eligible() {
let ctx = ContentContext {
enabled_activities: vec![],
..ContentContext::default()
};
let r = compose(9, Aspect::from_size(16, 9), &ctx);
assert_eq!(r.activity, None);
assert!(r.props.is_empty());
assert!(crate::terrain::PAINTED.contains(&r.archetype.as_str()));
}
}