Skip to main content

clairlune_scene/
compose.rs

1//! `compose(seed, aspect, ctx) -> SceneRecipe`: sequential, seeded, weighted picks.
2//!
3//! The activity is picked first (PLAN.md section 4.2, step 0) and constrains
4//! every later pick: archetype, time of day per theme, weather and props. Each
5//! subsystem draws from its own RNG stream, so adding a pick in one place never
6//! shifts the draws of another. When no activity is eligible, the scene falls back
7//! to an archetype-first composition with no character.
8
9use crate::activity::{Activity, Catalog, MotionKind, builtin_catalog, int_weight};
10use crate::archetype::{ARCHETYPE_INFO, ArchetypeInfo};
11use crate::palette::{Theme, families_for};
12use crate::recipe::{
13    Aspect, Composition, ContentContext, GENERATOR_VERSION, PalettePick, SceneRecipe, TimeOfDay,
14};
15use crate::rng::Rng;
16
17/// Builds a recipe from the built-in activity catalog.
18pub fn compose(seed: u64, aspect: Aspect, ctx: &ContentContext) -> SceneRecipe {
19    compose_with(builtin_catalog(), seed, aspect, ctx)
20}
21
22/// Builds a recipe. Pure: same inputs, same recipe, on every platform.
23pub fn compose_with(
24    catalog: &Catalog,
25    seed: u64,
26    aspect: Aspect,
27    ctx: &ContentContext,
28) -> SceneRecipe {
29    let archetypes: Vec<&'static ArchetypeInfo> = ARCHETYPE_INFO
30        .iter()
31        .filter(|a| a.implemented && ctx.enabled_archetypes.iter().any(|e| e == a.id))
32        .collect();
33
34    // Step 0: activity, among those with at least one archetype that fits.
35    let eligible: Vec<(&Activity, Vec<&'static ArchetypeInfo>)> = catalog
36        .activities
37        .iter()
38        .filter(|a| ctx.enabled_activities.contains(&a.id))
39        .filter_map(|a| {
40            let fits: Vec<_> = archetypes
41                .iter()
42                .copied()
43                .filter(|ar| a.fits(ar, &ctx.enabled_weather))
44                .collect();
45            (!fits.is_empty()).then_some((a, fits))
46        })
47        .collect();
48    tracing::debug!(
49        target: "clairlune_scene::compose",
50        seed,
51        candidates = ?eligible.iter().map(|(a, f)| (a.id.as_str(), f.len())).collect::<Vec<_>>(),
52        "activity candidates (id, fitting archetypes)"
53    );
54    let picked = pick_activity(seed, &eligible, ctx);
55    if picked.is_none() {
56        tracing::warn!(
57            target: "clairlune_scene::compose",
58            seed,
59            "no eligible activity; archetype-first fallback without a character"
60        );
61    }
62
63    // Step 1: archetype.
64    let fallback = [&ARCHETYPE_INFO[0]];
65    let candidates: &[&ArchetypeInfo] = match picked {
66        Some((_, fits)) => fits,
67        None if !archetypes.is_empty() => &archetypes,
68        None => &fallback,
69    };
70    let archetype = pick_archetype(seed, candidates, ctx);
71
72    // Step 2: one time of day per theme, from what the activity allows.
73    let mut tod = Rng::stream(seed, "time_of_day");
74    let (light_tod, dark_tod) = match picked {
75        Some((a, _)) => (
76            pick_opt(&mut tod, &a.times_in(&TimeOfDay::LIGHT)),
77            pick_opt(&mut tod, &a.times_in(&TimeOfDay::DARK)),
78        ),
79        None => (
80            Some(*tod.choose(&TimeOfDay::LIGHT)),
81            Some(*tod.choose(&TimeOfDay::DARK)),
82        ),
83    };
84
85    // Step 3: weather the activity, archetype and user all allow.
86    let mut wx = Rng::stream(seed, "weather");
87    let weather = match picked {
88        Some((a, _)) => {
89            pick_opt(&mut wx, &a.weathers_in(archetype, &ctx.enabled_weather)).unwrap_or("none")
90        }
91        None => "none",
92    };
93
94    let mut platform_rng = Rng::stream(seed, "platform");
95    let platform = *platform_rng.choose(archetype.platforms);
96
97    // Composition variables.
98    let mut comp = Rng::stream(seed, "composition");
99    let portrait = aspect.w < aspect.h;
100    let horizon_pm = comp.range_u32(560, 700);
101    // Rule-of-thirds lines are favoured over the centre. Portrait stays nearer the middle.
102    let lines: [u32; 3] = if portrait {
103        [420, 500, 580]
104    } else {
105        [333, 500, 667]
106    };
107    let focus_base = lines[comp.weighted_index(&[2, 1, 2])];
108    let focus_x_pm = (focus_base as i32 + comp.range_i32(-30, 30)) as u32;
109    let gap_pm = comp.range_u32(200, 340);
110    // Below 1 the wall profile is convex: steep cliff faces, then a plateau.
111    let shape_pow_pm = comp.range_u32(450, 850);
112    let platform_margin_pm = comp.range_u32(12, 40);
113
114    // Props and motion, from the activity.
115    let mut props_rng = Rng::stream(seed, "props");
116    let prop_left = props_rng.chance(1, 2);
117    let mut motion = Rng::stream(seed, "motion");
118    let (motion_speed_cc, pace_half_pm) =
119        match picked.map(|(a, _)| (&a.motion.kind, a.motion.speed_cells_per_s)) {
120            Some((MotionKind::Pace, Some([lo, hi]))) => {
121                let (lo, hi) = ((lo * 100.0).round() as u32, (hi * 100.0).round() as u32);
122                (motion.range_u32(lo, hi.max(lo)), motion.range_u32(60, 140))
123            }
124            _ => (0, 0),
125        };
126
127    let mut pal = Rng::stream(seed, "palette");
128    let light: Vec<_> = families_for(Theme::Light).collect();
129    let dark: Vec<_> = families_for(Theme::Dark).collect();
130    let light_family = pal.choose(&light).id.to_string();
131    let dark_family = pal.choose(&dark).id.to_string();
132
133    let recipe = SceneRecipe {
134        generator_version: GENERATOR_VERSION,
135        seed,
136        aspect,
137        content_ctx_hash: format!("{:016x}", ctx.hash()),
138        activity: picked.map(|(a, _)| a.id.clone()),
139        archetype: archetype.id.to_string(),
140        light_tod,
141        dark_tod,
142        platform: platform.to_string(),
143        props: picked
144            .map(|(a, _)| a.props.keys().cloned().collect())
145            .unwrap_or_default(),
146        weather: weather.to_string(),
147        composition: Composition {
148            horizon_pm,
149            focus_x_pm,
150            gap_pm,
151            shape_pow_pm,
152            platform_margin_pm,
153            cliff_layers: 3,
154            prop_left,
155            motion_speed_cc,
156            pace_half_pm,
157        },
158        palette: PalettePick {
159            light: light_family,
160            dark: dark_family,
161        },
162    };
163    log_composed(&recipe, eligible.len());
164    recipe
165}
166
167/// One `info` line per composed scene, with everything needed to reproduce it.
168fn log_composed(r: &SceneRecipe, eligible: usize) {
169    if tracing::enabled!(target: "clairlune_scene::compose", tracing::Level::INFO) {
170        tracing::info!(
171            target: "clairlune_scene::compose",
172            seed = r.seed,
173            recipe_hash = %r.hash_hex(),
174            generator_version = r.generator_version,
175            activity = r.activity.as_deref().unwrap_or("-"),
176            archetype = %r.archetype,
177            light_tod = ?r.light_tod,
178            dark_tod = ?r.dark_tod,
179            eligible,
180            "scene composed"
181        );
182    }
183}
184
185fn pick_opt<T: Copy>(rng: &mut Rng, items: &[T]) -> Option<T> {
186    (!items.is_empty()).then(|| *rng.choose(items))
187}
188
189/// Weighted pick. The most recent activity is excluded unless it is the only one,
190/// and activities used often in the recent history are down-weighted.
191fn pick_activity<'a, 'b>(
192    seed: u64,
193    eligible: &'b [(&'a Activity, Vec<&'static ArchetypeInfo>)],
194    ctx: &ContentContext,
195) -> Option<&'b (&'a Activity, Vec<&'static ArchetypeInfo>)> {
196    if eligible.is_empty() {
197        return None;
198    }
199    let last = ctx.recent.last().and_then(|h| h.activity.as_deref());
200    let weights: Vec<u32> = eligible
201        .iter()
202        .map(|(a, _)| {
203            if eligible.len() > 1 && Some(a.id.as_str()) == last {
204                return 0;
205            }
206            let uses = ctx
207                .recent
208                .iter()
209                .filter(|h| h.activity.as_deref() == Some(a.id.as_str()))
210                .count() as u32;
211            (int_weight(a.weight) * 4 / (4 + uses)).max(1)
212        })
213        .collect();
214    let mut rng = Rng::stream(seed, "activity");
215    Some(&eligible[rng.weighted_index(&weights)])
216}
217
218/// Weighted pick with the most recent archetype down-weighted.
219fn pick_archetype(
220    seed: u64,
221    candidates: &[&'static ArchetypeInfo],
222    ctx: &ContentContext,
223) -> &'static ArchetypeInfo {
224    let last = ctx.recent.last().map(|h| h.archetype.as_str());
225    let weights: Vec<u32> = candidates
226        .iter()
227        .map(|a| {
228            if candidates.len() > 1 && Some(a.id) == last {
229                1
230            } else {
231                4
232            }
233        })
234        .collect();
235    let mut rng = Rng::stream(seed, "archetype");
236    candidates[rng.weighted_index(&weights)]
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use crate::recipe::HistoryEntry;
243
244    #[test]
245    fn compose_is_deterministic() {
246        let ctx = ContentContext::default();
247        let a = compose(7, Aspect::from_size(3840, 2160), &ctx);
248        let b = compose(7, Aspect::from_size(3840, 2160), &ctx);
249        assert_eq!(a.to_json(), b.to_json());
250        assert_eq!(a.aspect, Aspect { w: 16, h: 9 });
251        assert!(a.activity.is_some());
252    }
253
254    #[test]
255    fn recipe_round_trips_through_json() {
256        let r = compose(
257            123,
258            Aspect::from_size(1920, 1080),
259            &ContentContext::default(),
260        );
261        let back = SceneRecipe::from_json(&r.to_json()).unwrap();
262        assert_eq!(r, back);
263    }
264
265    #[test]
266    fn different_seeds_differ() {
267        let ctx = ContentContext::default();
268        let a = compose(1, Aspect::from_size(16, 9), &ctx);
269        let b = compose(2, Aspect::from_size(16, 9), &ctx);
270        assert_ne!(a.composition, b.composition);
271    }
272
273    #[test]
274    fn night_only_activities_are_theme_locked() {
275        let ctx = ContentContext {
276            enabled_activities: vec!["stargaze".into()],
277            ..ContentContext::default()
278        };
279        let r = compose(5, Aspect::from_size(16, 9), &ctx);
280        assert_eq!(r.activity.as_deref(), Some("stargaze"));
281        assert!(r.light_tod.is_none() && r.dark_tod.is_some());
282        assert!(r.is_theme_locked());
283    }
284
285    #[test]
286    fn never_repeats_the_last_activity_when_there_is_a_choice() {
287        for seed in 0..200 {
288            let mut ctx = ContentContext::default();
289            ctx.recent.push(HistoryEntry {
290                activity: Some("warm_hands".into()),
291                archetype: "canyon".into(),
292                platform: "rock_ledge".into(),
293                prop: None,
294            });
295            assert_ne!(
296                compose(seed, Aspect::from_size(16, 9), &ctx)
297                    .activity
298                    .as_deref(),
299                Some("warm_hands")
300            );
301        }
302    }
303
304    #[test]
305    fn falls_back_when_nothing_is_eligible() {
306        let ctx = ContentContext {
307            enabled_activities: vec![],
308            ..ContentContext::default()
309        };
310        let r = compose(9, Aspect::from_size(16, 9), &ctx);
311        assert_eq!(r.activity, None);
312        assert!(r.props.is_empty());
313        assert_eq!(r.archetype, "canyon");
314    }
315}