Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/std/src/lib/util/loading/resource_manager.cc @ 7203

Last change on this file since 7203 was 7203, checked in by bensch, 18 years ago

orxonox/trunk: compiles again, BUT well…. i do not expect it to run anymore

File size: 30.2 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: Patrick Boenzli
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_LOAD
17
18#include "util/loading/resource_manager.h"
19
20#include "substring.h"
21#include "debug.h"
22
23#include <algorithm>
24#include <assert.h>
25
26// different resource Types
27#ifndef NO_MODEL
28#include "objModel.h"
29#include "primitive_model.h"
30#include "md2Model.h"
31#endif /* NO_MODEL */
32#ifndef NO_TEXTURES
33#include "texture.h"
34#endif /* NO_TEXTURES */
35#ifndef NO_TEXT
36#include "font.h"
37#endif /* NO_TEXT */
38#ifndef NO_AUDIO
39#include "sound_buffer.h"
40#include "ogg_player.h"
41#endif /* NO_AUDIO */
42#ifndef NO_SHADERS
43#include "shader.h"
44#endif /* NO_SHADERS */
45
46// File Handling Includes
47#include <sys/types.h>
48#include <sys/stat.h>
49#include <unistd.h>
50
51using namespace std;
52
53/**
54 * @brief standard constructor
55*/
56ResourceManager::ResourceManager ()
57{
58  this->setClassID(CL_RESOURCE_MANAGER, "ResourceManager");
59  this->setName("ResourceManager");
60
61  this->dataDir = new char[3];
62  this->dataDir = "./";
63  this->tryDataDir("./data");
64}
65
66//! Singleton Reference to the ResourceManager
67ResourceManager* ResourceManager::singletonRef = NULL;
68
69/**
70 * @brief standard destructor
71*/
72ResourceManager::~ResourceManager ()
73{
74  // deleting the Resources-List
75  this->unloadAllByPriority(RP_GAME);
76
77  if (!this->resourceList.empty())
78    PRINTF(1)("Not removed all Resources, since there are still %d resources registered\n", this->resourceList.size());
79
80  ResourceManager::singletonRef = NULL;
81}
82
83/**
84 * @brief sets the data main directory
85 * @param dataDir the DataDirectory.
86 */
87bool ResourceManager::setDataDir(const std::string& dataDir)
88{
89  std::string realDir = ResourceManager::homeDirCheck(dataDir);
90  if (isDir(realDir))
91  {
92    if (dataDir[dataDir.size()-1] == '/' || dataDir[dataDir.size()-1] == '\\')
93    {
94      this->dataDir = realDir;
95    }
96    else
97    {
98      this->dataDir = realDir;
99      this->dataDir += '/';
100    }
101    return true;
102  }
103  else
104  {
105    PRINTF(1)("%s is not a Directory, and can not be the Data Directory, leaving as %s \n", realDir.c_str(), this->dataDir.c_str());
106    return false;
107  }
108}
109
110/**
111 * @brief sets the data main directory
112 * @param dataDir the DataDirectory.
113 *
114 * this is essentially the same as setDataDir, but it ommits the error-message
115 */
116bool ResourceManager::tryDataDir(const std::string& dataDir)
117{
118  std::string realDir = ResourceManager::homeDirCheck(dataDir);
119  if (isDir(realDir))
120  {
121    if (dataDir[dataDir.size()-1] == '/' || dataDir[dataDir.size()-1] == '\\')
122    {
123      this->dataDir = realDir;
124    }
125    else
126    {
127      this->dataDir = realDir;
128      this->dataDir += '/';
129    }
130    return true;
131  }
132  return false;
133}
134
135
136/**
137 * @brief checks for the DataDirectory, by looking if
138 * @param fileInside is iniside of the given directory.
139*/
140bool ResourceManager::verifyDataDir(const std::string& fileInside)
141{
142  bool retVal;
143  if (!isDir(this->dataDir))
144  {
145    PRINTF(1)("%s is not a directory\n", this->dataDir.c_str());
146    return false;
147  }
148
149  std::string testFile = this->dataDir + fileInside;
150  retVal = isFile(testFile);
151  return retVal;
152}
153
154#ifndef NO_TEXTURES
155/**
156 * @brief adds a new Path for Images
157 * @param imageDir The path to insert
158 * @returns true, if the Path was well and injected (or already existent within the list)
159   false otherwise
160*/
161bool ResourceManager::addImageDir(const std::string& imageDir)
162{
163  std::string newDir;
164  if (imageDir[imageDir.size()-1] == '/' || imageDir[imageDir.size()-1] == '\\')
165  {
166    newDir = imageDir;
167  }
168  else
169  {
170    newDir = imageDir;
171    newDir += '/';
172  }
173  // check if the param is a Directory
174  if (isDir(newDir))
175  {
176    // check if the Directory has been added before
177    std::vector<std::string>::const_iterator imageDir;
178    for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
179    {
180      if (*imageDir == newDir)
181      {
182        PRINTF(3)("Path %s already loaded\n", newDir.c_str());
183        return true;
184      }
185    }
186    // adding the directory to the List
187    this->imageDirs.push_back(newDir);
188    return true;
189  }
190  else
191  {
192    PRINTF(1)("%s is not a Directory, and can not be added to the Paths of Images\n", newDir.c_str());
193    return false;
194  }
195}
196#endif /* NO_TEXTURES */
197
198/**
199 * @brief loads resources
200 * @param fileName: The fileName of the resource to load
201 * @param prio: The ResourcePriority of this resource (will only be increased)
202 * @param param0: an additional option to parse (see the constuctors for more help)
203 * @param param1: an additional option to parse (see the constuctors for more help)
204 * @param param2: an additional option to parse (see the constuctors for more help)
205 * @returns a pointer to a desired Resource.
206*/
207BaseObject* ResourceManager::load(const std::string& fileName, ResourcePriority prio,
208                                  const MultiType& param0, const MultiType& param1, const MultiType& param2)
209{
210  ResourceType tmpType;
211#ifndef NO_MODEL
212#define __IF_OK
213  if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".obj", 4))
214    tmpType = OBJ;
215  else if (!strncmp(fileName.c_str()+(fileName.size()-4), ".md2", 4))
216    tmpType = MD2;
217  else if (!strcasecmp(fileName.c_str(), "cube") ||
218            !strcasecmp(fileName.c_str(), "sphere") ||
219            !strcasecmp(fileName.c_str(), "plane") ||
220            !strcasecmp(fileName.c_str(), "cylinder") ||
221            !strcasecmp(fileName.c_str(), "cone"))
222    tmpType = PRIM;
223#endif /* NO_MODEL */
224#ifndef NO_AUDIO
225#ifdef __IF_OK
226  else
227#endif
228#define __IF_OK
229    if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".wav", 4))
230      tmpType = WAV;
231    else if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".mp3", 4))
232      tmpType = MP3;
233    else if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".ogg", 4))
234      tmpType = OGG;
235#endif /* NO_AUDIO */
236#ifndef NO_TEXT
237#ifdef __IF_OK
238    else
239#endif
240#define __IF_OK
241      if (!strncasecmp(fileName.c_str()+(fileName.size()-4), ".ttf", 4))
242        tmpType = TTF;
243#endif /* NO_TEXT */
244#ifndef NO_SHADERS
245#ifdef __IF_OK
246      else
247#endif
248#define __IF_OK
249        if (!strncasecmp(fileName.c_str()+(fileName.size()-5), ".vert", 5))
250          tmpType = SHADER;
251#endif /* NO_SHADERS */
252#ifndef NO_TEXTURES
253#ifdef __IF_OK
254        else
255#else
256  if
257#endif
258          tmpType = IMAGE;
259#endif /* NO_TEXTURES */
260#undef __IF_OK
261  return this->load(fileName, tmpType, prio, param0, param1, param2);
262}
263
264/**
265 * @brief caches a Resource
266 *
267 * @see load;
268 *
269 * @brief returns true if ok, false otherwise.
270 * This function loads a Resource without applying it to an Object.
271 * This is for loading purposes, e.g, when the user is loading a Resource
272 * during the initialisation instead of at Runtime.
273 */
274bool ResourceManager::cache(const std::string& fileName, ResourceType type, ResourcePriority prio,
275                            const MultiType& param0, const MultiType& param1, const MultiType& param2)
276{
277  // searching if the resource was loaded before.
278  Resource* tmpResource;
279  // check if we already loaded this Resource
280  tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);
281  // otherwise load it
282  if (tmpResource == NULL)
283    tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);
284  // return cached pointer.
285  if (tmpResource != NULL) // if the resource was loaded before.
286  {
287    if(tmpResource->prio < prio)
288      tmpResource->prio = prio;
289    return true;
290  }
291  else
292    return false;
293}
294
295/**
296 * tells the ResourceManager to generate a Copy of the Resource.
297 * @brief resourcePointer: The Pointer to the resource to copy
298 * @returns the Resource pointed to resourcePointer.
299 */
300BaseObject* ResourceManager::copy(BaseObject* resourcePointer)
301{
302  Resource* tmp = locateResourceByPointer(resourcePointer);
303  if (tmp!=NULL)
304  {
305    tmp->count++;
306    return tmp->pointer;
307  }
308  else
309    return NULL;
310}
311
312
313/**
314 * @brief loads resources
315 * @param fileName: The fileName of the resource to load
316 * @param type: The Type of Resource to load.
317 * @param prio: The ResourcePriority of this resource (will only be increased)
318 * @param param0: an additional option to parse (see the constuctors for more help)
319 * @param param1: an additional option to parse (see the constuctors for more help)
320 * @param param2: an additional option to parse (see the constuctors for more help)
321 * @returns a pointer to a desired Resource.
322*/
323BaseObject* ResourceManager::load(const std::string& fileName, ResourceType type, ResourcePriority prio,
324                                  const MultiType& param0, const MultiType& param1, const MultiType& param2)
325{
326  // searching if the resource was loaded before.
327  Resource* tmpResource;
328  // check if we already loaded this Resource
329  tmpResource = this->locateResourceByInfo(fileName, type, param0, param1, param2);
330  // otherwise load it
331  if (tmpResource == NULL)
332  {
333    tmpResource = this->loadResource(fileName, type, prio, param0, param1, param2);
334  }
335  // return cached pointer.
336  if (tmpResource != NULL) // if the resource was loaded before.
337  {
338    tmpResource->count++;
339    if(tmpResource->prio < prio)
340      tmpResource->prio = prio;
341
342    return tmpResource->pointer;
343  }
344  else
345    return NULL;
346}
347
348
349/**
350 * @brief loads resources for internal purposes
351 * @param fileName: The fileName of the resource to load
352 * @param type: The Type of Resource to load.
353 * @param prio: The ResourcePriority of this resource (will only be increased)
354 * @param param0: an additional option to parse (see the constuctors for more help)
355 * @param param1: an additional option to parse (see the constuctors for more help)
356 * @param param2: an additional option to parse (see the constuctors for more help)
357 * @returns a pointer to a desired Resource.
358 */
359Resource* ResourceManager::loadResource(const std::string& fileName, ResourceType type, ResourcePriority prio,
360                                        const MultiType& param0, const MultiType& param1, const MultiType& param2)
361{
362  // Setting up the new Resource
363  Resource* tmpResource = new Resource;
364  tmpResource->count = 0;
365  tmpResource->type = type;
366  tmpResource->prio = prio;
367  tmpResource->pointer = NULL;
368  tmpResource->name = fileName;
369
370  // creating the full name. (directoryName + FileName)
371  std::string fullName = ResourceManager::getFullName(fileName);
372  // Checking for the type of resource \see ResourceType
373  switch(type)
374  {
375#ifndef NO_MODEL
376    case OBJ:
377      if (param0.getType() != MT_NULL)
378        tmpResource->param[0] = param0;
379      else
380        tmpResource->param[0] = 1.0f;
381
382      if(ResourceManager::isFile(fullName))
383        tmpResource->pointer = new OBJModel(fullName, tmpResource->param[0].getFloat());
384      else
385      {
386        PRINTF(2)("File %s in %s does not exist. Loading a cube-Model instead\n", fileName.c_str(), dataDir.c_str());
387        tmpResource->pointer = ResourceManager::load("cube", PRIM, prio, tmpResource->param[0].getFloat());
388      }
389      break;
390    case PRIM:
391      if (param0 != MT_NULL)
392        tmpResource->param[0] = param0;
393      else
394        tmpResource->param[0] = 1.0f;
395
396      if (tmpResource->name == "cube")
397        tmpResource->pointer = new PrimitiveModel(PRIM_CUBE, tmpResource->param[0].getFloat());
398      else if (tmpResource->name == "sphere")
399        tmpResource->pointer = new PrimitiveModel(PRIM_SPHERE, tmpResource->param[0].getFloat());
400      else if (tmpResource->name == "plane")
401        tmpResource->pointer = new PrimitiveModel(PRIM_PLANE, tmpResource->param[0].getFloat());
402      else if (tmpResource->name == "cylinder")
403        tmpResource->pointer = new PrimitiveModel(PRIM_CYLINDER, tmpResource->param[0].getFloat());
404      else if (tmpResource->name == "cone")
405        tmpResource->pointer = new PrimitiveModel(PRIM_CONE, tmpResource->param[0].getFloat());
406      break;
407    case MD2:
408      if(ResourceManager::isFile(fullName))
409      {
410        tmpResource->param[0] = param0;
411        tmpResource->param[1] = param1;
412        tmpResource->pointer = new MD2Data(fullName, tmpResource->param[0].getCString(), tmpResource->param[1].getFloat());
413      }
414      break;
415#endif /* NO_MODEL */
416#ifndef NO_TEXT
417    case TTF:
418      if (param0 != MT_NULL)
419      {
420        assert(param0.getInt() >= 0);
421        tmpResource->param[0] = param0;
422      }
423      else
424        tmpResource->param[0] = FONT_DEFAULT_RENDER_SIZE;
425
426      if(isFile(fullName))
427        tmpResource->pointer = new Font(fullName, (unsigned int) tmpResource->param[0].getInt());
428      else
429        PRINTF(2)("%s does not exist in %s. Not loading Font\n", fileName.c_str(), this->dataDir.c_str());
430      break;
431#endif /* NO_TEXT */
432#ifndef NO_AUDIO
433    case WAV:
434      if(isFile(fullName))
435        tmpResource->pointer = new SoundBuffer(fullName);
436      break;
437    case OGG:
438      if (isFile(fullName))
439        tmpResource->pointer = new OggPlayer(fullName);
440      break;
441#endif /* NO_AUDIO */
442#ifndef NO_TEXTURES
443    case IMAGE:
444      if (param0 != MT_NULL)
445        tmpResource->param[0] = param0;
446      else
447        tmpResource->param[0] = GL_TEXTURE_2D;
448      if(isFile(fullName))
449      {
450        PRINTF(4)("Image %s resides to %s\n", fileName, fullName);
451        tmpResource->pointer = new Texture(fullName, tmpResource->param[0].getInt());
452      }
453      else
454      {
455        std::vector<std::string>::iterator imageDir;
456        for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
457        {
458          std::string imgName = *imageDir + fileName;
459          if(isFile(imgName))
460          {
461            PRINTF(4)("Image %s resides to %s\n", fileName, imgName);
462            tmpResource->pointer = new Texture(imgName, tmpResource->param[0].getInt());
463            break;
464          }
465        }
466      }
467      if(!tmpResource)
468        PRINTF(2)("!!Image %s not Found!!\n", fileName.c_str());
469      break;
470#endif /* NO_TEXTURES */
471#ifndef NO_SHADERS
472    case SHADER:
473      if(ResourceManager::isFile(fullName))
474      {
475        if (param0 != MT_NULL)
476        {
477          MultiType param = param0; /// HACK
478          std::string secFullName = ResourceManager::getFullName(param.getCString());
479          if (ResourceManager::isFile(secFullName))
480          {
481            tmpResource->param[0] = secFullName;
482            tmpResource->pointer = new Shader(fullName, secFullName);
483          }
484        }
485        else
486        {
487          tmpResource->param[0] = param0;
488          tmpResource->pointer = new Shader(fullName, NULL);
489        }
490      }
491      break;
492#endif /* NO_SHADERS */
493    default:
494      tmpResource->pointer = NULL;
495      PRINTF(1)("No type found for %s.\n   !!This should not happen unless the Type is not supported yet. JUST DO IT!!\n", tmpResource->name.c_str());
496      break;
497  }
498  if (tmpResource->pointer != NULL)
499    this->resourceList.push_back(tmpResource);
500
501  if (tmpResource->pointer != NULL)
502    return tmpResource;
503  else
504  {
505    PRINTF(2)("Resource %s could not be loaded\n", fileName.c_str());
506    delete tmpResource;
507    return NULL;
508  }
509}
510
511/**
512 * @brief unloads a Resource
513 * @param pointer: The pointer to free
514 * @param prio: the PriorityLevel to unload this resource
515 * @returns true if successful (pointer found, and deleted), false otherwise
516*/
517bool ResourceManager::unload(BaseObject* pointer, ResourcePriority prio)
518{
519  if (pointer == NULL)
520    return false;
521  // if pointer is existent. and only one resource of this type exists.
522  Resource* tmpResource = this->locateResourceByPointer(pointer);
523  if (tmpResource != NULL)
524    return unload(tmpResource, prio);
525  else
526  {
527    PRINTF(2)("Resource not Found %p\n", pointer);
528    return false;
529  }
530}
531
532/**
533 * @brief unloads a Resource
534 * @param resource: The resource to unloade
535 * @param prio the PriorityLevel to unload this resource
536 * @returns true on success, false otherwise.
537*/
538bool ResourceManager::unload(Resource* resource, ResourcePriority prio)
539{
540  if (resource == NULL)
541    return false;
542  if (resource->count > 0)
543    resource->count--;
544
545  if (resource->prio <= prio)
546  {
547    if (resource->count == 0)
548    {
549      delete resource->pointer;
550      // deleting the List Entry:
551      PRINTF(4)("Resource %s safely removed.\n", resource->name.c_str());
552      std::vector<Resource*>::iterator resourceIT = std::find(this->resourceList.begin(), this->resourceList.end(), resource);
553      this->resourceList.erase(resourceIT);
554      delete resource;
555    }
556    else
557      PRINTF(4)("Resource %s not removed, because there are still %d References to it.\n", resource->name.c_str(), resource->count);
558  }
559  else
560    PRINTF(4)("not deleting resource %s because DeleteLevel to high\n", resource->name.c_str());
561  return true;
562}
563
564
565/**
566 * @brief unloads all alocated Memory of Resources with a pririty lower than prio
567 * @param prio The priority to delete
568*/
569bool ResourceManager::unloadAllByPriority(ResourcePriority prio)
570{
571  unsigned int removeCount;
572  for (unsigned int round = 0; round < 3; round++)
573  {
574    int index = this->resourceList.size() - 1;
575    removeCount = 0;
576    while (index >= 0)
577    {
578      if (this->resourceList[index]->prio <= prio)
579      {
580        if (this->resourceList[index]->count == 0)
581          unload(this->resourceList[index], prio);
582        else
583        {
584          if (round == 3)
585            PRINTF(2)("unable to unload %s because there are still %d references to it\n",
586                      this->resourceList[index]->name.c_str(), this->resourceList[index]->count);
587          removeCount++;
588        }
589      }
590      index--;
591    }
592    if (removeCount == 0) break;
593  }
594}
595
596
597/**
598 * @brief Searches for a Resource by some information
599 * @param fileName: The name to look for
600 * @param type the Type of resource to locate.
601 * @param param0: an additional option to parse (see the constuctors for more help)
602 * @param param1: an additional option to parse (see the constuctors for more help)
603 * @param param2: an additional option to parse (see the constuctors for more help)
604 * @returns a Pointer to the Resource if found, NULL otherwise.
605*/
606Resource* ResourceManager::locateResourceByInfo(const std::string& fileName, ResourceType type,
607    const MultiType& param0, const MultiType& param1, const MultiType& param2) const
608{
609  std::vector<Resource*>::const_iterator resource;
610  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
611  {
612    if ((*resource)->type == type && fileName == (*resource)->name)
613    {
614      bool match = false;
615      switch (type)
616      {
617#ifndef NO_MODEL
618        case PRIM:
619        case OBJ:
620          if (param0 == MT_NULL)
621          {
622            if ((*resource)->param[0] == 1.0f)
623              match = true;
624          }
625          else if ((*resource)->param[0] == param0.getFloat())
626            match = true;
627          break;
628        case MD2:
629          if (param0 == MT_NULL && ((*resource)->param[0] == "") && param1 == MT_NULL && ((*resource)->param[0] == 1.0f))
630              match = true;
631          else if ((*resource)->param[0] == ((MultiType)param0).getString() && (*resource)->param[1] == ((MultiType)param1).getFloat())
632            match = true;
633          break;
634#endif /* NO_MODEL */
635#ifndef NO_TEXT
636        case TTF:
637          if (param0 == MT_NULL)
638          {
639            if ((*resource)->param[0] == FONT_DEFAULT_RENDER_SIZE)
640              match = true;
641          }
642          else if ((*resource)->param[0] == param0.getInt())
643            match = true;
644          break;
645#endif /* NO_TEXT */
646#ifndef NO_SHADERS
647        case SHADER:
648          if (param0 == MT_NULL)
649          {
650            if ((*resource)->param[0] == "")
651              match = true;
652          }
653          else if ((*resource)->param[0] == ((MultiType)param0).getString())
654            match = true;
655          break;
656#endif /* NO_SHADERS */
657#ifndef NO_TEXTURES
658        case IMAGE:
659          if (param0 == MT_NULL)
660          {
661            if ((*resource)->param[0] == GL_TEXTURE_2D)
662              match = true;
663          }
664          else if ((*resource)->param[0] ==  param0.getInt())
665            match = true;
666          break;
667#endif /* NO_TEXTURES */
668        default:
669          match = true;
670          break;
671      }
672      if (match)
673      {
674        return (*resource);
675      }
676    }
677  }
678  return NULL;
679}
680
681/**
682 * @brief Searches for a Resource by Pointer
683 * @param pointer the Pointer to search for
684 * @returns a Pointer to the Resource if found, NULL otherwise.
685 */
686Resource* ResourceManager::locateResourceByPointer(const void* pointer) const
687{
688  //  Resource* enumRes = resourceList->enumerate();
689  std::vector<Resource*>::const_iterator resource;
690  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
691    if (pointer == (*resource)->pointer)
692      return (*resource);
693  return NULL;
694}
695
696std::string ResourceManager::toResourcableString(unsigned int i)
697{
698/*  int len = strlen(ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));
699  len += this->resourceList[i]->name.size();
700  if (this->resourceList[i]->param[0].getCString()) len += strlen(this->resourceList[i]->param[0].getCString()) +1;
701  if (this->resourceList[i]->param[1].getCString()) len += strlen(this->resourceList[i]->param[1].getCString()) +1;
702  if (this->resourceList[i]->param[2].getCString()) len += strlen(this->resourceList[i]->param[2].getCString()) +1;
703  len += 10;
704  std::string tmp = new char[len];
705  tmp[0] = '\0';
706  strcat(tmp, ResourceManager::ResourceTypeToChar(this->resourceList[i]->type));
707  strcat(tmp,",");
708  strcat (tmp, this->resourceList[i]->name);
709  if (this->resourceList[i]->param[0].getCString() && this->resourceList[i]->param[0].getCString() != '\0')
710  {
711    strcat(tmp,",");
712    strcat( tmp, this->resourceList[i]->param[0].getCString());
713  }
714  if (this->resourceList[i]->param[1].getCString() && this->resourceList[i]->param[1].getCString() != '\0')
715  {
716    strcat(tmp,",");
717    strcat( tmp, this->resourceList[i]->param[1].getCString());
718  }
719  if (this->resourceList[i]->param[2].getCString() && this->resourceList[i]->param[2].getCString() != '\0')
720  {
721    strcat(tmp,",");
722    strcat( tmp, this->resourceList[i]->param[2].getCString());
723  }
724  return tmp;*/
725}
726
727/**
728 * @brief caches a Resource from a ResourceableString created with the toResourcableString-function
729 * @param resourceableString the String to cache the resource from.
730 */
731bool ResourceManager::fromResourceableString(const std::string& resourceableString)
732{
733/*  SubString splits(resourceableString, ',');
734  splits.debug();
735  if (splits.getCount() == 2)
736    this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
737                RP_LEVEL);
738  else if (splits.getCount() == 3)
739    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
740                RP_LEVEL, splits[2]);
741  else if (splits.getCount() == 4)
742    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
743                RP_LEVEL, splits[2], splits[3]);
744  else if (splits.getCount() == 5)
745    return this->cache(splits[1], ResourceManager::stringToResourceType(splits[0]),
746                RP_LEVEL, splits[2], splits[3], splits[4]);*/
747}
748
749
750/**
751 * @brief Checks if it is a Directory
752 * @param directoryName the Directory to check for
753 * @returns true if it is a directory/symlink false otherwise
754*/
755bool ResourceManager::isDir(const std::string& directoryName)
756{
757  std::string tmpDirName = directoryName;
758  struct stat status;
759
760  // checking for the termination of the string given. If there is a "/" at the end cut it away
761  if (directoryName[directoryName.size()-1] == '/' ||
762      directoryName[directoryName.size()-1] == '\\')
763  {
764    tmpDirName.erase(tmpDirName.size()-1);
765  }
766
767  if(!stat(tmpDirName.c_str(), &status))
768  {
769    if (status.st_mode & (S_IFDIR
770#ifndef __WIN32__
771                          | S_IFLNK
772#endif
773                         ))
774    {
775      return true;
776    }
777    else
778      return false;
779  }
780  else
781    return false;
782}
783
784/**
785 * @brief Checks if the file is either a Regular file or a Symlink
786 * @param fileName the File to check for
787 * @returns true if it is a regular file/symlink, false otherwise
788*/
789bool ResourceManager::isFile(const std::string& fileName)
790{
791  std::string tmpFileName = ResourceManager::homeDirCheck(fileName);
792  // actually checks the File
793  struct stat status;
794  if (!stat(tmpFileName.c_str(), &status))
795  {
796    if (status.st_mode & (S_IFREG
797#ifndef __WIN32__
798                          | S_IFLNK
799#endif
800                         ))
801    {
802      return true;
803    }
804    else
805      return false;
806  }
807  else
808    return false;
809}
810
811/**
812 * @brief touches a File on the disk (thereby creating it)
813 * @param fileName The file to touch
814*/
815bool ResourceManager::touchFile(const std::string& fileName)
816{
817  std::string tmpName = ResourceManager::homeDirCheck(fileName);
818  if (tmpName.empty())
819    return false;
820  FILE* stream;
821  if( (stream = fopen (tmpName.c_str(), "w")) == NULL)
822  {
823    PRINTF(1)("could not open %s fro writing\n", fileName.c_str());
824    return false;
825  }
826  fclose(stream);
827}
828
829/**
830 * @brief deletes a File from disk
831 * @param fileName the File to delete
832*/
833bool ResourceManager::deleteFile(const std::string& fileName)
834{
835  std::string tmpName = ResourceManager::homeDirCheck(fileName);
836  unlink(tmpName.c_str());
837}
838
839/**
840 * @param name the Name of the file to check
841 * @returns The name of the file, including the HomeDir
842 * IMPORTANT: this has to be deleted from the outside
843 */
844std::string ResourceManager::homeDirCheck(const std::string& name)
845{
846  std::string retName;
847  if (!strncmp(name.c_str(), "~/", 2))
848  {
849    char tmpFileName[500];
850#ifdef __WIN32__
851    strcpy(tmpFileName, getenv("USERPROFILE"));
852#else
853    strcpy(tmpFileName, getenv("HOME"));
854#endif
855    retName = tmpFileName + name;
856  }
857  else
858  {
859    retName = name;
860  }
861  return retName;
862}
863
864/**
865 * @param name the relative name of the File/Directory.
866 * @returns a new std::string with the name in abs-dir-format
867 */
868std::string ResourceManager::getAbsDir(const std::string& name)
869{
870  if (name.empty())
871    return "";
872  std::string retName = name;
873  if (strncmp(name.c_str(), "/", 1))
874  {
875    if (name[0] == '.' && name[1] != '.')
876      retName.erase(0);
877    const std::string& absDir = ResourceManager::cwd();
878    retName = absDir + retName;
879  }
880  return retName;
881}
882
883
884/**
885 * @param fileName the Name of the File to check
886 * @returns The full name of the file, including the DataDir, and NULL if the file does not exist
887 * !!IMPORTANT: this has to be deleted from the outside!!
888*/
889std::string ResourceManager::getFullName(const std::string& fileName)
890{
891  if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())
892    return NULL;
893
894  std::string retName = ResourceManager::getInstance()->getDataDir() +fileName;
895  if (ResourceManager::isFile(retName) || ResourceManager::isDir(retName))
896    return retName;
897  else
898    return NULL;
899}
900
901#ifdef __unix__
902  #include <unistd.h>
903#elif __WIN32__ || _MS_DOS_
904  #include <dir.h>
905#else
906  #include <direct.h> /* Visual C++ */
907#endif
908/**
909 * @returns the Current Woring Directory
910 */
911const std::string& ResourceManager::cwd()
912{
913  if (ResourceManager::getInstance()->_cwd.empty())
914  {
915    char cwd[1024];
916    char* errorCode = getcwd(cwd, 1024);
917    if (errorCode == 0)
918      return ResourceManager::getInstance()->_cwd;
919
920    ResourceManager::getInstance()->_cwd = cwd;
921  }
922  return ResourceManager::getInstance()->_cwd;
923}
924
925
926/**
927 * @brief checks wether a file is in the DataDir.
928 * @param fileName the File to check if it is in the Data-Dir structure.
929 * @returns true if the file exists, false otherwise
930 */
931bool ResourceManager::isInDataDir(const std::string& fileName)
932{
933  if (fileName.empty() || ResourceManager::getInstance()->getDataDir().empty())
934    return false;
935
936  bool retVal = false;
937  std::string checkFile = ResourceManager::getInstance()->getDataDir() + fileName;
938
939  if (ResourceManager::isFile(checkFile) || ResourceManager::isDir(checkFile))
940    retVal = true;
941  else
942    retVal = false;
943  return retVal;
944}
945
946
947/**
948 * @brief outputs debug information about the ResourceManager
949 */
950void ResourceManager::debug() const
951{
952  PRINT(0)("=RM===================================\n");
953  PRINT(0)("= RESOURCE-MANAGER DEBUG INFORMATION =\n");
954  PRINT(0)("======================================\n");
955  // if it is not initialized
956  PRINT(0)(" Reference is: %p\n", ResourceManager::singletonRef);
957  PRINT(0)(" Data-Directory is: %s\n", this->dataDir.c_str());
958  PRINT(0)(" List of Image-Directories: ");
959  std::vector<std::string>::const_iterator imageDir;
960  for (imageDir = this->imageDirs.begin(); imageDir != this->imageDirs.end(); imageDir++)
961    PRINT(0)("%s ", (*imageDir).c_str());
962  PRINT(0)("\n");
963
964  PRINT(0)("List of all stored Resources:\n");
965  std::vector<Resource*>::const_iterator resource;
966  for (resource = this->resourceList.begin(); resource != this->resourceList.end(); resource++)
967
968  {
969    PRINT(0)("-----------------------------------------\n");
970    PRINT(0)("Name: %s; References: %d; Type: %s ", (*resource)->name.c_str(), (*resource)->count, ResourceManager::ResourceTypeToChar((*resource)->type));
971
972    PRINT(0)("gets deleted at ");
973    switch((*resource)->prio)
974    {
975      default:
976      case RP_NO:
977        PRINT(0)("first posibility (0)\n");
978        break;
979      case RP_LEVEL:
980        PRINT(0)("the end of the Level (1)\n");
981        break;
982      case RP_CAMPAIGN:
983        PRINT(0)("the end of the campaign (2)\n");
984        break;
985      case RP_GAME:
986        PRINT(0)("when leaving the game (3)\n");
987        break;
988    }
989  }
990
991
992
993  PRINT(0)("==================================RM==\n");
994}
995
996
997/**
998 * @brief converts a ResourceType into the corresponding String
999 * @param type the ResourceType to translate
1000 * @returns the converted String.
1001 */
1002const char* ResourceManager::ResourceTypeToChar(ResourceType type)
1003{
1004  return ResourceManager::resourceNames[type];
1005}
1006
1007/**
1008 * @brief converts a String into a ResourceType (good for loading)
1009 * @param resourceType the name of the Type
1010 * @returns the Number of the Type, or 0 (defautl) if not found.
1011 */
1012ResourceType ResourceManager::stringToResourceType(const char* resourceType)
1013{
1014  assert(resourceType != NULL);
1015  for (unsigned int i = 0; i < RESOURCE_TYPE_SIZE; i++)
1016    if (!strcmp(resourceType, ResourceManager::resourceNames[i]))
1017      return (ResourceType)i;
1018  return (ResourceType)0;
1019}
1020
1021/**
1022 * The Names of the ResourceTypes
1023 */
1024const char* ResourceManager::resourceNames[] =
1025  {
1026#ifndef NO_MODEL
1027    "ObjectModel",
1028    "PrimitiveModel",
1029    "MD2-Data",
1030#endif
1031#ifndef NO_TEXT
1032    "Font",
1033#endif
1034#ifndef NO_AUDIO
1035    "Wav",
1036    "mp3",
1037    "ogg",
1038#endif
1039#ifndef NO_TEXTURES
1040    "Texture",
1041#endif
1042#ifndef NO_SHADERS
1043    "Shader",
1044#endif
1045
1046  };
Note: See TracBrowser for help on using the repository browser.