Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/util/loading/resource_manager.cc @ 6691

Last change on this file since 6691 was 6467, checked in by bensch, 19 years ago

orxonox/trunk: Texture loading with GL_TEXTURE_* in ResourceManager and Material

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