Skip to main content

grafik/
scene.rs

1use core::fmt;
2use serde::{Deserialize, Serialize};
3
4use crate::{FinalDisposition, Point, Rect};
5
6const SCENE_FORMAT_VERSION: u16 = 1;
7const ABSOLUTE_MAX_NODES: u8 = 48;
8const ABSOLUTE_MAX_DEPTH: u8 = 5;
9const ABSOLUTE_MAX_ACTIONS: u8 = 8;
10const ABSOLUTE_MAX_DIAGRAM_NODES: u8 = 16;
11const ABSOLUTE_MAX_DIAGRAM_EDGES: u8 = 24;
12const ABSOLUTE_MAX_EFFECTS: u8 = 12;
13const ABSOLUTE_MAX_PHASES: u8 = 4;
14const ABSOLUTE_MAX_LIVE_EFFECTS: u8 = 5;
15const ABSOLUTE_MAX_FRAGMENTS: u8 = 8;
16const ABSOLUTE_MAX_DISPLACEMENT: u8 = 3;
17const ABSOLUTE_MAX_PHASE_MS: u16 = 2_400;
18const ABSOLUTE_MAX_INTERACTION_MS: u32 = 8_000;
19const ABSOLUTE_MAX_JSON_BYTES: u32 = 65_536;
20const MAX_TEXT_BYTES: usize = 512;
21
22/// Curated amount of decorative motion and variation in a scene.
23#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum SceneRecipe {
26    /// Sparse decoration and the shortest scripts.
27    Calm,
28    /// A balanced selection of local patterns.
29    Balanced,
30    /// The highest density allowed by the supplied hard budgets.
31    Vivid,
32}
33
34/// Hard caller limits that may only narrow Grafik's absolute budgets.
35#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
36pub struct SceneBudgets {
37    /// Maximum nodes in the complete scene tree.
38    pub max_nodes: u8,
39    /// Maximum scene-tree depth.
40    pub max_depth: u8,
41    /// Maximum actions in the scene.
42    pub max_actions: u8,
43    /// Maximum diagram nodes.
44    pub max_diagram_nodes: u8,
45    /// Maximum diagram edges.
46    pub max_diagram_edges: u8,
47    /// Maximum effect plans in the scene.
48    pub max_effects: u8,
49    /// Maximum phases in one effect plan.
50    pub max_phases_per_effect: u8,
51    /// Maximum simultaneously live effects.
52    pub max_live_effects: u8,
53    /// Maximum fragments emitted by one effect.
54    pub max_fragments: u8,
55    /// Maximum decorative displacement in CSS pixels.
56    pub max_displacement: u8,
57    /// Maximum duration of one phase in milliseconds.
58    pub max_phase_ms: u16,
59    /// Maximum duration of one interaction in milliseconds.
60    pub max_interaction_ms: u32,
61    /// Maximum serialized scene-plan size in bytes.
62    pub max_json_bytes: u32,
63}
64
65impl Default for SceneBudgets {
66    fn default() -> Self {
67        Self {
68            max_nodes: ABSOLUTE_MAX_NODES,
69            max_depth: ABSOLUTE_MAX_DEPTH,
70            max_actions: ABSOLUTE_MAX_ACTIONS,
71            max_diagram_nodes: ABSOLUTE_MAX_DIAGRAM_NODES,
72            max_diagram_edges: ABSOLUTE_MAX_DIAGRAM_EDGES,
73            max_effects: ABSOLUTE_MAX_EFFECTS,
74            max_phases_per_effect: ABSOLUTE_MAX_PHASES,
75            max_live_effects: ABSOLUTE_MAX_LIVE_EFFECTS,
76            max_fragments: ABSOLUTE_MAX_FRAGMENTS,
77            max_displacement: ABSOLUTE_MAX_DISPLACEMENT,
78            max_phase_ms: ABSOLUTE_MAX_PHASE_MS,
79            max_interaction_ms: ABSOLUTE_MAX_INTERACTION_MS,
80            max_json_bytes: ABSOLUTE_MAX_JSON_BYTES,
81        }
82    }
83}
84
85/// One key/value fact displayed in a receipt.
86#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
87pub struct FactContent {
88    /// Visible fact label.
89    pub label: String,
90    /// Visible fact value.
91    pub value: String,
92}
93
94/// One caller-provided action displayed as a native browser control.
95#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
96pub struct ActionContent {
97    /// Stable caller key used to derive a generated action ID.
98    pub key: String,
99    /// Visible accessible action label.
100    pub label: String,
101}
102
103/// Bounded semantic display content used to generate a receipt scene.
104#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
105pub struct ReceiptContent {
106    /// Short context line above the title.
107    pub eyebrow: String,
108    /// Primary receipt title.
109    pub title: String,
110    /// Canonical result value preserved by Grafik.
111    pub outcome: FinalDisposition,
112    /// Label/value facts.
113    pub facts: Vec<FactContent>,
114    /// Ordered evidence list.
115    pub evidence: Vec<String>,
116    /// Table column labels.
117    pub table_headers: Vec<String>,
118    /// Table rows, each matching the header count.
119    pub table_rows: Vec<Vec<String>>,
120    /// Labels used to construct generated diagram topology.
121    pub diagram_labels: Vec<String>,
122    /// Native actions with deterministic generated IDs.
123    pub actions: Vec<ActionContent>,
124    /// Native menu item labels.
125    pub menu_items: Vec<String>,
126}
127
128/// Complete controlled input for renderer-neutral scene generation.
129#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
130pub struct SceneRequest {
131    /// Nonzero deterministic replay seed.
132    pub seed: u64,
133    /// Curated variation profile.
134    pub recipe: SceneRecipe,
135    /// Caller-provided bounded display content.
136    pub content: ReceiptContent,
137    /// Hard limits that generation must not exceed.
138    pub budgets: SceneBudgets,
139}
140
141/// Curated responsive receipt arrangement.
142#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
143#[serde(rename_all = "snake_case")]
144pub enum LayoutProfile {
145    /// Single-column technical instrument.
146    Instrument,
147    /// Evidence and result split across the field.
148    Split,
149    /// Asymmetric twelve-column composition.
150    Asymmetric,
151    /// Result-first composition.
152    ResultLed,
153    /// Diagram-first composition.
154    DiagramLed,
155    /// Dense terminal-like receipt.
156    Terminal,
157    /// Sparse editorial receipt.
158    Editorial,
159}
160
161/// Stable kind of one scene-tree node.
162#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
163#[serde(rename_all = "snake_case")]
164pub enum SceneNodeKind {
165    /// Root scene frame.
166    Frame,
167    /// Receipt heading group.
168    Header,
169    /// Label/value fact group.
170    Facts,
171    /// Ordered evidence list.
172    List,
173    /// Bounded data table.
174    Table,
175    /// Diagram host.
176    Diagram,
177    /// Canonical result group.
178    Result,
179    /// Native action group.
180    Actions,
181    /// Native menu group.
182    Menu,
183}
184
185/// Curated placement role interpreted responsively by a browser adapter.
186#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
187#[serde(rename_all = "snake_case")]
188pub enum GridRole {
189    /// Scene-wide frame.
190    Frame,
191    /// Leading region.
192    Lead,
193    /// Primary content region.
194    Primary,
195    /// Secondary content region.
196    Secondary,
197    /// Full-width content region.
198    Full,
199    /// Result emphasis region.
200    Outcome,
201    /// Trailing action region.
202    Footer,
203}
204
205/// Semantic visual intent interpreted by a concrete renderer.
206#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
207#[serde(rename_all = "snake_case")]
208pub enum VisualRole {
209    /// Visually subordinate content.
210    Quiet,
211    /// Default readable content.
212    Standard,
213    /// Strong explanatory emphasis.
214    Emphasis,
215    /// Canonical result emphasis.
216    Outcome,
217    /// Interactive content.
218    Interactive,
219}
220
221/// Semantic size of a native action control.
222#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
223#[serde(rename_all = "snake_case")]
224pub enum ButtonSize {
225    /// Smallest accessible control treatment.
226    Compact,
227    /// Default control treatment.
228    Regular,
229    /// Strong primary control treatment.
230    Prominent,
231}
232
233/// One generated native action description.
234#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
235pub struct SceneAction {
236    /// Stable generated action ID.
237    pub id: String,
238    /// Stable caller key.
239    pub key: String,
240    /// Visible accessible label.
241    pub label: String,
242    /// Generated semantic control size.
243    pub size: ButtonSize,
244}
245
246/// Structured content carried by one scene node.
247#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
248#[serde(tag = "kind", rename_all = "snake_case")]
249pub enum SceneNodeContent {
250    /// A node with no direct readable content.
251    Empty,
252    /// Receipt eyebrow and title.
253    Header {
254        /// Short context line.
255        eyebrow: String,
256        /// Primary title.
257        title: String,
258    },
259    /// Label/value facts.
260    Facts {
261        /// Ordered facts.
262        items: Vec<FactContent>,
263    },
264    /// Ordered evidence strings.
265    List {
266        /// Ordered list items.
267        items: Vec<String>,
268    },
269    /// Bounded table content.
270    Table {
271        /// Column labels.
272        headers: Vec<String>,
273        /// Rows matching the header count.
274        rows: Vec<Vec<String>>,
275    },
276    /// Canonical result value.
277    Result {
278        /// Preserved final disposition.
279        disposition: FinalDisposition,
280    },
281    /// Generated native actions.
282    Actions {
283        /// Ordered action descriptions.
284        items: Vec<SceneAction>,
285    },
286    /// Native menu item labels.
287    Menu {
288        /// Ordered menu items.
289        items: Vec<String>,
290    },
291}
292
293/// One stable node in the logical receipt tree.
294#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
295pub struct SceneNode {
296    /// Stable generated node ID.
297    pub id: String,
298    /// Semantic node kind.
299    pub kind: SceneNodeKind,
300    /// Responsive grid role.
301    pub grid_role: GridRole,
302    /// Theme-independent visual role.
303    pub visual_role: VisualRole,
304    /// Whether decorative effects may target this node.
305    pub effect_target: bool,
306    /// Structured readable content.
307    pub content: SceneNodeContent,
308    /// Child nodes in logical reading order.
309    pub children: Vec<Self>,
310}
311
312/// Generated diagram family.
313#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
314#[serde(rename_all = "snake_case")]
315pub enum DiagramForm {
316    /// Linear segmented progress.
317    Linear,
318    /// Branched functional tree.
319    Tree,
320    /// Directed state diagram.
321    State,
322    /// Network with cross-connections.
323    Network,
324}
325
326/// One stable generated diagram node.
327#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
328pub struct DiagramNode {
329    /// Stable generated diagram-node ID.
330    pub id: String,
331    /// Visible node label.
332    pub label: String,
333    /// Whether this node is the canonical terminal result.
334    pub terminal: bool,
335}
336
337/// One stable directed topology edge.
338#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
339pub struct DiagramEdge {
340    /// Stable generated edge ID.
341    pub id: String,
342    /// Source diagram-node ID.
343    pub from: String,
344    /// Target diagram-node ID.
345    pub to: String,
346}
347
348/// Complete renderer-neutral diagram topology.
349#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
350pub struct DiagramPlan {
351    /// Generated diagram family.
352    pub form: DiagramForm,
353    /// Stable nodes.
354    pub nodes: Vec<DiagramNode>,
355    /// Directed edges derived from node relationships.
356    pub edges: Vec<DiagramEdge>,
357}
358
359/// Bounded decorative primitive selected by scene generation.
360#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
361#[serde(rename_all = "snake_case")]
362pub enum EffectPattern {
363    /// Local decorative backing pulse.
364    Pulse,
365    /// Local decorative backing glitch.
366    Glitch,
367    /// Local decorative backing inversion.
368    Invert,
369    /// Bounded local fragment emission.
370    Fragment,
371    /// Traversal along one measured diagram edge.
372    EdgeTraverse,
373    /// Packet traversal along one measured diagram edge.
374    Packet,
375    /// Local decorative scanline sweep.
376    Scanline,
377}
378
379/// Stable target of a generated decorative effect.
380#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
381#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
382pub enum EffectTarget {
383    /// One stable scene or diagram node.
384    Node(String),
385    /// One stable diagram edge.
386    Edge(String),
387}
388
389/// One controlled interval in an effect plan.
390#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
391pub struct EffectPhase {
392    /// Start time relative to the interaction in milliseconds.
393    pub at_ms: u32,
394    /// Phase duration in milliseconds.
395    pub duration_ms: u16,
396}
397
398/// Seeded bounded parameters carried by an effect plan.
399#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
400pub struct EffectParameters {
401    /// Semantic intensity from one through three.
402    pub intensity: u8,
403    /// Decorative horizontal displacement in CSS pixels.
404    pub offset_x: i8,
405    /// Decorative vertical displacement in CSS pixels.
406    pub offset_y: i8,
407    /// Number of local decorative fragments.
408    pub fragments: u8,
409}
410
411/// One generated decorative pattern and its complete phase plan.
412#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
413pub struct EffectPlan {
414    /// Stable generated effect ID.
415    pub id: String,
416    /// Decorative pattern.
417    pub pattern: EffectPattern,
418    /// Stable node or edge target.
419    pub target: EffectTarget,
420    /// Bounded seeded parameters.
421    pub parameters: EffectParameters,
422    /// Ordered controlled phases.
423    pub phases: Vec<EffectPhase>,
424}
425
426/// Trigger selecting one deterministic interaction script.
427#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
428#[serde(tag = "kind", content = "action_id", rename_all = "snake_case")]
429pub enum InteractionTrigger {
430    /// Scene-load script.
431    Load,
432    /// Script for one generated native action.
433    Action(String),
434}
435
436/// One trigger and the generated effect plans it runs.
437#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
438pub struct InteractionScript {
439    /// Trigger selecting this script.
440    pub trigger: InteractionTrigger,
441    /// Stable effect IDs in deterministic order.
442    pub effect_ids: Vec<String>,
443}
444
445/// Complete renderer-neutral receipt and diagram description.
446#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
447pub struct ScenePlan {
448    /// Experimental scene schema version.
449    pub format_version: u16,
450    /// Seed used for every generated choice.
451    pub seed: u64,
452    /// Caller-selected recipe.
453    pub recipe: SceneRecipe,
454    /// Generated curated layout profile.
455    pub layout: LayoutProfile,
456    /// Logical receipt tree.
457    pub root: SceneNode,
458    /// Generated diagram topology.
459    pub diagram: DiagramPlan,
460    /// Generated decorative effect plans.
461    pub effects: Vec<EffectPlan>,
462    /// Generated load and action scripts.
463    pub scripts: Vec<InteractionScript>,
464}
465
466impl ScenePlan {
467    /// Serializes this plan for a concrete renderer.
468    ///
469    /// # Errors
470    ///
471    /// Returns [`SceneError::Serialization`] if JSON serialization fails.
472    pub fn to_json(&self) -> Result<String, SceneError> {
473        serde_json::to_string(self).map_err(|error| SceneError::Serialization(error.to_string()))
474    }
475}
476
477/// Browser-measured geometry for one stable scene or diagram node.
478#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
479pub struct NodeGeometry {
480    /// Stable scene or diagram node ID.
481    pub id: String,
482    /// Measured node rectangle in the shared CSS-pixel field.
483    pub rect: Rect,
484    /// Selected incoming edge port.
485    pub incoming: Point,
486    /// Selected outgoing edge port.
487    pub outgoing: Point,
488}
489
490/// Complete controlled input for one measured scene interaction.
491#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
492pub struct SceneSimulationInput {
493    /// Generated scene plan being replayed.
494    pub plan: ScenePlan,
495    /// Browser-measured geometry keyed by stable node ID.
496    pub geometry: Vec<NodeGeometry>,
497    /// Declared load or action interaction.
498    pub trigger: InteractionTrigger,
499}
500
501/// One renderer-neutral event in a measured scene interaction.
502#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
503#[serde(tag = "kind", rename_all = "snake_case")]
504pub enum SceneEvent {
505    /// Marks the beginning of one interaction.
506    InteractionStarted {
507        /// Controlled simulation time in milliseconds.
508        at_ms: u32,
509    },
510    /// Marks the beginning of one generated effect phase.
511    PhaseStarted {
512        /// Stable effect ID.
513        effect_id: String,
514        /// Zero-based phase index.
515        phase_index: u8,
516        /// Controlled simulation time in milliseconds.
517        at_ms: u32,
518        /// Phase duration in milliseconds.
519        duration_ms: u16,
520    },
521    /// Activates a decorative backing for one node.
522    NodeActivated {
523        /// Stable target node ID.
524        target_id: String,
525        /// Measured target center.
526        point: Point,
527        /// Controlled simulation time in milliseconds.
528        at_ms: u32,
529        /// Effect duration in milliseconds.
530        duration_ms: u16,
531        /// Semantic intensity from one through three.
532        intensity: u8,
533    },
534    /// Glitches a decorative backing without moving readable content.
535    BackingGlitched {
536        /// Stable target node ID.
537        target_id: String,
538        /// Controlled simulation time in milliseconds.
539        at_ms: u32,
540        /// Effect duration in milliseconds.
541        duration_ms: u16,
542        /// Horizontal decorative displacement in CSS pixels.
543        offset_x: i8,
544        /// Vertical decorative displacement in CSS pixels.
545        offset_y: i8,
546    },
547    /// Inverts one decorative backing.
548    BackingInverted {
549        /// Stable target node ID.
550        target_id: String,
551        /// Controlled simulation time in milliseconds.
552        at_ms: u32,
553        /// Effect duration in milliseconds.
554        duration_ms: u16,
555    },
556    /// Emits bounded local decorative fragments.
557    FragmentsEmitted {
558        /// Stable target node ID.
559        target_id: String,
560        /// Measured target center.
561        point: Point,
562        /// Controlled simulation time in milliseconds.
563        at_ms: u32,
564        /// Effect duration in milliseconds.
565        duration_ms: u16,
566        /// Number of decorative fragments.
567        count: u8,
568    },
569    /// Traverses one measured directed edge.
570    EdgeTraversed {
571        /// Stable diagram-edge ID.
572        edge_id: String,
573        /// Measured source port.
574        from: Point,
575        /// Measured target port.
576        to: Point,
577        /// Controlled simulation time in milliseconds.
578        at_ms: u32,
579        /// Traversal duration in milliseconds.
580        duration_ms: u16,
581    },
582    /// Moves one decorative packet along a measured directed edge.
583    PacketTraversed {
584        /// Stable diagram-edge ID.
585        edge_id: String,
586        /// Measured source port.
587        from: Point,
588        /// Measured target port.
589        to: Point,
590        /// Controlled simulation time in milliseconds.
591        at_ms: u32,
592        /// Traversal duration in milliseconds.
593        duration_ms: u16,
594    },
595    /// Sweeps one decorative scanline across a measured node.
596    ScanlineSwept {
597        /// Stable target node ID.
598        target_id: String,
599        /// Measured target rectangle.
600        rect: Rect,
601        /// Controlled simulation time in milliseconds.
602        at_ms: u32,
603        /// Sweep duration in milliseconds.
604        duration_ms: u16,
605    },
606    /// Marks the end of one interaction.
607    InteractionFinished {
608        /// Final controlled simulation time in milliseconds.
609        at_ms: u32,
610    },
611}
612
613/// Complete replayable renderer-neutral scene interaction.
614#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
615pub struct SceneTrace {
616    /// Scene format version.
617    pub format_version: u16,
618    /// Scene replay seed.
619    pub seed: u64,
620    /// Interaction that produced the trace.
621    pub trigger: InteractionTrigger,
622    /// Ordered renderer-neutral events.
623    pub events: Vec<SceneEvent>,
624}
625
626impl SceneTrace {
627    /// Serializes this trace for a concrete renderer.
628    ///
629    /// # Errors
630    ///
631    /// Returns [`SceneError::Serialization`] if JSON serialization fails.
632    pub fn to_json(&self) -> Result<String, SceneError> {
633        serde_json::to_string(self).map_err(|error| SceneError::Serialization(error.to_string()))
634    }
635}
636
637/// Validation, budget, geometry, interaction, or serialization failure.
638#[derive(Clone, Debug, Eq, PartialEq)]
639pub enum SceneError {
640    /// Seed zero cannot identify a replayable scene.
641    ZeroSeed,
642    /// A named content invariant was violated.
643    InvalidContent(&'static str),
644    /// A named hard budget was invalid or exceeded.
645    BudgetExceeded(&'static str),
646    /// A stable generated identifier was missing, duplicated, or stale.
647    InvalidIdentifier(&'static str),
648    /// Browser-measured geometry was missing, duplicated, or invalid.
649    InvalidGeometry(&'static str),
650    /// The selected interaction was not declared by the plan.
651    UnknownInteraction,
652    /// A plan or trace could not be encoded as JSON.
653    Serialization(String),
654}
655
656impl fmt::Display for SceneError {
657    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
658        match self {
659            Self::ZeroSeed => formatter.write_str("scene seed must be nonzero"),
660            Self::InvalidContent(name) => write!(formatter, "invalid scene content: {name}"),
661            Self::BudgetExceeded(name) => write!(formatter, "scene budget exceeded: {name}"),
662            Self::InvalidIdentifier(name) => write!(formatter, "invalid scene identifier: {name}"),
663            Self::InvalidGeometry(name) => write!(formatter, "invalid scene geometry: {name}"),
664            Self::UnknownInteraction => formatter.write_str("interaction is not declared by scene"),
665            Self::Serialization(message) => {
666                write!(formatter, "scene serialization failed: {message}")
667            }
668        }
669    }
670}
671
672impl std::error::Error for SceneError {}
673
674/// Generates one complete deterministic renderer-neutral receipt scene.
675///
676/// # Errors
677///
678/// Returns [`SceneError`] when content or budgets violate the scene contract.
679pub fn generate_scene(request: &SceneRequest) -> Result<ScenePlan, SceneError> {
680    validate_request(request)?;
681    let mut choice_random = SceneRandom::new(request.seed);
682    let mut timing_random = SceneRandom::new(request.seed ^ 0xe703_7ed1_a0b4_28db);
683    let layout = choice_random.layout();
684    let diagram = generate_diagram(
685        &request.content.diagram_labels,
686        choice_random.diagram_form(),
687    );
688    let actions = generate_actions(&request.content.actions, &mut choice_random);
689    let root = generate_tree(&request.content, &actions, layout);
690    let (effects, scripts) = generate_effects(
691        request,
692        &root,
693        &diagram,
694        &actions,
695        &mut choice_random,
696        &mut timing_random,
697    )?;
698    let plan = ScenePlan {
699        format_version: SCENE_FORMAT_VERSION,
700        seed: request.seed,
701        recipe: request.recipe,
702        layout,
703        root,
704        diagram,
705        effects,
706        scripts,
707    };
708    validate_plan(&plan, request.budgets)?;
709    let byte_count = plan.to_json()?.len();
710    let byte_limit = usize::try_from(request.budgets.max_json_bytes)
711        .map_err(|_| SceneError::BudgetExceeded("serialized scene bytes"))?;
712    if byte_count > byte_limit {
713        return Err(SceneError::BudgetExceeded("serialized scene bytes"));
714    }
715    Ok(plan)
716}
717
718/// Simulates one declared scene interaction against browser-measured geometry.
719///
720/// # Errors
721///
722/// Returns [`SceneError`] when the plan, interaction, or geometry violates the scene contract.
723pub fn simulate_scene(input: &SceneSimulationInput) -> Result<SceneTrace, SceneError> {
724    validate_plan(&input.plan, SceneBudgets::default())?;
725    validate_geometry(&input.plan, &input.geometry)?;
726    let script = input
727        .plan
728        .scripts
729        .iter()
730        .find(|script| script.trigger == input.trigger)
731        .ok_or(SceneError::UnknownInteraction)?;
732    let mut events = vec![SceneEvent::InteractionStarted { at_ms: 0 }];
733    let mut finish_ms = 0_u32;
734    for effect_id in &script.effect_ids {
735        let effect = input
736            .plan
737            .effects
738            .iter()
739            .find(|effect| effect.id == *effect_id)
740            .ok_or(SceneError::InvalidIdentifier("script effect"))?;
741        for (phase_index, phase) in effect.phases.iter().enumerate() {
742            let phase_index = u8::try_from(phase_index)
743                .map_err(|_| SceneError::BudgetExceeded("phases per effect"))?;
744            events.push(SceneEvent::PhaseStarted {
745                effect_id: effect.id.clone(),
746                phase_index,
747                at_ms: phase.at_ms,
748                duration_ms: phase.duration_ms,
749            });
750            push_effect_event(&mut events, effect, *phase, &input.plan, &input.geometry)?;
751            finish_ms = finish_ms.max(phase.at_ms + u32::from(phase.duration_ms));
752        }
753    }
754    events.sort_by_key(event_time);
755    events.push(SceneEvent::InteractionFinished { at_ms: finish_ms });
756    Ok(SceneTrace {
757        format_version: input.plan.format_version,
758        seed: input.plan.seed,
759        trigger: input.trigger.clone(),
760        events,
761    })
762}
763
764fn validate_request(request: &SceneRequest) -> Result<(), SceneError> {
765    if request.seed == 0 {
766        return Err(SceneError::ZeroSeed);
767    }
768    validate_budgets(request.budgets)?;
769    validate_text(&request.content.eyebrow, "eyebrow")?;
770    validate_text(&request.content.title, "title")?;
771    if request.content.facts.is_empty() || request.content.facts.len() > 12 {
772        return Err(SceneError::InvalidContent("facts"));
773    }
774    for fact in &request.content.facts {
775        validate_text(&fact.label, "fact label")?;
776        validate_text(&fact.value, "fact value")?;
777    }
778    if request.content.evidence.is_empty() || request.content.evidence.len() > 12 {
779        return Err(SceneError::InvalidContent("evidence list"));
780    }
781    for item in &request.content.evidence {
782        validate_text(item, "evidence item")?;
783    }
784    if request.content.table_headers.is_empty() || request.content.table_headers.len() > 6 {
785        return Err(SceneError::InvalidContent("table headers"));
786    }
787    for header in &request.content.table_headers {
788        validate_text(header, "table header")?;
789    }
790    if request.content.table_rows.is_empty() || request.content.table_rows.len() > 12 {
791        return Err(SceneError::InvalidContent("table rows"));
792    }
793    for row in &request.content.table_rows {
794        if row.len() != request.content.table_headers.len() {
795            return Err(SceneError::InvalidContent("table row width"));
796        }
797        for cell in row {
798            validate_text(cell, "table cell")?;
799        }
800    }
801    let diagram_count = request.content.diagram_labels.len();
802    if !(2..=usize::from(request.budgets.max_diagram_nodes)).contains(&diagram_count) {
803        return Err(SceneError::InvalidContent("diagram labels"));
804    }
805    let worst_case_edges = if diagram_count > 3 {
806        diagram_count + 1
807    } else {
808        diagram_count.saturating_sub(1)
809    };
810    if worst_case_edges > usize::from(request.budgets.max_diagram_edges) {
811        return Err(SceneError::BudgetExceeded("diagram edges"));
812    }
813    for label in &request.content.diagram_labels {
814        validate_text(label, "diagram label")?;
815    }
816    if request.content.actions.is_empty()
817        || request.content.actions.len() > usize::from(request.budgets.max_actions)
818    {
819        return Err(SceneError::InvalidContent("actions"));
820    }
821    if request.content.actions.len() >= usize::from(request.budgets.max_effects) {
822        return Err(SceneError::BudgetExceeded("action and load effects"));
823    }
824    if request.content.actions.len() + 9 > usize::from(request.budgets.max_nodes) {
825        return Err(SceneError::BudgetExceeded("scene and action nodes"));
826    }
827    for action in &request.content.actions {
828        validate_key(&action.key, "action key")?;
829        validate_text(&action.label, "action label")?;
830    }
831    if request.content.menu_items.is_empty() || request.content.menu_items.len() > 8 {
832        return Err(SceneError::InvalidContent("menu items"));
833    }
834    for item in &request.content.menu_items {
835        validate_text(item, "menu item")?;
836    }
837    Ok(())
838}
839
840fn validate_budgets(budgets: SceneBudgets) -> Result<(), SceneError> {
841    let valid = budgets.max_nodes >= 9
842        && budgets.max_nodes <= ABSOLUTE_MAX_NODES
843        && budgets.max_depth >= 2
844        && budgets.max_depth <= ABSOLUTE_MAX_DEPTH
845        && budgets.max_actions > 0
846        && budgets.max_actions <= ABSOLUTE_MAX_ACTIONS
847        && budgets.max_diagram_nodes >= 2
848        && budgets.max_diagram_nodes <= ABSOLUTE_MAX_DIAGRAM_NODES
849        && budgets.max_diagram_edges > 0
850        && budgets.max_diagram_edges <= ABSOLUTE_MAX_DIAGRAM_EDGES
851        && budgets.max_effects > 0
852        && budgets.max_effects <= ABSOLUTE_MAX_EFFECTS
853        && budgets.max_phases_per_effect > 0
854        && budgets.max_phases_per_effect <= ABSOLUTE_MAX_PHASES
855        && budgets.max_live_effects > 0
856        && budgets.max_live_effects <= ABSOLUTE_MAX_LIVE_EFFECTS
857        && budgets.max_fragments > 0
858        && budgets.max_fragments <= ABSOLUTE_MAX_FRAGMENTS
859        && budgets.max_displacement <= ABSOLUTE_MAX_DISPLACEMENT
860        && budgets.max_phase_ms >= 60
861        && budgets.max_phase_ms <= ABSOLUTE_MAX_PHASE_MS
862        && budgets.max_interaction_ms >= u32::from(budgets.max_phase_ms)
863        && budgets.max_interaction_ms <= ABSOLUTE_MAX_INTERACTION_MS
864        && budgets.max_json_bytes > 0
865        && budgets.max_json_bytes <= ABSOLUTE_MAX_JSON_BYTES;
866    if !valid {
867        return Err(SceneError::BudgetExceeded("invalid hard limits"));
868    }
869    Ok(())
870}
871
872fn validate_text(value: &str, name: &'static str) -> Result<(), SceneError> {
873    if value.trim().is_empty() || value.len() > MAX_TEXT_BYTES {
874        return Err(SceneError::InvalidContent(name));
875    }
876    Ok(())
877}
878
879fn validate_key(value: &str, name: &'static str) -> Result<(), SceneError> {
880    validate_text(value, name)?;
881    if !value
882        .bytes()
883        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
884    {
885        return Err(SceneError::InvalidContent(name));
886    }
887    Ok(())
888}
889
890fn generate_actions(actions: &[ActionContent], random: &mut SceneRandom) -> Vec<SceneAction> {
891    actions
892        .iter()
893        .enumerate()
894        .map(|(index, action)| SceneAction {
895            id: format!("action-{index}"),
896            key: action.key.clone(),
897            label: action.label.clone(),
898            size: random.button_size(),
899        })
900        .collect()
901}
902
903fn generate_tree(
904    content: &ReceiptContent,
905    actions: &[SceneAction],
906    layout: LayoutProfile,
907) -> SceneNode {
908    let roles = layout_roles(layout);
909    let children = vec![
910        scene_node(
911            "header",
912            SceneNodeKind::Header,
913            roles[0],
914            VisualRole::Emphasis,
915            true,
916            SceneNodeContent::Header {
917                eyebrow: content.eyebrow.clone(),
918                title: content.title.clone(),
919            },
920        ),
921        scene_node(
922            "facts",
923            SceneNodeKind::Facts,
924            roles[1],
925            VisualRole::Standard,
926            true,
927            SceneNodeContent::Facts {
928                items: content.facts.clone(),
929            },
930        ),
931        scene_node(
932            "evidence",
933            SceneNodeKind::List,
934            roles[2],
935            VisualRole::Quiet,
936            true,
937            SceneNodeContent::List {
938                items: content.evidence.clone(),
939            },
940        ),
941        scene_node(
942            "records",
943            SceneNodeKind::Table,
944            roles[3],
945            VisualRole::Standard,
946            true,
947            SceneNodeContent::Table {
948                headers: content.table_headers.clone(),
949                rows: content.table_rows.clone(),
950            },
951        ),
952        scene_node(
953            "diagram",
954            SceneNodeKind::Diagram,
955            roles[4],
956            VisualRole::Emphasis,
957            true,
958            SceneNodeContent::Empty,
959        ),
960        scene_node(
961            "result",
962            SceneNodeKind::Result,
963            roles[5],
964            VisualRole::Outcome,
965            true,
966            SceneNodeContent::Result {
967                disposition: content.outcome,
968            },
969        ),
970        scene_node(
971            "actions",
972            SceneNodeKind::Actions,
973            roles[6],
974            VisualRole::Interactive,
975            true,
976            SceneNodeContent::Actions {
977                items: actions.to_vec(),
978            },
979        ),
980        scene_node(
981            "menu",
982            SceneNodeKind::Menu,
983            GridRole::Footer,
984            VisualRole::Interactive,
985            true,
986            SceneNodeContent::Menu {
987                items: content.menu_items.clone(),
988            },
989        ),
990    ];
991    SceneNode {
992        id: "scene".to_owned(),
993        kind: SceneNodeKind::Frame,
994        grid_role: GridRole::Frame,
995        visual_role: VisualRole::Standard,
996        effect_target: true,
997        content: SceneNodeContent::Empty,
998        children,
999    }
1000}
1001
1002fn scene_node(
1003    id: &str,
1004    kind: SceneNodeKind,
1005    grid_role: GridRole,
1006    visual_role: VisualRole,
1007    effect_target: bool,
1008    content: SceneNodeContent,
1009) -> SceneNode {
1010    SceneNode {
1011        id: id.to_owned(),
1012        kind,
1013        grid_role,
1014        visual_role,
1015        effect_target,
1016        content,
1017        children: Vec::new(),
1018    }
1019}
1020
1021fn layout_roles(layout: LayoutProfile) -> [GridRole; 7] {
1022    match layout {
1023        LayoutProfile::Instrument | LayoutProfile::Terminal => [
1024            GridRole::Lead,
1025            GridRole::Primary,
1026            GridRole::Primary,
1027            GridRole::Full,
1028            GridRole::Full,
1029            GridRole::Outcome,
1030            GridRole::Footer,
1031        ],
1032        LayoutProfile::Split | LayoutProfile::Asymmetric => [
1033            GridRole::Lead,
1034            GridRole::Primary,
1035            GridRole::Secondary,
1036            GridRole::Primary,
1037            GridRole::Secondary,
1038            GridRole::Outcome,
1039            GridRole::Footer,
1040        ],
1041        LayoutProfile::ResultLed | LayoutProfile::DiagramLed => [
1042            GridRole::Lead,
1043            GridRole::Secondary,
1044            GridRole::Secondary,
1045            GridRole::Full,
1046            GridRole::Primary,
1047            GridRole::Outcome,
1048            GridRole::Footer,
1049        ],
1050        LayoutProfile::Editorial => [
1051            GridRole::Lead,
1052            GridRole::Primary,
1053            GridRole::Secondary,
1054            GridRole::Full,
1055            GridRole::Full,
1056            GridRole::Outcome,
1057            GridRole::Footer,
1058        ],
1059    }
1060}
1061
1062fn generate_diagram(labels: &[String], form: DiagramForm) -> DiagramPlan {
1063    let nodes = labels
1064        .iter()
1065        .enumerate()
1066        .map(|(index, label)| DiagramNode {
1067            id: format!("diagram-node-{index}"),
1068            label: label.clone(),
1069            terminal: index + 1 == labels.len(),
1070        })
1071        .collect::<Vec<_>>();
1072    let mut pairs = Vec::new();
1073    match form {
1074        DiagramForm::Linear | DiagramForm::State => {
1075            for index in 1..nodes.len() {
1076                pairs.push((index - 1, index));
1077            }
1078            if form == DiagramForm::State && nodes.len() > 2 {
1079                pairs.push((nodes.len() - 1, 0));
1080            }
1081        }
1082        DiagramForm::Tree => {
1083            for index in 1..nodes.len() {
1084                pairs.push(((index - 1) / 2, index));
1085            }
1086        }
1087        DiagramForm::Network => {
1088            for index in 1..nodes.len() {
1089                pairs.push((index - 1, index));
1090            }
1091            if nodes.len() > 3 {
1092                pairs.push((0, 2));
1093                pairs.push((1, nodes.len() - 1));
1094            }
1095        }
1096    }
1097    let edges = pairs
1098        .into_iter()
1099        .enumerate()
1100        .map(|(index, (from, to))| DiagramEdge {
1101            id: format!("diagram-edge-{index}"),
1102            from: nodes[from].id.clone(),
1103            to: nodes[to].id.clone(),
1104        })
1105        .collect();
1106    DiagramPlan { form, nodes, edges }
1107}
1108
1109fn generate_effects(
1110    request: &SceneRequest,
1111    root: &SceneNode,
1112    diagram: &DiagramPlan,
1113    actions: &[SceneAction],
1114    choice_random: &mut SceneRandom,
1115    timing_random: &mut SceneRandom,
1116) -> Result<(Vec<EffectPlan>, Vec<InteractionScript>), SceneError> {
1117    let mut node_targets = Vec::new();
1118    collect_effect_targets(root, &mut node_targets);
1119    node_targets.extend(diagram.nodes.iter().map(|node| node.id.clone()));
1120    let desired_load_effects = match request.recipe {
1121        SceneRecipe::Calm => 2,
1122        SceneRecipe::Balanced => 4,
1123        SceneRecipe::Vivid => 6,
1124    };
1125    let action_effects = actions.len();
1126    let effect_limit = usize::from(request.budgets.max_effects);
1127    let load_effects = desired_load_effects.min(effect_limit.saturating_sub(action_effects));
1128    if load_effects == 0 {
1129        return Err(SceneError::BudgetExceeded("load effects"));
1130    }
1131    let mut effects = Vec::with_capacity(load_effects + action_effects);
1132    let mut load_ids = Vec::with_capacity(load_effects);
1133    let mut cursor_ms = 0_u32;
1134    for index in 0..load_effects {
1135        let pattern = choice_random.pattern(!diagram.edges.is_empty());
1136        let target = target_for_pattern(pattern, &node_targets, diagram, choice_random)?;
1137        let effect = generated_effect(
1138            format!("effect-load-{index}"),
1139            pattern,
1140            target,
1141            cursor_ms,
1142            request.budgets,
1143            timing_random,
1144        );
1145        cursor_ms = effect_end(&effect).saturating_add(40);
1146        load_ids.push(effect.id.clone());
1147        effects.push(effect);
1148    }
1149    let mut scripts = vec![InteractionScript {
1150        trigger: InteractionTrigger::Load,
1151        effect_ids: load_ids,
1152    }];
1153    for (index, action) in actions.iter().enumerate() {
1154        let pattern = choice_random.action_pattern();
1155        let target = EffectTarget::Node(action.id.clone());
1156        let effect = generated_effect(
1157            format!("effect-action-{index}"),
1158            pattern,
1159            target,
1160            0,
1161            request.budgets,
1162            timing_random,
1163        );
1164        scripts.push(InteractionScript {
1165            trigger: InteractionTrigger::Action(action.id.clone()),
1166            effect_ids: vec![effect.id.clone()],
1167        });
1168        effects.push(effect);
1169    }
1170    Ok((effects, scripts))
1171}
1172
1173fn generated_effect(
1174    id: String,
1175    pattern: EffectPattern,
1176    target: EffectTarget,
1177    start_ms: u32,
1178    budgets: SceneBudgets,
1179    random: &mut SceneRandom,
1180) -> EffectPlan {
1181    let maximum_phases = budgets.max_phases_per_effect.min(3);
1182    let phase_count = random.range_u8(1, maximum_phases);
1183    let mut phases = Vec::with_capacity(usize::from(phase_count));
1184    let mut cursor_ms = start_ms;
1185    for _ in 0..phase_count {
1186        let maximum_duration = budgets.max_phase_ms.min(640);
1187        let minimum_duration = maximum_duration.min(120);
1188        let duration_ms = random.range_u16(minimum_duration, maximum_duration);
1189        phases.push(EffectPhase {
1190            at_ms: cursor_ms,
1191            duration_ms,
1192        });
1193        cursor_ms = cursor_ms.saturating_add(u32::from(duration_ms) + 30);
1194    }
1195    let displacement = i8::try_from(budgets.max_displacement).map_or(3, |value| value);
1196    EffectPlan {
1197        id,
1198        pattern,
1199        target,
1200        parameters: EffectParameters {
1201            intensity: random.range_u8(1, 3),
1202            offset_x: random.signed_range(displacement),
1203            offset_y: random.signed_range(displacement),
1204            fragments: random.range_u8(1, budgets.max_fragments),
1205        },
1206        phases,
1207    }
1208}
1209
1210fn target_for_pattern(
1211    pattern: EffectPattern,
1212    node_targets: &[String],
1213    diagram: &DiagramPlan,
1214    random: &mut SceneRandom,
1215) -> Result<EffectTarget, SceneError> {
1216    if matches!(pattern, EffectPattern::EdgeTraverse | EffectPattern::Packet) {
1217        let index = random.index(diagram.edges.len());
1218        return diagram
1219            .edges
1220            .get(index)
1221            .map(|edge| EffectTarget::Edge(edge.id.clone()))
1222            .ok_or(SceneError::InvalidContent("diagram edge target"));
1223    }
1224    let index = random.index(node_targets.len());
1225    node_targets
1226        .get(index)
1227        .cloned()
1228        .map(EffectTarget::Node)
1229        .ok_or(SceneError::InvalidContent("scene node target"))
1230}
1231
1232fn collect_effect_targets(node: &SceneNode, targets: &mut Vec<String>) {
1233    if node.effect_target {
1234        targets.push(node.id.clone());
1235    }
1236    for child in &node.children {
1237        collect_effect_targets(child, targets);
1238    }
1239}
1240
1241fn effect_end(effect: &EffectPlan) -> u32 {
1242    effect.phases.iter().fold(0, |end_ms, phase| {
1243        end_ms.max(phase.at_ms + u32::from(phase.duration_ms))
1244    })
1245}
1246
1247fn validate_plan(plan: &ScenePlan, budgets: SceneBudgets) -> Result<(), SceneError> {
1248    if plan.format_version != SCENE_FORMAT_VERSION {
1249        return Err(SceneError::InvalidIdentifier("scene format version"));
1250    }
1251    if plan.seed == 0 {
1252        return Err(SceneError::ZeroSeed);
1253    }
1254    validate_budgets(budgets)?;
1255    let mut node_ids = Vec::new();
1256    validate_tree(&plan.root, 1, budgets, &mut node_ids)?;
1257    let mut action_ids = Vec::new();
1258    collect_action_ids(&plan.root, &mut action_ids)?;
1259    for action_id in &action_ids {
1260        if node_ids.contains(action_id) {
1261            return Err(SceneError::InvalidIdentifier("duplicate action node"));
1262        }
1263        node_ids.push(action_id.clone());
1264    }
1265    if node_ids.len() > usize::from(budgets.max_nodes) {
1266        return Err(SceneError::BudgetExceeded("scene and action nodes"));
1267    }
1268    let diagram_node_limit = usize::from(budgets.max_diagram_nodes);
1269    if plan.diagram.nodes.len() > diagram_node_limit {
1270        return Err(SceneError::BudgetExceeded("diagram nodes"));
1271    }
1272    let diagram_edge_limit = usize::from(budgets.max_diagram_edges);
1273    if plan.diagram.edges.len() > diagram_edge_limit {
1274        return Err(SceneError::BudgetExceeded("diagram edges"));
1275    }
1276    for node in &plan.diagram.nodes {
1277        if node_ids.contains(&node.id) {
1278            return Err(SceneError::InvalidIdentifier("duplicate node"));
1279        }
1280        node_ids.push(node.id.clone());
1281    }
1282    let mut edge_ids = Vec::new();
1283    for edge in &plan.diagram.edges {
1284        if edge_ids.contains(&edge.id)
1285            || !node_ids.contains(&edge.from)
1286            || !node_ids.contains(&edge.to)
1287        {
1288            return Err(SceneError::InvalidIdentifier("diagram edge"));
1289        }
1290        edge_ids.push(edge.id.clone());
1291    }
1292    if plan.effects.len() > usize::from(budgets.max_effects) {
1293        return Err(SceneError::BudgetExceeded("effects"));
1294    }
1295    let mut effect_ids = Vec::new();
1296    for effect in &plan.effects {
1297        validate_effect(effect, &node_ids, &edge_ids, budgets)?;
1298        if effect_ids.contains(&effect.id) {
1299            return Err(SceneError::InvalidIdentifier("duplicate effect"));
1300        }
1301        effect_ids.push(effect.id.clone());
1302    }
1303    let mut triggers = Vec::new();
1304    for script in &plan.scripts {
1305        if triggers.contains(&script.trigger) {
1306            return Err(SceneError::InvalidIdentifier("duplicate interaction"));
1307        }
1308        if let InteractionTrigger::Action(action_id) = &script.trigger {
1309            if !action_ids.contains(action_id) {
1310                return Err(SceneError::InvalidIdentifier("interaction action"));
1311            }
1312        }
1313        triggers.push(script.trigger.clone());
1314        if script.effect_ids.is_empty()
1315            || script
1316                .effect_ids
1317                .iter()
1318                .any(|effect_id| !effect_ids.contains(effect_id))
1319        {
1320            return Err(SceneError::InvalidIdentifier("script effect"));
1321        }
1322        let script_effects = script
1323            .effect_ids
1324            .iter()
1325            .filter_map(|id| plan.effects.iter().find(|effect| effect.id == **id))
1326            .collect::<Vec<_>>();
1327        if script_effects
1328            .iter()
1329            .fold(0, |end_ms, effect| end_ms.max(effect_end(effect)))
1330            > budgets.max_interaction_ms
1331        {
1332            return Err(SceneError::BudgetExceeded("interaction duration"));
1333        }
1334        validate_live_effects(&script_effects, budgets.max_live_effects)?;
1335    }
1336    if !triggers.contains(&InteractionTrigger::Load)
1337        || action_ids
1338            .iter()
1339            .any(|action_id| !triggers.contains(&InteractionTrigger::Action(action_id.clone())))
1340    {
1341        return Err(SceneError::InvalidIdentifier("missing interaction"));
1342    }
1343    Ok(())
1344}
1345
1346fn validate_tree(
1347    node: &SceneNode,
1348    depth: u8,
1349    budgets: SceneBudgets,
1350    ids: &mut Vec<String>,
1351) -> Result<(), SceneError> {
1352    if depth > budgets.max_depth {
1353        return Err(SceneError::BudgetExceeded("scene depth"));
1354    }
1355    if ids.contains(&node.id) {
1356        return Err(SceneError::InvalidIdentifier("duplicate scene node"));
1357    }
1358    ids.push(node.id.clone());
1359    if ids.len() > usize::from(budgets.max_nodes) {
1360        return Err(SceneError::BudgetExceeded("scene nodes"));
1361    }
1362    for child in &node.children {
1363        validate_tree(child, depth + 1, budgets, ids)?;
1364    }
1365    Ok(())
1366}
1367
1368fn collect_action_ids(node: &SceneNode, ids: &mut Vec<String>) -> Result<(), SceneError> {
1369    if let SceneNodeContent::Actions { items } = &node.content {
1370        for action in items {
1371            if ids.contains(&action.id) {
1372                return Err(SceneError::InvalidIdentifier("duplicate action node"));
1373            }
1374            ids.push(action.id.clone());
1375        }
1376    }
1377    for child in &node.children {
1378        collect_action_ids(child, ids)?;
1379    }
1380    Ok(())
1381}
1382
1383fn validate_live_effects(effects: &[&EffectPlan], maximum_live: u8) -> Result<(), SceneError> {
1384    let intervals = effects
1385        .iter()
1386        .flat_map(|effect| {
1387            effect
1388                .phases
1389                .iter()
1390                .map(|phase| (phase.at_ms, phase.at_ms + u32::from(phase.duration_ms)))
1391        })
1392        .collect::<Vec<_>>();
1393    let exceeds_limit = intervals.iter().any(|(start, _)| {
1394        intervals
1395            .iter()
1396            .filter(|(other_start, other_end)| other_start <= start && start < other_end)
1397            .count()
1398            > usize::from(maximum_live)
1399    });
1400    if exceeds_limit {
1401        return Err(SceneError::BudgetExceeded("simultaneously live effects"));
1402    }
1403    Ok(())
1404}
1405
1406fn validate_effect(
1407    effect: &EffectPlan,
1408    node_ids: &[String],
1409    edge_ids: &[String],
1410    budgets: SceneBudgets,
1411) -> Result<(), SceneError> {
1412    let target_valid = match &effect.target {
1413        EffectTarget::Node(id) => node_ids.contains(id),
1414        EffectTarget::Edge(id) => edge_ids.contains(id),
1415    };
1416    if !target_valid {
1417        return Err(SceneError::InvalidIdentifier("effect target"));
1418    }
1419    let target_kind_valid = matches!(
1420        (&effect.pattern, &effect.target),
1421        (
1422            EffectPattern::EdgeTraverse | EffectPattern::Packet,
1423            EffectTarget::Edge(_)
1424        ) | (
1425            EffectPattern::Pulse
1426                | EffectPattern::Glitch
1427                | EffectPattern::Invert
1428                | EffectPattern::Fragment
1429                | EffectPattern::Scanline,
1430            EffectTarget::Node(_)
1431        )
1432    );
1433    if !target_kind_valid {
1434        return Err(SceneError::InvalidIdentifier("pattern target kind"));
1435    }
1436    if effect.phases.is_empty() || effect.phases.len() > usize::from(budgets.max_phases_per_effect)
1437    {
1438        return Err(SceneError::BudgetExceeded("effect phases"));
1439    }
1440    for phase in &effect.phases {
1441        if phase.duration_ms == 0 || phase.duration_ms > budgets.max_phase_ms {
1442            return Err(SceneError::BudgetExceeded("phase duration"));
1443        }
1444    }
1445    if effect
1446        .phases
1447        .windows(2)
1448        .any(|pair| pair[0].at_ms > pair[1].at_ms)
1449    {
1450        return Err(SceneError::InvalidIdentifier("phase order"));
1451    }
1452    let displacement_limit = i16::from(budgets.max_displacement);
1453    if i16::from(effect.parameters.offset_x).abs() > displacement_limit
1454        || i16::from(effect.parameters.offset_y).abs() > displacement_limit
1455        || effect.parameters.fragments == 0
1456        || effect.parameters.fragments > budgets.max_fragments
1457        || !(1..=3).contains(&effect.parameters.intensity)
1458    {
1459        return Err(SceneError::BudgetExceeded("effect parameters"));
1460    }
1461    Ok(())
1462}
1463
1464fn validate_geometry(plan: &ScenePlan, geometry: &[NodeGeometry]) -> Result<(), SceneError> {
1465    let mut required = Vec::new();
1466    for effect in &plan.effects {
1467        match &effect.target {
1468            EffectTarget::Node(id) => push_unique(&mut required, id),
1469            EffectTarget::Edge(id) => {
1470                let edge = plan
1471                    .diagram
1472                    .edges
1473                    .iter()
1474                    .find(|edge| edge.id == *id)
1475                    .ok_or(SceneError::InvalidIdentifier("effect edge"))?;
1476                push_unique(&mut required, &edge.from);
1477                push_unique(&mut required, &edge.to);
1478            }
1479        }
1480    }
1481    let mut seen = Vec::new();
1482    for measurement in geometry {
1483        if seen.contains(&measurement.id) {
1484            return Err(SceneError::InvalidGeometry("duplicate node"));
1485        }
1486        seen.push(measurement.id.clone());
1487        if !rect_is_valid(measurement.rect)
1488            || !point_is_finite(measurement.incoming)
1489            || !point_is_finite(measurement.outgoing)
1490        {
1491            return Err(SceneError::InvalidGeometry("non-finite node"));
1492        }
1493    }
1494    if required.iter().any(|id| !seen.contains(id)) {
1495        return Err(SceneError::InvalidGeometry("missing required node"));
1496    }
1497    Ok(())
1498}
1499
1500fn push_unique(values: &mut Vec<String>, value: &str) {
1501    if !values.iter().any(|existing| existing == value) {
1502        values.push(value.to_owned());
1503    }
1504}
1505
1506fn point_is_finite(point: Point) -> bool {
1507    point.x.is_finite() && point.y.is_finite()
1508}
1509
1510fn rect_is_valid(rect: Rect) -> bool {
1511    rect.x.is_finite()
1512        && rect.y.is_finite()
1513        && rect.width.is_finite()
1514        && rect.height.is_finite()
1515        && rect.width > 0.0
1516        && rect.height > 0.0
1517}
1518
1519fn push_effect_event(
1520    events: &mut Vec<SceneEvent>,
1521    effect: &EffectPlan,
1522    phase: EffectPhase,
1523    plan: &ScenePlan,
1524    geometry: &[NodeGeometry],
1525) -> Result<(), SceneError> {
1526    match (&effect.pattern, &effect.target) {
1527        (EffectPattern::Pulse, EffectTarget::Node(id)) => {
1528            let measurement = find_geometry(geometry, id)?;
1529            events.push(SceneEvent::NodeActivated {
1530                target_id: id.clone(),
1531                point: rect_center(measurement.rect),
1532                at_ms: phase.at_ms,
1533                duration_ms: phase.duration_ms,
1534                intensity: effect.parameters.intensity,
1535            });
1536        }
1537        (EffectPattern::Glitch, EffectTarget::Node(id)) => {
1538            events.push(SceneEvent::BackingGlitched {
1539                target_id: id.clone(),
1540                at_ms: phase.at_ms,
1541                duration_ms: phase.duration_ms,
1542                offset_x: effect.parameters.offset_x,
1543                offset_y: effect.parameters.offset_y,
1544            });
1545        }
1546        (EffectPattern::Invert, EffectTarget::Node(id)) => {
1547            events.push(SceneEvent::BackingInverted {
1548                target_id: id.clone(),
1549                at_ms: phase.at_ms,
1550                duration_ms: phase.duration_ms,
1551            });
1552        }
1553        (EffectPattern::Fragment, EffectTarget::Node(id)) => {
1554            let measurement = find_geometry(geometry, id)?;
1555            events.push(SceneEvent::FragmentsEmitted {
1556                target_id: id.clone(),
1557                point: rect_center(measurement.rect),
1558                at_ms: phase.at_ms,
1559                duration_ms: phase.duration_ms,
1560                count: effect.parameters.fragments,
1561            });
1562        }
1563        (EffectPattern::Scanline, EffectTarget::Node(id)) => {
1564            let measurement = find_geometry(geometry, id)?;
1565            events.push(SceneEvent::ScanlineSwept {
1566                target_id: id.clone(),
1567                rect: measurement.rect,
1568                at_ms: phase.at_ms,
1569                duration_ms: phase.duration_ms,
1570            });
1571        }
1572        (EffectPattern::EdgeTraverse, EffectTarget::Edge(id)) => {
1573            let (from, to) = measured_edge(plan, geometry, id)?;
1574            events.push(SceneEvent::EdgeTraversed {
1575                edge_id: id.clone(),
1576                from,
1577                to,
1578                at_ms: phase.at_ms,
1579                duration_ms: phase.duration_ms,
1580            });
1581        }
1582        (EffectPattern::Packet, EffectTarget::Edge(id)) => {
1583            let (from, to) = measured_edge(plan, geometry, id)?;
1584            events.push(SceneEvent::PacketTraversed {
1585                edge_id: id.clone(),
1586                from,
1587                to,
1588                at_ms: phase.at_ms,
1589                duration_ms: phase.duration_ms,
1590            });
1591        }
1592        _ => return Err(SceneError::InvalidIdentifier("pattern target kind")),
1593    }
1594    Ok(())
1595}
1596
1597fn find_geometry<'a>(
1598    geometry: &'a [NodeGeometry],
1599    id: &str,
1600) -> Result<&'a NodeGeometry, SceneError> {
1601    geometry
1602        .iter()
1603        .find(|measurement| measurement.id == id)
1604        .ok_or(SceneError::InvalidGeometry("missing effect target"))
1605}
1606
1607fn measured_edge(
1608    plan: &ScenePlan,
1609    geometry: &[NodeGeometry],
1610    id: &str,
1611) -> Result<(Point, Point), SceneError> {
1612    let edge = plan
1613        .diagram
1614        .edges
1615        .iter()
1616        .find(|edge| edge.id == id)
1617        .ok_or(SceneError::InvalidIdentifier("diagram edge"))?;
1618    let from = find_geometry(geometry, &edge.from)?;
1619    let to = find_geometry(geometry, &edge.to)?;
1620    Ok((from.outgoing, to.incoming))
1621}
1622
1623fn rect_center(rect: Rect) -> Point {
1624    Point::new(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0)
1625}
1626
1627fn event_time(event: &SceneEvent) -> u32 {
1628    match event {
1629        SceneEvent::InteractionStarted { at_ms }
1630        | SceneEvent::PhaseStarted { at_ms, .. }
1631        | SceneEvent::NodeActivated { at_ms, .. }
1632        | SceneEvent::BackingGlitched { at_ms, .. }
1633        | SceneEvent::BackingInverted { at_ms, .. }
1634        | SceneEvent::FragmentsEmitted { at_ms, .. }
1635        | SceneEvent::EdgeTraversed { at_ms, .. }
1636        | SceneEvent::PacketTraversed { at_ms, .. }
1637        | SceneEvent::ScanlineSwept { at_ms, .. }
1638        | SceneEvent::InteractionFinished { at_ms } => *at_ms,
1639    }
1640}
1641
1642struct SceneRandom {
1643    state: u64,
1644}
1645
1646impl SceneRandom {
1647    const fn new(seed: u64) -> Self {
1648        Self {
1649            state: seed ^ 0xa076_1d64_78bd_642f,
1650        }
1651    }
1652
1653    fn next_u64(&mut self) -> u64 {
1654        self.state = self.state.wrapping_add(0x9e37_79b9_7f4a_7c15);
1655        let mut value = self.state;
1656        value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1657        value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1658        value ^ (value >> 31)
1659    }
1660
1661    fn index(&mut self, length: usize) -> usize {
1662        if length == 0 {
1663            return 0;
1664        }
1665        usize::from(self.next_u64().to_le_bytes()[0]) % length
1666    }
1667
1668    fn layout(&mut self) -> LayoutProfile {
1669        match self.index(7) {
1670            0 => LayoutProfile::Instrument,
1671            1 => LayoutProfile::Split,
1672            2 => LayoutProfile::Asymmetric,
1673            3 => LayoutProfile::ResultLed,
1674            4 => LayoutProfile::DiagramLed,
1675            5 => LayoutProfile::Terminal,
1676            _ => LayoutProfile::Editorial,
1677        }
1678    }
1679
1680    fn diagram_form(&mut self) -> DiagramForm {
1681        match self.index(4) {
1682            0 => DiagramForm::Linear,
1683            1 => DiagramForm::Tree,
1684            2 => DiagramForm::State,
1685            _ => DiagramForm::Network,
1686        }
1687    }
1688
1689    fn button_size(&mut self) -> ButtonSize {
1690        match self.index(3) {
1691            0 => ButtonSize::Compact,
1692            1 => ButtonSize::Regular,
1693            _ => ButtonSize::Prominent,
1694        }
1695    }
1696
1697    fn pattern(&mut self, allow_edge: bool) -> EffectPattern {
1698        match self.index(if allow_edge { 7 } else { 5 }) {
1699            0 => EffectPattern::Pulse,
1700            1 => EffectPattern::Glitch,
1701            2 => EffectPattern::Invert,
1702            3 => EffectPattern::Fragment,
1703            4 => EffectPattern::Scanline,
1704            5 => EffectPattern::EdgeTraverse,
1705            _ => EffectPattern::Packet,
1706        }
1707    }
1708
1709    fn action_pattern(&mut self) -> EffectPattern {
1710        match self.index(4) {
1711            0 => EffectPattern::Pulse,
1712            1 => EffectPattern::Glitch,
1713            2 => EffectPattern::Invert,
1714            _ => EffectPattern::Fragment,
1715        }
1716    }
1717
1718    fn range_u8(&mut self, minimum: u8, maximum: u8) -> u8 {
1719        let width = maximum - minimum + 1;
1720        minimum + self.next_u64().to_le_bytes()[0] % width
1721    }
1722
1723    fn range_u16(&mut self, minimum: u16, maximum: u16) -> u16 {
1724        let width = maximum - minimum + 1;
1725        let sample = u16::from(self.next_u64().to_le_bytes()[0]);
1726        minimum + sample % width
1727    }
1728
1729    fn signed_range(&mut self, maximum: i8) -> i8 {
1730        if maximum == 0 {
1731            return 0;
1732        }
1733        let width = u8::try_from(i16::from(maximum) * 2 + 1).map_or(1, |value| value);
1734        let sample = self.next_u64().to_le_bytes()[0] % width;
1735        i8::try_from(sample).map_or(0, |value| value) - maximum
1736    }
1737}