scal-runtime 1.1.0

Runtime for SCAL- easy animation system focused on code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Animation timeline and scene graph.
//!
//! The [`Animator`] owns all scene objects, their transforms, and manages
//! the animation timeline. Key design:
//!
//! - **Ownership**: Objects live in `objects: Vec<Object>`. The `objects_lookup`
//!   maps `Uuid -> index` and is rebuilt every frame after z-sorting.
//! - **Transforms**: Each object carries its own local `Transform`. World matrices
//!   are computed on-demand in [`Animator::get_object_world_matrix()`] and cached
//!   in [`ObjectRenderData::world_matrix_cache`].
//! - **Cache lifetime**: The world-matrix cache is invalidated at the start of
//!   each call to [`Animator::animate_next_frame()`] (set to `Mat4::ZERO`), then
//!   lazily recomputed by [`Animator::update_object_matrix_cache()`].
//! - **Update order**: `animate_next_frame()` → (run animation step) →
//!   `update_object_matrix_cache()` → `sort_objects_by_z()`. This guarantees
//!   that transform changes from the current frame are reflected before rendering.
//! - **Dirty propagation**: Every frame recomputes *all* world matrices from
//!   scratch. There is no dirty-flag system — correctness is simpler at the cost
//!   of O(n×depth) for deep parent chains.

use std::collections::HashMap;

#[cfg(test)]
use crate::anim_object::primitive_shapes::Rectangle;
#[cfg(test)]
use crate::anim_object::render::PipelineKind;
use crate::{anim_object::object_trait::DynAnimObj, anim_op::resolve_op};
use crate::{
    anim_object::{
        Transform,
        compose::LayoutContainer,
        render::ObjectRenderData,
        text::{TextManager, atlas::GlyphUpdateData},
    },
    anim_op::{AnimOperation, Animation},
    anim_render::AnimationState,
    renderer::{Index, Vertex},
};
use anyhow::{Context, Result, bail};
use glam::Mat4;
use log::debug;
use scal_core::Camera;
use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct Object {
    pub anim_data: DynAnimObj,
    pub render_data: ObjectRenderData,
}
impl Object {
    pub fn transform(&self) -> &Transform {
        self.anim_data.transform()
    }
    pub fn uuid(&self) -> &Uuid {
        &self.anim_data.transform().uuid
    }
    pub fn z_pos(&self) -> f32 {
        self.render_data.world_matrix_cache.w_axis.z
    }
}

pub struct Animator {
    pub camera: Camera,
    pub fps: u32,
    pub anim_state: AnimationState,
    pub animations_left: Vec<AnimOperation>,

    pub objects_lookup: HashMap<Uuid, usize>,
    pub objects: Vec<Object>,
    pub vertices: Vec<Vertex>,
    pub indices: Vec<Index>,
    pub text_manager: TextManager,
    pub layout_containers: HashMap<Uuid, LayoutContainer>,
    pub layout_resizing_in_progress: bool,
}

pub struct Scene<'a> {
    pub camera: &'a Camera,
    pub mesh_changed_this_frame: bool,
    pub object_lookup: &'a HashMap<Uuid, usize>,
    pub objects_sorted_by_z: &'a Vec<Object>,
    pub vertices: &'a Vec<Vertex>,
    pub indices: &'a Vec<Index>,
}
impl<'a> Scene<'a> {
    pub fn get_object(&self, uuid: &Uuid) -> &Object {
        &self.objects_sorted_by_z[self.object_lookup[uuid]]
    }
}
pub struct FrameAnimationOutput<'a> {
    pub scene: Scene<'a>,
    pub glyph_update_data: Option<GlyphUpdateData<'a>>,
}
impl Animator {
    pub fn new(
        mut animations: Vec<AnimOperation>,
        fps: u32,
        camera: Camera,
        text_scale: f32,
    ) -> Result<Self> {
        animations.reverse();
        let first_anim = animations
            .pop()
            .take()
            .context("you need at least one anim op to init anim renderer")?;
        debug!("first_anim: {first_anim:?}");
        Ok(Self {
            camera,
            text_manager: TextManager::new(text_scale),
            fps,
            anim_state: AnimationState::new(first_anim)?,
            animations_left: animations,
            objects: vec![],
            indices: vec![],
            vertices: vec![],
            objects_lookup: HashMap::new(),
            layout_containers: HashMap::new(),
            layout_resizing_in_progress: false,
        })
    }

    pub fn animate_next_frame(&mut self) -> Result<Option<FrameAnimationOutput<'_>>> {
        debug!(
            "animate_next_frame- current_anim_state:{:?}",
            self.anim_state
        );

        loop {
            let op = self.anim_state.anim_op.clone();
            let loc_str = op.location().map(|l| l.to_string()).unwrap_or_default();
            let animation: Animation = resolve_op(op).with_context(|| {
                format!("while converting anim_op to animation for the next frame {loc_str}")
            })?;

            let mut storage = self.anim_state.storage.clone();

            if self.anim_state.time == 0. {
                let loc_str = animation
                    .location
                    .as_ref()
                    .map(|l| l.to_string())
                    .unwrap_or_default();
                (*animation.start)(self, &mut storage).context(format!(
                    "while running the start function of an animation {loc_str}"
                ))?;
            }
            if let Some(update) = animation.update
                && self.anim_state.time < animation.total_duration
            {
                let t = if self.anim_state.time + 1. / self.fps as f32 >= animation.total_duration {
                    1.0
                } else {
                    self.anim_state.time / animation.total_duration
                };
                let loc_str = animation
                    .location
                    .as_ref()
                    .map(|l| l.to_string())
                    .unwrap_or_default();
                (*update)(self, animation.curve.apply(t), &mut storage).context(format!(
                    "while running the update function of an animation {loc_str}"
                ))?;
                self.anim_state.time += 1. / self.fps as f32;

                self.anim_state.storage = storage;
                break;
            } else {
                self.anim_state.storage = storage;
                match self.animations_left.pop() {
                    Some(op) => {
                        debug!("handle next animation");
                        self.anim_state =
                            AnimationState::new(op).context("while setting up a new anim op")?
                    }
                    None => {
                        debug!("no animations left");
                        return Ok(None);
                    }
                }
            }
        }

        self.update_object_matrix_cache()
            .context("while updating object matrix caches")?;
        self.sort_objects_by_z();

        let scene = Scene {
            mesh_changed_this_frame: true,
            camera: &self.camera,
            object_lookup: &self.objects_lookup,
            indices: &self.indices,
            objects_sorted_by_z: &self.objects,
            vertices: &self.vertices,
        };

        Ok(Some(FrameAnimationOutput {
            scene,
            glyph_update_data: self.text_manager.atlas.get_glyph_update_data(),
        }))
    }
    pub fn sort_objects_by_z(&mut self) {
        self.objects.sort_by(|a, b| a.z_pos().total_cmp(&b.z_pos()));
        self.objects_lookup = self
            .objects
            .iter()
            .enumerate()
            .map(|(i, obj)| (obj.anim_data.transform().uuid, i))
            .collect();
    }
    pub fn update_object_matrix_cache(&mut self) -> Result<()> {
        self.objects
            .iter_mut()
            .for_each(|obj| obj.render_data.world_matrix_cache = Mat4::ZERO);
        let uuids: Vec<Uuid> = self.objects_lookup.keys().copied().collect();
        let updated_count = uuids.len();
        for uuid in &uuids {
            let matrix = self.get_object_world_matrix(uuid)?;
            self.get_object_mut(uuid)?.render_data.world_matrix_cache = matrix;
        }
        debug!(
            "update_object_matrix_cache: objects={}, updated={}",
            self.objects.len(),
            updated_count,
        );
        Ok(())
    }

    pub fn check_cycle(&self, child_uuid: &Uuid, parent_uuid: &Uuid) -> Result<()> {
        let mut current = *parent_uuid;
        loop {
            if current == *child_uuid {
                bail!(
                    "circular parent reference: {} would be an ancestor of {}",
                    child_uuid,
                    parent_uuid
                );
            }
            let Some(&idx) = self.objects_lookup.get(&current) else {
                return Ok(());
            };
            let Some(next) = self.objects[idx].anim_data.transform().parent else {
                return Ok(());
            };
            current = next;
        }
    }

    pub(crate) fn get_object(&self, uuid: &Uuid) -> Result<&Object> {
        let index = self
            .objects_lookup
            .get(uuid)
            .with_context(|| format!("there was no object with uuid {uuid}"))?;

        self.objects
            .get(*index)
            .context("index from the object lookup was out of bounds")
    }
    pub(crate) fn get_object_mut(&mut self, uuid: &Uuid) -> Result<&mut Object> {
        let index = self
            .objects_lookup
            .get(uuid)
            .with_context(|| format!("there was no object with uuid {uuid}"))?;
        self.objects
            .get_mut(*index)
            .context("index from the object lookup was out of bounds ")
    }

    pub fn apply_scroll_offset(&mut self, uuid: &Uuid) -> Result<()> {
        let (direction, scroll_offset, child_uuids, base_positions) = {
            let obj = self.get_object(uuid)?;
            let scroll = obj
                .anim_data
                .as_any()
                .downcast_ref::<crate::anim_object::scroll::ScrollLayout>()
                .context("apply_scroll_offset target is not a ScrollLayout")?;
            (
                scroll.direction,
                scroll.scroll_offset,
                scroll.child_uuids.clone(),
                scroll.child_base_positions.clone(),
            )
        };

        for (child_uuid, base_pos) in child_uuids.iter().zip(base_positions.iter()) {
            let child = self.get_object_mut(child_uuid)?;
            let transform = child.anim_data.transform_mut();
            match direction {
                crate::anim_object::compose::LayoutDir::Column => {
                    transform.position.x = base_pos.x;
                    transform.position.y = base_pos.y - scroll_offset;
                }
                crate::anim_object::compose::LayoutDir::Row => {
                    transform.position.x = base_pos.x - scroll_offset;
                    transform.position.y = base_pos.y;
                }
            }
        }
        Ok(())
    }

    pub fn get_object_world_matrix(&self, uuid: &Uuid) -> Result<Mat4> {
        const Z_CHILD_CHANGE: f32 = 0.1;
        let obj = self.get_object(uuid)?;
        if obj.transform().parent.unwrap_or(Uuid::nil()) == *uuid {
            bail!("parent == child");
        }

        if obj.render_data.world_matrix_cache != Mat4::ZERO {
            Ok(obj.render_data.world_matrix_cache)
        } else {
            let transf = obj.transform();
            let local = transf.get_local_matrix();
            match transf.parent {
                Some(parent_id) => {
                    let mut parent_matrix = self.get_object_world_matrix(&parent_id)?;
                    parent_matrix.w_axis.z += Z_CHILD_CHANGE;
                    Ok(parent_matrix * local)
                }
                None => Ok(local),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use glam::{Vec2, Vec3};
    use scal_core::Color;

    fn make_rect_obj(uuid: Uuid, parent: Option<Uuid>) -> Object {
        Object {
            anim_data: DynAnimObj(Box::new(Rectangle {
                size: Vec2::new(10.0, 10.0),
                corner_radius: 0.0,
                color: Color::WHITE,
                transform: Transform {
                    uuid,
                    parent,
                    position: Vec3::ZERO,
                    rotation: 0.0,
                    scale: Vec2::ONE,
                    layout_container: None,
                    world_uniform: None,
                    clip_rect: None,
                },
            })),
            render_data: ObjectRenderData {
                world_matrix_cache: Mat4::ZERO,
                vertices_base_index: 0,
                vertices: vec![],
                indices_base_index: 0,
                indices_count: 0,
                pipeline: PipelineKind::Shape,
                object_bind_groups: vec![],
            },
        }
    }

    fn make_animator() -> Animator {
        let anim = AnimOperation::Wait(0.001, None);
        let camera = Camera::new(Vec2::new(100.0, 100.0), Vec2::ZERO, 1.0);
        Animator::new(vec![anim], 60, camera, 1.0).unwrap()
    }

    #[test]
    fn check_cycle_self_reference() {
        let mut animator = make_animator();
        let uuid = Uuid::new_v4();
        animator.objects.push(make_rect_obj(uuid, Some(uuid)));
        animator.objects_lookup.insert(uuid, 0);
        assert!(animator.check_cycle(&uuid, &uuid).is_err());
    }

    #[test]
    fn check_cycle_no_parent_ok() {
        let mut animator = make_animator();
        let uuid_a = Uuid::new_v4();
        let uuid_b = Uuid::new_v4();
        animator.objects.push(make_rect_obj(uuid_a, None));
        animator.objects_lookup.insert(uuid_a, 0);
        animator.objects.push(make_rect_obj(uuid_b, Some(uuid_a)));
        animator.objects_lookup.insert(uuid_b, 1);
        assert!(animator.check_cycle(&uuid_a, &uuid_b).is_err());
    }

    #[test]
    fn check_cycle_unrelated_ok() {
        let mut animator = make_animator();
        let uuid_a = Uuid::new_v4();
        let uuid_b = Uuid::new_v4();
        animator.objects.push(make_rect_obj(uuid_a, None));
        animator.objects_lookup.insert(uuid_a, 0);
        assert!(animator.check_cycle(&uuid_a, &uuid_b).is_ok());
        assert!(animator.check_cycle(&uuid_b, &Uuid::new_v4()).is_ok());
    }

    #[test]
    fn check_cycle_transitive_cycle() {
        let mut animator = make_animator();
        let uuid_a = Uuid::new_v4();
        let uuid_b = Uuid::new_v4();
        let uuid_c = Uuid::new_v4();
        animator.objects.push(make_rect_obj(uuid_a, Some(uuid_c)));
        animator.objects_lookup.insert(uuid_a, 0);
        animator.objects.push(make_rect_obj(uuid_b, Some(uuid_a)));
        animator.objects_lookup.insert(uuid_b, 1);
        animator.objects.push(make_rect_obj(uuid_c, Some(uuid_b)));
        animator.objects_lookup.insert(uuid_c, 2);
        assert!(animator.check_cycle(&uuid_c, &uuid_b).is_err());
    }

    #[test]
    fn check_cycle_nonexistent_parent_ok() {
        let mut animator = make_animator();
        let uuid = Uuid::new_v4();
        let nonexistent = Uuid::new_v4();
        animator.objects.push(make_rect_obj(uuid, None));
        animator.objects_lookup.insert(uuid, 0);
        assert!(animator.check_cycle(&uuid, &nonexistent).is_ok());
    }
}