Skip to main content

webizen_studio/render/
command_stack.rs

1//! Bounded, Zero-Heap Reversible Command Stack (`command_stack.rs`)
2//!
3//! Implements Epic 9.3b of the QualiaDB Superior Game Engine architecture:
4//! - Bounded undo/redo ring/stack ([`StudioCommandStack<CAP>`]) operating in **zero heap**.
5//! - Supports [`StudioCommand::TransformNode`], [`StudioCommand::EditTensor10D`],
6//!   [`StudioCommand::EditProcSynthesis`], and [`StudioCommand::EditOntogeny`].
7//! - Supports command coalescing (`execute_coalesced`) so continuous 60 Hz gizmo drags or
8//!   10D slider scrubs merge into a single atomic undo step.
9
10use crate::render::gizmo_3d::Motor;
11use crate::render::inspector_10d::{
12    ProceduralSynthesisHeader, StudioNodeInspector10D, Tensor10D,
13};
14
15/// Reversible studio editing command over 10D scene nodes and `.10d` sections.
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub enum StudioCommand {
18    /// PGA `Motor` + 3D scale manipulation (`MotorGizmo3D`).
19    TransformNode {
20        node_id: u32,
21        old_motor: Motor,
22        new_motor: Motor,
23        old_scale: [f32; 3],
24        new_scale: [f32; 3],
25    },
26    /// 10D manifold coordinate (`[q, v, w, x, y, z, t, α, μ, σ]`) edit.
27    EditTensor10D {
28        node_id: u32,
29        old_tensor: Tensor10D,
30        new_tensor: Tensor10D,
31    },
32    /// `.10d` `PROC1` (`ProceduralSynthesisHeader`) parameter edit.
33    EditProcSynthesis {
34        node_id: u32,
35        old_header: ProceduralSynthesisHeader,
36        new_header: ProceduralSynthesisHeader,
37    },
38    /// `.10d` `EONT1` ontogenetic stage and `[energy, damage, hydration, wear]` permill edit.
39    EditOntogeny {
40        node_id: u32,
41        old_stage: u8,
42        new_stage: u8,
43        old_permill: [u16; 4],
44        new_permill: [u16; 4],
45    },
46}
47
48impl Default for StudioCommand {
49    fn default() -> Self {
50        Self::TransformNode {
51            node_id: 0,
52            old_motor: Motor::identity(),
53            new_motor: Motor::identity(),
54            old_scale: [1.0, 1.0, 1.0],
55            new_scale: [1.0, 1.0, 1.0],
56        }
57    }
58}
59
60impl StudioCommand {
61    /// Returns the `node_id` targeted by this command.
62    #[inline]
63    pub const fn node_id(&self) -> u32 {
64        match *self {
65            Self::TransformNode { node_id, .. }
66            | Self::EditTensor10D { node_id, .. }
67            | Self::EditProcSynthesis { node_id, .. }
68            | Self::EditOntogeny { node_id, .. } => node_id,
69        }
70    }
71
72    /// Returns the exact inverse command (swapping `old_*` and `new_*` states).
73    #[inline]
74    pub const fn inverted(self) -> Self {
75        match self {
76            Self::TransformNode {
77                node_id,
78                old_motor,
79                new_motor,
80                old_scale,
81                new_scale,
82            } => Self::TransformNode {
83                node_id,
84                old_motor: new_motor,
85                new_motor: old_motor,
86                old_scale: new_scale,
87                new_scale: old_scale,
88            },
89            Self::EditTensor10D {
90                node_id,
91                old_tensor,
92                new_tensor,
93            } => Self::EditTensor10D {
94                node_id,
95                old_tensor: new_tensor,
96                new_tensor: old_tensor,
97            },
98            Self::EditProcSynthesis {
99                node_id,
100                old_header,
101                new_header,
102            } => Self::EditProcSynthesis {
103                node_id,
104                old_header: new_header,
105                new_header: old_header,
106            },
107            Self::EditOntogeny {
108                node_id,
109                old_stage,
110                new_stage,
111                old_permill,
112                new_permill,
113            } => Self::EditOntogeny {
114                node_id,
115                old_stage: new_stage,
116                new_stage: old_stage,
117                old_permill: new_permill,
118                new_permill: old_permill,
119            },
120        }
121    }
122
123    /// Attempts to coalesce `next` into `self` if both commands target the same `node_id`
124    /// and the same property variant (e.g. continuous gizmo drag).
125    #[inline]
126    pub fn try_coalesce(&mut self, next: &StudioCommand) -> bool {
127        match (self, next) {
128            (
129                Self::TransformNode {
130                    node_id: id_a,
131                    new_motor: ref mut nm_a,
132                    new_scale: ref mut ns_a,
133                    ..
134                },
135                Self::TransformNode {
136                    node_id: id_b,
137                    new_motor: nm_b,
138                    new_scale: ns_b,
139                    ..
140                },
141            ) if *id_a == *id_b => {
142                *nm_a = *nm_b;
143                *ns_a = *ns_b;
144                true
145            }
146            (
147                Self::EditTensor10D {
148                    node_id: id_a,
149                    new_tensor: ref mut nt_a,
150                    ..
151                },
152                Self::EditTensor10D {
153                    node_id: id_b,
154                    new_tensor: nt_b,
155                    ..
156                },
157            ) if *id_a == *id_b => {
158                *nt_a = *nt_b;
159                true
160            }
161            (
162                Self::EditProcSynthesis {
163                    node_id: id_a,
164                    new_header: ref mut nh_a,
165                    ..
166                },
167                Self::EditProcSynthesis {
168                    node_id: id_b,
169                    new_header: nh_b,
170                    ..
171                },
172            ) if *id_a == *id_b => {
173                *nh_a = *nh_b;
174                true
175            }
176            (
177                Self::EditOntogeny {
178                    node_id: id_a,
179                    new_stage: ref mut ns_a,
180                    new_permill: ref mut np_a,
181                    ..
182                },
183                Self::EditOntogeny {
184                    node_id: id_b,
185                    new_stage: ns_b,
186                    new_permill: np_b,
187                    ..
188                },
189            ) if *id_a == *id_b => {
190                *ns_a = *ns_b;
191                *np_a = *np_b;
192                true
193            }
194            _ => false,
195        }
196    }
197
198    /// Applies the forward (`new_*`) state of this command to a [`StudioNodeInspector10D`].
199    #[inline]
200    pub fn apply_to_inspector(&self, inspector: &mut StudioNodeInspector10D) {
201        if inspector.node_id != self.node_id() {
202            return;
203        }
204        match *self {
205            Self::TransformNode {
206                new_motor,
207                new_scale,
208                ..
209            } => {
210                inspector.local_motor = new_motor;
211                inspector.local_scale = new_scale;
212            }
213            Self::EditTensor10D { new_tensor, .. } => {
214                inspector.tensor_10d = new_tensor;
215            }
216            Self::EditProcSynthesis { new_header, .. } => {
217                inspector.proc_header = new_header;
218            }
219            Self::EditOntogeny {
220                new_stage,
221                new_permill,
222                ..
223            } => {
224                inspector.eont_header.stage = new_stage;
225                inspector.eont_header.energy_permill = new_permill[0];
226                inspector.eont_header.damage_permill = new_permill[1];
227                inspector.eont_header.hydration_permill = new_permill[2];
228                inspector.eont_header.wear_permill = new_permill[3];
229            }
230        }
231    }
232}
233
234/// Bounded zero-heap reversible command stack (`CAP = 128` by default).
235#[derive(Debug, Clone)]
236pub struct StudioCommandStack<const CAP: usize = 128> {
237    entries: [StudioCommand; CAP],
238    /// Current undo cursor (`0..=len`).
239    cursor: usize,
240    /// Total valid entries (`>= cursor`; entries in `cursor..len` are available for `redo`).
241    len: usize,
242}
243
244impl<const CAP: usize> Default for StudioCommandStack<CAP> {
245    fn default() -> Self {
246        Self::new()
247    }
248}
249
250impl<const CAP: usize> StudioCommandStack<CAP> {
251    /// Creates an empty command stack.
252    pub fn new() -> Self {
253        Self {
254            entries: [StudioCommand::default(); CAP],
255            cursor: 0,
256            len: 0,
257        }
258    }
259
260    /// Clears all undo/redo history.
261    #[inline]
262    pub fn clear(&mut self) {
263        self.cursor = 0;
264        self.len = 0;
265    }
266
267    /// Number of commands available to undo.
268    #[inline]
269    pub const fn undo_count(&self) -> usize {
270        self.cursor
271    }
272
273    /// Number of commands available to redo.
274    #[inline]
275    pub const fn redo_count(&self) -> usize {
276        self.len.saturating_sub(self.cursor)
277    }
278
279    #[inline]
280    pub const fn can_undo(&self) -> bool {
281        self.cursor > 0
282    }
283
284    #[inline]
285    pub const fn can_redo(&self) -> bool {
286        self.cursor < self.len
287    }
288
289    /// Pushes a new command onto the stack (truncating any redo tail). If the stack is full,
290    /// shifts the oldest entry out so capacity remains strictly bounded in zero heap.
291    pub fn execute(&mut self, cmd: StudioCommand, inspector: &mut StudioNodeInspector10D) {
292        cmd.apply_to_inspector(inspector);
293        if CAP == 0 {
294            return;
295        }
296        if self.cursor >= CAP {
297            // Shift left by 1 to drop the oldest entry
298            for i in 1..CAP {
299                self.entries[i - 1] = self.entries[i];
300            }
301            self.cursor = CAP - 1;
302        }
303        self.entries[self.cursor] = cmd;
304        self.cursor += 1;
305        self.len = self.cursor;
306    }
307
308    /// Executes `cmd`, coalescing it with the top undo entry if `coalesce == true` and both
309    /// target the same node & variant (e.g., during a continuous gizmo drag).
310    pub fn execute_coalesced(
311        &mut self,
312        cmd: StudioCommand,
313        coalesce: bool,
314        inspector: &mut StudioNodeInspector10D,
315    ) {
316        cmd.apply_to_inspector(inspector);
317        if coalesce && self.cursor > 0 && self.cursor == self.len {
318            if self.entries[self.cursor - 1].try_coalesce(&cmd) {
319                return;
320            }
321        }
322        self.execute(cmd, inspector);
323    }
324
325    /// Undoes the most recent command, applying its inverse to `inspector` and returning the
326    /// inverted command.
327    pub fn undo(&mut self, inspector: &mut StudioNodeInspector10D) -> Option<StudioCommand> {
328        if self.cursor == 0 {
329            return None;
330        }
331        self.cursor -= 1;
332        let inv = self.entries[self.cursor].inverted();
333        inv.apply_to_inspector(inspector);
334        Some(inv)
335    }
336
337    /// Redoes the next command in the redo tail, applying it to `inspector`.
338    pub fn redo(&mut self, inspector: &mut StudioNodeInspector10D) -> Option<StudioCommand> {
339        if self.cursor >= self.len {
340            return None;
341        }
342        let cmd = self.entries[self.cursor];
343        self.cursor += 1;
344        cmd.apply_to_inspector(inspector);
345        Some(cmd)
346    }
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn command_stack_executes_coalesces_undoes_and_redoes() {
355        let mut stack: StudioCommandStack<16> = StudioCommandStack::new();
356        let mut inspector = StudioNodeInspector10D::new(7);
357
358        let m0 = Motor::identity();
359        let m1 = Motor::from_translation([1.0, 0.0, 0.0]);
360        let m2 = Motor::from_translation([3.5, 0.0, 0.0]);
361
362        // Initial drag step
363        stack.execute_coalesced(
364            StudioCommand::TransformNode {
365                node_id: 7,
366                old_motor: m0,
367                new_motor: m1,
368                old_scale: [1.0; 3],
369                new_scale: [1.0; 3],
370            },
371            true,
372            &mut inspector,
373        );
374        // Second drag step coalesced into the first
375        stack.execute_coalesced(
376            StudioCommand::TransformNode {
377                node_id: 7,
378                old_motor: m1,
379                new_motor: m2,
380                old_scale: [1.0; 3],
381                new_scale: [2.0, 2.0, 2.0],
382            },
383            true,
384            &mut inspector,
385        );
386
387        assert_eq!(stack.undo_count(), 1, "Continuous drag should coalesce into 1 undo step");
388        assert_eq!(inspector.local_motor, m2);
389        assert_eq!(inspector.local_scale, [2.0, 2.0, 2.0]);
390
391        // Undo should restore m0 and [1.0; 3] in a single step
392        stack.undo(&mut inspector).expect("Expected undo");
393        assert_eq!(inspector.local_motor, m0);
394        assert_eq!(inspector.local_scale, [1.0, 1.0, 1.0]);
395        assert!(stack.can_redo());
396
397        // Redo should reapply m2 and [2.0; 3]
398        stack.redo(&mut inspector).expect("Expected redo");
399        assert_eq!(inspector.local_motor, m2);
400        assert_eq!(inspector.local_scale, [2.0, 2.0, 2.0]);
401    }
402}