<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>RasterGrid Blog &#187; General</title>
	<atom:link href="http://rastergrid.com/blog/category/programming/general/feed/" rel="self" type="application/rss+xml" />
	<link>http://rastergrid.com/blog</link>
	<description>A technical blog from Daniel Rákos (aka aqnuep)</description>
	<lastBuildDate>Fri, 04 Nov 2011 18:10:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Common pitfalls of iPhone development</title>
		<link>http://rastergrid.com/blog/2010/05/common-pitfalls-of-iphone-development/</link>
		<comments>http://rastergrid.com/blog/2010/05/common-pitfalls-of-iphone-development/#comments</comments>
		<pubDate>Mon, 10 May 2010 19:04:20 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Telecommunication]]></category>
		<category><![CDATA[Apple]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[mobile technology]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[phone]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=234</guid>
		<description><![CDATA[I haven&#8217;t written any posts lately. This is because I dug into iPhone application development and this really consumed most of my spare time. As you may remember, I&#8217;ve already mentioned that I would like to start dealing with mobile platforms as a target for my OpenGL related experiments and projects.  After Android, this time]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F05%252Fcommon-pitfalls-of-iphone-development%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FcZPyzL%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Common%20pitfalls%20of%20iPhone%20development%22%20%7D);"></div>
<p>I haven&#8217;t written any posts lately. This is because I dug into iPhone application development and this really consumed most of my spare time. As you may remember, I&#8217;ve already mentioned that I would like to start dealing with mobile platforms as a target for my OpenGL related experiments and projects.  After Android, this time I got my hands on a Mac mini and took a look at the currently most popular mobile gaming platform. Actually, these initial experiments wouldn&#8217;t take that long time if I would have to deal with just a new API and not with a brand new world with its own benefits and drawbacks.</p>
<p><span id="more-234"></span>I have a long experience in using Windows and Linux as a development platform with tons of different development environment and programming languages. Beside that, I&#8217;ve also done some Mac application development, at least if we can call a cross-platform application so that works on all of these three desktop operating systems. Taking in consideration these facts I thought that starting to develop under Mac OS X targeting the iPhone platform will be piece of cake as I just have to master one another programming language and API, namely Objective-C and Cocoa Touch. Well, it turned out that I was too optimistic and this is not that simple as it looks like (at least for me, who hardly ever used a Macintosh before).</p>
<h2><img class="alignleft" title="Mac OS X Leopard" src="http://www.rastergrid.com/blog/wp-content/uploads/2010/05/leopard-logo.png" alt="Mac OS X Leopard" width="150" height="172" />The GUI of Mac OS X Leopard</h2>
<p>The first thing I&#8217;ve found very unusual is the user interface of the operating system. Primarily, I&#8217;m talking about the following little differences:</p>
<p>- The menu of the windows is at the top of the desktop, not the top of the window.</p>
<p>- The system buttons on the window title bar are on the left side, not on the right side.</p>
<p>- Double-clicking the title bar doesn&#8217;t maximize the window, it minimizes it instead.</p>
<p>- The most used key combinations like Copy-Paste and stuff like that are also different.</p>
<p>Okay, I know that these are such things that everybody know who already seen the GUI of Mac OS X, but still, it&#8217;s quite annoying that Apple is going totally against the rest of the PC world. I agree that different operating systems can define their own direction regarding to the layout of the GUI, but I wonder how I didn&#8217;t notice such huge conceptual differences when I&#8217;ve first started to work on Linux after several years of Windows user experience?</p>
<p>Anyway, these are just small things and it&#8217;s just a matter of time to get used to the new interface. Also, I can say that the Mac OS X user experience is excellent. I don&#8217;t say that it is any better than that of Windows or some well-made Linux distributions but it is not worse either.</p>
<h2><img class="alignleft" title="Xcode" src="http://www.rastergrid.com/blog/wp-content/uploads/2010/05/xcode.png" alt="" width="150" height="150" />The Xcode IDE</h2>
<p>Those who heard anything about iPhone development know that the only legal possibility to write applications for this mobile platform is to do it under Mac OS X using the Xcode development environment. I know that thousands of people will blame me for what I&#8217;m going to say but I sincerely think that Xcode is the worst development environment I&#8217;ve worked with lately.</p>
<p>First of all, it was completely alien for me even though I worked with dozens of development environments ranging from basic text editors to full-fledged development environments with every tool integrated within them. While the most used editor features like syntax highlighting and code completion work flawless, there are huge amount of features missing from it that are common in other IDEs like a source code outline window. But this is not the only thing I can complain about&#8230;</p>
<p>As I mentioned it before, I dealt with many different development environments, the most noticeable ones are CodeGear RAD Studio, Visual Studio and Eclipse. What is common in these (and a lot of other Windows and Linux IDEs)  is that if you migrate from one to another you&#8217;ll most probably won&#8217;t notice too much except some minor differences in key bindings. I think actually this is the way how it should work as if I would be the head of a software development company I would invest in a development environment that can be easily learned no matter what my future employees used earlier. This reduces competence development cost and enables the programmers to work more effectively in a relatively short time-frame. Well, it seems that Apple disagrees with me as comparing the aforementioned IDEs and Xcode is like comparing an armchair with a stool.</p>
<p>In spite of all his faults, Xcode has also some clever solutions for some usual tasks that makes it popular even though Apple gone again against the rest of the world with this software so I don&#8217;t say that Xcode is completely useless, but what&#8217;s for sure is that it has a long way to go in order to be able to compete with the other development environments out there. I don&#8217;t even understand why didn&#8217;t they just made a simple Eclipse plugin for their purposes like all other players do?</p>
<p>While maybe I&#8217;ve already scared many of you from using Xcode, yet I haven&#8217;t talked about the &#8220;feature&#8221; that made me the most frustrated about my new development platform. As I already mentioned, there are big differences between the key bindings of usual PC platforms and Mac OS X. I haven&#8217;t really worried about them, because for the basic navigation it is not a huge burden to get used to it, but when it comes to code writing I&#8217;m more choosy&#8230;</p>
<p>It seems like in the Mac world the Home and End keys have totally different meaning, in particular they don&#8217;t control the position of the cursor in the current line instead they control it in the scope of the file. As I&#8217;m heavily using these keys during source code editing I figured out it would be a huge burden to get used to this little but important difference. Fortunately, Xcode has possibility to change the key bindings of the editor but I was already quite pessimistic about how much hassle I will have with the key binding so I thought one step further and started to google for a quasi normal key binding for Xcode. Soon, I&#8217;ve found a Visual Studio-like one <a title="Code Dojo - How to make Xcode feel like MS Visual Studio (MSVC)" href="http://www.codedojo.com/?p=580" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codedojo.com/?p=580&amp;referer=');">here</a> that you can download below:</p>
<p><a title="Visual Studio Key Bindings for Xcode" href="http://rastergrid.com/blog/wp-content/uploads/2010/05/files/MSVC_xcode_config.zip">Visual Studio Key Bindings for Xcode</a></p>
<p>In order to install it, you only need to unzip the file <strong>MSVC.pbxkeys</strong>, copy it to /Users/YourUserName/Library/Application Support/Xcode/Key Bindings/ (if the directory doesn&#8217;t exist, just create it), restart Xcode and select the configuration set in the key binding tab of Xcode&#8217;s preferences window.</p>
<h2><img class="alignleft" title="Apple Developer Program" src="http://www.rastergrid.com/blog/wp-content/uploads/2010/05/apple-logo.png" alt="" width="150" height="184" />The Apple Developer Program</h2>
<p>While the new key configuration already solved most of my problems that prevented me to efficiently start working on my first iPhone application, soon I realized how much of hassle an iPhone developer has to deal with on a daily basis&#8230;</p>
<p>As soon as I mastered the very basics of developing for the iPhone OS, I registered myself for the Apple Developer Program. It costs you $99 per year but it most probably worths its price as beside the fact that they deal with the publishing and marketing of your application, according to other developers I know, they also give adequate support for the money. The registration itself was very straightforward. I just had to fill and fax an application form and next day my developer program was already active. What made me outrageous at the end is the amount of administrative work that is required from the iPhone developers in order to solve the most simple tasks.</p>
<p>If you just want to play with the iPhone Simulator, the basic configuration of Xcode and the iPhone SDK is adequate, but as soon as you would like to try out your application on a real device, things get more complicated. As an example, I wrote my first cube rotating OpenGL app and wanted to test it on the iPhone of my friend. First, I thought that this will need only three things: connect the iPhone to the Mac, select the real device as target in Xcode and then press the Build&amp;Go button. Well, it turned out that it is much much more complicated.</p>
<p>First, you have to create a certificate on your Mac that you have to upload in the Apple Provisioning Portal and then download it from there, install on your Mac, then connect the iPhone to the Mac, open the Organizer in Xcode, copy the device identifier of the iPhone, go back to the Portal, add the device, then go back to Xcode and copy the reverse URI of your application and then add the application in the Portal, create a provisioning profile with the device-application pair on the Portal, download it and add to Xcode and now you can select the device as target and press the Build&amp;Go. This would be even acceptable if you would have to do it only once, as a preparation for development, but this is not the case. You have to create an individual provisioning profile for each and every device-application pair that you want to test. This is simply too much, especially in the early phases of development as you may start with several different test projects.</p>
<h2><img class="alignleft" title="iPhone SDK" src="http://www.rastergrid.com/blog/wp-content/uploads/2010/05/iphone_sdk.png" alt="" width="150" height="187" />iPhone SDK and Mac OS X Leopard</h2>
<p>You may think that after these steps I&#8217;ve already had my box rotating app running on the iPhone. Well, if it is so, then you&#8217;re wrong. Things got just more annoying after this&#8230; After investing money into a Mac mini and paying $99 to Apple for entering the Developer Program I though that I can startup with my first real project but I was wrong as well.</p>
<p>I bought the Mac mini from the brother-in-law of one of my friends. As he already developed some iPhone applications on the Mac earlier, I&#8217;ve already had Xcode and iPhone SDK 3.0 installed on it. The problem I&#8217;ve encountered is that just the day before my friend, Imi brought his iPhone to my place in order to test the application he had to update the firmware of the phone to iPhone OS 3.1.3. You may wonder, but Xcode with iPhone SDK 3.0 doesn&#8217;t work with an iPhone device that has the version 3.1.3 of OS installed on it.</p>
<p>Well, I thought I will just download the latest version of the SDK from Apple&#8217;s website, but I faced some further surprises&#8230; Actually there is a free download of Xcode 3.2 and iPhone SDK 3.2 at the site what you can freely download. The problem with this is that it works only on Mac OS X Snow Leopard but not on Leopard.</p>
<p>At this point I was thinking about that I&#8217;ve already invested a huge amount of money and now I have to pay another $29 for the OS update just to run my box rotating app on a real device. Anyway, I&#8217;ve chosen to invest this remaining amount as I really want to develop some games for iPhone. Unfortunately, I figured it out soon that you can order the OS update only inside US and there is no any way to grab a downloadable version for your money (at least as far as I can tell because I was already too pissed off to spend more time on Apple&#8217;s site to look around for a solution).</p>
<p>Our next idea was to downgrade the operating system of the phone to match the SDK what we have but Imi informed me that the oldest OS what you can downgrade for is 3.1.2. This was the time when I gone mad. I really found it ridiculous that someone buys a developer machine that was earlier capable for the purpose and afterwards, due to some stupid decision at Apple, it is simply not capable for it anymore, unless you pay more money to them for the OS upgrade. Anyway, at this time I would have been already satisfied if I can pay that $29 for the upgrade just to run the app.</p>
<p>It was actually pure luck that I didn&#8217;t give it up and started to google for people who met the same problem lately. Fortunately, I&#8217;ve found a guy struggling with the same problem and he <a title="iPhone SDK 3.1.3 Download for Leopard (if you don’t have Snow Leopard!)" href="http://www.dropthenerd.com/iphone-sdk-3-1-3-download-for-leopard-if-you-dont-have-snow-leopard/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.dropthenerd.com/iphone-sdk-3-1-3-download-for-leopard-if-you-dont-have-snow-leopard/?referer=');">posted</a> a download link for the SDK 3.1.3 that works also on Leopard. He really saved the day! If you are having the same problem just grab the SDK from the following address:</p>
<p><a title="iPhone SDK 3.1.3 and Xcode 3.1.4" href="http://developer.apple.com/iphone/download.action?path=%2Fiphone%2Fiphone_sdk_3.1.3__final%2Fiphone_sdk_3.1.3_with_xcode_3.1.4__leopard__9m2809a.dmg" onclick="pageTracker._trackPageview('/outgoing/developer.apple.com/iphone/download.action?path=_2Fiphone_2Fiphone_sdk_3.1.3_final_2Fiphone_sdk_3.1.3_with_xcode_3.1.4_leopard_9m2809a.dmg&amp;referer=');">Download iPhone SDK 3.1.3 and Xcode 3.1.4</a></p>
<h2>Conclusion</h2>
<p>Without the intension to blame the guys at Apple or anybody else, I can say that becoming an iPhone developer involves much more trouble that I have ever thought it could. Anyway, now I managed to get to the point where I can actually start to be productive so I won&#8217;t give it up now&#8230;</p>
<p>I planned to talk also about implementation related issues and tips in this article that you are most probably more interested in, but it seems that this topic is left for a future article as I had so much things to share now that it simply didn&#8217;t fit into the time-box. Anyway, I will recap on the topic in the near future.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/05/common-pitfalls-of-iphone-development/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Flexible static analysis for C++ code bases</title>
		<link>http://rastergrid.com/blog/2010/03/flexible-static-analysis-for-c-code-bases/</link>
		<comments>http://rastergrid.com/blog/2010/03/flexible-static-analysis-for-c-code-bases/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 17:12:37 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[code analysis]]></category>
		<category><![CDATA[CppDepend]]></category>
		<category><![CDATA[GLM]]></category>
		<category><![CDATA[GoogleMock]]></category>
		<category><![CDATA[maintenance]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=190</guid>
		<description><![CDATA[The importance of static code analysis is already a well known thing in the domain of software development. There are plenty of useful and less useful tools for the purpose, especially in the case of C++. However, even if in general the quality of these softwares is adequate they usually suffer from the inability for]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F03%252Fflexible-static-analysis-for-c-code-bases%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2Fap60wo%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Flexible%20static%20analysis%20for%20C%2B%2B%20code%20bases%22%20%7D);"></div>
<p>The importance of static code analysis is already a well known thing in the domain of software development. There are plenty of useful and less useful tools for the purpose, especially in the case of C++. However, even if in general the quality of these softwares is adequate they usually suffer from the inability for extending or customizing behavior. Also, a usual problem arises from the fact that the C++ language syntax is overwhelmingly complex and it makes the code parser of any static analysis tool a nightmare. In this article I would like to present a tool called CppDepend that gracefully solves the aforementioned problems primarily focusing on providing an interface that enables 100% adaptability and extensibility for creating customized metrics that are relevant or applicable in a particular domain.</p>
<p><span id="more-190"></span></p>
<h3>Why static code analysis?</h3>
<p>Analysis of computer software, in particular verification and validation, is a very important factor in professional software development. The process behind itself can come in different forms. Generally all kind of verification and validation techniques can be categorized in two major groups: static analysis and dynamic analysis. The key difference between the two is while dynamic analysis verifies the execution of the code, static analysis strictly works on the code base itself.</p>
<p>Well, there are thousands of reasons why using a static code analysis tool makes any benefits to a particular software development process. If you ask various people they will all have their own reasons and rationale behind that. Just to mention my favorites here is a brief excerpt from the long list:</p>
<ul>
<li>Find coding errors before executing a single line of code. This is important as it does not require the project to be built or executed as in many cases these two additional phases can be quite expensive from both time and budget point of view.</li>
<li>Identifies parts of the code that seem to be difficult to maintain or do not conform to various policies of a particular company or organization. This provides us the benefit to move towards a sustainable development by heavily reducing maintenance costs.</li>
<li>Provides us miscellaneous metrics about our code that can have key importance in measuring the quality of the code base.</li>
</ul>
<blockquote><p>If you can&#8217;t measure it, you can&#8217;t improve it &#8211; Lord Kelvin</p></blockquote>
<p>Many people still think that code metrics are overrated. Even if at first sight it seems to be true for micro-projects its importance becomes very obvious when one mets a large code bases specifically talking about situations when legacy code is inherited from earlier software developer generations. When the magnitude of the software goes out of the limits a programmer is capable to keep in mind (this means the 99% of software products) code metrics provide great value to identify &#8220;hot spots&#8221; in the code base, no matter what actual situation we are talking about.</p>
<p>Also, making decision about whether the evolution of the software goes in the right direction is very difficult if not impossible without ways of measuring the quality of the code. The most naive solution for this problem is to measure the amount of bug reports reported over time, however, code metrics provide a much more sophisticated way of measuring the quality by different aspects and on different levels.</p>
<p>During my career, as a software developer, I also faced many situations when the inspection of the legacy code was necessary in order to introduce new functionalities. Unfortunately, in most of the cases, due to the lack of an adequate static code analyst, this required developers to read and manually inspect the code in order to solve the particular problem. I can tell you that it&#8217;s not a joyful duty. Just to mention some of the most critical situations that current developers meet regarding to the topic:</p>
<p><strong>Removing dependencies on deprecated features.</strong> This is a thing that each software development faces from time to time. This time interval is usually relatively low, as we talk about few years which can be called quite often compared to other industries. Just think about situations when one migrates to a new version of a third party library that the whole software depends on. As a recent event, we can talk about the release of version 3 of the OpenGL specification. CAD software developer companies faced a huge challenge by being forced to adopt the new features as the old ones became deprecated and obsolete. Actually they were quite lucky that vendors denied to drop features from their implementations. Using a code analyst one can easily identify the modules that needs to be modified in order to adopt to the latest changes.</p>
<p><strong>Introducing multiprocessing.</strong> This is also a very imminent problem that every software development company will face sooner or later. Code bases inherited from the previous decades were not prepared to handle concurrent execution of the code thus making big headaches to software architects to redesign the code in order to be SMP compliant, especially when dealing with multi-core processors. I&#8217;ve also faced this situation during my career and it was a painful lesson that code analyzing possibilities have a great importance. Before inspecting carefully the whole code base it is very difficult to identify the possible problems that may arise by the introduction of multiprocessing. Automatic inspection of the code can be a very handy tool for minimizing the required efforts.</p>
<h3>What makes up a good static code analysis tool?</h3>
<p>There are many different aspects that affect how good a particular static code analysis tool is. In many situations having competing alternatives for this purpose is at a premium. Fortunately, this is not the case regarding to C++ as being a well supported programming language from the community. However, in order to choose a suitable alternative we have to collect our requirements:</p>
<ul>
<li><strong>Correctness</strong> &#8211; It must correctly analyze the code. This is a very basic requirement against any software development tool. While this seems to be a completely obvious requirement and one expects that tools behave as expected from this point of view, most of such tools for C++ do not conform to this principle. Those who know the C++ language standard know well that writing a good parser for it is almost impossible.</li>
<li><strong>Usefulness</strong> &#8211; There is no sense in using a static code analyst if we don&#8217;t get any benefits from it. The reports generated by the analyst should provide useful information that are directly applicable in a particular use case. One typical example that I also faced quite often is that when one analyses legacy code and gets a report about thousands of problematic code parts. These reports are almost impossible to be handled and it makes headaches to the developers even to answer the very simple question: where to start?</li>
<li><strong>Customizability</strong> &#8211; This requirement directly relates to the previous one. By examining the previous example if there would be some customization possibility to get reports only about the 10 most problematic module it would be much easier to handle it. However, this requirement goes far beyond this. As an example, beside the build-in metrics of the analysis tool, it should provide means to add or modify metrics in order to have more relevant measures about the code fitting a particular domain or use case.</li>
</ul>
<p>We&#8217;ve just mentioned three requirements explicitly and we already heavily reduced the number of alternatives&#8230;</p>
<h3>CppDepend as a flawless alternative</h3>
<p>Recently I&#8217;ve got a request to review a C++ static code analyst tool called CppDepend. After having a brief eye shot on the product I realized that it deserves a thorough inspection as it features a revolutionary technology called CQL that I will talk about a bit later in the article.</p>
<p>CppDepend was developed in partnership with NDepend, it was released six months ago having a two years development history by a very small team of experts. Actually it is accompanied with it&#8217;s brothers NDepend and XDepend that accomplish the same job for .NET and Java projects respectively.</p>
<p>We are talking about a Windows application that has tight integration with Visual Studio projects but also provides ways to be applicable in case of projects built with other development tool-set. Beside it is a command-line static code analysis tool for the C++ language, it provides a powerful GUI tool for visual inspection of different aspects of the code base thus enabling increased productivity and ease of use.</p>
<p>Lets have our first sight on the tool by using the visual interface to analyse a sample code base that will be in our case the source code of <a title="Simple and Fast Multimedia Library" href="http://www.sfml-dev.org/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.sfml-dev.org/?referer=');">SFML</a>.</p>
<p>Setting up the basic configuration for an analysis project is very straightforward. Beside that, the code analysis itself is surprisingly fast. While testing, the longest time it took was in case when I parsed the code of the <a title="Bullet Physics Library" href="http://bulletphysics.org/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/bulletphysics.org/?referer=');">Bullet Physics Library</a> but even that didn&#8217;t required a minute on my system.</p>
<div id="attachment_194" class="wp-caption aligncenter" style="width: 624px"><a href="http://rastergrid.com/blog/wp-content/uploads/2010/03/cppdepend.png"><img class="size-large wp-image-194 " title="CppDepend graphical user interface" src="http://rastergrid.com/blog/wp-content/uploads/2010/03/cppdepend-1024x789.png" alt="CppDepend graphical user interface" width="614" height="473" /></a><p class="wp-caption-text">CppDepend graphical user interface</p></div>
<p>The visual controls themselves sometimes lack of good responsiveness due to the complex structures and relationships presented by them but we soon forgive CppDepend this minor issue when we take a closer look at the navigation possibilities offered by the tool.</p>
<p>At first sight, the user interface seems to be a bit overcomplicated but we soon realize that each and every element of it is made by purpose in order to provide as much freedom in navigation as possible. Just to mention the most interesting ones here&#8217;s the explanation of the purpose of the graphical figures at the top right part of the GUI:</p>
<ul>
<li>At top left we see a graphical representation of the currently selected code metric. It shows the magnitude of the result of the metric according to the selected level of granularity. We can easily visualize here as an example how the size of different classes of our project compare to each other.</li>
<li>At middle left is the dependency matrix of our solution. We can easily find &#8220;hot spots&#8221; in our code regarding to coupling, by default, on project level. The granularity of the table can be easily changed in a non-proportional way from project level down to method level. I used the word &#8220;non-proportional&#8221; by intension as we can examine dependency even between a method and a foreign project thus providing additional flexibility over how fine grained we would like to have our numbers.</li>
<li>My favorite is in the middle, called dependency graph. It can present the dependencies between different software elements from project level down to method level, as usual, by means of a graph that is very convenient for human inspection.</li>
</ul>
<p>The whole user interface is designed in a way that each time we point on a particular element it shows convenient information about that particular element and its environment, no matter if we talk about the metrics view, the dependency graph or matrix.</p>
<p>Beside the tools for navigation and easy visualization, the GUI provides a collection of built-in reports about different aspects of the code. One of the first thing everybody would try out from these is the query called &#8220;Quick summary of methods to refactor&#8221;. This is exactly the answer what the developer would like to have for the question &#8220;where to start?&#8221; that I mentioned earlier.</p>
<p>To emphasize even more the fact that how convenient is the user interface, when one selects a particular query it will immediately show the results by means of a list of classes, methods or whatever, but beside this, the code elements in question are immediately highlighted in the relevant graphical views as well.</p>
<p>Maybe I already convinced most of you that CppDepend is a tool that deserves attention as being a valuable tool in good hands but I haven&#8217;t even talked about the most interesting feature that really makes it a uniquely powerful software.</p>
<h3>The power of extensibility</h3>
<p>I have often brought to relief the importance of extensibility and customizability of a static code analyst. This, in fact, is not just my craze but it is an important factor in the decision of most software developers out there. Being able to get some common metrics about the code is one thing, having the possibility to define own metrics and analysis criterias is another&#8230;</p>
<p>The power of CppDepend is behind a revolutionary technology that provides us an interface to retrieve information about the code that is relevant for us as easy as querying a relational database. The apparatus in our hand to achieve this is the <a title="Code Query Language 1.8 Specification" href="http://www.cppdepend.com/CQL.htm" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.cppdepend.com/CQL.htm?referer=');">Code Query Language (CQL)</a>. CppDepend actually builds some internal database structure from the source code and provides us an SQL-like language to make queries that fetches reports from this internal database. Those who are already familiar with SQL will adore this feature. Just to illustrate how easy it is to use CQL in order to build custom queries, let&#8217;s query the classes that have more than 20 methods is as simple as the following line of CQL code:</p>
<pre class="brush: sql">SELECT TYPES WHERE NbMethods &gt; 20</pre>
<p>Simple, isn&#8217;t it? For further details, please refer to the specification of the Code Query Language: <a href="http://www.cppdepend.com/CQL.htm" onclick="pageTracker._trackPageview('/outgoing/www.cppdepend.com/CQL.htm?referer=');">http://www.cppdepend.com/CQL.htm</a></p>
<p>This means that the software developers have complete freedom over how they define the metrics that indicate whether the code quality reaches the levels required by company policies or individual needs. It is also useful to solve the problems arising from the sample situations I&#8217;ve mentioned earlier, namely the problem with dependency on deprecated features and the introduction of multiprocessing, by easily and clearly identifying the modules that need to be changed even in situations when the code base is extremely huge and traditional ways for identifying affected modules are not applicable or simply not feasible.</p>
<h3>Endurance test</h3>
<p>Well, I&#8217;ve already talked enough about the abilities of CppDepend regarding to usefulness and customizability, however, I&#8217;ve barely touched the topic of correctness. As I&#8217;ve already mentioned, parsing C++ code correctly is not as easy as it may look like. For this purpose I&#8217;ve prepared a bunch of template heavy libraries like <a title="OpenGL Mathematics" href="http://glm.g-truc.net/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/glm.g-truc.net/?referer=');">GLM</a> and <a title="GoogleMock" href="http://code.google.com/p/googlemock/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/googlemock/?referer=');">GoogleMock</a> to check how well CppDepend handles code bases when it comes to awkward features of the C++ language.</p>
<p>Even though generally static analyst tools does not provide too much useful information about such project, due to their special nature, it still looked convenient to try to make parsed these libraries by CppDepend in order to have a picture about how it would handle huge projects that also take advantage of the templating mechanisms of C++. I have to say that the results are very promising as it had problems only with GoogleMock but the developers were already informed about the problem I&#8217;ve encountered.</p>
<h3>The dark side of the story</h3>
<p>While CppDepend is an excellent tool for software developers working under Windows, especially if they use Visual Studio, I would like to see a cross-platform version of CppDepend in the future, at least for Linux and MacOSX.</p>
<p>Also, CppDepend does not come for free but at a reasonable price. Even though most probably individuals and hobbyists would not consider buying it, for enterprises, even for small ones, the price of the tool will most probably pay back soon by heavily decreasing short- and long-run maintenance costs of the development.</p>
<h3>Conclusion</h3>
<p>A clever static code analyst tool is nowadays a must for every software development company that deals with code whose size have already ran over a certain threshold but it is also good to use one from the very beginning of a new project. Selecting a particular tool for this purpose is the choice of the enterprise, still, the requirements against such a software are usually the same.</p>
<p>CppDepend proved to me of being a valuable software in the tool-chain of every C++ programmer using Windows as primary development platform. If you are still not convinced then check out the <a title="CppDepend - Features" href="http://www.cppdepend.com/Features.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.cppdepend.com/Features.aspx?referer=');">full feature list</a> on the official site.</p>
<p>Even if you are not interested in using CppDepend or in static analysis tools at all, you should still take a look at CQL and the great idea behind it as it is a perfect example how a solution for a well discussed problem can ascend to new levels by adopting good practices from other domains, in this case from relational databases and related technologies.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/03/flexible-static-analysis-for-c-code-bases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing OpenGL applications</title>
		<link>http://rastergrid.com/blog/2010/02/unit-testing-opengl-applications/</link>
		<comments>http://rastergrid.com/blog/2010/02/unit-testing-opengl-applications/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 19:54:15 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[GLEW]]></category>
		<category><![CDATA[GoogleMock]]></category>
		<category><![CDATA[macro]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=182</guid>
		<description><![CDATA[Nowadays comprehensive testing is a must for any software product. However, it isn&#8217;t such a general rule when it comes to graphics applications. Many developers face difficulties when they have to test their rendering codes. Manual tests and visual feedback is sometimes satisfactory but if one would like to have automated regression tests usual approaches]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F02%252Funit-testing-opengl-applications%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2F9vHcy8%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Unit%20testing%20OpenGL%20applications%22%20%7D);"></div>
<p>Nowadays comprehensive testing is a must for any software product. However, it isn&#8217;t such a general rule when it comes to graphics applications. Many developers face difficulties when they have to test their rendering codes. Manual tests and visual feedback is sometimes satisfactory but if one would like to have automated regression tests usual approaches seem to fail. Even if at first sight unit testing of rendering code doesn&#8217;t look really straightforward, in fact it is. OpenGL is not an exception from this rule as well. In this article I would like to briefly present a few methods how to unit test OpenGL rendering code and also present my choice and the reasons behind the decision.</p>
<p><span id="more-182"></span>There are several ways how to create automated test cases for rendering code. To present the different approaches we first have to select a small portion of our rendering code to demonstrate the differences of each technique, mentioning the strengths and weaknesses of them.</p>
<p>Before going any further, we have to lay down our requirements against a good OpenGL unit testing environment:</p>
<ul>
<li><strong>Verifies results</strong> &#8211; This is the most basic requirement for any testing framework. We have to have the ability to check whether the rendering code executed by the module is valid and works as expected.</li>
<li><strong>Productive</strong> &#8211; The usage and maintenance of the framework shall require minimal effort. Many times unit testing is attacked because it requires additional code writing. While this is generally true, a nice unit testing environment can be kept very simple yet flexible. An OpenGL testing environment shouldn&#8217;t be different.</li>
<li><strong>Fast</strong> &#8211; This is a general requirement for any unit testing environment especially when combined with a continuous integration framework. We want our test results as fast as possible as long feedback cycles severely slow down the development process.</li>
<li><strong>Standalone</strong> &#8211; Does not require complex setup or environmental support in order to be executed. This is a general requirement when we deal with unit testing as if the code is tightly coupled by any of the surroundings then both development and maintenance costs increase.</li>
<li><strong>Compatible</strong> &#8211; Does not require any special hardware so it can be tested on a machine that wouldn&#8217;t necessarily be suitable for manually testing the actual product. This is especially important when the target hardware is some type of embedded platform. It is also important to ensure that it will work on hardware provided by different vendors. In one word, it should comply to the standard, not to driver implementations.</li>
<li><strong>Cross-platform</strong> &#8211; Does not rely on the services of a particular operating system or platform, instead it can be executed on any machine as usually all unit tests. Of course, this restriction can be relaxed depending on actual use case scenarios.</li>
</ul>
<p>Now that we know what we would like to achieve, we can continue with a sample use case. Lets say we would like to create an OpenGL 3.2 based rendering engine. One of the first things that we would write is a class (or set of classes) that will help us handling OpenGL buffer objects as it seems to be one of the main building blocks of such a system. As a very basic example, our first version of the buffer handling class will act simply as a wrapper for buffer objects having the following interface:</p>
<pre class="brush: cpp">class Buffer {
public:
    Buffer();
    virtual ~Buffer();
};</pre>
<p>As it can be seen for now we just require that our class to handle the creation and deletion of a buffer object. Obviously, our test has to check that the constructor successfully creates a buffer by calling <em>glGenBuffers</em> and the destructor deletes that by calling <em>glDeleteBuffers</em> with proper arguments. Now lets see what possibilities we have to test OpenGL rendering code and whether it conforms to our requirements and is able to test our simple module.</p>
<h3>Checking rendered image</h3>
<p>The most naive solution for creating automated tests for rendering code is to actually execute the OpenGL commands and check whether the rendering happened as expected. This can be done by comparing reference rendering results to the actual ones. This approach has the benefit that we actually verify the concrete behavior but lets see how it looks like when we check against our previously laid down requirements:</p>
<ul>
<li><strong>Verifies results</strong> &#8211; Partially fulfilled. We check against the correct behavior, however, the ability to reproduce the actual same image is often difficult if not impossible due to different relaxations regarding to precision in both the standard and driver implementations. In order to have reproducible results the testing environment shall also provide some mechanisms to allow slight differences.</li>
<li><strong>Productive</strong> &#8211; Not met. It can be quite expensive to create an assertion system. Also, the production of reference data can be quite time consuming.</li>
<li><strong>Fast</strong> &#8211; Not met. Even if the checkers are highly optimized components of the framework, it wouldn&#8217;t fit into the time-frame of unit test cycles to execute possibly thousands of test cases that require complete verification of the produced image.</li>
<li><strong>Standalone</strong> &#8211; Not met. We have to setup a complete rendering environment in order to test even the simplest rendering code. Also, it relies on the assumption that the rendering code actually produces some image. As we can see in our buffer handling example, this is not always the case.</li>
<li><strong>Compatible</strong> &#8211; Not met. We need a testing machine that has the hardware capabilities to execute the rendering code and produce the required image.</li>
<li><strong>Cross-platform</strong> &#8211; Partially fulfilled. If our rendering code is cross-platform then it is possible to test it on any of the supported platforms. However, this makes the assertion system even more complicated as it also has to support the target platforms. Also, driver implementations may vary even further when dealing with different operating systems.</li>
</ul>
<p>As we can see, even if this version is quite natural way of thinking for anybody it&#8217;s simply impractical and not feasible for actual use. To be able to find a good solution we must look deeper into what unit testing exactly is as the presented solution has nothing to do with it. In order to be able to do real unit testing we have to eliminate the dependency on OpenGL driver implementations and strictly concentrating on the module under test.</p>
<h3>Fake OpenGL driver</h3>
<p>The second presented solution is to create a layer between the code under testing and the actual OpenGL driver implementation. This can be easily achieved by creating a fake driver, as an example a dynamic library called <em>opengl32.dll</em> in case of Windows. This additional layer would do nothing else than just recording and checking whether the required API calls happened as expected. Providing an interface towards the testing environment that can be used to request the informations needed to make a verdict about the successfulness of the test case.</p>
<p>Beside that this version accommodates much more to the idea behind unit testing it also has the benefit that it is acting as a totally independent layer and does not directly disturb the development of the actual code. Still, if we go back to our checklist we have some issues that raise some concerns regarding to the applicability of this approach:</p>
<ul>
<li><strong>Verifies results</strong> &#8211; Partially fulfilled. It is up to the implementation of the new layer whether it provides the required facilities to properly check the behavior of our tested code. Nevertheless, it also highly depends on the implementation on how we define correct behavior and the responsibility of the library.</li>
<li><strong>Productive</strong> &#8211; Partially fulfilled. Now we have a separate module that helps us in the testing. This may introduce some additional maintenance work but, of course, this depends on how intelligently is the library actually implemented.</li>
<li><strong>Fast</strong> &#8211; Mostly resolved. We do not have expensive assertions, however, as we have a quite restricted interface between our testing environment and the new layer we most probably met situations when we have to make trade-offs between speed and flexibility.</li>
<li><strong>Standalone</strong> &#8211; Resolved. We have a totally independent module that is responsible to simulate the surrounding environment of the code under testing as it should be when doing unit test. However, the question arises whether we would like this layer to be that separated from the testing code.</li>
<li><strong>Compatible</strong> &#8211; Resolved. There is no dependency on dedicated graphics hardware or any other piece of metal. In case of a robust driver simulation layer we can test our code on whatever platform we prefer.</li>
<li><strong>Cross-platform</strong> &#8211; Resolved. As previously mentioned, if the additional layer is well designed, there should be no problems regarding to this issue.</li>
</ul>
<p>Now we have a resolution that can be seriously taken into consideration as a good way to test rendering code. It can also be simply applied to test our buffer handling code as well. Also, as it is a totally standalone software element it is also very portable so it is easy to reuse between projects written in different programming languages and for different platforms.</p>
<p>Still, there is one thing that may need further investigation. Most probably for the other portions of our production code we already use some kind of mocking mechanisms for our unit testing. Having an additional interface type to handle the OpenGL related mocking (as the presented fake driver approach is nothing more than a mock library for OpenGL) may reduce the productivity of our developers. Also, it can make the testing code less uniform so introducing a slight maintenance penalty. At least for comparison, we should try to integrate the OpenGL mocking into our existing mocking facilities.</p>
<h3>API mocks</h3>
<p>All the people who seriously do unit testing use some mocking techniques to eliminate dependency on any external software element like databases, network or another code element. Why should the OpenGL API be different?</p>
<p>As I already written about that I use <a title="GoogleMock" href="http://code.google.com/p/googlemock/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/googlemock/?referer=');">GoogleMock</a> to test my C++ code. Lets see how this mocking framework is capable for removing OpenGL related dependencies. By default, GoogleMock does support only class mocks, however it is fairly straightforward to mock out OpenGL API functions as well. As an example, our buffer handling class needs at least a mock for the <em>glGenBuffers</em> and <em>glDeleteBuffers</em> API functions. These mocks can be very easily created using GoogleMock as part of a class in the following way:</p>
<pre class="brush: cpp">class CGLMock {
public:
    MOCK_METHOD2( GenBuffers, void(GLsizei n, GLuint* buffers) );
    MOCK_METHOD2( DeleteBuffers, void(GLsizei n, GLuint* buffers) );
};
CGLMock GLMock;</pre>
<p>This, however is not enough to replace the already existing real API function pointers with the fake ones. I did this with a nasty little trick by taking advantage of the C preprocessor:</p>
<pre class="brush: cpp">#undef glGenBuffers
#define glGenBuffers                  GLMock.GenBuffers
#undef glDeleteBuffers
#define glDeleteBuffers               GLMock.DeleteBuffers</pre>
<p>The <em>#undef</em> is needed because I use <a title="GLEW" href="http://glew.sourceforge.net/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/glew.sourceforge.net/?referer=');">GLEW</a> for accessing OpenGL API functions and it uses macros for the API function names as well.</p>
<p>All these are put into a file that can be called like <em>glmock.h</em>. In order to force the production code to use these definitions when trying to access the API inside a test case we have to create a wrapper header called something like <em>opengl.h</em> that will include original headers in case of normal build and include the mock library in case of unit test build. This is kind of a workaround but it works quite well in practice.</p>
<p>In theory, this trick can be applied in case of any mocking framework. As a result, from now we can write a very simple test case to check the creation and deletion of our buffer object as easily as the following few lines of code:</p>
<pre class="brush: cpp">TEST(BufferTest, CreationAndDestruction) {
    EXPECT_CALL(GLMock, GenBuffers(1,_))
        .WillOnce(SetArgumentPointee&lt;1&gt;(13));
    Buffer* buffer = new Buffer;
    EXPECT_CALL(GLMock, DeleteBuffers(1,Pointee(13)));
    delete buffer;
}</pre>
<p>I would not like to go into the details related to the interface of GoogleMock. In one word, the test case above checks whether the constructor calls <em>glGenBuffers</em> with a number of 1 for the requested number of buffer objects and returns a buffer ID in the pointer argument, and at the end it checks if <em>glDeleteBuffers</em> was called with the buffer ID value got at creation.</p>
<p>It is maybe a matter of taste whether the second or this third solution is more attractive for you. My choice was this last solution because I didn&#8217;t want to develop an separate library and also was afraid of messing up my test code with different syntactical representations of mocks. Finally, lets sum up the achievements of this last version:</p>
<ul>
<li><strong>Verifies results</strong> &#8211; Fulfilled. An existing mocking framework is used for emulating the OpenGL API thus we have all the facilities required for the proper checking of the API calls.</li>
<li><strong>Productive</strong> &#8211; Fulfilled. Again, we don&#8217;t have to deal with writing an own mocking mechanisms as we have everything out of the box. We can also incrementally extend our mock library on-the-fly while editing the test cases and the production code.</li>
<li><strong>Fast</strong> &#8211; Resolved. Our rendering related unit test cases should be as fast as any other test codes as they are indifferent, just the purposes are dissimilar.</li>
<li><strong>Standalone</strong> &#8211; Mostly resolved. The mocking library is independent, however, as we&#8217;ve seen, the introduction may require some nasty tricks in order to inject foreign code into the production code.</li>
<li><strong>Compatible</strong> &#8211; Resolved. From this point of view, this approach behaves the same as the previous version.</li>
<li><strong>Cross-platform</strong> &#8211; Resolved. Again, the same like in the previous case, maybe even a bit easier to make it portable.</li>
</ul>
<h3>Conclusion</h3>
<p>We&#8217;ve seen a few ways how we can extend our testing environment in order to support the verification of rendering code. We&#8217;ve also seen that the range varies from techniques that provide high level methods suitable especially for functional testing, until very low level methods that tightly integrate in the mocking methodology of unit testing. These, of course, do not replace traditional testing methods rather they extend it in order to find problems in the early phases of software development.</p>
<p>I also tried to present a very basic example of production code that needs such a facility in order to be tested, as well as a sample test case written using GoogleMocks applying the last presented technique.</p>
<p>While writing this article I got the idea that it would be nice to have a complete and general framework for OpenGL testing. If there is interest for it, maybe I&#8217;ll allocate some time to write one. I&#8217;m also interested which approach is the most attractive for you, especially if you have some concrete experience with any of these or with some other technique.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/02/unit-testing-opengl-applications/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>One more degree of freedom for C++</title>
		<link>http://rastergrid.com/blog/2010/02/one-more-degree-of-freedom-for-c/</link>
		<comments>http://rastergrid.com/blog/2010/02/one-more-degree-of-freedom-for-c/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 14:38:42 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[callback]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[delegation]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[event handling]]></category>
		<category><![CDATA[message]]></category>
		<category><![CDATA[signal]]></category>
		<category><![CDATA[signals and slots]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=176</guid>
		<description><![CDATA[Those who worked enough with C or other procedure oriented languages know how much flexibility callbacks provide. The simplest example is the qsort function of the C standard library. It is also not unintentional that many libraries, windowing system APIs and operating system APIs also highly rely on callbacks to pass a particular task over]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F02%252Fone-more-degree-of-freedom-for-c%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2Fdrfdzt%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22One%20more%20degree%20of%20freedom%20for%20C%2B%2B%22%20%7D);"></div>
<p>Those who worked enough with C or other procedure oriented languages know how much flexibility callbacks provide. The simplest example is the qsort function of the C standard library. It is also not unintentional that many libraries, windowing system APIs and operating system APIs also highly rely on callbacks to pass a particular task over to another program module and it is one of the fundamental tools needed to implement an event-driven application. At the same time, object oriented languages does not directly support the concept of callbacks as they don&#8217;t really fit into the paradigms used by these languages. Fortunately, even if not as a language feature, all object oriented languages support a similar facility like callbacks in the form of delegates.</p>
<p><span id="more-176"></span>Delegation as a design pattern is used to describe the situation when one object passes on the implementation of a particular task to another object. This clearly reflects the purpose of callbacks used in procedure oriented languages. Many languages does natively support some form of delegation, some of the well known ones are C# and Delphi.</p>
<h2>Callbacks</h2>
<p>As mentioned before, the facility present in procedure oriented languages that enables the delegation of functionalities to other modules is done with callbacks. These callbacks are specified by passing function pointers to some registration functions provided by the library. Here is a very simple C example:</p>
<pre class="brush: c">/* server header */
void registerFooCallback(int (*fooCB)(int, float));
int doFoo(int a, float b);

/* client code */
int myFooCallback(int a, float b) {
    /* ... do something ... */
}

int main() {
    registerFooCallback(myFooCallback);
    cout &lt;&lt; doFoo(5, 3.2f);
    return 0;
}</pre>
<p>Here we can see how easily callbacks provide injection of user code for handling events happened in the server.</p>
<h2>Delegation as a design pattern</h2>
<p>The simplest way to create object oriented callbacks is by applying the design pattern of delegation. If we would like to construct the C++ equivalent of the example above using the mentioned pattern, we end up with something like the following:</p>
<pre class="brush: cpp">/* server header */
class IFooCallback {
public:
    virtual int operator() (int a, float b) = 0;
};

class Foo {
private:
    IFooCallback* _fooCB;
public:
    void registerCallback(IFooCallback* fooCB);
    int doFoo(int a, float b);
};

/* client code */
class MyFooCallback: public IFooCallback {
    int operator() (int a, float b) {
        /* ... do something ... */
    }
};

int main() {
    Foo foo;
    MyFooCallback fooCB;
    foo.registerCallback(fooCB);
    cout &lt;&lt; foo.doFoo(5, 3.2f);
    return 0;
}</pre>
<p>As you can see, it is quite straightforward to provide an object oriented alternative to callbacks. However, there is a very significant drawback when using the technique above, namely the type intrusion inherently coming from this definition of a callback. The client code needs to explicitly inherit it&#8217;s own code from a type defined in the server. This results in tight coupling and is likely to carry other disadvantages inside regarding to maintainability and migration issues.</p>
<h2>Delegate methods</h2>
<p>In our previous attempt to provide an easy to use C++ alternative for callbacks with OOP in mind we tried to replace function pointers with a pure virtual base class that acts like an interface definition for our callback. However, it somewhat violates the original goals of delegates which by definition should be some form of run-time inheritance (this varies from definition to definition, still, this is the one that I&#8217;m referring to in this article). We soon figure out that the most convenient way would be to be able to assign member functions of any class as a callback. Obviously, the parameters and return type should still match as previously to provide type safety, but we would like to remove any additional dependencies between the client and the server.</p>
<p>While C++ does have the term of pointers to member functions there is no easy and standard way to implement callbacks using them. Or is there? First of all, there is no particular problem with class static member functions as they are much like C functions, however, limiting delegates to static methods heavily affects the freedom of the developer. The problem with object member functions and especially with virtual member functions is that they have the implicit parameter <strong>this</strong> that enables them to access the object they correspond to.</p>
<p>The popular Boost library provides mechanisms that enables the use of object member functions as separate entities by using the <strong>bind</strong> functor adaptor which became part of the language standard as part of <a title="ISO/IEC TR 19768:2007" href="http://www.iso.org/iso/catalogue_detail.htm?csnumber=43289" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.iso.org/iso/catalogue_detail.htm?csnumber=43289&amp;referer=');">Technical Report 1</a>. This extension makes it possible to use member functions as delegates in a way that does not involve any type intrusion side effects.</p>
<p>Unfortunately, these facilities involve a noticeable performance hit when the callback is invoked compared to simple method invocations. Also, using functor adaptors for implementing delegates is not the most straightforward and makes the code quite ugly compared to an ideal situation when delegates are part of the language itself. Of course, this is only my opinion, others who used these libraries more often may have a different vision about the topic.</p>
<p>Anyway, as for me performance is always a concern, I started to look around for alternatives. It surprised me that I&#8217;ve found even two of them very soon:</p>
<ul>
<li><a title="Fastest Possible C++ Delegates" href="http://www.codeproject.com/KB/cpp/FastDelegate.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeproject.com/KB/cpp/FastDelegate.aspx?referer=');">Fastest Possible C++ Delegates</a> by Don Clugston &#8211; This is a library that provides delegates that are as fast as simple virtual method invocations. The implementation strongly relies on the behavior of different compilers, yet is very portable, at least as far as I can tell.</li>
<li><a title="The Impossibly Fast C++ Delegates" href="http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx?referer=');">The Impossibly Fast C++ Delegates</a> by Sergey Ryazanov &#8211; This library was introduced as an alternative to the previous one that strictly relies only on standard features of the languages. Surprisingly, this later is less supported by different compiler implementations and it is also somewhat slower than the previous one.</li>
</ul>
<p>Personally, I go with the first one as for me performance and portability is more important than conformance with the standard. And, of course, it is not that hard to change the back-end for the delegate support at some time if I change my mind. Finally, lets see how our foo callback looks like when using the fast delegates of Don Clugston:</p>
<pre class="brush: cpp">/* server header */
class Foo {
private:
    FastDelegate2&lt;int, float, int&gt; _fooCB;
public:
    void registerCallback(FastDelegate2&lt;int, float, int&gt; fooCB);
    int doFoo(int a, float b);
};

/* client code */
class MyClass {
    virtual int handleFoo(int a, float b) {
        /* ... do something ... */
    }
};

int main() {
    Foo foo;
    MyClass myObj;
    foo.registerCallback( MakeDelegate(&amp;myObj, &amp;MyClass::handleFoo) );
    cout &lt;&lt; foo.doFoo(5, 3.2f);
    return 0;
}</pre>
<h2>Multicast delegates</h2>
<p>The delegates presented previously can only be bound to a single method, as usually delegates behave this way, although a single method can be bound by many delegates. The signals and slots model extends this to a many-to-many relationship. Thus a signal is actually just a delegate that can bind to multiple methods at once. Such a primitive is sometimes also referred to as a multicast delegate.</p>
<p>Multicast delegates come handy especially in case of user interface programming and other situations where the event based programming model is used. The basic foundation behind this programming model is the idea of &#8220;subscribe and notify&#8221;. That means there are <em>publishers</em> who will do some logic and sometimes publish <em>events</em>. When such an <em>event</em> is published, it is actually sent out to the <em>subscribers</em> who have subscribed to receive the specific event. At implementation level this is nothing more than having a multicast delegate in the <em>publisher</em> object and providing an interface that will be used by the <em>subscriber</em> objects to register one of their methods that has to be called in case a particular <em>event</em> occurs.</p>
<p>There are plenty of signals and slots libraries out there including but not limited to the Boost Signals library. However, again, if performance is a concern one must look around carefully to find the appropriate library suitable for a particular purpose. One such library that extends the fast delegates of Clugston with a signals and slots framework is that of <a title="Simpler UI Code With Signals and Slots" href="http://www.gallantgames.com/2009/12/13/simpler-ui-code-with-signals-and-slots" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.gallantgames.com/2009/12/13/simpler-ui-code-with-signals-and-slots?referer=');">Patrick Hogan</a>&#8216;s.</p>
<h2>Asynchronous delegates</h2>
<p>If we do one more step forward, we arrive to asynchronous delegates that can provide us a flexible yet efficient messaging system for multi-threaded applications. The only additional thing we have to implement a message queue on the callee side and optionally some form of synchronization if we would like to also make it possible for the asynchronous delegates to return data to the caller.</p>
<p>As this topic deserves a thorough discussion on its own, I would recap on the subject in a future article and try to provide a sample implementation using OpenMP as usual.</p>
<h2>Conclusion</h2>
<p>We&#8217;ve just touched the surface of what possible use case scenarios of delegates one can met during software development, still, we&#8217;ve seen how many advantages such a programming primitive can give to C++ developers no matter if they are implementing a very simple library of sorting algorithms like the qsort C standard library function or a robust, fully event-driven multi-threaded application. We&#8217;ve also seen that there exist several efficient implementations of such a framework for those performance fanatics like me.</p>
<p>It is a perfect example how easily one can extend C++ with another facility that is usually available only in the most modern managed languages. By the way, I would be interested in your opinion what do you like the most in other languages like Java and C#, and you are disappointed that C++ does not directly provide the same thing. Maybe there exists a C++ alternative for those facilities as well, just we have to look around to find them&#8230;</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/02/one-more-degree-of-freedom-for-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Synchronizable objects for C++</title>
		<link>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/</link>
		<comments>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 19:01:56 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Multiprocessing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[macro]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[OpenMP]]></category>
		<category><![CDATA[synchronization]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=120</guid>
		<description><![CDATA[Previously I talked about how one can easily take advantage of multiprocessing using OpenMP. Even if the C pragmas introduced by the parallel programming API standard is very straightforward for simple programs, it simply doesn&#8217;t fit nicely in a complex C++ application that is built from the ground with the OOP in mind. To smoothly]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F02%252Fsynchronizable-objects-for-c%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FbbpIPT%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Synchronizable%20objects%20for%20C%2B%2B%22%20%7D);"></div>
<p>Previously I talked about how one can easily take advantage of multiprocessing using OpenMP. Even if the C pragmas introduced by the parallel programming API standard is very straightforward for simple programs, it simply doesn&#8217;t fit nicely in a complex C++ application that is built from the ground with the OOP in mind. To smoothly introduce OpenMP into such projects one need higher level constructs that hide the actual implementation details. This is the first article of a series that will try to provide reference implementations of such an abstraction. First, we will start with synchronizable primitives that try to reflect the functionality provided by the &#8220;synchronized&#8221; statement of Java.</p>
<p><span id="more-120"></span>This article is highly inspired by an article written by <a title="A &quot;synchronized&quot; statement for C++ like in Java" href="http://www.codeproject.com/KB/threads/cppsyncstm.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeproject.com/KB/threads/cppsyncstm.aspx?referer=');">Achilleas Margaritis</a><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;"> and is mostly equivalent with his thoughts. My article tries to provide a portable reference implementation of a slightly modified version of the trick presented by Margaritis that uses OpenMP as the multiprocessing API back-end.</span></p>
<h2>Motivation</h2>
<p><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;">According to the OO paradigm, classes and consequently objects provide an abstract interface to the underlying internal data or services of the modeled entity or entity class. When it comes to parallel programing we should provide facilities to enable concurrent access to shared resources that are in this case objects. Using plain OpenMP can be satisfactory, however when used extensively the OpenMP pragmas and API function calls introduced can greatly affect the readability and the maintainability of the code. Nevertheless, there can be platforms that use other APIs for handling race conditions. It is obvious that we need to encapsulate these facilities and provide an abstract tool-set instead.</span></p>
<h2>Implementation</h2>
<p><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;">The very first building block of such a framework can be a mutex class that provides mutually exclusive access to certain resources. In the world of OpenMP this should look like something similar to the following:</span></p>
<pre class="brush: cpp">class Mutex {
public:
    Mutex() { omp_init_lock(&amp;_mutex); }
    ~Mutex() { omp_destroy_lock(&amp;_mutex); }
    void lock() { omp_set_lock(&amp;_mutex); }
    void unlock() { omp_unset_lock(&amp;_mutex); }
private:
    omp_lock_t _mutex;
};</pre>
<p>This seems already enough for us to make our Java-like &#8220;synchronized&#8221; statement, however we would like to create a framework that makes usage as easy and safe as possible. In order to get closer to this goal we apply the RAII (Resource Acquisition Is Initialization) design pattern to create our lock class:</p>
<pre class="brush: cpp">class Lock {
public:
    Lock(Mutex&amp; mutex) : _mutex(mutex), _release(false) { _mutex.lock(); }
    ~Lock() { _mutex.unlock(); }
    bool operator() const { return !_release; }
    void release() { _release = true; }
private:
    Mutex&amp; _mutex;
    bool _release;
};</pre>
<p>Our goal is to provide an inheritable interface for such objects that needs synchronization. However, this step has to involve severe considerations regarding to the provided interface as we explicitly need to conform to the following requirements:</p>
<ul>
<li>The interface shall not expose the interface of the underlying synchronization primitive, in our case the mutex class methods.</li>
<li>The interface shall be available only to the synchronizable objects but not for the external world as we would like to not just hide the implementation details of our abstract entity but also prevent the users to synchronize our objects as it should be the responsibility of the object itself.</li>
<li>The interface shall expose methods which are less prone to name collision, for convenience.</li>
</ul>
<p>If we take care of the presented conventions we end up with an interface similar to the following:</p>
<pre class="brush: cpp">class Synchronizable: protected Mutex {
protected:
	void enterSyncBlock() { this-&gt;lock(); }
	void exitSyncBlock() { this-&gt;unlock(); }
};</pre>
<p>Now we are almost at the finish line. We just need to inherit this class in order to have the needed facilities for an object that needs synchronization. However, using this interface directly is not the most comfortable and safe. If we would like to have a Java-like &#8220;synchronized&#8221; statement we have to call for additional help. Fortunately, we have our not so well respected C macro language coming to rescue us as we can use it to make some pseudo-language extensions. The simplest way to define our new statement is using the following line:</p>
<pre class="brush: cpp">#define synchronized(obj)  for(Lock obj##_lock = *obj; obj##_lock; obj##_lock.release())</pre>
<p>From now, we can really use object synchronization in C++ as easy as in Java, we just need the following syntax in the method of our shared objects:</p>
<pre class="brush: cpp">synchronized(this) {
    // some code that needs synchronization
}</pre>
<p>Now it is clearly visible how handy the RAII pattern became in our case. Beside that it is now very straightforward to use this statement it provides additional benefits:</p>
<ul>
<li>It makes the code more readable and as a result it is easier to maintain.</li>
<li>No need to call inconveniently named methods and use lock variables.</li>
<li>The synchronized code has it&#8217;s own scope inside the code.</li>
<li>It is exception-safe as the mutex is unlocked upon destruction.</li>
</ul>
<p>Additionally, we can also take advantage of the inherent problem in C++ regarding to multiple inheritance. If we inherit our object from other two synchronized objects then using a simple type casting we can explicitly specify which ancestor we would like to synchronize in a particular block. Also, to ease this we can define our synchronization statement instead of the Java-like one using the following line:</p>
<pre class="brush: cpp">#define synchronized(cls)  for(Lock obj##_lock = *static_cast&lt;cls*&gt;(this); obj##_lock; obj##_lock.release())</pre>
<p>In this case we pass the class name instead of the object pointer <em>this</em>. Using this later construct we can easily specify the correct ancestor that we would like to synchronize in case when we deal with multiple inheritance situations. Personally I prefer the later syntax as it is much more customized for C++ use cases.</p>
<p>As from now we don&#8217;t need a direct interface for entering and exiting our synchronization block we can simplify our synchronizable interface to the following chunk:</p>
<pre class="brush: cpp">class Synchronizable: protected Mutex {
};</pre>
<p>This is enough from now to provide the facilities needed for a synchronization block but still complies to the requirement that we would like to hide the synchronization primitive related details.</p>
<p>Beside this, Jörg came up with the idea today to replace the for loop in our macro with a single if statement. This seems reasonable as we don&#8217;t have to sacrifice any scoping and safety related benefits of our framework. This simplifies our lock class to the following:</p>
<pre class="brush: cpp">class Lock {
public:
    Lock(Mutex&amp; mutex) : _mutex(mutex) { _mutex.lock(); }
    ~Lock() { _mutex.unlock(); }
    bool operator() const { return true; }
private:
    Mutex&amp; _mutex;
};</pre>
<p>This definition of the lock class is satisfactory if we redefine our synchronized macro to use an if statement instead:</p>
<pre class="brush: cpp">/* Java-like synchronized statement */
#define synchronized(obj)  if (Lock obj##_lock = *obj)
/* alternative synchronized statement to support multiple inheritance */
#define synchronized(cls)  if (Lock obj##_lock = *static_cast&lt;cls*&gt;(this))</pre>
<p>Thanks to the useful comments we even managed to further optimize and minimize the support code needed for our new pseudo-language extension.</p>
<h2>Conclusion</h2>
<p>We have seen an example how one can implement an easy to use synchronizable interface for C++. Also, we&#8217;ve provided a concrete implementation that is based on OpenMP. This library is still far from an API that provides all the necessary constructs that one needs for using parallel programming in their C++ projects, however we made our first step and I will recap on the subject in subsequent articles to further extend this framework.</p>
<p>Credits go to Achilleas Margaritis whose article inspired me to write mine and to Jörg for the useful improvement ideas.</p>
<h3>Full source code</h3>
<p><strong>Language:</strong> C++<br />
<strong> Platform:</strong> cross-platform<br />
<strong> Dependency:</strong> OpenMP<br />
<strong> Download link:</strong> <a title="omp_sync.h" href="/blog/wp-content/uploads/2010/02/files/omp_sync.h" target="_blank">omp_sync.h</a><br />
<strong> Comments:</strong> In order to use it as it is, you will need a C++ compiler supporting OpenMP like GCC 4.2 or Visual C++ 2008.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Flawless alternative to SDL</title>
		<link>http://rastergrid.com/blog/2010/01/flawless-alternative-to-sdl/</link>
		<comments>http://rastergrid.com/blog/2010/01/flawless-alternative-to-sdl/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 19:47:01 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[GLFW]]></category>
		<category><![CDATA[multimedia]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[OpenAL]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[SDL]]></category>
		<category><![CDATA[SFML]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=108</guid>
		<description><![CDATA[There was always big need for libraries that provide an abstract interface towards the basic platform specific facilities that are necessary for setting up an execution environment for a particular application. In the OpenGL world one of the first such libraries was GLUT. After a while more and more functionalities were put into these libraries]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F01%252Fflawless-alternative-to-sdl%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FaXVqCz%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Flawless%20alternative%20to%20SDL%22%20%7D);"></div>
<p>There was always big need for libraries that provide an abstract interface towards the basic platform specific facilities that are necessary for setting up an execution environment for a particular application. In the OpenGL world one of the first such libraries was GLUT. After a while more and more functionalities were put into these libraries that reflect more or less the requirements of application developers. One such framework is SDL. It seems that SDL is still the most respected one of these and it is preferred by the developer community. However, in this topic I will present an alternative that proved its superiority to me in the last few months&#8230;<br />
<span id="more-108"></span><img title="More..." src="http://rastergrid.com/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /></p>
<h2>Why would I need such a library?</h2>
<p>There are loads of reasons why it is good to have such a framework in your toolkit. I would like to present only a few that I consider important. First of all, having some easy to use API to setup the basic environment for your application, like a window with an OpenGL rendering context, simply removes the burden from dealing with such platform specific details and concentrate on the actual product. Next, they usually give a quite good degree of platform portability so you don&#8217;t have to study specific operating system APIs and you can still deploy your application on multiple platforms. I can recite many other reasons but the most important one is that they are reusable components so you don&#8217;t reinvent the wheel.</p>
<p>For a while I was quite satisfied with my own implementation of such a toolkit until I moved from Delphi to C++ development. This forced me to look around on the market to find a replacement for my proprietary solution as C++ has a very large developer community so it shouldn&#8217;t be that hard to find a suitable framework. Well, actually this wasn&#8217;t the case as it was the time when the OpenGL 3 specification came out with its new context creation and deprecation model. It was very embarrassing to observe that even the most popular multimedia frameworks are hardly adopting these new features.</p>
<p>At that time I realized that my library choice will heavily affect my productivity in the future so I have to think well which one I will use afterwards. To ease the selection I created something like a wish-list about what I expect from such a library. The most important issues were the following:</p>
<ul>
<li>Feature-rich - The library must provide the most basic functionalities needed for an average OpenGL application. This includes window and rendering context handling, keyboard and mouse user input capture, timing facilities and, of course, supports OpenGL 3 contexts. Optionally it would be nice if the API also provides multi-threading, image and audio handling, basic network operations, joystick support, etc.</li>
<li>Modular - The library must be modular, that means I can select which components of the framework I would like to use in a particular application. Sometimes less is more so, as an example, in a very simple cube rotating OpenGL demo I don&#8217;t want to link against a library which contains network handling. Such monolithic libraries makes life much harder as they usually rely on exotic dependencies and prevent easy deployment of the application.</li>
<li>Portable - It should be portable, at least it should work on the three most popular PC platforms: Windows, Linux and MacOSX. It has to work also with a variety of build systems, preferably with Visual C++, GCC and Xcode. Optionally it would be nice if it can be interfaced by applications written in other programming languages than C/C++.</li>
<li>Easy to use - In an ideal world such a framework should have a very clean interface and its usage must be very natural for the developer. This issue is however rather subjective so what it easy to use for one developer maybe it&#8217;s not the best for another. Regarding to this issue I will present the alternatives, obviously, from my perspective.</li>
</ul>
<p>Maybe choosing such a multimedia library for an OpenGL hobby project is just a matter of taste, but when it comes to support for OpenGL 3 context support, developers have very limited choices and one most probably faces decisions when they have to make some trade-offs when selecting any of  these libraries. Anyway, as one of my key requirements is that the library must support OpenGL 3 contexts, it is not that difficult to present all the most popular alternatives.</p>
<h2>Simple DirectMedia Layer</h2>
<p>SDL has a long history in this domain and it proved that it is an excellent choice for most hobbyists and even for professionals. It has been used in tons of different free and commercial applications and it is probably still the most preferred library in this category. Lets examine it regarding to the issues presented previously.</p>
<p>SDL provides almost all the facilities that are needed for an average graphics application. Together with some additional libraries developed as an extension to SDL like SDL_image and SDL_net it conforms to almost all of my requirements regarding to feature content. The most important is that its latest development branch also has support for OpenGL 3.</p>
<p>From point of view of modularity, especially taking into account that the less common used facilities are provided by different add-ons, SDL seems to be a good choice. However, the SDL core itself has already a bit too much dependencies on other operating system specific libraries, especially the reliance on DirectX on the Windows platform. Even if probably most of you can live with this, it is simply unacceptable for me. Anyway, this is still not the biggest problem what I&#8217;ve faced with when I checked out whether SDL suites my needs.</p>
<p>Platform portability is one of the key advantages of SDL as it even supports many other platforms than what was on my wish-list. Also regarding to language portability, the C interface of SDL makes it very easy to drop into a Delphi project as an example. Actually there are also plenty of  bindings for other languages for interfacing SDL including but not limited to Java, C#, Delphi, Ada, Perl and python. However, when it comes to build system portability I have to mention my bad experiences.</p>
<p>First of all I am that kind of animal who uses GCC also for compilations under Windows. As SDL comes with an automake based build system which proved to be unusable using MSYS and I would rather not use Cygwin as it also introduces quite many unwanted external dependencies. After giving up compilation using MinGW, I tried to build the library using the good old Visual C++ IDE. This is when I faced the problem that I would have to install the DirectX SDK in order to compile SDL. The final hit was that even after downloading and installing the huge DirectX SDK, SDL still refused to compile with weird compiler errors.</p>
<p>By the way, all these compilation related issues wouldn&#8217;t be a problem for me if SDL would come with a binary release. Even if it has such releases for earlier versions, it does not have it for the latest development branch which contains the OpenGL 3 related stuff. So actually I cannot even prove that the OpenGL 3 specific implementation in SDL works in practice or not.</p>
<p>The API interface provided by SDL got skewed up meanwhile, arising from the fact that SDL has a long history, but still I cannot say that the interface is not clean enough to be easily used in any project. So in this regard SDL is still a major player.</p>
<h2>The OpenGL Framework</h2>
<p>My second was GLFW as it was the only library that supported OpenGL 3 as far as I knew at that time. For those who are not familiar with this library, GLFW is a simple yet powerful toolkit with a similar interface like GLUT but with added capabilities like multi-threading and joystick support (see <a title="GLFW Home Page" href="http://glfw.sourceforge.net/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/glfw.sourceforge.net/?referer=');">GLFW home page</a>).</p>
<p>It is a very feature-rich framework compared to its size and even not being very modular, it still does not involve that much external dependencies as SDL. As it also provides OpenGL 3 support only in it&#8217;s latest development branch I had to compile the code here as well, however, it was straightforward to do it even using MinGW so I don&#8217;t have any complains regarding to this subject. Also it supports multiple platforms, at least those that I am mainly interested in.</p>
<p>Unfortunately, as many other early OpenGL 3 context handling implementations, it wasn&#8217;t working on all platforms. More precisely, under Windows the OpenGL 3 code in the development at that time (about half year ago) worked only with NVIDIA cards as, non-compatible with the Microsoft WGL specification, NVIDIA&#8217;s ICD exposed the wglCreateContextAttribARB function even if there was no valid OpenGL context bound and, as usual, the developers used only NVIDIA cards for testing which resulted in a partially working OpenGL 3 context handling implementation.</p>
<p>As the code of GLFW is also very straightforward and handy to read, I easily corrected the bug in the OpenGL 3 context handling and I used GLFW for a few months for my hobby projects. After a while, however, the lack of some facilities in GLFW made me to think through this library selection again as I didn&#8217;t want to end up using several different libraries for different purposes which would result in a barely well designed code structure.</p>
<h2>Simple and Fast Multimedia Library</h2>
<p>We&#8217;ve arrived to the main topic of this article. Finally I&#8217;ve found SFML which at first sight seemed to be &#8220;just another multimedia library&#8221; but I soon realized that it&#8217;s far more than that.</p>
<p>First of all, it has all the features I needed. Beside the basic ones, it has very nice support for networking but not just basic socket programming using TCP or UDP packets, but a more comprehensive toolkit for even HTTP and FTP transactions. It also has built-in sound support via OpenAL which was another thing that caught my attention as I also preferred OpenAL over other audio libraries like fmod. Beside this, it has many other interesting features but you&#8217;d better check out the <a title="SFML Home Page" href="http://www.sfml-dev.org/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.sfml-dev.org/?referer=');">SFML project site</a>.</p>
<p>As I already got used to, SFML had also support for OpenGL 3 context handling but only in the latest development branch. Anyway, this seemed to be no problem as I had no building issues like that what I met in case of SDL. What is more important that the OpenGL 3 implementation actually worked flawlessly, there was no need for any modification. Just to demonstrate, setting up an OpenGL 3 window with SFML can be as easy as writing the following line of code:</p>
<pre class="brush: cpp">sf::Window App(sf::VideoMode(800, 600, 32), "OpenGL 3 window", sf::Style::Close, sf::ContextSettings(24, 8, 0, 3, 2));</pre>
<p>When it comes to modularity, SFML also wins at me. First, it does not need any exotic libraries or headers for rebuilding the framework. Beside this, it has minimal number of external dependencies but only to the operating system libraries used. It is also modular as different sub-systems of the framework are compiled into different library modules so in your project you can simply select which ones do you intend to use to further minimize deployment issues.</p>
<p>From portability point of view, SFML supports all the platforms that are important for me. Also SFML works with no fuss indifferent with all the compiler tool-chains I&#8217;ve tried. At first sight I had concerns regarding to the language portability of SFML as is was written in C++ and this C++ interface is exposed to the client. However, this issue was solved by the library by providing a C wrapper called CSFML together with the framework itself which makes it rather straightforward to write binding for virtually any programming language.</p>
<h2>Conclusion</h2>
<p>If I haven&#8217;t convinced you so far that SFML can be the perfect choice as a multimedia library for almost any hobby or commercial product then you should check out the full feature list and see for yourself. I will probably write more about SFML in the future and you will also meet some usage examples in my upcoming demos.</p>
<p>If you are not interested in the additional features provided by SFML, instead you are just searching for a very basic framework that provides you a window and some user input handling then GLFW can be your choice. However, based on my bad experiences I would not advise anymore the usage of SDL to anybody but maybe I&#8217;m a bit too inclement.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/01/flawless-alternative-to-sdl/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Unit testing in C++</title>
		<link>http://rastergrid.com/blog/2010/01/unit-testing-in-c/</link>
		<comments>http://rastergrid.com/blog/2010/01/unit-testing-in-c/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 16:41:39 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[CPPUTest]]></category>
		<category><![CDATA[CxxTest]]></category>
		<category><![CDATA[GoogleMock]]></category>
		<category><![CDATA[GoogleTest]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=9</guid>
		<description><![CDATA[Many people are looking for information about which particular C++ unit testing framework they should use for their project and there are also many articles discuss the topic but few articles talk about mock frameworks which are even more important factor when applying unit testing in practice and they have much greater effect on the]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F01%252Funit-testing-in-c%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FadyyfS%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Unit%20testing%20in%20C%2B%2B%22%20%7D);"></div>
<p>Many people are looking for information about which particular C++ unit testing framework they should use for their project and there are also many articles discuss the topic but few articles talk about mock frameworks which are even more important factor when applying unit testing in practice and they have much greater effect on the productivity when doing test-driven development.<br />
<span id="more-9"></span></p>
<h2>Test-driven development in a nutshell</h2>
<p>My first experience with unit testing happened to be during my university studies. As we learned Java development, we also worked a little with JUnit as it is the most popular unit testing framework for Java and also the grandfather of almost all current frameworks. I felt about it like pain in the a** because it seemed ridiculous to use it for our very dummy programs and because I&#8217;m really not a big fan of Java and it&#8217;s monolithic development environment called NetBeans, but I will talk about it in another article.</p>
<p>Next I&#8217;ve met unit testing at my current job where we used TNSDLUnit which is a proprietary framework developed by the employees as an internal open-source project for our TNSDL language. Basically this framework is just a TNSDL specific version of the well known CPPUTest framework. This time I&#8217;ve seen real life examples and I soon discovered the potentials in unit testing and in particular its application in test-driven development.</p>
<p>Test-driven development, or TDD in short, is a software development process that became very popular in the recent past and not accidentally as it is a very powerful tool in good hands. It introduces a very simple development cycle that results in simple, clean and test covered code. The process consists of five straightforward steps:</p>
<ol>
<li><strong>Add a test</strong> &#8211; this is made based on a particular requirement</li>
<li><strong>Run all tests and see if the new one fails</strong> &#8211; this ensures that the test really needs modification to the code</li>
<li><strong>Write some code</strong> &#8211; modify code to make the new test pass</li>
<li><strong>Run all tests and see them succeed</strong> &#8211; if the implementation is good then the new test now must pass</li>
<li><strong>Refactor code</strong> &#8211; tidy up the code as you can be sure now that if you do something wrong then tests will fail</li>
</ol>
<p>Not just this development method provides 100% test coverage for your code but it forces you to make the implementation based on requirements not vice versa.</p>
<p>TDD in a more strict manner also states that one must not write more code than it is necessary to make the test pass. This results sometimes in very awkward implementation stubs at the beginning but it prevents the developer from creating untested code (note that 100% coverage usually does not enough for proper testing).</p>
<h2>Why use unit testing?</h2>
<p>Many people have concerns about the necessity of testing and ask why test and why use unit testing. Well, as it maybe seems ridiculous to unit test a code which consists of a few hundreds or thousands of source line and is perspicuous even for the less competent people, the importance of testing comes into force when developing huge sized codes which are continuously modified by a group of people. One can not just test whether a newly implemented functionality is working as expected but can execute automated regression sets in order to ensure that no old functionality is crashed due to a modification.</p>
<p>Others have concerns about that unit testing doubles the code as so increases maintenance because the testing code is as big as the implementation itself. By the way, in a real life example the testing code can even be double the size of the production code. However, the added benefit of a well tested product eliminates most of the cost of bug fixes as they are discovered in the very beginning of the development process.</p>
<h2>C++ unit test frameworks</h2>
<p>When I&#8217;ve started to work with C++ one of my first thing was to look around for a good unit test framework. There are plenty of them so I will mention only some of the most popular ones: CPPUnit, CPPUTest, CxxTest, UnitTest++, Boost Test Library, GoogleTest, etc.</p>
<p>Most people spend too much time on deciding which unit test framework to use while they all have very similar syntax structure and all support the most needed assertions and facilities that are needed to get started with TDD. I think this is just a matter of taste.</p>
<h2>Resolving dependencies</h2>
<p>As one starts to actively use unit testing will face difficulties that rise from the dependencies between different elements of the software system, whether it be an external database, a foreign module or just an own class referenced by the code unit under test. These problems force people to write stubs or mocks to remove external dependencies.</p>
<p>Stubs are just not flexible enough and writing mocks sometimes seems to be too expensive. However, both have a great penalty on development time and maintenance cost. So, at a point, dependencies become the main problem and as such the relevance of which unit test framework to use gets hidden and people start to look for a mock framework. These libraries not just enable easy creation of mock objects but also integrates them tightly into the unit test framework and sometimes they even provide automated mock generation. Fortunately there are also plenty of mock frameworks for C++. Here are some of them: mockpp, Mock Objects, mockcpp, GoogleMock, etc.</p>
<p>Here the differences are much more visible from both from usability, portability and maturity point of view. Some of them automatically generate mocks, others need code for that as well. Some of them depend on specific application binary interface (ABI) formats, others not. Some of them need exotic language features while others work on all the significant compilers. Also, due to the complexity of the C++ language it is very hard to correctly parse code that is heavily obfuscated by macros, so in many cases the automatic generation of mocks simply doesn&#8217;t work.</p>
<p>I&#8217;ve put my vote on GoogleMock and as such I started to use GoogleTest as a unit test framework because of the following reasons:</p>
<ul>
<li>It does not depend on any special language feature or ABI format so it&#8217;s portable</li>
<li>It is natively integrates with GoogleTest so no need to worry about compatibility issues</li>
<li>Mocks have to be hand written, however it needs just a few lines of code (it also has a mock generator, however I don&#8217;t use it)</li>
</ul>
<h2>Summary</h2>
<p>As a final conclusion, if you take my advice then you don&#8217;t take anybody&#8217;s advice. Try it out yourself and see it whether a particular tool set fits your taste or not. It strongly depends on what you plan to unit test. Just keep it simple and have fun with TDD. Yes, it&#8217;s really fun!</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/01/unit-testing-in-c/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Manage code yourself</title>
		<link>http://rastergrid.com/blog/2010/01/manage-code-yourself/</link>
		<comments>http://rastergrid.com/blog/2010/01/manage-code-yourself/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 16:41:25 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[byte code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=10</guid>
		<description><![CDATA[Those who know me know it well that I am not a big fan of languages which produce managed code. In this article I would like to cover the reasons behind my skepticism. Also I would like to dispel the myths around such languages and try to prove them with facts (we will see how]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F01%252Fmanage-code-yourself%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2F4FH6No%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Manage%20code%20yourself%22%20%7D);"></div>
<p>Those who know me know it well that I am not a big fan of languages which produce managed code. In this article I would like to cover the reasons behind my skepticism. Also I would like to dispel the myths around such languages and try to prove them with facts (we will see how well I manage to achieve this). If you disagree with me, you&#8217;ll most probably hate me because of making this post but please, respect my personal point of view.</p>
<p><span id="more-10"></span>As I&#8217;ll mostly talk in this post in general about managed code I would like to emphasize that I have worthwhile experience only with Java and have barely used C# and other managed languages so my primary arguments maybe apply directly only to Java but still would like to present my arguments in general as they still apply in some way to all such languages.</p>
<p>Without the intension to insult anybody, I would like to start with a citation from one of my friends, who often says that &#8220;Java is just a pseudo-language&#8221;. Mostly I agree with him and it&#8217;s not just because I have my not so delightful experiences with the language but also because it introduced a brand new way of coding style that is a complete nightmare for an old-school coder like me. As I don&#8217;t want to start another religious war, I&#8217;ll stop my preposterous arguments here as I would like to prove my concerns with facts that nobody can disclaim.</p>
<blockquote><p>&#8220;&#8230; nowadays Java is almost as fast as native code&#8230;&#8221;</p></blockquote>
<p>This used to be a common myth in the last few years. For those who are still arguing by shouting this loud on forums and blogs, I would like to draw their attention to the fact that Java is <strong>still</strong> an interpreted language no matter if the latest JVM versions do some on-the-fly compilation of the code and as such it is inherently slower than any language that generates native code.</p>
<p>As my hobby is computer graphics I have to talk a bit about the case of PC games. Have anybody seen a game fully written in Java or any other interpreter based language that produces state-of-the-art graphics which competes with the best professional games and it also provides the same performance? I think not, and this is not a coincidence.</p>
<p>GPUs are getting more horsepower in a much faster pace than CPUs. That is what resulted in the batch crisis lately. It&#8217;s already happening for several years that the CPU is simply not powerful enough to feed the GPU with enough data in complex real-time rendering situations. There have been already tons of different software and hardware technologies which already targeted this issue a long time ago but as a perfect example that <strong>is</strong> the reason which resulted in the appearance of the completely redesigned DirectX 10 API and which emerged the need for a cleaner architecture for OpenGL as well. That&#8217;s why there are no advanced games written in interpreted languages as they waste those very valuable CPU cycles which would have great benefits otherwise.</p>
<blockquote><p>&#8220;&#8230; Java has a much greater expression power&#8230;&#8221;</p></blockquote>
<p>I tend to agree with this one. As these languages are interpreted by a virtual machine they provide great room for such features that would be impossible or simply very inefficient in a native language. That&#8217;s why one of my favorite programming language is PHP as an example. It is even more flexible then Java, for example, but never forget that PHP never meant to try to replace native languages as instead it is used in a totally different domain.</p>
<p>There are many language features that are not available in native languages but they weren&#8217;t left out unintentionally. Their lack is primarily justified by the fact that most of these features are rather inefficient and they simply not fit in the philosophy of a performance oriented language like C++. However, the most important ones like reflection, delegates and most OOP related facilities are present for example in Delphi, which is one if not the best OOP language that doesn&#8217;t make too much trade of between flexibility and run-time performance. Also, even if most of these features are not present in C++, Objective-C and other popular native languages, they can be made available with a little programming knowledge in the particular language (maybe not just little).</p>
<blockquote><p>&#8220;&#8230; you don&#8217;t have to care about resource deallocation as there is the garbage collector&#8230;&#8221;</p></blockquote>
<p>This is one of the most annoying &#8220;features&#8221; of managed code based languages. I understand that the prevention of memory leaks can have a great impact on development effort, however the unpredictable behavior of garbage collectors is simply unacceptable in certain situations. The issue of lost references has been already addressed in almost all native languages with the use of reference counted objects so I simply don&#8217;t get it why is this still an important feature. For efficient resource management you need much finer control over the time and way how resources are released.</p>
<blockquote><p>&#8220;&#8230; you just have to care about the basics and Java will make you the rest&#8230;&#8221;</p></blockquote>
<p>While I strongly support the idea of COTS, the way how Java and friends interprets this concept is simply unacceptable for me. Sometimes you need to know what is going on under-the-hood. This is basically the same issue like that of the garbage collector. Beside that, according to my personal taste, I don&#8217;t like if the compiler tells me how to do a particular thing. I rather do it in my way and even if I tend to agree that the compile time static analysis what the Java compiler does can be very valuable in some situations, simply denying code generation even in the case of a very minor semantic problem is simply makes me angry.</p>
<blockquote><p>&#8220;&#8230; Java eliminated almost all unsafe features inherited from C++&#8230;&#8221;</p></blockquote>
<p>This is one of the things that hurts me most. While Java really managed to achieve this, it sacrificed flexibility, ease of use and the fun of programming to make this possible. One such removed feature is operator overloading. I love them! As an example a linear algebraic library, which is often used in graphics programming, or the string library is not just makes the coding more natural, it eases the reading of code which is written with these in mind and that greatly effects the maintenance cost of a particular software as the code is read ten times more than modified. Java in this domain seems too verbose for me and it is much harder to read the long method invocation chains, that is not just used to be used by the developers, but is the recommended way how to code in Java.</p>
<p>This post already ran wildly long so I will close the topic for now. As a conclusion, I have to point it out that this article presented the subject from a rather subjective perspective at the end. Sorry for that, I will recap on the topic in a later post where I will try to be more detached and I&#8217;ll present actual use case examples but for now, this is all that came from my heart so please, don&#8217;t be very harsh with me if I was very biased. I hope you enjoyed the article anyway.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/01/manage-code-yourself/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

