summary refs log tree commit diff stats
path: root/src/animation.cpp
blob: fbf7ccf9de30dc4ee5d28c91387b0ece2678ef06 (plain) (blame)
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
#include "animation.h"
#include <string_view>
#include <fstream>
#include <stdexcept>
#include <string>
#include <regex>
#include <list>
#include "direction.h"
#include "util.h"

Animation::Animation(std::string_view path) {
  std::ifstream datafile(path.data());
  if (!datafile.is_open()) {
    throw std::invalid_argument(std::string("Could not find sprite datafile: ") + path.data());
  }

  std::string animLine;
  char ch;
  int cellWidth;
  int cellHeight;
  datafile >> cellWidth;
  datafile >> ch; //,
  datafile >> cellHeight;
  std::getline(datafile, animLine); // cell size

  int framesPerRow;
  datafile >> framesPerRow;
  std::getline(datafile, animLine); // frames per row

  int numFrames;
  datafile >> numFrames;
  std::getline(datafile, animLine); // frames
  std::getline(datafile, animLine); // blank

  for (int i=0; i<numFrames; i++) {
    SDL_Rect srcRect;
    srcRect.x = (i % framesPerRow) * cellWidth;
    srcRect.y = (i / framesPerRow) * cellHeight;
    srcRect.w = cellWidth;
    srcRect.h = cellHeight;
    frames_.push_back(srcRect);
  }

  while (std::getline(datafile, animLine)) {
    std::regex re(R"(([a-z!._]+)\[([a-z_]+)\]: ([0-9,]+))");
    std::smatch m;
    std::regex_match(animLine, m, re);

    std::string animName = m[1];
    std::vector<int> anim;
    auto framestrs = splitStr<std::list<std::string>>(m[3], ",");
    for (const std::string& f : framestrs) {
      anim.push_back(std::stoi(f));
    }

    int animId = animations_.size();
    animations_.push_back(std::move(anim));

    Direction dir = directionFromString(std::string(m[2]));
    nameDirToAnim_[animName][dir] = animId;
  }

  updateAnim();
}

void Animation::setDirection(Direction dir) {
  dir_ = dir;
  updateAnim();
}

void Animation::setAnimation(std::string_view anim) {
  animationName_ = anim;
  updateAnim();
}

void Animation::update(int dt) {
  animTimer_.accumulate(dt);

  while (animTimer_.step()) {
    animationFrame_++;

    if (animationFrame_ >= animations_.at(animationId_).size()) {
      animationFrame_ = 0;
    }
  }
}

void Animation::updateAnim() {
  if (nameDirToAnim_.at(animationName_).at(dir_) != animationId_) {
    animationId_ = nameDirToAnim_.at(animationName_).at(dir_);
    animationFrame_ = 0;
  }
}