comfy 0.3.1

A comfy 2d game engine in Rust.
Documentation
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
use crate::*;

pub struct AnimatedSprite {
    pub animations: HashMap<String, Animation>,
    pub state: AnimationState,

    pub z_index: i32,
    pub size: Vec2,
    pub color: Color,

    pub rotation_x: f32,

    pub flip_x: bool,
    pub flip_y: bool,

    pub blend_mode: BlendMode,
    pub offset: Vec2,

    pub on_finished: ContextFn,
}

impl AnimatedSprite {
    pub fn play(&mut self, animation_name: &str) {
        if let Some(animation) = self.animations.get(animation_name) {
            if animation.name != self.state.animation_name {
                self.state = animation.to_state();
            }
        }
    }

    // pub fn from_files(
    //     prefix: impl Into<Cow<'static, str>>,
    //     frames: i32,
    //     interval: f32,
    //     looping: bool,
    //     z_index: i32,
    //     size: Vec2,
    //     color: Color,
    //     offset: Vec2,
    //     on_finished: ContextFn,
    // ) -> Self {
    //     Self {
    //         animations: HashMap::default(),
    //         state: AnimationState {
    //             source: AnimationSource::Files {
    //                 prefix: prefix.into(),
    //                 frames,
    //             },
    //             interval,
    //             looping,
    //             timer: 0.0,
    //             current_frame: 0,
    //         },
    //
    //         z_index,
    //         size,
    //         color,
    //
    //         flip_x: false,
    //         flip_y: false,
    //
    //         blend_mode: BlendMode::None,
    //
    //         offset,
    //
    //         on_finished,
    //     }
    // }

    // pub fn spritesheet(
    //     name: impl Into<Cow<'static, str>>,
    //     spritesheet: Spritesheet,
    //     interval: f32,
    //     looping: bool,
    //     z_index: i32,
    //     world_size: Vec2,
    //     color: Color,
    //     px_offset: Vec2,
    //     on_finished: ContextFn,
    // ) -> Self {
    //     Self {
    //         animations: HashMap::default(),
    //         state: AnimationState {
    //             source: AnimationSource::Spritesheet {
    //                 name: name.into(),
    //                 spritesheet,
    //             },
    //             interval,
    //             looping,
    //             timer: 0.0,
    //             current_frame: 0,
    //         },
    //
    //         z_index,
    //         size: world_size,
    //         color,
    //
    //         flip_x: false,
    //         flip_y: false,
    //
    //         blend_mode: BlendMode::None,
    //
    //         offset: px_offset,
    //
    //         on_finished,
    //         // on_finished,
    //         // on_finished_meta: Arc::new(Mutex::new(None as Option<()>)),
    //     }
    // }
    //
    // pub fn atlas(
    //     name: impl Into<Cow<'static, str>>,
    //     offset: IVec2,
    //     step: IVec2,
    //     sprite_size: IVec2,
    //     frames: i32,
    //     interval: f32,
    //     looping: bool,
    //     z_index: i32,
    //     world_size: Vec2,
    //     color: Color,
    //     px_offset: Vec2,
    //     on_finished: ContextFn,
    // ) -> Self {
    //     Self {
    //         animations: HashMap::default(),
    //         state: AnimationState {
    //             source: AnimationSource::Atlas {
    //                 name: name.into(),
    //                 offset,
    //                 step,
    //                 size: sprite_size,
    //                 frames,
    //             },
    //             interval,
    //             looping,
    //             timer: 0.0,
    //             current_frame: 0,
    //         },
    //
    //         z_index,
    //         size: world_size,
    //         color,
    //
    //         flip_x: false,
    //         flip_y: false,
    //
    //         blend_mode: BlendMode::None,
    //
    //         offset: px_offset,
    //
    //         on_finished,
    //     }
    // }

    pub fn with_blend_mode(self, blend_mode: BlendMode) -> Self {
        Self { blend_mode, ..self }
    }

    pub fn to_quad_draw(&self, transform: &Transform) -> QuadDraw {
        let (texture, source_rect) = self.state.current_rect();

        QuadDraw {
            transform: *transform,
            texture: texture_id(&texture),
            z_index: self.z_index,
            color: self.color,
            blend_mode: self.blend_mode,
            dest_size: self.size * transform.scale,
            source_rect,
            rotation_x: self.rotation_x,
            flip_x: self.flip_x,
            flip_y: self.flip_y,
        }
    }
}

// impl Default for AnimatedSprite {
//     fn default() -> Self {
//         Self {
//             animations: Default::default(),
//             state: AnimationState {
//                 source: AnimationSource::Atlas {
//                     name: "1px".into(),
//                     offset: IVec2::ZERO,
//                     step: IVec2::ZERO,
//                     size: ivec2(16, 16),
//                     frames: 1,
//                 },
//                 interval: 0.2,
//                 looping: true,
//                 timer: 0.0,
//                 current_frame: 0,
//             },
//
//             z_index: 10,
//             size: splat(1.0),
//             color: WHITE,
//             flip_x: false,
//             flip_y: false,
//             blend_mode: BlendMode::None,
//             offset: Vec2::ZERO,
//             on_finished: Box::new(|_| {}),
//         }
//     }
// }

pub struct AnimatedSpriteBuilder {
    pub animations: HashMap<String, Animation>,
    pub state: Option<AnimationState>,
    pub z_index: i32,
    pub size: Vec2,
    pub color: Color,
    pub flip_x: bool,
    pub flip_y: bool,
    pub rotation_x: f32,
    pub blend_mode: BlendMode,
    pub offset: Vec2,
    pub on_finished: Option<ContextFn>,
}

impl AnimatedSpriteBuilder {
    pub fn new() -> Self {
        Self {
            animations: HashMap::new(),
            state: None,
            z_index: 0,
            size: splat(1.0),
            color: WHITE,
            flip_x: false,
            flip_y: false,
            rotation_x: 0.0,
            blend_mode: BlendMode::None,
            offset: Vec2::ZERO,
            on_finished: None,
        }
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn size(mut self, size: Vec2) -> Self {
        self.size = size;
        self
    }

    pub fn z_index(mut self, z_index: i32) -> Self {
        self.z_index = z_index;
        self
    }

    pub fn rotation_x(mut self, rotation_x: f32) -> Self {
        self.rotation_x = rotation_x;
        self
    }

    pub fn flip_x(mut self, flip_x: bool) -> Self {
        self.flip_x = flip_x;
        self
    }

    pub fn flip_y(mut self, flip_y: bool) -> Self {
        self.flip_y = flip_y;
        self
    }

    pub fn blend_mode(mut self, blend_mode: BlendMode) -> Self {
        self.blend_mode = blend_mode;
        self
    }

    pub fn on_finished(mut self, on_finished: ContextFn) -> Self {
        self.on_finished = Some(on_finished);
        self
    }

    pub fn with_animations(mut self, animations: Vec<Animation>) -> Self {
        assert!(
            self.state.is_none(),
            "with_animations can only be used on a new AnimatedSpriteBuilder"
        );

        self.state = Some(
            animations.first().expect("animations can't be empty").to_state(),
        );

        for animation in animations.into_iter() {
            self.animations.insert(animation.name.clone(), animation);
        }

        self
    }

    pub fn add_anim(mut self, animation: Animation) -> Self {
        if self.state.is_none() {
            self.state = Some(animation.to_state());
        }

        self.animations.insert(animation.name.to_string(), animation);

        self
    }

    pub fn add_animation(
        mut self,
        name: &str,
        frame_time: f32,
        looping: bool,
        source: AnimationSource,
    ) -> AnimatedSpriteBuilder {
        let animation =
            Animation { name: name.to_string(), frame_time, looping, source };

        if self.state.is_none() {
            self.state = Some(animation.to_state());
        }


        self.animations.insert(name.to_string(), animation);

        self
    }

    pub fn with_timer(mut self, timer: f32) -> Self {
        let state = self
            .state
            .as_mut()
            .expect("with_timer() can be only used after adding an animation");

        state.timer = timer;

        self
    }

    pub fn build(self) -> AnimatedSprite {
        AnimatedSprite {
            animations: self.animations,
            state: self
                .state
                .expect("AnimatedSpriteBuilder's `state` must be set."),
            z_index: self.z_index,
            size: self.size,
            color: self.color,
            flip_x: self.flip_x,
            flip_y: self.flip_y,
            rotation_x: self.rotation_x,
            blend_mode: self.blend_mode,
            offset: self.offset,
            on_finished: self.on_finished.unwrap_or_else(|| Box::new(|_| {})),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Animation {
    // TODO: we need a better way of identifying animations when doing .play()
    // to avoid excessive string allocations
    pub name: String,
    pub source: AnimationSource,
    pub looping: bool,
    pub frame_time: f32,
}

impl Animation {
    pub fn to_state(&self) -> AnimationState {
        AnimationState {
            animation_name: self.name.clone(),
            source: self.source.clone(),
            interval: self.frame_time,
            looping: self.looping,
            timer: 0.0,
            current_frame: 0,
        }
    }
}

#[derive(Clone, Debug)]
pub enum AnimationSource {
    Files {
        prefix: Cow<'static, str>,
        frames: i32,
    },
    Atlas {
        name: Cow<'static, str>,
        offset: IVec2,
        step: IVec2,
        size: IVec2,
        frames: i32,
    },
    Spritesheet {
        name: Cow<'static, str>,
        spritesheet: Spritesheet,
    },
}

impl AnimationSource {
    pub fn frames(&self) -> i32 {
        match self {
            AnimationSource::Files { frames, .. } => *frames,
            AnimationSource::Atlas { frames, .. } => *frames,
            AnimationSource::Spritesheet { spritesheet, .. } => {
                (spritesheet.rows * spritesheet.columns) as i32
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct AnimationState {
    pub animation_name: String,
    pub source: AnimationSource,
    pub interval: f32,
    pub looping: bool,
    pub timer: f32,
    pub current_frame: i32,
}

impl AnimationState {
    pub fn new(
        animation_name: String,
        source: AnimationSource,
        time: f32,
        looping: bool,
    ) -> Self {
        Self {
            animation_name,
            looping,
            interval: time / source.frames() as f32,
            timer: 0.0,
            current_frame: 0,
            source,
        }
    }

    pub fn with_timer(self, timer: f32) -> Self {
        Self { timer, ..self }
    }

    pub fn progress(&self) -> f32 {
        self.timer / (self.interval * self.source.frames() as f32)
    }

    pub fn update_and_finished(&mut self, delta: f32) -> bool {
        let mut should_despawn = false;

        self.timer += delta;

        let idx = (self.timer / self.interval) as i32;

        if idx >= self.source.frames() && !self.looping {
            should_despawn = true;
        }

        self.current_frame = idx % self.source.frames();

        should_despawn
    }

    pub fn current_rect(&self) -> (Cow<'static, str>, Option<IRect>) {
        match self.source {
            AnimationSource::Files { ref prefix, .. } => {
                (
                    Into::<Cow<'static, str>>::into(format!(
                        "{}{}",
                        prefix, self.current_frame
                    )),
                    None,
                )
            }
            AnimationSource::Atlas { ref name, offset, step, size, .. } => {
                (
                    name.clone(),
                    Some(IRect::new(offset + step * self.current_frame, size)),
                )
            }
            AnimationSource::Spritesheet { ref name, spritesheet } => {
                // let image_size = Assets::image_size(texture_id(name))
                //     .unwrap_or_else(|| {
                //         error!("failed to get size for {name}");
                //         uvec2(64, 64)
                //     })
                //     .as_ivec2();

                let image_size = match Assets::image_size(texture_id(name)) {
                    ImageSizeResult::Loaded(size) => size,
                    // TODO: this is probably not the best way to handle this
                    ImageSizeResult::LoadingInProgress => uvec2(64, 64),
                    _ => {
                        error!("NO SIZE FOR TEXTURE {:?}", name);
                        uvec2(64, 64)
                    }
                }
                .as_ivec2();


                let size = ivec2(
                    image_size.x / spritesheet.columns as i32,
                    image_size.y / spritesheet.rows as i32,
                );

                let row = self.current_frame / spritesheet.columns as i32;
                let col = self.current_frame % spritesheet.columns as i32;

                let offset = ivec2(col, row) * size;

                let rect = IRect::new(offset, size);


                (name.clone(), Some(rect))
            }
        }
    }
}