Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Upgrading a function that loads config files.


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 Iceey   Members   -  Reputation: 139

Like
0Likes
Like

Posted 20 August 2014 - 06:46 AM

Hello everyone.

This is my first thread here but that's not important. The real problem is my member function of cGame class which load config files from the same folder where the .exe files is. It works but the statements must hardcoded. Here is what I mean (behold the chaos):

void cGame::FindOption(std::string wantedTag, std::string wantedOption, std::ifstream *InputStream)
{
	//It works somehow
	char buffer[10];
	std::string tagName;
	std::string optionName;
	bool success = false;
	bool tagFound = false;
	while (!(InputStream->eof()) && (success == false)) // Keeps doing it's stuff untill EOF
	{
		while (buffer[0] != '[' && tagFound == false && !(InputStream->eof())) // looks for a tag eg. [TAG]
			InputStream->get(buffer[0]);
		if (buffer[0] == '[') // if [ sign found then it gets the word between []
		{
			InputStream->get(buffer[0]);
			while (buffer[0] != ']')
			{
				tagName += buffer[0]; // letter by letter T - A - G
				InputStream->get(buffer[0]);
			}
		}
		if (tagName == wantedTag) // if the tag matches the wanted tag it begins to search for option names
		{
			tagFound = true; // also sets the tagFound to success if the tag matches
			InputStream->get(buffer[0]); // skips to next line
			while (InputStream->get(buffer[0]) && buffer[0] != '=' && buffer[0] != ' ' && optionName != wantedOption && !(InputStream->eof())) // begins to get words untill wantedoption found
			{
				if (buffer[0] != '\n') // if not a new line then ...
					optionName += buffer[0]; // letter by letter again :D it works...
				else if (buffer[0] == '\n') // new lines mean that a word hasn't been found in the current line...
					optionName = ""; // so we clear the buffer
			}
			if (optionName == wantedOption) // checks for possible matches // TODO: find a way to make a template for this chaos ( so it doesn't have to be hardcoded this way : / )
			{
				if (wantedOption == "WINDOWED")
				{
					InputStream->get(buffer[0]); // 
					InputStream->get(buffer[0]); // skips " = "
					bool get; 
					*InputStream >> get;
					GraphicsManager->SetWindowed(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "VSYNC")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					bool get;
					*InputStream >> get;
					GraphicsManager->SetVsync(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "SCREEN_WIDTH")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					GraphicsManager->SetWidth(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "SCREEN_HEIGHT")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					GraphicsManager->SetHeight(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "FREQUENCY")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					SoundManager->SetFrequency(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "FORMAT")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					Uint16 get;
					*InputStream >> get;
					SoundManager->SetFormat(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "CHANNELS")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					SoundManager->SetChannels(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}
				else if (wantedOption == "CHUNK_SIZE")
				{
					InputStream->get(buffer[0]);
					InputStream->get(buffer[0]);
					int get;
					*InputStream >> get;
					SoundManager->SetChunkSize(get);
					std::cout << wantedOption << " = " << get << std::endl;
				}

				success = true; // if optionName matches wantedName it sets success to true, meaning that we can end this loop
			}
			else
				optionName = ""; // if option hasn't been found, check another line
		}
		else 
			tagName = ""; // if tag hasn't been found, check another line
	}
	InputStream->seekg(0, std::ios::beg); // if we're done with this TAG - OPTION set we shall return the bricks to original state ( get to the beginning of the file )
}
void cGame::LoadSettings()
{
	std::ifstream Input; // creates our input variable

	Input.open("game.cfg"); // open cfg file

	if (!(Input.good())) // this checks of the file has been opened and if not it creates a new cfg file with default variables from cGraphicsManager.h and cSoundManager.h
	{
		std::cout << "File doesn't exist. Creating new CFG file.\n";
		Input.close(); // we don't need input now
		std::ofstream Output;
		Output.open("game.cfg");

		SDL_Delay(2000);
		GraphicsManager->SetWindowed();
		GraphicsManager->SetVsync();
		GraphicsManager->SetWidth();
		GraphicsManager->SetHeight();
		SoundManager->SetFrequency();
		SoundManager->SetFormat();
		SoundManager->SetChannels();
		SoundManager->SetChunkSize();

		Output << "[GRAPHICS]\n";
		Output << "WINDOWED = " << GraphicsManager->GetWindowed() << "\n";
		Output << "VSYNC = " << GraphicsManager->GetVsync() << "\n";						
		Output << "SCREEN_WIDTH = " << GraphicsManager->GetWidth() << "\n";					
		Output << "SCREEN_HEIGHT = " << GraphicsManager->GetHeight() << "\n";				
																							
		Output << "[SOUND]\n";																
		Output << "FREQUENCY = " << SoundManager->GetFrequency() << '\n';					
		Output << "FORMAT = " << SoundManager->GetFormat() << '\n';							
		Output << "CHANNELS = " << SoundManager->GetChannels() << '\n';						
		Output << "CHUNNK_SIZE = " << SoundManager->GetChunkSize() << '\n';					
																							
		Output.close();

	}
	else if (Input.good()) // if file has been found then it begins to load the settings 
	{
		std::cout << "CFG file found. Loading settings.\n";

		std::cout << "GRAPHICS: \n";
		FindOption("GRAPHICS", "WINDOWED", &Input);
		FindOption("GRAPHICS", "SCREEN_WIDTH", &Input);
		FindOption("GRAPHICS", "SCREEN_HEIGHT", &Input);
		FindOption("GRAPHICS", "VSYNC", &Input);

		std::cout << "\nSOUND: \n";
		FindOption("SOUND", "FREQUENCY", &Input);
		FindOption("SOUND", "FORMAT", &Input);
		FindOption("SOUND", "CHANNELS", &Input);
		FindOption("SOUND", "CHUNK_SIZE", &Input);

		Input.close();
	}
	std::cout << "CFG file loaded.\n\n";
}

Is there any way to shorten this example:

if (optionName == wantedOption) 
{
     if (wantedOption == "WINDOWED")
     {
          InputStream->get(buffer[0]); //
          InputStream->get(buffer[0]); // skips " = "
          bool get;
          *InputStream >> get;
          GraphicsManager->SetWindowed(get);
          std::cout << wantedOption << " = " << get << std::endl;
     }
}

into something like this:

if (optionName == wantedOption)
{
       InputStream->get(buffer[0]); //
       InputStream->get(buffer[0]); // skips " = "
       type get; // type declared in function call or template?
       *InputStream >> Function() // function passed by pointer as an argument
}

So instead of making dozens of new cases I could call one which will automaticaly detect what type of variable I'd like to get from the file and pass it to a function (function pointer) that might be my FindOption function parameter.

Here's function prototype that I thought about but after all it didn't make any sense to me:

void cGame::FindOption(std::string wantedTag, std::string wantedOption, std::ifstream *InputStream, type (*function)(some type));

Function call:

FindOption("SOUND", "CHANNELS", &Input, SoundManager->SetChannels(type must be integer));

 

Normally I'd just keep on adding new statements until I'd end up with 30 of them and a vacation in a hospital with mental disorder but I'd like make this project clear for future developement and not waste my time in any kind of hospital.

Thanks in advance.


Edited by Iceey, 20 August 2014 - 07:29 AM.


Sponsor:

#2 BeerNutts   Crossbones+   -  Reputation: 2978

Like
7Likes
Like

Posted 20 August 2014 - 07:35 AM

My suggestion would be to look at storing your config files using a standard type, like json.  You could then use the jsoncpp lib (or jansson, or any other C/C++ compatible json API) to load the config file, and simply get the values using jsoncpp API's.  Take a look at it, I think you'll like it better than creating your own config file.


My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#3 Iceey   Members   -  Reputation: 139

Like
0Likes
Like

Posted 20 August 2014 - 08:08 AM

Thanks for the suggestion. I shall give it a try and respond when I find it useful or not :)



#4 Juliean   GDNet+   -  Reputation: 2691

Like
0Likes
Like

Posted 20 August 2014 - 08:19 AM

Aside from what BeerNutts suggested, you might also replace the whole "if" conditions with a registry-system of some kind. I don't know how familiar you are with templates, but here is a possible solution:

// base interface for handling a setting change.
class SettingHandlerBase
{
public:
	
	virtual ~SettingHandlerBase(void) = 0 {}
	
	virtual void FromString(const std::string& strValue) = 0;
}

// proxy class that offers an interface for a specific setting value type
template<typename Type>
class SettingHandlerProxy :
	public SettingHandlerBase
{
public:
	void FromString(const std::string& strValue) override final
	{
		const Type value = FromString<Type>(strValue);
		
		OnFromString(value);
	}
	
private:
	
	virtual void OnFromString(Type type) = 0;
}

// convenience class that wraps a setter call for a certain object
template<typename Type, typename ObjectType>
class SettingHandler :
	public SettingHandlerProxy<Type>
{
private:

	SettingHandler(ObjectType& object, void (ObjectType::*pFunction)(Type)) : m_pObject(&object),
		m_pFunction(pFunction)
	{
	}

	void OnFromString(Type type) override final;
	{
		m_pObject->*pFunction(type);
	}
	
	ObjectType* m_pObject;
	void (ObjectType::*m_pFunction)(Type);
}

template<typename Type>
Type fromString(const std::string& strValue)
{
	static_assert(false, "Type cannot be converted to string");
}

// overload the template function for every type you want to support like bool, int, etc..
template<>
Type fromString<bool>(const std::string& strValue)
{
	// add type specific conversion code here
}


// in your code

std::map<std::wstring, SettingHandlerBase*> m_mHandler; // store this in your Loader-class

// for every setting, do:

auto pHandler = new SettingHandler(GraphicsManager, &GraphicsManager::SetWindowed); // should be able to deduce the template arguments automatically
// if not, write this:
auto pHandler = new SettingHandler<bool, GraphicsManager>(GraphicsManager, &GraphicsManager::SetWindowed);
// store it in the map

m_mHandler["WINDOWED"] = pHandler;

Instead of hard-coding the handling of the setting, you have general SettingHandlerBase-class, which has a virtual method called "FromString" (could be SetFromString, if thats more clear). Then you have a map of SettingHandlerBase-pointer associated with the name of the setting. At some point, you register all your setting to that map. Thats where the two templated classes from below come into play - you could just create a single class per setting, but its more convenient to be able to use the "SettingHandler"-class to quickly create a class that calls a specific setter on a certain object, like your GraphisManager.

 

As for actually using it, you can loop over the map, and see if your file has a certain tag with that name (especially easy with JSON/XML/...), and then simply call the FromString(valueString) method.

 

Hopefully I haven't confused you too much, since I don't really know your skills in c++. Just wanted to offer a more flexible/scalable solution. Also note that this code is not tested and probably contains a few compilation errors - which I might fix once I get home.


Edited by Juliean, 20 August 2014 - 08:21 AM.


#5 Iceey   Members   -  Reputation: 139

Like
0Likes
Like

Posted 20 August 2014 - 09:03 AM

Sooner or later I'd have to learn to use templates and now there's an oportunity. I only covered the basics of templates so far but my current knowledge is not enought to understand what you wrote. Give me a day and I'll try fix the lack of it ^^ and of course thank you for your suggestion.



#6 Johnnie   Members   -  Reputation: 136

Like
0Likes
Like

Posted 20 August 2014 - 11:30 AM

You could also use XML. It will make the code more organized and TinyXML (http://www.grinninglizard.com/tinyxml2/) is awesome for file loading in this style. Using it in my Engine and it has worked really well.



#7 BeerNutts   Crossbones+   -  Reputation: 2978

Like
2Likes
Like

Posted 20 August 2014 - 12:32 PM

You could also use XML. It will make the code more organized and TinyXML (http://www.grinninglizard.com/tinyxml2/) is awesome for file loading in this style. Using it in my Engine and it has worked really well.

 

FWIW, I used to use XML before I found out about JSON, but JSON is so easy and non-verbose, while xml can be a pain in the butt.

 

For example:

{ "Hero" :
  {"Health": 100, "Strength": 10, "Mana": 100, "Image": "HeroImage.png", "Inventory": ["Map", "Compass", "Sword"]}
}

In json defines a hero and his inventory.  To do the same in XML:

<Hero>
  <Health>100</Health>
  <Strength>10</Strength>
  <Mana>100</Mana>
  <Image>"HeroImage.png"</Image>
  <Inventory>
    <Item>"Map"</Item>
    <Item>"Compass"</Item>
    <Item>"Sword"</Item>
  </Inventory>
</Hero>

IMO, I found json to be much easier to work with, and the C++ json API's were easy to use too.


Edited by BeerNutts, 20 August 2014 - 12:34 PM.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#8 Iceey   Members   -  Reputation: 139

Like
0Likes
Like

Posted 20 August 2014 - 02:09 PM

I found TinyXML much easier to set up. It was ready to go in 20 minutes. Can't same the same thing about jsoncpp because I still haven't figured out how to get necessary header and source files.

Using CMake is really confusing. Will the header and source files copied from jsoncpp-master (raw zip file from github) work?


Edited by Iceey, 20 August 2014 - 02:38 PM.


#9 BeerNutts   Crossbones+   -  Reputation: 2978

Like
0Likes
Like

Posted 20 August 2014 - 03:29 PM

I found TinyXML much easier to set up. It was ready to go in 20 minutes. Can't same the same thing about jsoncpp because I still haven't figured out how to get necessary header and source files.

Using CMake is really confusing. Will the header and source files copied from jsoncpp-master (raw zip file from github) work?

Are you using visual studio?  There's a makefile you can use to build it under makefiles/msvc2010 (and one for vs71 too).  Otherwise, you can use python to make the amalgamated build (read the docs), but you need python 2.6+ at least. 

 

Good luck!


My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#10 Juliean   GDNet+   -  Reputation: 2691

Like
0Likes
Like

Posted 20 August 2014 - 04:12 PM


For example:

{ "Hero" :
{"Health": 100, "Strength": 10, "Mana": 100, "Image": "HeroImage.png", "Inventory": ["Map", "Compass", "Sword"]}
}

In json defines a hero and his inventory. To do the same in XML:


100
10
100
"HeroImage.png"

"Map"
"Compass"
"Sword"



IMO, I found json to be much easier to work with, and the C++ json API's were easy to use too.

 

Thats kind of a contrived example though. First of all, you can use attributes in XML, which kind of goes against "best practices", but for a private project, whatever. Also, while both XML and JSON are selles as "human readable file formats", that argument kind of falls flat for any project that uses some sort of toolchain for e.g. generating levels, but doesn't want to enroll their own file format. So the recommendation from my side was, use whatever you please. If you only intendt to read/write files from c++-code, use whatever file format/libary works the best.



#11 Strewya   Members   -  Reputation: 1492

Like
0Likes
Like

Posted 21 August 2014 - 01:01 AM

Personally, i use Lua for config files. Since i use it for scripting anyway, i don't see a reason why i wouldn't also use it for configuration.


devstropo.blogspot.com - Random stuff about my gamedev hobby


#12 Iceey   Members   -  Reputation: 139

Like
0Likes
Like

Posted 21 August 2014 - 04:24 AM

 

I found TinyXML much easier to set up. It was ready to go in 20 minutes. Can't same the same thing about jsoncpp because I still haven't figured out how to get necessary header and source files.

Using CMake is really confusing. Will the header and source files copied from jsoncpp-master (raw zip file from github) work?

Are you using visual studio?  There's a makefile you can use to build it under makefiles/msvc2010 (and one for vs71 too).  Otherwise, you can use python to make the amalgamated build (read the docs), but you need python 2.6+ at least. 

 

Good luck!

 

Yes, I am using visual studio. Just managed to build jsoncpp properly. I had to change some code generations settings and it built just fine. Now the only thing I need is to find the documentation or tutorials. Any tips where to search?



#13 BeerNutts   Crossbones+   -  Reputation: 2978

Like
0Likes
Like

Posted 21 August 2014 - 06:36 AM

 

 

I found TinyXML much easier to set up. It was ready to go in 20 minutes. Can't same the same thing about jsoncpp because I still haven't figured out how to get necessary header and source files.

Using CMake is really confusing. Will the header and source files copied from jsoncpp-master (raw zip file from github) work?

Are you using visual studio?  There's a makefile you can use to build it under makefiles/msvc2010 (and one for vs71 too).  Otherwise, you can use python to make the amalgamated build (read the docs), but you need python 2.6+ at least. 

 

Good luck!

 

Yes, I am using visual studio. Just managed to build jsoncpp properly. I had to change some code generations settings and it built just fine. Now the only thing I need is to find the documentation or tutorials. Any tips where to search?

 

The wiki on github has some documentation, and the old project page has doxygen documentation

 

Looks like there is some documentation in the docs folder too from the zipped source.


My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

#14 Iceey   Members   -  Reputation: 139

Like
0Likes
Like

Posted 21 August 2014 - 06:51 AM

Thanks. I also found this if someone is interested in more documentation about Jsoncpp.

 

Edit:

So far so good:

ofkO1lQ.png

 

 

Now I need to find a way to get it into my program.

 

 

Edit:

IT WORKS!

4xsOgqo.png

 

 

Thanks everyone for your suggestions, especially BeerNutts for suggesting JsonCPP. I hope this thread will help someone else :)


Edited by Iceey, 21 August 2014 - 11:27 AM.


#15 SeanMiddleditch   Members   -  Reputation: 6351

Like
0Likes
Like

Posted 25 August 2014 - 11:48 AM

FWIW, I used to use XML before I found out about JSON, but JSON is so easy and non-verbose, while xml can be a pain in the butt.


I also had switched to JSON back when I did a lot of Web work, since that was the hot thing that everyone said you had to use or were dumb, but since working on games I've switched back to XML. XML still has a number of small advantages including a better set of mature editors and RelaxNG/schema support.

Most importantly, though, XML is much easier to merge safely when pulling from a source repo than JSON. This is because JSON has the mandatory trailing commas in arrays/objects on every entry but the last; this makes each item have a slightly different line format depending on where it is in the container. XML items in a container are all uniformly formatted. Non-uniformity means that merging changes from two different sources that both added lines requires attention to the format and no automatic merges, which is terribad for content folks and usually just a pain in the rump for engineers.

This is primary for content files that will have their own editor and aren't end-user facing.

For user-facing configuration files, the good ol' INI format still wins. It's significantly easier to use than JSON, is still mergable if you check-in default files or the like, and also has drop-in parsers to use like https://code.google.com/p/inih/.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS