Example #1
0
    inline bool FindModule(std::string baseName, std::string *fileName, Module *hint)
    {
        // Try first in the current directory.
        if(ExistsFile(baseName))
        {
            *fileName = baseName;
            return true;
        }

        // Now, use the hint.
        if(hint)
        {
            // Check in the same directory as the module.
            std::string modDir = DirName(hint->GetName().filename);
            *fileName = JoinPath(modDir, baseName);
            if(ExistsFile(*fileName))
                return true;

            // Check in the library search path.
            for(size_t i = 0; i < hint->GetLibraryPathCount(); ++i)
            {
                *fileName = JoinPath(hint->GetLibraryPath(i), baseName);
                if(ExistsFile(*fileName))
                    return true;
            }
        }

        return false;
    }
int ParseXMLTaggingRules(const char *filename)
{
 FILE *file;
 int retval;

 if(!ExistsFile(filename))
   {
    fprintf(stderr,"Error: Specified tagging rules file '%s' does not exist.\n",filename);
    return(1);
   }

 file=fopen(filename,"r");

 if(!file)
   {
    fprintf(stderr,"Error: Cannot open tagging rules file '%s' for reading.\n",filename);
    return(1);
   }

 retval=ParseXML(file,xml_toplevel_tags,XMLPARSE_UNKNOWN_ATTR_ERRNONAME);

 fclose(file);

 if(retval)
    return(1);

 return(0);
}
Example #3
0
WaysX *NewWayList(int append,int readonly)
{
 WaysX *waysx;

 waysx=(WaysX*)calloc(1,sizeof(WaysX));

 logassert(waysx,"Failed to allocate memory (try using slim mode?)"); /* Check calloc() worked */

 waysx->filename    =(char*)malloc(strlen(option_tmpdirname)+32);
 waysx->filename_tmp=(char*)malloc(strlen(option_tmpdirname)+32);

 sprintf(waysx->filename    ,"%s/waysx.parsed.mem",option_tmpdirname);
 sprintf(waysx->filename_tmp,"%s/waysx.%p.tmp"    ,option_tmpdirname,(void*)waysx);

 if(append || readonly)
    if(ExistsFile(waysx->filename))
      {
       FILESORT_VARINT waysize;
       int fd;

       fd=ReOpenFileBuffered(waysx->filename);

       while(!ReadFileBuffered(fd,&waysize,FILESORT_VARSIZE))
         {
          SkipFileBuffered(fd,waysize);

          waysx->number++;
         }

       CloseFileBuffered(fd);

       RenameFile(waysx->filename,waysx->filename_tmp);
      }

 if(append)
    waysx->fd=OpenFileBufferedAppend(waysx->filename_tmp);
 else if(!readonly)
    waysx->fd=OpenFileBufferedNew(waysx->filename_tmp);
 else
    waysx->fd=-1;

#if SLIM
 waysx->cache=NewWayXCache();
#endif


 waysx->nfilename_tmp=(char*)malloc(strlen(option_tmpdirname)+32);

 sprintf(waysx->nfilename_tmp,"%s/waynames.%p.tmp",option_tmpdirname,(void*)waysx);

 return(waysx);
}
Example #4
0
bool ConnetMySql()
 {
     string Host,Login,Password,db,St,filename,ty;
     unsigned int Port=0;
     filename = db_conf;//"/etc/palarabic.conf";

     if(ExistsFile(filename)){
         vector<string> arr,arr2;
         St = ReadAllFile(filename);
         arr = Split(St,"\n");
         if ((int)arr[0].find("File Config DataBase (Bouhssini)")== -1) goto aa;
         for (Uint i=2;i<arr.size();i++)
         {
             arr2 = Split(arr[i],"=");
                  if ((int)LCASE(arr2[0]).find("host")!=-1) Host = Trim(arr2[1]);
             else if ((int)LCASE(arr2[0]).find("port")!=-1) Port = atoi(Trim(arr2[1]).c_str());
             else if ((int)LCASE(arr2[0]).find("login")!=-1) Login = Trim(arr2[1]).c_str();
             else if ((int)LCASE(arr2[0]).find("password")!=-1) Password = Trim(arr2[1]).c_str();
             else if ((int)LCASE(arr2[0]).find("db")!=-1) db = Trim(arr2[1]).c_str();
             else if ((int)LCASE(arr2[0]).find("type")!=-1) ty = Trim(arr2[1]).c_str();
         }
         if (LCASE(ty)!="mysql") goto Err;
     }else{
         Host     = "localhost";
         Port     = 3306;
         Login    = "******";
         Password = "******";
         db       = "maahad_hakiba";
         ty       = "MySQL" ;

         WriteFile(filename,"##  File Config DataBase (Bouhssini) ##\n");
         WriteFile(filename,"#######################################\n");
         WriteFile(filename,"\n");
         WriteFile(filename,"Host       = "+Host+"\n");
         WriteFile(filename,"Port       = "+convertInt(Port)+"\n");
         WriteFile(filename,"Login      = "******"\n");
         WriteFile(filename,"Password   = "******"\n");
         WriteFile(filename,"DB         = "+db+"\n");
         WriteFile(filename,"Type       = "+ty+"\n");
     }
     aa:
     conn = mysql_init(NULL);
     if (conn == NULL) goto Err;
     if (mysql_real_connect(conn, Host.c_str(), Login.c_str(), Password.c_str(), db.c_str(), Port, NULL, 0)==NULL) goto Err;
     mysql_query(conn, "SET CHARACTER SET utf8");
     mysql_query(conn, "SET NAMES utf8");
         return true;
     Err:
         conn = NULL;
         return false;
 }
Example #5
0
void open_errorlog(const char *filename,int append,int bin)
{
 /* Text log file */

 errorlogfilename=(char*)malloc(strlen(filename)+8);

 strcpy(errorlogfilename,filename);

#if defined(_MSC_VER) || defined(__MINGW32__)
 errorlogfile=fopen(errorlogfilename,append?"ab":"wb");
#else
 errorlogfile=fopen(errorlogfilename,append?"a" :"w" );
#endif

 if(!errorlogfile)
   {
    fprintf(stderr,"Cannot open file '%s' for writing [%s].\n",errorlogfilename,strerror(errno));
    exit(EXIT_FAILURE);
   }

 /* Binary log file */

 if(bin)
   {
    errorbinfilename=(char*)malloc(strlen(filename)+8);

    sprintf(errorbinfilename,"%s.tmp",filename);

    errorfileoffset=0;

    if(append)
      {
       if(ExistsFile(filename))
          errorfileoffset=SizeFile(filename);

       errorbinfile=OpenFileBufferedAppend(errorbinfilename);
      }
    else
       errorbinfile=OpenFileBufferedNew(errorbinfilename);
   }
 else
    errorbinfile=-1;
}
Example #6
0
File: cunit.c Project: asu88/SOT
/* CREAR EL FICHERO .OUT Y SI ESO .OK*/
int
check_ok(char* file_out , char* file_ok, int fd_out){
	int success, fd_ok;
	if(ExistsFile(file_ok)){
		success=Comparate(file_out, file_ok);
		if(success){
			return 1;
		}else{
			return 0;
		}
	}else{
		//creamos el archivo .ok
		fd_out=open(file_out, O_RDONLY);
		fd_ok=CreatFile(file_ok);
		//metemos el contenido de .out en .ok
		if(fd_out>0 && fd_ok>0){
			ReadWrite(fd_out, fd_ok);			
		}else{
			return 0;
		}
	}
	close(fd_ok);
	return 1;
}
Example #7
0
bool FileStorage::SearchFilesToAdd(const StringRef& searchPath, DirectoryEntry* destDir /*= nullptr*/, bool recursively /*= true*/, bool isReadonly /*= false*/, bool overwrite /*= true*/, bool deleteOriginalFile /*= false*/)
{
	SearchDirectoriesToAdd(searchPath, destDir, recursively);
	if (destDir == nullptr)
	{
		destDir = &mRootDir;
	}
	List<HeapString> fileList;
	Directory::SearchFiles(searchPath, fileList, recursively);
	HeapString searchDir = Path::GetDirectory(searchPath);

	for (const auto& file : fileList)
	{
		auto fs = File::OpenBinaryReader(file);
		if (!fs)
		{
			Log::FormatError("Cannot read file:{}", file);
			return false;
		}


		StringRef destFile;
		if (searchDir.IsEmpty())
		{
			destFile = file;
		}
		else
		{
			destFile = file.ToString().SubString(searchDir.Length() + 1);	//+1 to skip '/'
		}
		bool overwriteFile = false;
		if (overwrite)
		{
			if (RemoveFile(destFile))
			{
				overwriteFile = true;
			}
		}
		else
		{
			if (ExistsFile(destFile))
			{
				Log::FormatInfo("NOT overwrite file:{}", destFile);
				continue;
			}
		}

		auto* fileEntry = SaveFile(*fs, destFile, destDir);
		fileEntry->SetPermission(isReadonly ? FilePermission::Read : FilePermission::All);
		Log::FormatInfo("Add file:{} to {}", destFile, file);

		if (overwriteFile)
		{
			Log::FormatInfo("Overwrite file:{}", destFile);
		}
	}

	if (deleteOriginalFile)
	{
		for (const auto& file : fileList)
		{
			File::Delete(file);
		}
	}

	return true;
}
Example #8
0
vbool VSimpleVfs::Exists(VStringParam in_strFSObject) const
{
	return 
		ExistsDir(in_strFSObject) || 
		ExistsFile(in_strFSObject);
}
Example #9
0
// check basename for texture, and try to return jpg or png file 
void CheckTexture(const char *baseName, String &textureFileName)
{

	const char *ext = strrchr(baseName,'.');

	// check if jpg exists
	textureFileName=baseName;
	if (!ext) {
		textureFileName+=".jpg";

		if (ExistsFile(textureFileName.c_str()))
			return;
	}


	// check if png exists
	textureFileName=baseName;
	if (ext)  // erase ext 
		textureFileName.erase(textureFileName.size()-strlen(ext),strlen(ext));

	textureFileName+=".png";

	if (ExistsFile(textureFileName.c_str()))
		return;

	// check if tga exists
	textureFileName=baseName;
	if (ext)  // erase ext 
		textureFileName.erase(textureFileName.size()-strlen(ext),strlen(ext));

	textureFileName+=".tga";

	if (ExistsFile(textureFileName.c_str())) {
		// convert tga to png
		String outFileName=baseName;
		if (ext)  // erase ext 
			outFileName.erase(outFileName.size()-strlen(ext),strlen(ext));

		outFileName+=".png";

		// bmp.TGAToPNG(textureFileName.c_str(),outFileName.c_str());
		int width, height, comp;
		unsigned char *data = stbi_load(textureFileName.c_str(), &width, &height, &comp	, 0);
		stbi_write_png(outFileName.c_str(), width, height, comp, data, width*comp);
		stbi_image_free(data);

		textureFileName = outFileName;
		return;
	
	}

	// check if jpg exists
	textureFileName=baseName;
	if (ext)  // erase ext 
		textureFileName.erase(textureFileName.size()-strlen(ext),strlen(ext));

	textureFileName+=".jpg";

	if (ExistsFile(textureFileName.c_str()))
		return;

	printf("Texture file not found:'%s'\n",baseName);

}
Example #10
0
int main(int argc,char** argv)
{
 Nodes       *OSMNodes;
 Segments    *OSMSegments;
 Ways        *OSMWays;
 Relations   *OSMRelations;
 Results     *results[NWAYPOINTS+1]={NULL};
 int          point_used[NWAYPOINTS+1]={0};
 double       point_lon[NWAYPOINTS+1],point_lat[NWAYPOINTS+1];
 index_t      point_node[NWAYPOINTS+1]={NO_NODE};
 double       heading=-999;
 int          help_profile=0,help_profile_xml=0,help_profile_json=0,help_profile_pl=0;
 char        *dirname=NULL,*prefix=NULL;
 char        *profiles=NULL,*profilename=NULL;
 char        *translations=NULL,*language=NULL;
 int          exactnodes=0,reverse=0,loop=0;
 Transport    transport=Transport_None;
 Profile     *profile=NULL;
 Translation *translation=NULL;
 index_t      start_node,finish_node=NO_NODE;
 index_t      join_segment=NO_SEGMENT;
 int          arg,nresults=0;
 waypoint_t   start_waypoint,finish_waypoint=NO_WAYPOINT;
 waypoint_t   first_waypoint=NWAYPOINTS,last_waypoint=1,waypoint;
 int          inc_dec_waypoint=1;

 printf_program_start();

 /* Parse the command line arguments */

 if(argc<2)
    print_usage(0,NULL,NULL);

 /* Get the non-routing, general program options */

 for(arg=1;arg<argc;arg++)
   {
    if(!strcmp(argv[arg],"--version"))
       print_usage(-1,NULL,NULL);
    else if(!strcmp(argv[arg],"--help"))
       print_usage(1,NULL,NULL);
    else if(!strcmp(argv[arg],"--help-profile"))
       help_profile=1;
    else if(!strcmp(argv[arg],"--help-profile-xml"))
       help_profile_xml=1;
    else if(!strcmp(argv[arg],"--help-profile-json"))
       help_profile_json=1;
    else if(!strcmp(argv[arg],"--help-profile-perl"))
       help_profile_pl=1;
    else if(!strncmp(argv[arg],"--dir=",6))
       dirname=&argv[arg][6];
    else if(!strncmp(argv[arg],"--prefix=",9))
       prefix=&argv[arg][9];
    else if(!strncmp(argv[arg],"--profiles=",11))
       profiles=&argv[arg][11];
    else if(!strncmp(argv[arg],"--translations=",15))
       translations=&argv[arg][15];
    else if(!strcmp(argv[arg],"--exact-nodes-only"))
       exactnodes=1;
    else if(!strncmp(argv[arg],"--reverse",9))
      {
       if(argv[arg][9]=='=')
          reverse=atoi(&argv[arg][10]);
       else
          reverse=1;
      }
    else if(!strncmp(argv[arg],"--loop",6))
      {
       if(argv[arg][6]=='=')
          loop=atoi(&argv[arg][7]);
       else
          loop=1;
      }
    else if(!strcmp(argv[arg],"--quiet"))
       option_quiet=1;
    else if(!strcmp(argv[arg],"--loggable"))
       option_loggable=1;
    else if(!strcmp(argv[arg],"--logtime"))
       option_logtime=2;
    else if(!strcmp(argv[arg],"--logmemory"))
       option_logmemory=1;
    else if(!strcmp(argv[arg],"--output-html"))
       option_file_html=1;
    else if(!strcmp(argv[arg],"--output-gpx-track"))
       option_file_gpx_track=1;
    else if(!strcmp(argv[arg],"--output-gpx-route"))
       option_file_gpx_route=1;
    else if(!strcmp(argv[arg],"--output-text"))
       option_file_text=1;
    else if(!strcmp(argv[arg],"--output-text-all"))
       option_file_text_all=1;
    else if(!strcmp(argv[arg],"--output-none"))
       option_file_none=1;
    else if(!strcmp(argv[arg],"--output-stdout"))
      { option_file_stdout=1; option_quiet=1; }
    else if(!strncmp(argv[arg],"--profile=",10))
       profilename=&argv[arg][10];
    else if(!strncmp(argv[arg],"--language=",11))
       language=&argv[arg][11];
    else if(!strcmp(argv[arg],"--shortest"))
       option_quickest=0;
    else if(!strcmp(argv[arg],"--quickest"))
       option_quickest=1;
    else if(!strncmp(argv[arg],"--lon",5) && isdigit(argv[arg][5]))
      {
       int point;
       char *p=&argv[arg][6];

       while(isdigit(*p)) p++;
       if(*p++!='=')
          print_usage(0,argv[arg],NULL);

       point=atoi(&argv[arg][5]);
       if(point>NWAYPOINTS || point_used[point]&1)
          print_usage(0,argv[arg],NULL);

       point_lon[point]=degrees_to_radians(atof(p));
       point_used[point]+=1;

       if(point<first_waypoint)
          first_waypoint=point;
       if(point>last_waypoint)
          last_waypoint=point;
      }
    else if(!strncmp(argv[arg],"--lat",5) && isdigit(argv[arg][5]))
      {
       int point;
       char *p=&argv[arg][6];

       while(isdigit(*p)) p++;
       if(*p++!='=')
          print_usage(0,argv[arg],NULL);

       point=atoi(&argv[arg][5]);
       if(point>NWAYPOINTS || point_used[point]&2)
          print_usage(0,argv[arg],NULL);

       point_lat[point]=degrees_to_radians(atof(p));
       point_used[point]+=2;

       if(point<first_waypoint)
          first_waypoint=point;
       if(point>last_waypoint)
          last_waypoint=point;
      }
    else if(!strncmp(argv[arg],"--heading=",10))
      {
       double h=atof(&argv[arg][10]);

       if(h>=-360 && h<=360)
         {
          heading=h;

          if(heading<0) heading+=360;
         }
      }
    else if(!strncmp(argv[arg],"--transport=",12))
      {
       transport=TransportType(&argv[arg][12]);

       if(transport==Transport_None)
          print_usage(0,argv[arg],NULL);
      }
    else
       continue;

    argv[arg]=NULL;
   }

 /* Check the specified command line options */

 if(option_file_stdout && (option_file_html+option_file_gpx_track+option_file_gpx_route+option_file_text+option_file_text_all)!=1)
   {
    fprintf(stderr,"Error: The '--output-stdout' option requires exactly one other output option (but not '--output-none').\n");
    exit(EXIT_FAILURE);
   }

 if(option_file_html==0 && option_file_gpx_track==0 && option_file_gpx_route==0 && option_file_text==0 && option_file_text_all==0 && option_file_none==0)
    option_file_html=option_file_gpx_track=option_file_gpx_route=option_file_text=option_file_text_all=1;

 /* Load in the selected profiles */

 if(transport==Transport_None)
    transport=Transport_Motorcar;

 if(profiles)
   {
    if(!ExistsFile(profiles))
      {
       fprintf(stderr,"Error: The '--profiles' option specifies a file '%s' that does not exist.\n",profiles);
       exit(EXIT_FAILURE);
      }
   }
 else
   {
    profiles=FileName(dirname,prefix,"profiles.xml");

    if(!ExistsFile(profiles))
      {
       char *defaultprofiles=FileName(ROUTINO_DATADIR,NULL,"profiles.xml");

       if(!ExistsFile(defaultprofiles))
         {
          fprintf(stderr,"Error: The '--profiles' option was not used and the files '%s' and '%s' do not exist.\n",profiles,defaultprofiles);
          exit(EXIT_FAILURE);
         }

       free(profiles);
       profiles=defaultprofiles;
      }
   }

 if(!profilename)
    profilename=(char*)TransportName(transport);

 if(ParseXMLProfiles(profiles,profilename,(help_profile_xml|help_profile_json|help_profile_pl)))
   {
    fprintf(stderr,"Error: Cannot read the profiles in the file '%s'.\n",profiles);
    exit(EXIT_FAILURE);
   }

 profile=GetProfile(profilename);

 if(!profile)
   {
    fprintf(stderr,"Error: Cannot find a profile called '%s' in the file '%s'.\n",profilename,profiles);

    profile=(Profile*)calloc(1,sizeof(Profile));
    profile->transport=transport;
   }

 /* Parse the other command line arguments that modify the profile */

 for(arg=1;arg<argc;arg++)
   {
    if(!argv[arg])
       continue;
    else if(!strncmp(argv[arg],"--highway-",10))
      {
       Highway highway;
       char *equal=strchr(argv[arg],'=');
       char *string;
       double p;

       if(!equal)
           print_usage(0,argv[arg],NULL);

       string=strcpy((char*)malloc(strlen(argv[arg])),argv[arg]+10);
       string[equal-argv[arg]-10]=0;

       highway=HighwayType(string);

       if(highway==Highway_None)
          print_usage(0,argv[arg],NULL);

       p=atof(equal+1);

       if(p<0 || p>100)
          print_usage(0,argv[arg],NULL);

       profile->highway[highway]=(score_t)(p/100);

       free(string);
      }
    else if(!strncmp(argv[arg],"--speed-",8))
      {
       Highway highway;
       char *equal=strchr(argv[arg],'=');
       char *string;
       double s;

       if(!equal)
          print_usage(0,argv[arg],NULL);

       string=strcpy((char*)malloc(strlen(argv[arg])),argv[arg]+8);
       string[equal-argv[arg]-8]=0;

       highway=HighwayType(string);

       if(highway==Highway_None)
          print_usage(0,argv[arg],NULL);

       s=atof(equal+1);

       if(s<0)
          print_usage(0,argv[arg],NULL);

       profile->speed[highway]=kph_to_speed(s);

       free(string);
      }
    else if(!strncmp(argv[arg],"--property-",11))
      {
       Property property;
       char *equal=strchr(argv[arg],'=');
       char *string;
       double p;

       if(!equal)
          print_usage(0,argv[arg],NULL);

       string=strcpy((char*)malloc(strlen(argv[arg])),argv[arg]+11);
       string[equal-argv[arg]-11]=0;

       property=PropertyType(string);

       if(property==Property_None)
          print_usage(0,argv[arg],NULL);

       p=atof(equal+1);

       if(p<0 || p>100)
          print_usage(0,argv[arg],NULL);

       profile->props[property]=(score_t)(p/100);

       free(string);
      }
    else if(!strncmp(argv[arg],"--oneway=",9))
       profile->oneway=!!atoi(&argv[arg][9]);
    else if(!strncmp(argv[arg],"--turns=",8))
       profile->turns=!!atoi(&argv[arg][8]);
    else if(!strncmp(argv[arg],"--weight=",9))
       profile->weight=tonnes_to_weight(atof(&argv[arg][9]));
    else if(!strncmp(argv[arg],"--height=",9))
       profile->height=metres_to_height(atof(&argv[arg][9]));
    else if(!strncmp(argv[arg],"--width=",8))
       profile->width=metres_to_width(atof(&argv[arg][8]));
    else if(!strncmp(argv[arg],"--length=",9))
       profile->length=metres_to_length(atof(&argv[arg][9]));
    else
       print_usage(0,argv[arg],NULL);
   }

 /* Print one of the profiles if requested */

 if(help_profile)
   {
    PrintProfile(profile);

    exit(EXIT_SUCCESS);
   }
 else if(help_profile_xml)
   {
    PrintProfilesXML();

    exit(EXIT_SUCCESS);
   }
 else if(help_profile_json)
   {
    PrintProfilesJSON();

    exit(EXIT_SUCCESS);
   }
 else if(help_profile_pl)
   {
    PrintProfilesPerl();

    exit(EXIT_SUCCESS);
   }

 /* Load in the selected translation */

 if(option_file_html || option_file_gpx_route || option_file_gpx_track || option_file_text || option_file_text_all)
   {
    if(translations)
      {
       if(!ExistsFile(translations))
         {
          fprintf(stderr,"Error: The '--translations' option specifies a file '%s' that does not exist.\n",translations);
          exit(EXIT_FAILURE);
         }
      }
    else
      {
       translations=FileName(dirname,prefix,"translations.xml");

       if(!ExistsFile(translations))
         {
          char *defaulttranslations=FileName(ROUTINO_DATADIR,NULL,"translations.xml");

          if(!ExistsFile(defaulttranslations))
            {
             fprintf(stderr,"Error: The '--translations' option was not used and the files '%s' and '%s' do not exist.\n",translations,defaulttranslations);
             exit(EXIT_FAILURE);
            }

          free(translations);
          translations=defaulttranslations;
         }
      }

    if(ParseXMLTranslations(translations,language,0))
      {
       fprintf(stderr,"Error: Cannot read the translations in the file '%s'.\n",translations);
       exit(EXIT_FAILURE);
      }

    if(language)
      {
       translation=GetTranslation(language);

       if(!translation)
         {
          fprintf(stderr,"Warning: Cannot find a translation called '%s' in the file '%s'.\n",language,translations);
          exit(EXIT_FAILURE);
         }
      }
    else
      {
       translation=GetTranslation("");

       if(!translation)
         {
          fprintf(stderr,"Warning: No translations in '%s'.\n",translations);
          exit(EXIT_FAILURE);
         }
      }
   }

 /* Check the waypoints are valid */

 for(waypoint=1;waypoint<=NWAYPOINTS;waypoint++)
    if(point_used[waypoint]==1 || point_used[waypoint]==2)
       print_usage(0,NULL,"All waypoints must have latitude and longitude.");

 if(first_waypoint>=last_waypoint)
    print_usage(0,NULL,"At least two waypoints must be specified.");

 /* Load in the data - Note: No error checking because Load*List() will call exit() in case of an error. */

 if(!option_quiet)
    printf_first("Loading Files:");

 OSMNodes=LoadNodeList(FileName(dirname,prefix,"nodes.mem"));

 OSMSegments=LoadSegmentList(FileName(dirname,prefix,"segments.mem"));

 OSMWays=LoadWayList(FileName(dirname,prefix,"ways.mem"));

 OSMRelations=LoadRelationList(FileName(dirname,prefix,"relations.mem"));

 if(!option_quiet)
    printf_last("Loaded Files: nodes, segments, ways & relations");

 /* Check the profile is valid for use with this database */

 if(UpdateProfile(profile,OSMWays))
   {
    fprintf(stderr,"Error: Profile is invalid or not compatible with database.\n");
    exit(EXIT_FAILURE);
   }

 /* Find all waypoints */

 for(waypoint=first_waypoint;waypoint<=last_waypoint;waypoint++)
   {
    distance_t distmax=km_to_distance(MAXSEARCH);
    distance_t distmin;
    index_t segment=NO_SEGMENT;
    index_t node1,node2,node=NO_NODE;

    if(point_used[waypoint]!=3)
       continue;

    /* Find the closest point */

    if(!option_quiet)
       printf_first("Finding Closest Point: Waypoint %d",waypoint);

    if(exactnodes)
       node=FindClosestNode(OSMNodes,OSMSegments,OSMWays,point_lat[waypoint],point_lon[waypoint],distmax,profile,&distmin);
    else
      {
       distance_t dist1,dist2;

       segment=FindClosestSegment(OSMNodes,OSMSegments,OSMWays,point_lat[waypoint],point_lon[waypoint],distmax,profile,&distmin,&node1,&node2,&dist1,&dist2);

       if(segment!=NO_SEGMENT)
          node=CreateFakes(OSMNodes,OSMSegments,waypoint,LookupSegment(OSMSegments,segment,1),node1,node2,dist1,dist2);
      }

    if(!option_quiet)
       printf_last("Found Closest Point: Waypoint %d",waypoint);

    if(node==NO_NODE)
      {
       fprintf(stderr,"Error: Cannot find node close to specified point %d.\n",waypoint);
       exit(EXIT_FAILURE);
      }

    if(!option_quiet)
      {
       double lat,lon;

       if(IsFakeNode(node))
          GetFakeLatLong(node,&lat,&lon);
       else
          GetLatLong(OSMNodes,node,NULL,&lat,&lon);

       if(IsFakeNode(node))
          printf("Waypoint %d is segment %"Pindex_t" (node %"Pindex_t" -> %"Pindex_t"): %3.6f %4.6f = %2.3f km\n",waypoint,segment,node1,node2,
                 radians_to_degrees(lon),radians_to_degrees(lat),distance_to_km(distmin));
       else
          printf("Waypoint %d is node %"Pindex_t": %3.6f %4.6f = %2.3f km\n",waypoint,node,
                 radians_to_degrees(lon),radians_to_degrees(lat),distance_to_km(distmin));
      }

    point_node[waypoint]=node;
   }

 /* Check for reverse direction */

 if(reverse)
   {
    waypoint_t temp;

    temp=first_waypoint;
    first_waypoint=last_waypoint;
    last_waypoint=temp;

    inc_dec_waypoint=-1;
   }

 /* Loop through all pairs of waypoints */

 if(loop && reverse)
   {
    finish_node=point_node[last_waypoint];

    finish_waypoint=last_waypoint;
   }

 for(waypoint=first_waypoint;waypoint!=(last_waypoint+inc_dec_waypoint);waypoint+=inc_dec_waypoint)
   {
    if(point_used[waypoint]!=3)
       continue;

    start_node=finish_node;
    finish_node=point_node[waypoint];

    start_waypoint=finish_waypoint;
    finish_waypoint=waypoint;

    if(start_node==NO_NODE)
       continue;

    if(heading!=-999 && join_segment==NO_SEGMENT)
       join_segment=FindClosestSegmentHeading(OSMNodes,OSMSegments,OSMWays,start_node,heading,profile);

    /* Calculate the route */

    if(!option_quiet)
       printf("Routing from waypoint %d to waypoint %d\n",start_waypoint,finish_waypoint);

    results[nresults]=CalculateRoute(OSMNodes,OSMSegments,OSMWays,OSMRelations,profile,start_node,join_segment,finish_node,start_waypoint,finish_waypoint);

    if(!results[nresults])
       exit(EXIT_FAILURE);

    join_segment=results[nresults]->last_segment;

    nresults++;
   }

 if(loop && !reverse)
   {
    start_node=finish_node;
    finish_node=point_node[first_waypoint];

    start_waypoint=finish_waypoint;
    finish_waypoint=first_waypoint;

    /* Calculate the route */

    if(!option_quiet)
       printf("Routing from waypoint %d to waypoint %d\n",start_waypoint,finish_waypoint);

    results[nresults]=CalculateRoute(OSMNodes,OSMSegments,OSMWays,OSMRelations,profile,start_node,join_segment,finish_node,start_waypoint,finish_waypoint);

    if(!results[nresults])
       exit(EXIT_FAILURE);

    nresults++;
   }

 if(!option_quiet)
   {
    printf("Routed OK\n");
    fflush(stdout);
   }

 /* Print out the combined route */

 if(!option_quiet)
    printf_first("Generating Result Outputs");

 if(!option_file_none)
    PrintRoute(results,nresults,OSMNodes,OSMSegments,OSMWays,OSMRelations,profile,translation);

 if(!option_quiet)
    printf_last("Generated Result Outputs");

 /* Destroy the remaining results lists and data structures */

#ifdef DEBUG_MEMORY_LEAK

 for(waypoint=0;waypoint<nresults;waypoint++)
    FreeResultsList(results[waypoint]);

 DestroyNodeList(OSMNodes);
 DestroySegmentList(OSMSegments);
 DestroyWayList(OSMWays);
 DestroyRelationList(OSMRelations);

 FreeXMLProfiles();

 FreeXMLTranslations();

#endif

 if(!option_quiet)
    printf_program_end();

 exit(EXIT_SUCCESS);
}
Example #11
0
int main(int argc,char** argv)
{
 NodesX     *OSMNodes;
 WaysX      *OSMWays;
 RelationsX *OSMRelations;
 ErrorLogsX *OSMErrorLogs;
 char       *dirname=NULL,*prefix=NULL,*tagging=NULL;
 int         option_keep=1;
 int         option_filenames=0;
 int         arg;

 printf_program_start();

 /* Parse the command line arguments */

 for(arg=1;arg<argc;arg++)
   {
    if(!strcmp(argv[arg],"--version"))
       print_usage(-1,NULL,NULL);
    else if(!strcmp(argv[arg],"--help"))
       print_usage(1,NULL,NULL);
    else if(!strncmp(argv[arg],"--dir=",6))
       dirname=&argv[arg][6];
    else if(!strncmp(argv[arg],"--sort-ram-size=",16))
       option_filesort_ramsize=atoi(&argv[arg][16]);
#if defined(USE_PTHREADS) && USE_PTHREADS
    else if(!strncmp(argv[arg],"--sort-threads=",15))
       option_filesort_threads=atoi(&argv[arg][15]);
#endif
    else if(!strncmp(argv[arg],"--tmpdir=",9))
       option_tmpdirname=&argv[arg][9];
    else if(!strncmp(argv[arg],"--tagging=",10))
       tagging=&argv[arg][10];
    else if(!strcmp(argv[arg],"--loggable"))
       option_loggable=1;
    else if(!strcmp(argv[arg],"--logtime"))
       option_logtime=1;
    else if(!strcmp(argv[arg],"--logmemory"))
       option_logmemory=1;
    else if(argv[arg][0]=='-' && argv[arg][1]=='-')
       print_usage(0,argv[arg],NULL);
    else
       option_filenames++;
   }

 /* Check the specified command line options */

 if(!option_filesort_ramsize)
   {
#if SLIM
    option_filesort_ramsize=64*1024*1024;
#else
    option_filesort_ramsize=256*1024*1024;
#endif
   }
 else
    option_filesort_ramsize*=1024*1024;

 if(!option_tmpdirname)
   {
    if(!dirname)
       option_tmpdirname=".";
    else
       option_tmpdirname=dirname;
   }

 if(tagging)
   {
    if(!ExistsFile(tagging))
      {
       fprintf(stderr,"Error: The '--tagging' option specifies a file that does not exist.\n");
       exit(EXIT_FAILURE);
      }
   }
 else
   {
    tagging=FileName(dirname,prefix,"fixme.xml");

    if(!ExistsFile(tagging))
      {
       fprintf(stderr,"Error: The '--tagging' option was not used and the default 'fixme.xml' does not exist.\n");
       exit(EXIT_FAILURE);
      }
   }

 if(ParseXMLTaggingRules(tagging))
   {
    fprintf(stderr,"Error: Cannot read the tagging rules in the file '%s'.\n",tagging);
    exit(EXIT_FAILURE);
   }

 /* Create new node, segment, way and relation variables */

 OSMNodes=NewNodeList(0,0);

 OSMWays=NewWayList(0,0);

 OSMRelations=NewRelationList(0,0);

 /* Create the error log file */

 open_errorlog(FileName(dirname,prefix,"fixme.log"),0,option_keep);

 /* Parse the file */

 for(arg=1;arg<argc;arg++)
   {
    int fd;
    char *filename,*p;

    if(argv[arg][0]=='-' && argv[arg][1]=='-')
       continue;

    filename=strcpy(malloc(strlen(argv[arg])+1),argv[arg]);

    fd=OpenFile(filename);

    if((p=strstr(filename,".bz2")) && !strcmp(p,".bz2"))
      {
       fd=Uncompress_Bzip2(fd);
       *p=0;
      }

    if((p=strstr(filename,".gz")) && !strcmp(p,".gz"))
      {
       fd=Uncompress_Gzip(fd);
       *p=0;
      }

    if((p=strstr(filename,".xz")) && !strcmp(p,".xz"))
      {
       fd=Uncompress_Xz(fd);
       *p=0;
      }

    printf("\nParse OSM Data [%s]\n==============\n\n",filename);
    fflush(stdout);

    if((p=strstr(filename,".pbf")) && !strcmp(p,".pbf"))
      {
       if(ParsePBFFile(fd,OSMNodes,OSMWays,OSMRelations))
          exit(EXIT_FAILURE);
      }
    else if((p=strstr(filename,".o5m")) && !strcmp(p,".o5m"))
      {
       if(ParseO5MFile(fd,OSMNodes,OSMWays,OSMRelations))
          exit(EXIT_FAILURE);
      }
    else
      {
       if(ParseOSMFile(fd,OSMNodes,OSMWays,OSMRelations))
          exit(EXIT_FAILURE);
      }

    CloseFile(fd);

    free(filename);
   }

 DeleteXMLTaggingRules();

 FinishNodeList(OSMNodes);
 FinishWayList(OSMWays);
 FinishRelationList(OSMRelations);

 /* Sort the data */

 printf("\nSort OSM Data\n=============\n\n");
 fflush(stdout);

 /* Sort the nodes, ways and relations */

 SortNodeList(OSMNodes);

 SortWayList(OSMWays);

 SortRelationList(OSMRelations);

 /* Process the data */

 RenameFile(OSMNodes->filename_tmp,OSMNodes->filename);
 RenameFile(OSMWays->filename_tmp,OSMWays->filename);
 RenameFile(OSMRelations->rrfilename_tmp,OSMRelations->rrfilename);
 RenameFile(OSMRelations->trfilename_tmp,OSMRelations->trfilename);

 close_errorlog();

 printf("\nCreate Error Log\n================\n\n");
 fflush(stdout);

 OSMErrorLogs=NewErrorLogList();

 ProcessErrorLogs(OSMErrorLogs,OSMNodes,OSMWays,OSMRelations);

 SortErrorLogsGeographically(OSMErrorLogs);

 SaveErrorLogs(OSMErrorLogs,FileName(dirname,prefix,"fixme.mem"));

 FreeErrorLogList(OSMErrorLogs);

 /* Free the memory (delete the temporary files) */

 FreeNodeList(OSMNodes,0);
 FreeWayList(OSMWays,0);
 FreeRelationList(OSMRelations,0);

 printf("\n");
 fflush(stdout);

 printf_program_end();

 exit(EXIT_SUCCESS);
}
Example #12
0
int main(int argc,char** argv)
{
 NodesX    *Nodes;
 SegmentsX *Segments,*SuperSegments=NULL,*MergedSegments=NULL;
 WaysX     *Ways;
 int        iteration=0,quit=0;
 int        max_iterations=10;
 char      *dirname=NULL,*prefix=NULL,*tagging=NULL;
 int        option_parse_only=0,option_process_only=0;
 int        option_filenames=0;
 int        arg;

 /* Parse the command line arguments */

 for(arg=1;arg<argc;arg++)
   {
    if(!strcmp(argv[arg],"--help"))
       print_usage(1);
    else if(!strcmp(argv[arg],"--slim"))
       option_slim=1;
    else if(!strncmp(argv[arg],"--sort-ram-size=",16))
       option_filesort_ramsize=atoi(&argv[arg][16]);
    else if(!strncmp(argv[arg],"--dir=",6))
       dirname=&argv[arg][6];
    else if(!strncmp(argv[arg],"--tmpdir=",9))
       option_tmpdirname=&argv[arg][9];
    else if(!strncmp(argv[arg],"--prefix=",9))
       prefix=&argv[arg][9];
    else if(!strcmp(argv[arg],"--parse-only"))
       option_parse_only=1;
    else if(!strcmp(argv[arg],"--process-only"))
       option_process_only=1;
    else if(!strncmp(argv[arg],"--max-iterations=",17))
       max_iterations=atoi(&argv[arg][17]);
    else if(!strncmp(argv[arg],"--tagging=",10))
       tagging=&argv[arg][10];
    else if(argv[arg][0]=='-' && argv[arg][1]=='-')
       print_usage(0);
    else
       option_filenames++;
   }

 /* Check the specified command line options */

 if(option_parse_only && option_process_only)
    print_usage(0);

 if(option_filenames && option_process_only)
    print_usage(0);

 if(!option_filesort_ramsize)
   {
    if(option_slim)
       option_filesort_ramsize=64*1024*1024;
    else
       option_filesort_ramsize=256*1024*1024;
   }
 else
    option_filesort_ramsize*=1024*1024;

 if(!option_tmpdirname)
   {
    if(!dirname)
       option_tmpdirname=".";
    else
       option_tmpdirname=dirname;
   }

 if(tagging && ExistsFile(tagging))
    ;
 else if(!tagging && ExistsFile(FileName(dirname,prefix,"tagging.xml")))
    tagging=FileName(dirname,prefix,"tagging.xml");

 if(tagging && ParseXMLTaggingRules(tagging))
   {
    fprintf(stderr,"Error: Cannot read the tagging rules in the file '%s'.\n",tagging);
    return(1);
   }

 if(!tagging)
   {
    fprintf(stderr,"Error: Cannot run without reading some tagging rules.\n");
    return(1);
   }

 /* Create new node, segment and way variables */

 Nodes=NewNodeList(option_parse_only||option_process_only);

 Segments=NewSegmentList(option_parse_only||option_process_only);

 Ways=NewWayList(option_parse_only||option_process_only);

 /* Parse the file */

 if(option_filenames)
   {
    for(arg=1;arg<argc;arg++)
      {
       FILE *file;

       if(argv[arg][0]=='-' && argv[arg][1]=='-')
          continue;

       file=fopen(argv[arg],"rb");

       if(!file)
         {
          fprintf(stderr,"Cannot open file '%s' for reading [%s].\n",argv[arg],strerror(errno));
          exit(EXIT_FAILURE);
         }

       printf("\nParse OSM Data [%s]\n==============\n\n",argv[arg]);
       fflush(stdout);

       if(ParseOSM(file,Nodes,Segments,Ways))
          exit(EXIT_FAILURE);

       fclose(file);
      }
   }
 else if(!option_process_only)
   {
    printf("\nParse OSM Data\n==============\n\n");
    fflush(stdout);

    if(ParseOSM(stdin,Nodes,Segments,Ways))
       exit(EXIT_FAILURE);
   }

 if(option_parse_only)
   {
    FreeNodeList(Nodes,1);
    FreeSegmentList(Segments,1);
    FreeWayList(Ways,1);

    return(0);
   }

 /* Process the data */

 printf("\nProcess OSM Data\n================\n\n");
 fflush(stdout);

 /* Sort the nodes, segments and ways */

 SortNodeList(Nodes);

 SortSegmentList(Segments);

 SortWayList(Ways);

 /* Remove bad segments (must be after sorting the nodes and segments) */

 RemoveBadSegments(Nodes,Segments);

 /* Remove non-highway nodes (must be after removing the bad segments) */

 RemoveNonHighwayNodes(Nodes,Segments);

 /* Measure the segments and replace node/way id with index (must be after removing non-highway nodes) */

 UpdateSegments(Segments,Nodes,Ways);


 /* Repeated iteration on Super-Nodes and Super-Segments */

 do
   {
    printf("\nProcess Super-Data (iteration %d)\n================================%s\n\n",iteration,iteration>9?"=":"");
    fflush(stdout);

    if(iteration==0)
      {
       /* Select the super-nodes */

       ChooseSuperNodes(Nodes,Segments,Ways);

       /* Select the super-segments */

       SuperSegments=CreateSuperSegments(Nodes,Segments,Ways,iteration);
      }
    else
      {
       SegmentsX *SuperSegments2;

       /* Select the super-nodes */

       ChooseSuperNodes(Nodes,SuperSegments,Ways);

       /* Select the super-segments */

       SuperSegments2=CreateSuperSegments(Nodes,SuperSegments,Ways,iteration);

       if(SuperSegments->xnumber==SuperSegments2->xnumber)
          quit=1;

       FreeSegmentList(SuperSegments,0);

       SuperSegments=SuperSegments2;
      }

    /* Sort the super-segments */

    SortSegmentList(SuperSegments);

    /* Remove duplicated super-segments */

    DeduplicateSegments(SuperSegments,Nodes,Ways);

    iteration++;

    if(iteration>max_iterations)
       quit=1;
   }
 while(!quit);

 /* Combine the super-segments */

 printf("\nCombine Segments and Super-Segments\n===================================\n\n");
 fflush(stdout);

 /* Merge the super-segments */

 MergedSegments=MergeSuperSegments(Segments,SuperSegments);

 FreeSegmentList(Segments,0);

 FreeSegmentList(SuperSegments,0);

 Segments=MergedSegments;

 /* Rotate segments so that node1<node2 */

 RotateSegments(Segments);

 /* Sort the segments */

 SortSegmentList(Segments);

 /* Remove duplicated segments */

 DeduplicateSegments(Segments,Nodes,Ways);

 /* Cross reference the nodes and segments */

 printf("\nCross-Reference Nodes and Segments\n==================================\n\n");
 fflush(stdout);

 /* Sort the node list geographically */

 SortNodeListGeographically(Nodes);

 /* Create the real segments and nodes */

 CreateRealNodes(Nodes,iteration);

 CreateRealSegments(Segments,Ways);

 /* Fix the segment and node indexes */

 IndexNodes(Nodes,Segments);

 IndexSegments(Segments,Nodes);

 /* Output the results */

 printf("\nWrite Out Database Files\n========================\n\n");
 fflush(stdout);

 /* Write out the nodes */

 SaveNodeList(Nodes,FileName(dirname,prefix,"nodes.mem"));

 FreeNodeList(Nodes,0);

 /* Write out the segments */

 SaveSegmentList(Segments,FileName(dirname,prefix,"segments.mem"));

 FreeSegmentList(Segments,0);

 /* Write out the ways */

 SaveWayList(Ways,FileName(dirname,prefix,"ways.mem"));

 FreeWayList(Ways,0);

 return(0);
}
int main(int argc, char *argv[])
{
	// init fnkdat
	if(fnkdat(NULL, NULL, 0, FNKDAT_INIT) < 0) {
      perror("Could not initialize fnkdat");
      exit(EXIT_FAILURE);
	}

	bool bShowDebug = false;
    for(int i=1; i < argc; i++) {
	    //check for overiding params
		if (strcmp(argv[i], "--showlog") == 0)
			bShowDebug = true;
	}

	if(bShowDebug == false) {
        int d = open(GetLogFilepath().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if(d < 0) {
            perror("Opening logfile failed");
            exit(EXIT_FAILURE);
        }

        if(dup2(d, STDOUT_FILENO) < 0) {
            perror("Redirecting stdout failed");
            exit(EXIT_FAILURE);
        }

        if(dup2(d, STDERR_FILENO) < 0) {
            perror("Redirecting stderr failed");
            exit(EXIT_FAILURE);
        }
	}

    // First check for missing files
    std::vector<std::string> MissingFiles = FileManager::getMissingFiles(LNG_ENG);

    if(MissingFiles.size() > 0) {
        // create data directory inside config directory
        char tmp[FILENAME_MAX];
        fnkdat("data/", tmp, FILENAME_MAX, FNKDAT_USER | FNKDAT_CREAT);

        bool cannotShowMissingScreen = false;
        fprintf(stderr,"The following files are missing:\n");
        std::vector<std::string>::const_iterator iter;
        for(iter = MissingFiles.begin() ; iter != MissingFiles.end(); ++iter) {
            fprintf(stderr," %s\n",iter->c_str());
            if(iter->find("LEGACY.PAK") != std::string::npos) {
                cannotShowMissingScreen = true;
            }
        }

        fprintf(stderr,"Put them in one of the following directories:\n");
        std::vector<std::string> searchPath = FileManager::getSearchPath();
        std::vector<std::string>::const_iterator searchPathIter;
        for(searchPathIter = searchPath.begin(); searchPathIter != searchPath.end(); ++searchPathIter) {
            fprintf(stderr," %s\n",searchPathIter->c_str());
        }

        if(cannotShowMissingScreen == true) {
            return EXIT_FAILURE;
        }
    }

	bool ExitGame = false;
	bool FirstInit = true;
	bool FirstGamestart = false;

    debug = false;
    cursorFrame = UI_CursorNormal;

	do {
		int seed = time(NULL);
		srand(seed);

        // check if configfile exists
        std::string configfilepath = GetConfigFilepath();
        if(ExistsFile(configfilepath) == false) {
            int UserLanguage = GetUserLanguage();
            if(UserLanguage == LNG_UNKNOWN) {
                UserLanguage = LNG_ENG;
            }

            if(MissingFiles.empty() == true) {
                // if all pak files were found we can create the ini file
                FirstGamestart = true;
                CreateDefaultConfigFile(configfilepath, UserLanguage);
            }
        }

		INIFile myINIFile(configfilepath);

		settings.General.PlayIntro = myINIFile.getBoolValue("General","Play Intro",false);
		settings.General.ConcreteRequired = myINIFile.getBoolValue("General","Concrete Required",true);
        settings.General.FogOfWar = myINIFile.getBoolValue("General","Fog of War",false);
		settings.General.PlayerName = myINIFile.getStringValue("General","Player Name","Player");
		settings.Video.Width = myINIFile.getIntValue("Video","Width",640);
		settings.Video.Height = myINIFile.getIntValue("Video","Height",480);
		settings.Video.Fullscreen = myINIFile.getBoolValue("Video","Fullscreen",true);
		settings.Video.DoubleBuffering = myINIFile.getBoolValue("Video","Double Buffering",true);
		settings.Video.FrameLimit = myINIFile.getBoolValue("Video","FrameLimit",true);
		settings.Audio.MusicType = myINIFile.getStringValue("Audio","Music Type","adl");
		std::string Lng = myINIFile.getStringValue("General","Language","en");
		if(Lng == "en") {
			settings.General.setLanguage(LNG_ENG);
		} else if (Lng == "fr") {
			settings.General.setLanguage(LNG_FRE);
		} else if (Lng == "de") {
			settings.General.setLanguage(LNG_GER);
		} else {
			fprintf(stderr,"INI-File: Invalid Language \"%s\"! Default Language (en) is used.\n",Lng.c_str());
			settings.General.setLanguage(LNG_ENG);
		}

		if(FileManager::getMissingFiles(settings.General.Language).size() > 0) {
		    // set back to english
            std::vector<std::string> MissingFiles = FileManager::getMissingFiles(settings.General.Language);
            fprintf(stderr,"The following files are missing for language \"%s\":\n",settings.General.LanguageExt.c_str());
            std::vector<std::string>::const_iterator iter;
            for(iter = MissingFiles.begin() ; iter != MissingFiles.end(); ++iter) {
                fprintf(stderr," %s\n",iter->c_str());
            }
            fprintf(stderr,"Language is changed to English!\n");
            settings.General.setLanguage(LNG_ENG);
		}

		lookDist[0] = 10;lookDist[1] = 10;lookDist[2] = 9;lookDist[3] = 9;lookDist[4] = 9;lookDist[5] = 8;lookDist[6] = 8;lookDist[7] = 7;lookDist[8] = 6;lookDist[9] = 4;lookDist[10] = 1;


		for(int i=1; i < argc; i++) {
		    //check for overiding params
			if((strcmp(argv[i], "-f") == 0) || (strcmp(argv[i], "--fullscreen") == 0))
				settings.Video.Fullscreen = true;
			else if((strcmp(argv[i], "-w") == 0) || (strcmp(argv[i], "--window") == 0))
				settings.Video.Fullscreen = false;
		}

		if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
			fprintf(stderr, "ERROR: Couldn't initialise SDL: %s\n", SDL_GetError());
			exit(EXIT_FAILURE);
		}

		if(FirstGamestart == true && FirstInit == true) {
            // detect 800x600 screen resolution
            if(SDL_VideoModeOK(800, 600, 8, SDL_HWSURFACE | SDL_FULLSCREEN) > 0) {
                settings.Video.Width = 800;
                settings.Video.Height = 600;

                myINIFile.setIntValue("Video","Width",settings.Video.Width);
                myINIFile.setIntValue("Video","Height",settings.Video.Height);

                myINIFile.SaveChangesTo(GetConfigFilepath());
            }
		}

		SDL_EnableUNICODE(1);
		SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
		char strenv[] = "SDL_VIDEO_CENTERED=center";
        SDL_putenv(strenv);
		SDL_WM_SetCaption("Dune Legacy", "Dune Legacy");

		if(FirstInit == true) {
			fprintf(stdout, "initialising sound..... \t");fflush(stdout);
			if( Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 1024) < 0 ) {
				SDL_Quit();
				fprintf(stderr,"Warning: Couldn't set 22050 Hz 16-bit audio\n- Reason: %s\n",SDL_GetError());
				exit(EXIT_FAILURE);
			} else {
				fprintf(stdout, "allocated %d channels.\n", Mix_AllocateChannels(4)); fflush(stdout);
			}
		}

        pFileManager = new FileManager( (MissingFiles.size() > 0) );

        if(pFileManager->exists("IBM.PAL") == true) {
            palette = LoadPalette_RW(pFileManager->OpenFile("IBM.PAL"), true);
        } else {
            // create dummy palette for showing missing files info
            palette = Palette(256);
            palette[255].r = 255;
            palette[255].g = 255;
            palette[255].b = 255;
        }

		screen = NULL;
		setVideoMode();


		fprintf(stdout, "loading fonts.....");fflush(stdout);
		pFontManager = new FontManager();

		fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

		if(MissingFiles.size() > 0) {
		    // some files are missing
		    ExitGame = true;
		    PrintMissingFilesToScreen();
		    fprintf(stdout, "Deinitialize....."); fflush(stdout);
		} else {
		    // everything is just fine and we can start the game

            //get the house palettes
            houseColor[HOUSE_ATREIDES]  =   COLOR_ATREIDES;
            houseColor[HOUSE_ORDOS]     =   COLOR_ORDOS;
            houseColor[HOUSE_HARKONNEN] =   COLOR_HARKONNEN;
            houseColor[HOUSE_SARDAUKAR] =   COLOR_SARDAUKAR;
            houseColor[HOUSE_FREMEN]    =   COLOR_FREMEN;
            houseColor[HOUSE_MERCENARY] =   COLOR_MERCENARY;

            fprintf(stdout, "loading graphics....."); fflush(stdout);
            if((pGFXManager = new GFXManager()) == NULL) {
                fprintf(stderr,"main: Cannot create GFXManager!\n");
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            fprintf(stdout, "loading sounds....."); fflush(stdout);
            if((pSFXManager = new SFXManager()) == NULL) {
                fprintf(stderr,"main: Cannot create SFXManager!\n");
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            fprintf(stdout, "loading texts....."); fflush(stdout);
            if((pTextManager = new TextManager()) == NULL) {
                fprintf(stderr,"main: Cannot create TextManager!\n");
                exit(EXIT_FAILURE);
            }
            fprintf(stdout, "\t\tfinished\n"); fflush(stdout);

            GUIStyle::SetGUIStyle(new DuneStyle);

            if(FirstInit == true) {
                fprintf(stdout, "starting sound player..."); fflush(stdout);
                soundPlayer = new SoundPlayer();
                fprintf(stdout, "\tfinished\n");

                fprintf(stdout, "starting music player...\t"); fflush(stdout);
                if(settings.Audio.MusicType == "directory") {
                    fprintf(stdout, "playing from music directory\n"); fflush(stdout);
                    musicPlayer = new DirectoryPlayer();
                } else if(settings.Audio.MusicType == "adl") {
                    fprintf(stdout, "playing ADL files\n"); fflush(stdout);
                    musicPlayer = new ADLPlayer();
                } else if(settings.Audio.MusicType == "xmi") {
                    fprintf(stdout, "playing XMI files\n"); fflush(stdout);
                    musicPlayer = new XMIPlayer();
                } else {
                    fprintf(stdout, "failed\n"); fflush(stdout);
                    exit(EXIT_FAILURE);
                }

                //musicPlayer->changeMusic(MUSIC_INTRO);
            }

            // Playing intro
            if(((FirstGamestart == true) || (settings.General.PlayIntro == true)) && (FirstInit==true)) {
                fprintf(stdout, "playing intro.....");fflush(stdout);
                Intro* pIntro = new Intro();

                pIntro->run();

                delete pIntro;
                fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
            }

            FirstInit = false;

            fprintf(stdout, "starting main menu.......");fflush(stdout);

            MainMenu * myMenu = new MainMenu();

            fprintf(stdout, "\tfinished\n"); fflush(stdout);

            if(myMenu->showMenu() == -1) {
                ExitGame = true;
            }
            delete myMenu;

            fprintf(stdout, "Deinitialize....."); fflush(stdout);

            GUIStyle::DestroyGUIStyle();

            // clear everything
            if(ExitGame == true) {
                delete musicPlayer;
                delete soundPlayer;
                Mix_HaltMusic();
                Mix_CloseAudio();
            }

            delete pTextManager;
            delete pSFXManager;
            delete pGFXManager;
		}

		delete pFontManager;
		delete pFileManager;
		if(ExitGame == true) {
			SDL_Quit();
		}
		fprintf(stdout, "\t\tfinished\n"); fflush(stdout);
	} while(ExitGame == false);

	// deinit fnkdat
	if(fnkdat(NULL, NULL, 0, FNKDAT_UNINIT) < 0) {
		perror("Could not uninitialize fnkdat");
		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
Example #14
0
	bool FileSystem::Exists(const std::string & path)
	{
		return ExistsFile(path) || ExistsDirectory(path);
	}