82c78699787fab511325d817812eb87b9454ecee
[supertux.git] / src / physfs / physfs_sdl.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "physfs/physfs_sdl.hpp"
18
19 #include <physfs.h>
20 #include <sstream>
21 #include <stdexcept>
22 #include <assert.h>
23
24 #include "util/log.hpp"
25
26 static int funcSeek(struct SDL_RWops* context, int offset, int whence)
27 {
28   PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
29   int res;
30   switch(whence) {
31     case SEEK_SET:
32       res = PHYSFS_seek(file, offset);
33       break;
34     case SEEK_CUR:
35       res = PHYSFS_seek(file, PHYSFS_tell(file) + offset);
36       break;
37     case SEEK_END:
38       res = PHYSFS_seek(file, PHYSFS_fileLength(file) + offset);
39       break;
40     default:
41       res = 0;
42       assert(false);
43       break;
44   }
45   if(res == 0) {
46     log_warning << "Error seeking in file: " << PHYSFS_getLastError() << std::endl;
47     return -1;
48   }
49
50   return (int) PHYSFS_tell(file);
51 }
52
53 static int funcRead(struct SDL_RWops* context, void* ptr, int size, int maxnum)
54 {
55   PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
56
57   int res = PHYSFS_read(file, ptr, size, maxnum);
58   return res;
59 }
60
61 static int funcClose(struct SDL_RWops* context)
62 {
63   PHYSFS_file* file = (PHYSFS_file*) context->hidden.unknown.data1;
64
65   PHYSFS_close(file);
66   delete context;
67
68   return 0;
69 }
70
71 SDL_RWops* get_physfs_SDLRWops(const std::string& filename)
72 {
73   // check this as PHYSFS seems to be buggy and still returns a
74   // valid pointer in this case
75   if(filename == "") {
76     throw std::runtime_error("Couldn't open file: empty filename");
77   }
78
79   PHYSFS_file* file = (PHYSFS_file*) PHYSFS_openRead(filename.c_str());
80   if(!file) {
81     std::stringstream msg;
82     msg << "Couldn't open '" << filename << "': "
83         << PHYSFS_getLastError();
84     throw std::runtime_error(msg.str());
85   }
86
87   SDL_RWops* ops = new SDL_RWops();
88   ops->type = 0;
89   ops->hidden.unknown.data1 = file;
90   ops->seek = funcSeek;
91   ops->read = funcRead;
92   ops->write = 0;
93   ops->close = funcClose;
94   return ops;
95 }
96
97 /* EOF */