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
pub mod texel;
pub mod draw;
mod err;

use std::collections::HashMap;
use std::usize;
use std::mem;

use Cursor;

pub use self::draw::SPEC_MAX_XY;

use self::draw::Draw;
pub use self::texel::Texel;

pub use self::err::{SpriteError, Result};
pub use super::tuple::Tuple;
pub use super::Part;
pub use super::emotion::{Emotion, EmotionError};
pub use super::position::{Posture, PostureError};

/// The limit of draws by sprite.
pub const SPEC_MAX_DRAW: usize = 16;

#[derive(Debug)]
pub struct Sprite {
    texel: HashMap<Tuple, Vec<Texel>>,
    sheet: Cursor<[Draw; SPEC_MAX_DRAW]>,
    count: usize,
}

impl Sprite {

    pub fn explicite_emotion(&mut self,
        change: &[[Tuple; SPEC_MAX_XY]; SPEC_MAX_DRAW]
    ) {
        let board: Vec<Vec<(Emotion, Vec<Texel>)>> =
            change.iter().map(|tuples: &[Tuple; SPEC_MAX_XY]| {
                 tuples.iter().filter_map(|tuple| {
                      self.texel.get(&Tuple::from((tuple.part, tuple.emotion)))
                          .and_then(|texels| Some((tuple.emotion, texels.clone())))
                 })
                 .collect::<Vec<(Emotion, Vec<Texel>)>>()
            })
            .collect::<Vec<Vec<(Emotion, Vec<Texel>)>>>();

        self.sheet.get_mut()
            .iter_mut()
            .zip(board.iter())
            .all(|(draw, tuple): (&mut Draw, &Vec<(Emotion, Vec<Texel>)>)|
                tuple.iter()
                     .all(|&(emotion, ref texels): &(Emotion, Vec<Texel>)|
                        texels.iter()
                              .enumerate()
                              .all(|(index, texel): (usize, &Texel)| {
                                    draw.set_cell_at(index, texel, &emotion);
                                    true
                              })
                     ));
    }

    /// The function `insert_list` push a new draw from a list of
    /// tuple of emotion by part.
    pub fn insert_list(&mut self,
        duration: i64,
        posture: &Posture,
        source: &[Tuple],
    ) {
        let mut draw: Vec<(Emotion, Texel)> = Vec::with_capacity(SPEC_MAX_XY);
    
        source.iter().all(|&tuple: &Tuple| {
           self.texel.get(&tuple)
                     .and_then(|texels: &Vec<Texel>| {
                let index: usize = draw.iter().filter(|&&(_, ref texel)| {
                    texel.get_part().eq(&tuple.part)
                }).count();
                Some(draw.push((tuple.emotion, *texels.get(index).unwrap())))
            }).is_some()
        });
        if let Ok(draw) = Draw::new(posture, duration, draw.as_slice()) {
            unsafe {
                *self.sheet.get_mut()
                     .get_unchecked_mut(self.count) = draw;
                self.count += 1;
            }
        }
    }

    /// The function `extend` extends the local dictionary of texel.
    pub fn extend(&mut self,
                 texels: &HashMap<Tuple, Vec<Texel>>
    ) {
        texels.iter()
               .all(|(&Tuple { part, emotion }, value):
                     (&Tuple, &Vec<Texel>)|
                    self.texel.insert(Tuple::from((part, emotion)),
                                      value.clone())
                              .is_none());
    }

    pub fn current(&self) -> Option<(&Emotion, &Texel)> {
        self.sheet
            .get_ref()
            .get(self.sheet.position())
            .and_then(|draw| draw.current())
    }

    pub fn set_current(&mut self, cell: (&Emotion, &Vec<Texel>)) -> Option<()> {
        let position: usize = self.sheet.position();
        self.sheet
            .get_mut()
            .get_mut(position)
            .and_then(|board| Some(board.set_current(cell)))
    }

    pub fn get_posture(&self) -> Option<&Posture> {
        self.sheet
            .get_ref()
            .get(self.sheet.position())
            .and_then(|draw| Some(draw.get_posture()))
    }

    pub fn get_current_draw(&self) -> Option<&Draw> {
        self.sheet.get_ref().get(self.sheet.position())
    }

    /// The mutator method `set_position` changes the position of
    /// the file sprite cursor.
    fn set_position(&mut self, position: usize) {
        self.sheet.set_position(position);
    }

    /// The mutator method `add_position_draw` increments the position of
    /// the draw sheet cursor.
    pub fn add_position(&mut self, position: usize) -> Option<()> {
        match (self.sheet.position().checked_add(position),
               self.sheet.get_ref().len()) {
            (Some(pos), len) if pos < len => Some(self.set_position(pos)),
            _ => None,
        }
    }

    /// The mutator method `sub_position` decrements the position of
    /// the draw sheet cursor.
    pub fn sub_position(&mut self, position: usize) -> Option<()> {
        self.sheet.position()
            .checked_sub(position)
            .or_else(|| self.sheet.get_ref().len().checked_sub(1))
            .and_then(|pos| Some(self.set_position(pos)))
    }

    /// The mutator method `add_position_draw` increments the position of
    /// the cell board cursor.
    pub fn add_position_draw(&mut self, position: usize) -> Option<()> {
        let current_position: usize = self.sheet.position();
        self.sheet
            .get_mut()
            .get_mut(current_position)
            .and_then(|ref mut draw|
                      draw.add_position(position))
            .or_else(|| self.add_position(1))
    }

    /// The mutator method `sub_position_draw` decrements the position of
    /// the cell board cursor.
    pub fn sub_position_draw(&mut self, position: usize) -> Option<()> {
        let current_position: usize = self.sheet.position();
        self.sheet
            .get_mut()
            .get_mut(current_position)
            .and_then(|ref mut draw| draw.sub_position(position))
            .or_else(|| self.sub_position(1))
    }
}

impl Clone for Sprite {
       fn clone(&self) -> Sprite {
            unsafe {
                let mut sheet: [Draw; SPEC_MAX_DRAW] = mem::uninitialized();

                sheet.clone_from_slice(self.sheet.get_ref());
                Sprite {
                    texel: self.texel.clone(),
                    sheet: Cursor::new(sheet),
                    count: self.count,
                }
            }
       }
}

impl<'a> IntoIterator for &'a Sprite {
    type Item = &'a Draw;
    type IntoIter = ::std::slice::Iter<'a, Draw>;

    fn into_iter(self) -> Self::IntoIter {
        self.sheet.get_ref().split_at(self.count).0.into_iter()
    }
}

impl Default for Sprite {
    fn default() -> Sprite {
        unsafe {
            let mut sheet: [Draw; SPEC_MAX_DRAW] = mem::uninitialized();

            assert!(sheet.iter_mut().all(|mut draw| {
                *draw = Draw::default();
                true
            }));
            Sprite {
                texel: HashMap::with_capacity(SPEC_MAX_XY),
                sheet: Cursor::new(sheet),
                count: 0,
            }
        }
    }
}