Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/util/loading/resource_manager.cc @ 7196

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

orxonox/trunk: spliced a nice patch from the dylib branche back here with:
svn diff -r 7168 resource_manager.* > ../../../../../trunk/fancy.resource.manager.patch

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