• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Iceey

Upgrading a function that loads config files.

14 posts in this topic

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
0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
2

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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!

0

Share this post


Link to post
Share on other sites


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.

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

 

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?

0

Share this post


Link to post
Share on other sites

 

 

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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/.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0