scal-runtime 1.2.1

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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
use glam::{Vec2, Vec3, vec2, vec3};
use scal_core::Color;
use uuid::Uuid;

use crate::{
    anim_object::{
        Transform, TransformUniform,
        object_trait::{AnimObjectTrait, BindGroupLoader, DynAnimObj, MeshResult},
        primitive_shapes::Rectangle,
        render::PipelineKind,
        text::TextManager,
    },
    anim_op::AnimOperation,
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PinPoint {
    TL,
    TC,
    TR,
    LC,
    C,
    RC,
    BL,
    BC,
    BR,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayoutDir {
    Column,
    Row,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Alignment {
    Start,
    Center,
    End,
}

#[derive(Clone, Debug)]
pub struct LayoutBackground {
    pub color: Color,
    pub corner_radius: f32,
}

#[derive(Clone, Debug)]
pub enum LayoutItem {
    Object(DynAnimObj),
    Layout(LayoutResult),
}

impl From<DynAnimObj> for LayoutItem {
    fn from(obj: DynAnimObj) -> Self {
        LayoutItem::Object(obj)
    }
}

impl<T: AnimObjectTrait + 'static> From<T> for LayoutItem {
    fn from(obj: T) -> Self {
        LayoutItem::Object(DynAnimObj(Box::new(obj)))
    }
}

impl From<LayoutResult> for LayoutItem {
    fn from(lr: LayoutResult) -> Self {
        LayoutItem::Layout(lr)
    }
}

#[derive(Clone, Debug)]
pub struct LayoutContainer {
    pub id: Uuid,
    pub transform: Transform,
    pub background_uuid: Uuid,
    pub child_uuids: Vec<Uuid>,
    pub padding_top: f32,
    pub padding_bottom: f32,
    pub padding_left: f32,
    pub padding_right: f32,
    pub gap: f32,
    pub direction: LayoutDir,
    pub align: Alignment,
    pub justify: Alignment,
    pub min_width: f32,
    pub min_height: f32,
}

impl LayoutContainer {
    fn new(
        background_uuid: Uuid,
        child_uuids: Vec<Uuid>,
        direction: LayoutDir,
        align: Alignment,
        justify: Alignment,
        gap: f32,
        padding_top: f32,
        padding_bottom: f32,
        padding_left: f32,
        padding_right: f32,
        min_width: f32,
        min_height: f32,
    ) -> Self {
        Self::with_uuid(
            Uuid::new_v4(),
            background_uuid,
            child_uuids,
            direction,
            align,
            justify,
            gap,
            padding_top,
            padding_bottom,
            padding_left,
            padding_right,
            min_width,
            min_height,
        )
    }

    fn with_uuid(
        id: Uuid,
        background_uuid: Uuid,
        child_uuids: Vec<Uuid>,
        direction: LayoutDir,
        align: Alignment,
        justify: Alignment,
        gap: f32,
        padding_top: f32,
        padding_bottom: f32,
        padding_left: f32,
        padding_right: f32,
        min_width: f32,
        min_height: f32,
    ) -> Self {
        Self {
            id,
            transform: Transform {
                uuid: id,
                parent: None,
                position: Vec3::ZERO,
                rotation: 0.0,
                scale: Vec2::ONE,
                layout_container: None,
                world_uniform: None,
                clip_rect: None,
            },
            background_uuid,
            child_uuids,
            direction,
            align,
            justify,
            gap,
            padding_top,
            padding_bottom,
            padding_left,
            padding_right,
            min_width,
            min_height,
        }
    }
}

impl AnimObjectTrait for LayoutContainer {
    fn transform(&self) -> &Transform {
        &self.transform
    }
    fn transform_mut(&mut self) -> &mut Transform {
        &mut self.transform
    }
    fn generate_mesh(&mut self, _mgr: &mut TextManager) -> MeshResult {
        Ok((vec![], vec![], PipelineKind::Shape))
    }
    fn bind_group_loader(&self) -> Option<BindGroupLoader> {
        None
    }
    fn clone_box(&self) -> Box<dyn AnimObjectTrait> {
        Box::new(self.clone())
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

#[derive(Clone, Debug)]
pub struct LayoutResult {
    pub background: DynAnimObj,
    pub container: DynAnimObj,
    pub items: Vec<DynAnimObj>,
    pub nested: Vec<LayoutResult>,
    nested_ops: Vec<AnimOperation>,
}

impl LayoutResult {
    pub fn instantiate(&self) -> AnimOperation {
        let mut ops = Vec::new();
        ops.push(self.background.clone().instantiate());
        ops.push(self.container.clone().instantiate());
        for item in &self.items {
            ops.push(item.clone().instantiate());
        }
        // nested_ops already contains instantiate_children() of each nested layout,
        // which includes their container, items, and further nested items.
        ops.extend(self.nested_ops.iter().cloned());
        AnimOperation::All(ops, None)
    }

    pub fn instantiate_children(&self) -> AnimOperation {
        let mut ops = Vec::new();
        ops.push(self.container.clone().instantiate());
        for item in &self.items {
            ops.push(item.clone().instantiate());
        }
        // nested_ops already contains instantiate_children() of each nested layout
        ops.extend(self.nested_ops.iter().cloned());
        AnimOperation::All(ops, None)
    }

    /// Apply a world-space clip rectangle to this layout and all of its
    /// descendants (container, items, nested layouts).
    pub fn apply_clip_rect(&mut self, clip_rect: [f32; 4]) {
        self.background.transform_mut().clip_rect = Some(clip_rect);
        self.container.transform_mut().clip_rect = Some(clip_rect);
        for item in &mut self.items {
            item.transform_mut().clip_rect = Some(clip_rect);
        }
        for nested in &mut self.nested {
            nested.apply_clip_rect(clip_rect);
        }
    }
}

fn compute_bg_center(position: Vec3, w: f32, h: f32, pin: PinPoint) -> Vec3 {
    let (hw, hh) = (w / 2.0, h / 2.0);
    match pin {
        PinPoint::TL => position + vec3(hw, hh, 0.0),
        PinPoint::TC => position + vec3(0.0, hh, 0.0),
        PinPoint::TR => position + vec3(-hw, hh, 0.0),
        PinPoint::LC => position + vec3(hw, 0.0, 0.0),
        PinPoint::C => position,
        PinPoint::RC => position + vec3(-hw, 0.0, 0.0),
        PinPoint::BL => position + vec3(hw, -hh, 0.0),
        PinPoint::BC => position + vec3(0.0, -hh, 0.0),
        PinPoint::BR => position + vec3(-hw, -hh, 0.0),
    }
}

fn relayout_nested_children(bg_size: Vec2, container: &LayoutContainer, items: &mut [DynAnimObj]) {
    let content_left = -bg_size.x / 2.0 + container.padding_left;
    let content_right = bg_size.x / 2.0 - container.padding_right;
    let content_bottom = bg_size.y / 2.0 - container.padding_bottom;
    let content_top = -bg_size.y / 2.0 + container.padding_top;

    let sizes: Vec<Vec2> = items.iter().map(|c| c.size()).collect();
    let gaps = container.gap * (items.len() as f32 - 1.0).max(0.0);

    let (start_y, start_x) = match container.direction {
        LayoutDir::Column => {
            let total_content_h: f32 = sizes.iter().map(|s| s.y).sum();
            let content_size = content_bottom - content_top;
            let start = match container.justify {
                Alignment::Start => content_top,
                Alignment::Center => content_top + (content_size - (total_content_h + gaps)) / 2.0,
                Alignment::End => content_bottom - (total_content_h + gaps),
            };
            (start, content_left)
        }
        LayoutDir::Row => {
            let total_content_w: f32 = sizes.iter().map(|s| s.x).sum();
            let content_size = content_right - content_left;
            let start = match container.justify {
                Alignment::Start => content_left,
                Alignment::Center => content_left + (content_size - (total_content_w + gaps)) / 2.0,
                Alignment::End => content_right - (total_content_w + gaps),
            };
            (content_top, start)
        }
    };

    let mut y = start_y;
    let mut x = start_x;

    for (i, child) in items.iter_mut().enumerate() {
        let s = sizes[i];
        let (child_x, child_y) = match container.direction {
            LayoutDir::Column => {
                let cx = match container.align {
                    Alignment::Start => content_left + s.x / 2.0,
                    Alignment::Center => 0.0,
                    Alignment::End => content_right - s.x / 2.0,
                };
                let cy = y + s.y / 2.0;
                y += s.y + container.gap;
                (cx, cy)
            }
            LayoutDir::Row => {
                let cx = x + s.x / 2.0;
                let cy = match container.align {
                    Alignment::Start => content_bottom - s.y / 2.0,
                    Alignment::Center => 0.0,
                    Alignment::End => content_top + s.y / 2.0,
                };
                x += s.x + container.gap;
                (cx, cy)
            }
        };
        child.transform_mut().position = vec3(child_x, child_y, 0.0);
    }
}

pub fn layout(
    position: Vec3,
    pin_point: PinPoint,
    items: Vec<LayoutItem>,
    background: LayoutBackground,
    layout_dir: LayoutDir,
    align: Alignment,
    justify: Alignment,
    gap: f32,
    padding_top: f32,
    padding_bottom: f32,
    padding_left: f32,
    padding_right: f32,
    min_width: f32,
    min_height: f32,
) -> LayoutResult {
    layout_with_ids(
        position,
        pin_point,
        items,
        background,
        layout_dir,
        align,
        justify,
        gap,
        padding_top,
        padding_bottom,
        padding_left,
        padding_right,
        min_width,
        min_height,
        None,
        None,
    )
}

pub fn layout_with_ids(
    position: Vec3,
    pin_point: PinPoint,
    items: Vec<LayoutItem>,
    background: LayoutBackground,
    layout_dir: LayoutDir,
    align: Alignment,
    justify: Alignment,
    gap: f32,
    padding_top: f32,
    padding_bottom: f32,
    padding_left: f32,
    padding_right: f32,
    min_width: f32,
    min_height: f32,
    bg_uuid_override: Option<Uuid>,
    container_uuid_override: Option<Uuid>,
) -> LayoutResult {
    let mut anim_items = Vec::with_capacity(items.len());
    let mut nested_layouts: Vec<LayoutResult> = Vec::new();
    for item in items {
        match item {
            LayoutItem::Object(obj) => anim_items.push(obj),
            LayoutItem::Layout(lr) => {
                nested_layouts.push(lr.clone());
                anim_items.push(lr.background);
            }
        }
    }

    let sizes: Vec<Vec2> = anim_items.iter().map(|item| item.size()).collect();

    let gaps = gap * (anim_items.len() as f32 - 1.0).max(0.0);
    let (total_w, total_h) = match layout_dir {
        LayoutDir::Row => {
            let content_w: f32 = sizes.iter().map(|s| s.x).sum();
            let max_h = sizes.iter().map(|s| s.y).fold(0.0f32, f32::max);
            let total_w = (content_w + padding_left + padding_right + gaps).max(min_width);
            let total_h = (max_h + padding_top + padding_bottom).max(min_height);
            (total_w, total_h)
        }
        LayoutDir::Column => {
            let max_w = sizes.iter().map(|s| s.x).fold(0.0f32, f32::max);
            let content_h: f32 = sizes.iter().map(|s| s.y).sum();
            let total_w = (max_w + padding_left + padding_right).max(min_width);
            let total_h = (content_h + padding_top + padding_bottom + gaps).max(min_height);
            (total_w, total_h)
        }
    };

    let mut bg = match bg_uuid_override {
        Some(u) => crate::anim_object::rectangle(
            Transform::with_uuid(u, Vec3::ZERO),
            vec2(total_w, total_h),
            background.corner_radius,
            background.color,
        ),
        None => crate::anim_object::rectangle(
            Transform::new(None, Vec3::ZERO, 0.0, Vec2::ONE),
            vec2(total_w, total_h),
            background.corner_radius,
            background.color,
        ),
    };
    bg.transform_mut().position = compute_bg_center(position, total_w, total_h, pin_point);
    let bg_uuid = bg.uuid();

    let child_uuids: Vec<Uuid> = anim_items.iter().map(|item| item.uuid()).collect();
    let container_inner = match container_uuid_override {
        Some(u) => LayoutContainer::with_uuid(
            u,
            bg_uuid,
            child_uuids,
            layout_dir,
            align,
            justify,
            gap,
            padding_top,
            padding_bottom,
            padding_left,
            padding_right,
            min_width,
            min_height,
        ),
        None => LayoutContainer::new(
            bg_uuid,
            child_uuids,
            layout_dir,
            align,
            justify,
            gap,
            padding_top,
            padding_bottom,
            padding_left,
            padding_right,
            min_width,
            min_height,
        ),
    };
    let container_uuid = container_inner.id;
    let container_obj = DynAnimObj(Box::new(container_inner));

    // Stretch Rectangle children to fill the cross-axis of the layout
    let mut sizes = sizes;
    for (i, item) in anim_items.iter_mut().enumerate() {
        if let Some(rect) = item.as_any_mut().downcast_mut::<Rectangle>() {
            match layout_dir {
                LayoutDir::Column => rect.size.x = total_w,
                LayoutDir::Row => rect.size.y = total_h - padding_top - padding_bottom,
            }
        }
        sizes[i] = item.size();
    }
    // Relayout nested containers whose background was stretched
    for nested in &mut nested_layouts {
        let bg_size = {
            let bg = anim_items
                .iter()
                .find(|a| a.uuid() == nested.background.uuid());
            match bg.and_then(|b| b.as_any().downcast_ref::<Rectangle>()) {
                Some(r) => r.size,
                None => continue,
            }
        };
        let container = nested
            .container
            .as_any()
            .downcast_ref::<LayoutContainer>()
            .expect("nested container should always be a LayoutContainer")
            .clone();
        relayout_nested_children(bg_size, &container, &mut nested.items);
    }

    let content_top = -total_h / 2.0 + padding_top;
    let content_left = -total_w / 2.0 + padding_left;
    let content_right = total_w / 2.0 - padding_right;
    let content_bottom = total_h / 2.0 - padding_bottom;

    match layout_dir {
        LayoutDir::Column => {
            let total_h_content: f32 = sizes.iter().map(|s| s.y).sum();
            let content_size_y = content_bottom - content_top;
            let mut y = match justify {
                Alignment::Start => content_top,
                Alignment::Center => {
                    content_top + (content_size_y - (total_h_content + gaps)) / 2.0
                }
                Alignment::End => content_bottom - (total_h_content + gaps),
            };
            for (i, item) in anim_items.iter_mut().enumerate() {
                let s = sizes[i];
                let is_stretched = item.as_any().downcast_ref::<Rectangle>().is_some();
                let x = if is_stretched {
                    0.0
                } else {
                    match align {
                        Alignment::Start => content_left + s.x / 2.0,
                        Alignment::Center => 0.0,
                        Alignment::End => content_right - s.x / 2.0,
                    }
                };
                item.transform_mut().position = vec3(x, y + s.y / 2.0, 0.0);
                item.transform_mut().set_parent(Some(bg_uuid));
                item.transform_mut().layout_container = Some(container_uuid);
                {
                    let t = item.transform();
                    let local = glam::Mat4::from_scale_rotation_translation(
                        Vec3::new(t.scale.x, t.scale.y, 1.0),
                        glam::Quat::from_rotation_z(t.rotation.to_radians()),
                        Vec3::new(t.position.x, t.position.y, t.position.z),
                    );
                    let parent_local = bg.transform().get_local_matrix();
                    let (scale, rot, trans) =
                        (local * parent_local).to_scale_rotation_translation();
                    item.transform_mut().world_uniform = Some(TransformUniform {
                        scale: scale.truncate(),
                        position: trans,
                        rotation: rot.to_euler(glam::EulerRot::ZYX).0.to_degrees(),
                    });
                }
                y += s.y + gap;
            }
        }
        LayoutDir::Row => {
            let total_w_content: f32 = sizes.iter().map(|s| s.x).sum();
            let content_size_x = content_right - content_left;
            let mut x = match justify {
                Alignment::Start => content_left,
                Alignment::Center => {
                    content_left + (content_size_x - (total_w_content + gaps)) / 2.0
                }
                Alignment::End => content_right - (total_w_content + gaps),
            };
            for (i, item) in anim_items.iter_mut().enumerate() {
                let s = sizes[i];
                let is_stretched = item.as_any().downcast_ref::<Rectangle>().is_some();
                let y = if is_stretched {
                    0.0
                } else {
                    match align {
                        Alignment::Start => content_bottom - s.y / 2.0,
                        Alignment::Center => 0.0,
                        Alignment::End => content_top + s.y / 2.0,
                    }
                };
                item.transform_mut().position = vec3(x + s.x / 2.0, y, 0.0);
                item.transform_mut().set_parent(Some(bg_uuid));
                item.transform_mut().layout_container = Some(container_uuid);
                {
                    let t = item.transform();
                    let local = glam::Mat4::from_scale_rotation_translation(
                        Vec3::new(t.scale.x, t.scale.y, 1.0),
                        glam::Quat::from_rotation_z(t.rotation.to_radians()),
                        Vec3::new(t.position.x, t.position.y, t.position.z),
                    );
                    let parent_local = bg.transform().get_local_matrix();
                    let (scale, rot, trans) =
                        (local * parent_local).to_scale_rotation_translation();
                    item.transform_mut().world_uniform = Some(TransformUniform {
                        scale: scale.truncate(),
                        position: trans,
                        rotation: rot.to_euler(glam::EulerRot::ZYX).0.to_degrees(),
                    });
                }
                x += s.x + gap;
            }
        }
    }

    let nested_ops: Vec<AnimOperation> = nested_layouts
        .iter()
        .map(|n| n.instantiate_children())
        .collect();
    LayoutResult {
        background: bg,
        container: container_obj,
        items: anim_items,
        nested: nested_layouts,
        nested_ops,
    }
}