- added draw_part()
[supertux.git] / src / sprite.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <iostream>
21 #include "globals.h"
22 #include "sprite.h"
23
24 Sprite::Sprite(lisp_object_t* cur)
25 {
26   init_defaults();
27
28   LispReader reader(cur);
29
30   reader.read_string("name",   &name);
31   reader.read_int("x-hotspot", &x_hotspot);
32   reader.read_int("y-hotspot", &y_hotspot);
33   reader.read_float("fps",     &fps);
34   std::vector<std::string> images;
35   reader.read_string_vector("images", &images);
36   surfaces.resize(images.size());
37
38   for(std::vector<std::string>::size_type i = 0; i < images.size(); ++i)
39     {
40       surfaces[i] = new Surface(datadir + "/images/" + images[i], USE_ALPHA);
41     }        
42
43   frame_delay = 1000.0f/fps;
44 }
45
46 void
47 Sprite::init_defaults()
48 {
49   x_hotspot = 0;
50   y_hotspot = 0;
51   fps = 10;
52   time = 0;
53   frame_delay = 1000.0f/fps;
54 }
55
56 void
57 Sprite::update(float /*delta*/)
58 {
59   //time += 10*delta;
60   //std::cout << "Delta: " << delta << std::endl;
61 }
62
63 void
64 Sprite::draw(float x, float y)
65 {
66   time = SDL_GetTicks();
67   unsigned int frame = get_current_frame();
68
69   if (frame < surfaces.size())
70     surfaces[frame]->draw(x - x_hotspot, y - y_hotspot);
71 }
72
73 void
74 Sprite::draw_part(float sx, float sy, float x, float y, float w, float h)
75 {
76   time = SDL_GetTicks();
77   unsigned int frame = get_current_frame();
78
79   if (frame < surfaces.size())
80     surfaces[frame]->draw_part(sx, sy, x - x_hotspot, y - y_hotspot, w, h);
81 }
82
83 void
84 Sprite::reset()
85 {
86   time = 0;
87 }
88
89 int
90 Sprite::get_current_frame() const
91 {
92   unsigned int frame = static_cast<int>(fmodf(time, surfaces.size()*frame_delay)/frame_delay);
93   return frame % surfaces.size();
94 }
95
96 int
97 Sprite::get_width() const
98 {
99   return surfaces[get_current_frame()]->w;
100 }
101
102 int
103 Sprite::get_height() const
104 {
105   return surfaces[get_current_frame()]->h;
106 }
107
108 /* EOF */