<?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>Alejandro Segovia Azapian</title>
	<atom:link href="http://www.alejandrosegovia.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.alejandrosegovia.net</link>
	<description>C++ and Graphics</description>
	<lastBuildDate>Mon, 20 May 2013 08:00:39 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>The Mandelbrot Project</title>
		<link>http://www.alejandrosegovia.net/2013/05/20/the-mandelbrot-project/</link>
		<comments>http://www.alejandrosegovia.net/2013/05/20/the-mandelbrot-project/#comments</comments>
		<pubDate>Mon, 20 May 2013 08:00:39 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=189</guid>
		<description><![CDATA[I&#8217;ve published the source code of the program I wrote for my tech talk at the 2011 PyDay conference. It&#8217;s a Python script and a companion C library that calculates and draws the Mandelbrot set. The objective of the tech &#8230; <a href="http://www.alejandrosegovia.net/2013/05/20/the-mandelbrot-project/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve published the source code of the program I wrote for my tech talk at the 2011 PyDay conference. It&#8217;s a Python script and a companion C library that calculates and draws the Mandelbrot set.</p>
<p>The objective of the tech talk was to show how to speed up Python programs using the power of native code.</p>
<p><center><br />
<div id="attachment_190" class="wp-caption aligncenter" style="width: 602px"><a href="http://www.alejandrosegovia.net/wp-content/uploads/2013/05/mandelbrot.png"><img src="http://www.alejandrosegovia.net/wp-content/uploads/2013/05/mandelbrot.png" alt="A render of the Mandelbrot set as performed by the mandelbrot.py script. Computations were performed in C." width="592" height="614" class="size-full wp-image-190" /></a><p class="wp-caption-text">A render of the Mandelbrot set as performed by the mandelbrot.py script. Computations were performed in C.</p></div><br />
</center></p>
<p>What&#8217;s interesting about this program is that, although the core was written completely in Python, I wrote two compute backends for it: one in Python and one in C. The C code is interfaced with using the ctypes module.</p>
<p>The results of running the program are shown in the screenshot above. If you are interested in trying it, the full source code is hosted in GitHub, here: <a href="https://github.com/alesegovia/mandelbrot">https://github.com/alesegovia/mandelbrot</a>. I&#8217;ve licensed it under the GPLv3, so you can download, run it, test it and modify it.</p>
<p>As one would anticipate, the C implementation runs much faster than the Python one, even when taking into account the marshaling of objects from Python to C and back. Here&#8217;s the chart I prepared for the conference showing the specific numbers from my tests.</p>
<p>These tests were performed to compare the run times at different numer of iterations, note this is a logarithmic scale.</p>
<p><center><br />
<div id="attachment_191" class="wp-caption aligncenter" style="width: 980px"><a href="http://www.alejandrosegovia.net/wp-content/uploads/2013/05/speedup.png"><img src="http://www.alejandrosegovia.net/wp-content/uploads/2013/05/speedup.png" alt="Comparison of the Python + C implementation vs a pure Python one. Scale is Logarithmic." width="970" height="577" class="size-full wp-image-191" /></a><p class="wp-caption-text">Comparison of the Python + C implementation vs a pure Python one. Scale is Logarithmic.</p></div><br />
</center></p>
<p>As you can see, Python programs can be significantly sped up using ctypes, especially when we are dealing with compute-intensive operations.</p>
<p>It might be possible to speed up the Python implementation to improve its performance to some extent, and now that the source code is available under the GPL, you are encouraged to! I would always expect well-written C code to outperform the Python implementation, but I would like to learn about your results if you happen to give it a go.</p>
<p>Happy hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2013/05/20/the-mandelbrot-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On Java, C#, Objective-C and C++</title>
		<link>http://www.alejandrosegovia.net/2013/05/06/on-java-c-objective-c-and-c/</link>
		<comments>http://www.alejandrosegovia.net/2013/05/06/on-java-c-objective-c-and-c/#comments</comments>
		<pubDate>Mon, 06 May 2013 08:00:46 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=185</guid>
		<description><![CDATA[I&#8217;ve been meaning to write about this for a while. It&#8217;s something that comes up rather frequently at work, so I though I&#8217;d write it down to organize what&#8217;s on my mind. Contrary to what many may think, the Java &#8230; <a href="http://www.alejandrosegovia.net/2013/05/06/on-java-c-objective-c-and-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_186" class="wp-caption alignright" style="width: 206px"><img class=" wp-image-186  " alt="Objective-C, image taken from bigspaceship.com." src="http://www.alejandrosegovia.net/wp-content/uploads/2013/05/objectivec.jpg" width="196" height="158" /><p class="wp-caption-text">Objective-C, image taken from bigspaceship.com.</p></div>
<p>I&#8217;ve been meaning to write about this for a while. It&#8217;s something that comes up rather frequently at work, so I though I&#8217;d write it down to organize what&#8217;s on my mind.</p>
<p>Contrary to what many may think, the Java and C# languages are not based on C++ as much as on Objective-C. Indeed, Objective-C was a big influence in the design of the Java programming language. And since C# 1.0 was basically Microsoft&#8217;s Java, we shall consider it another derived language too.</p>
<p>So, why do people think of Java as a C++-derived language? Java was built on C++&#8217;s <strong>syntax</strong>, this is why Java code &#8220;looks like&#8221; C++ code. Java&#8217;s <strong>semantics</strong>, however, are heavily based on Objective-C&#8217;s.</p>
<p>Some Java and C# features borrowed directly from Objective-C include:</p>
<ul>
<li>Dynamic binding.</li>
<li>Dynamic loading.</li>
<li>Single inheritance.</li>
<li>Interfaces (called &#8220;protocols&#8221; in Objective-C).</li>
<li>Large runtime.</li>
<li>&#8220;Class&#8221; objects.</li>
<li>Reflection.</li>
<li>Objects cannot be allocated in the stack.</li>
<li>Garbage Collection (deprecated in Objective-C).</li>
<li>All methods virtual by default (Java).</li>
<li>Properties (C#).</li>
<li>int, float, double, etc. wrapper classes.</li>
</ul>
<p>Patrick Naughton, one of the original designers of the Java programming language, confirms this story in <a href="http://cs.gmu.edu/~sean/stuff/java-objc.html">this discussion on usenet</a>:</p>
<blockquote><p>Usually, this kind of urban legend stuff turns out to be completely inaccurate, but in this case, they are right on. When I left Sun to go to NeXT, I thought Objective-C was the coolest thing since sliced bread, and I hated C++. So, naturally when I stayed to start the (eventually) Java project, Obj-C had a big influence. James Gosling, being much older than I was, he had lots of experience with SmallTalk and Simula68, which we also borrowed from liberally.</p>
<p>The other influence, was that we had lots of friends working at NeXT at the time, whose faith in the black cube was flagging. Bruce Martin was working on the NeXTStep 486 port, Peter King, Mike Demoney, and John Seamons were working on the mysterious (and never shipped) NRW (NeXT RISC Workstation, 88110???). They all joined us in late &#8217;92 &#8211; early &#8217;93 after we had written the first version of Oak. I&#8217;m pretty sure that Java&#8217;s &#8216;interface&#8217; is a direct rip-off of Obj-C&#8217;s &#8216;protocol&#8217; which was largely designed by these ex-NeXT&#8217;ers&#8230; Many of those strange primitive wrapper classes, like Integer and Number came from Lee Boynton, one of the early NeXT Obj-C class library guys who hated &#8216;int&#8217; and &#8216;float&#8217; types.</p></blockquote>
<p>So, next time you look at Objective-C thinking how weird its syntax looks, remember this story and consider how much it influenced the programming language landscape.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2013/05/06/on-java-c-objective-c-and-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shadow Mapping on iPad</title>
		<link>http://www.alejandrosegovia.net/2013/04/29/shadow-mapping-on-ipad/</link>
		<comments>http://www.alejandrosegovia.net/2013/04/29/shadow-mapping-on-ipad/#comments</comments>
		<pubDate>Mon, 29 Apr 2013 08:00:59 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[3D Engine]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Vortex-Engine]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=180</guid>
		<description><![CDATA[I&#8217;ve implemented shadow mapping on the MD2 Library using the Vortex Engine for iOS wrapper. Shadow mapping is a technique originally proposed in a paper called &#8220;Casting Curved Shadows on Curved Surfaces&#8221; [1], and it brought a whole new approach &#8230; <a href="http://www.alejandrosegovia.net/2013/04/29/shadow-mapping-on-ipad/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve implemented shadow mapping on the MD2 Library using the Vortex Engine for iOS wrapper. Shadow mapping is a technique originally proposed in a paper called &#8220;Casting Curved Shadows on Curved Surfaces&#8221; [1], and it brought a whole new approach to implementing realtime shadows in 3D Apps.</p>
<div id="attachment_183" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.alejandrosegovia.net/wp-content/uploads/2013/04/sm4.png"><img src="http://www.alejandrosegovia.net/wp-content/uploads/2013/04/sm4-300x225.png" alt="Shadow mapping on iPad. The shadow is calculated in realtime and animates as the model moves." width="300" height="225" class="size-medium wp-image-183" /></a><p class="wp-caption-text">Shadow mapping on iPad. The shadow is calculated in realtime and animates as the model moves.</p></div>
<p>Implementing shadow mapping on iOS is by nature a problem that spans several programming languages. Objective-C for creating the UI, C/C++ for interfacing with OpenGL and GLSL for implementing the technique in the GPU&#8217;s fragment shader.</p>
<p>The math involved in shadow mapping spans all of these languages, with different coordinate space transformations being implemented in the language appropriate to the pipeline stage we&#8217;re working on. This makes the technique a little tricky to implement the first time you attempt to.</p>
<p>Here is another screenshot of the technique running on an actual iPad. Notice how the shadow is cast on the floor as well as on top of the crate in the background.</p>
<div id="attachment_182" class="wp-caption aligncenter" style="width: 235px"><a href="http://www.alejandrosegovia.net/wp-content/uploads/2013/04/sm2.png"><img src="http://www.alejandrosegovia.net/wp-content/uploads/2013/04/sm2-225x300.png" alt="Upfront capture of the shadow mapping technique running on the iPad simulator." width="225" height="300" class="size-medium wp-image-182" /></a><p class="wp-caption-text">Upfront capture of the shadow mapping technique running on the iPad simulator.</p></div>
<p>Shadow mapping will be coming up in the next version of the MD2 Library app.</p>
<p>[1] &#8211; Lance Williams &#8211; Casting Curved Shadows on Curved Surfaces. http://artis.imag.fr/~Cyril.Soler/DEA/Ombres/Papers/William.Sig78.pdf</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2013/04/29/shadow-mapping-on-ipad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fiddling with the HTML5 Canvas</title>
		<link>http://www.alejandrosegovia.net/2013/02/18/fiddling-with-the-html5-canvas/</link>
		<comments>http://www.alejandrosegovia.net/2013/02/18/fiddling-with-the-html5-canvas/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 08:00:23 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[Canvas]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=170</guid>
		<description><![CDATA[I&#8217;ve been doing some experimenting with HTML5&#8242;s Canvas element. After some brushing up on Javascript, I started working on a couple of proof-of-concept scripts to see how well the platform can be used. I have not been disappointed. Javascript, as &#8230; <a href="http://www.alejandrosegovia.net/2013/02/18/fiddling-with-the-html5-canvas/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been doing some experimenting with HTML5&#8242;s Canvas element. After some brushing up on Javascript, I started working on a couple of proof-of-concept scripts to see how well the platform can be used.</p>
<p>I have not been disappointed. Javascript, as a language, has evolved quite a bit since the old days of <strong>document.write()</strong>, with DOM editing as the one true way to manage dynamic content. Having said that, I find that Javascript is still quirky and flawed.</p>
<p>Here&#8217;s a short script I wrote (fewer than 160 lines) that animates a girl wearing the traditional Oktoberfest outfit. She walks back and forth within a given 500&#215;500 area. <strong>This is not a video</strong>, your browser is doing the math to update her animations and move her around in realtime!</p>
<div id="player_container" style="text-align:center; width:500; height:500;"></div>
<p>You should be able to see the demo just above this message, if you have a fairly recent browser that supports the HTML5 Canvas element. I was actually surprised about how mainstream Canvas support is: Chrome &ge; 22, Firefox &ge; 15, IE &ge; 9; Opera &ge; 12.1; Safari &ge; 5.1, Android &ge; 2.1 and Safari Mobile &ge; 3.2, all support this new element.</p>
<p>The animation atlas was taken from <a href=": http://www.untamed.wild-refuge.net/rmxpresources.php?characters">this cool website</a> with resources free to use. The script &#8220;slices&#8221; the image, taking the appropriate frames to draw depending on the time simulation and the direction the character is walking towards (left or right).</p>
<div id="attachment_171" class="wp-caption aligncenter" style="width: 138px"><a href="http://www.alejandrosegovia.net/wp-content/uploads/2013/02/german_f2.png"><img src="http://www.alejandrosegovia.net/wp-content/uploads/2013/02/german_f2.png" alt="Sprite animation atlas." width="128" height="192" class="size-full wp-image-171" /></a><p class="wp-caption-text">Sprite animation atlas.</p></div>
<p>Despite Javascript&#8217;s gotchas, with the addition of the HTML5 Canvas element, it&#8217;s become a nice tool that allows hacking together some easy 2D (or even 3D!) graphics and display them in a browser.</p>
<p>See you next time!</p>
<p><script type="text/javascript" src="/scripts/player.js"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2013/02/18/fiddling-with-the-html5-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Function Objects using Variadic Templates in C++11</title>
		<link>http://www.alejandrosegovia.net/2013/02/11/function-objects-using-variadic-templates-in-c11/</link>
		<comments>http://www.alejandrosegovia.net/2013/02/11/function-objects-using-variadic-templates-in-c11/#comments</comments>
		<pubDate>Mon, 11 Feb 2013 08:00:56 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=168</guid>
		<description><![CDATA[One of the biggest features introduced in C++11 are lambda expressions. Lamba expressions (or &#8220;lambdas&#8221;) are a powerful mechanism that allows defining functions &#8220;on-the-fly&#8221;. These can be stored in function objects and then be used by an object that doesn&#8217;t &#8230; <a href="http://www.alejandrosegovia.net/2013/02/11/function-objects-using-variadic-templates-in-c11/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>One of the biggest features introduced in C++11 are lambda expressions. Lamba expressions (or &#8220;lambdas&#8221;) are a powerful mechanism that allows defining functions &#8220;on-the-fly&#8221;. These can be stored in function objects and then be used by an object that doesn&#8217;t want to reveal its internal implementation, as well as to perform tasks on a parallel thread.</p>
<p>I was wondering how function objects could be implemented using other constructs of the language, mostly to see how much the language had to be changed in order to accomodate them. In this post I will show how to implement function objects using nothing but C++11&#8242;s variadic templates.</p>
<p>Variadic templates were introduced <a href="http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/">in our previous post</a> in this C++11 series. This post will help pave the way for us to move into the more advanced topic of lambda expressions and std::function objects.</p>
<h1>Function Pointers in C</h1>
<p>As far as I can tell, C has always had functions as first-class citizens. Although their syntax is vastly different from the way one declares variables of other types, you could always define a variable that can be assigned a pointer to a function.</p>
<pre class="brush:cpp">
#include &lt;stdio.h&gt;
void print_number(int number)
{
    printf("Argument is: %d\n", number);
}

int main(int argc, char* argv[])
{
    void (*f)(int);  // f is a variable that can 
                     // store a pointer to a 
                     // function that receives 
                     // an int an returns nothing.
    f = print_number // legal.

    f(1024);         // calls print_number.  

    return 0;
}
</pre>
<p>Because C is a statically-typed language, we must be very careful with the types we declare <strong>f</strong> with, otherwise the assignment may be deemed invalid by the compiler.</p>
<p>Another problem is that the syntax can be cumbersome to remember and handle. Notice how the name of the variable is declared within the associated types. </p>
<h2>Function Objects in C++</h2>
<p>Unless you were using boost, C++ never had its own version of function objects until C++11. Programmers had to rely on the traditional C construct or write <strong>functors</strong>, classes that implement <strong>operator()</strong> and allow mimicking a function&#8217;s behavior.</p>
<p>Unlike C function pointers, functors are more readable, but we need to declare a class and implement operator() inside it. It&#8217;s much more verbose.</p>
<p>C++11 introduced the standard <strong>std::function</strong> type, which allows encapsulating a function declared by lamba expressions (or by other means). In production code, you will most certainly want to use std::functions. In this post, however, because of academic interest only, we&#8217;re going to exercise C++11&#8242;s variadic templates by implementing a generic function wrapper object called <strong>alg::function</strong>.</p>
<h1>alg::function</h1>
<p>Using variadic templates, it&#8217;s very easy to implement a simple function wrapper capable of handling any function type. I&#8217;m going to implement my solution using C function pointers. Remember: in C++11 production code, you will never do this.</p>
<pre class="brush:cpp">
namespace alg
{
    template &lt;typename R, typename... T&gt;
    class function
    {
        public:
            function(R (*f)(T...)) { _f = f; }
            R operator()(T... args) {return _f(args...);}
		
        private:
            R (*_f)(T...);

    };
}
</pre>
<p>And that&#8217;s all there is to it, really. Let&#8217;s go over the code.</p>
<p>I declare the class alg::function as a template that is to be instanciated by two parameters: a return type dubbed &#8220;R&#8221; and a list of types which I will refer to as &#8220;T&#8221;. The list of types can be empty, the return type is mandatory.</p>
<p>alg::function objects will have a single private member that is declared to be a pointer to a C function that returns a value of type R and receives the list of argument types T.</p>
<p>The only two additional methods that we need are: a public constructor that receives the function to wrap, storing it, and <strong>operator()</strong>, which will let us call the function. Notice how easily we can unpack the arguments when we call <strong>_f</strong>.</p>
<h1>Instancing Examples</h1>
<p>Let&#8217;s see it in action!</p>
<p>These samples illustrate the basic idea without complex data structures. It is certainly possible to pass alg::function objects around as the first-class citizens that they are, as well as passing-in and returning arbitrary C++ objects and structs from these wrappers.</p>
<p>The only limitation is the fact that we don&#8217;t support const parameters. Adding support for them would require tweaking the alg::function class a bit more. We leave this as an exercise to the reader.</p>
<p>A single function that receives an int and prints it:</p>
<pre class="brush:cpp">
void fun(int arg)
{
    std::cout &lt;&lt; "hello from fun! (arg=" 
              &lt;&lt; arg 
              &lt;&lt; ")"
              &lt;&lt; std::endl;
}

int main(int argc, char* argv[])
{
    alg::function&lt;void, int&gt; f(fun);

    f(0); // prints "hello from fun! (arg=0)"
}
</pre>
<p>A function that receives no parameters:</p>
<pre class="brush:cpp">
void fun2()
{
    std::cout &lt;&lt; "hello from fun 2!" &lt;&lt; std::endl;
}

int main(int argc, char* argv[])
{
    alg::function&lt;void&gt; f2(fun2);

    f2();  // prints "hello from fun 2!"
}
</pre>
<p>A function that receives two std::string instances and prints them together:</p>
<pre class="brush:cpp">
void fun4(std::string msg1, std::string msg2)
{
    std::cout &lt;&lt; "hello from fun 4! (concat=" 
              &lt;&lt; msg1 &lt;&lt; msg2 
              &lt;&lt; ")" 
              &lt;&lt; std::endl;
}

int main(int argc, char* argv[])
{
    alg::function&lt;void, std::string, std::string&gt; f4(fun4);

    f4("hello, ", "world!"); // prints "hello from fun 4! (concat=hello, world!)"
}
</pre>
<h1>Conclusion</h1>
<p>Variadic templates offer a lot in terms of flexibility and allow us to extend the language even further than it was possible before. Remember, these examples are just food for thought. In C++11 production code, you will most certainly want to use std::function objects and lambda expressions.</p>
<p>See you next time!</p>
<h1>Other articles in this C++11 series</h1>
<ul>
<li><a href="http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/">Variadic Templates &#8211; Part 1</a>.</li>
<li><a href="http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-2-of-2/">Variadic Templates &#8211; Part 2</a>.</li>
<li><a href="http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/">Move Semantics &#8211; Part 1</a>.</li>
<li><a href="http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-2-of-2/">Move Semantics &#8211; Part 2</a>.</li>
<li><a href="http://www.alejandrosegovia.net/2012/08/27/playing-with-c11-using-clang-revisited/">Iterators and Lambdas</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2013/02/11/function-objects-using-variadic-templates-in-c11/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>libsdl-1.2 support for OpenGL 3.2</title>
		<link>http://www.alejandrosegovia.net/2012/11/05/libsdl-1-2-adds-support-for-opengl-3-2/</link>
		<comments>http://www.alejandrosegovia.net/2012/11/05/libsdl-1-2-adds-support-for-opengl-3-2/#comments</comments>
		<pubDate>Mon, 05 Nov 2012 08:00:17 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[OpenGL]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=163</guid>
		<description><![CDATA[This week we take a break from the C++ saga to talk a little about OpenGL. I&#8217;ve forked libsdl-1.2 and added support for creating OpenGL 3.2 forward-compatible contexts. This is something that could be deemed helpful until libsdl 2.0 is &#8230; <a href="http://www.alejandrosegovia.net/2012/11/05/libsdl-1-2-adds-support-for-opengl-3-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This week we take a break from the C++ saga to talk a little about OpenGL. I&#8217;ve forked libsdl-1.2 and added support for creating OpenGL 3.2 forward-compatible contexts. This is something that could be deemed helpful until libsdl 2.0 is released.</p>
<p>You can find the source code on my GitHub page, at: <a href="http://github.com/alesegovia">github.com/alesegovia</a>. In so far, only the Mac platform is supported, as it&#8217;s the only Operating System I currently have access to. I&#8217;ll hopefully be able to add Linux support as soon as I can get hold of a Linux box with a suitable video card.</p>
<p>Creating an OpenGL 3.2 compatible context is very simple. Once you have downloaded, compiled and installed <a href="https://github.com/alesegovia/libsdl-1.2-gl">libsdl-1.2-gl</a>, you just need to create your window using the new <strong>SDL_OPENGLCORE</strong> flag.</p>
<p>This sample program creates an OpenGL 3.2 context, displays the OpenGL version number and exits:</p>
<pre class="brush:cpp">
#include &lt;SDL.h&gt;
#include &lt;stdio.h&gt;
#include &lt;OpenGL/gl.h&gt;

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_VIDEO);

    SDL_Surface* pSurface = SDL_SetVideoMode(600, 600, 32, SDL_OPENGL|SDL_OPENGLCORE);

    printf("GL Version:%s\n", glGetString(GL_VERSION));

    SDL_Quit();

    return 0;
}
</pre>
<p>You need to be running Mac OS X Lion or higher in order to be able to create OpenGL 3.2 contexts. If you are running Snow Leopard or your video card does not support OpenGL 3.2, you might get a Compatibility profile and your OpenGL version might be stuck on 2.1.</p>
<p>Also note that Mac OS X reports the OpenGL version to be 2.1 unless you specifically create forward-compatible OpenGL contexts, so if you need to know whether your Mac supports OpenGL 3.2, you can look your system configuration up in <a href="https://developer.apple.com/graphicsimaging/opengl/capabilities/">this great table</a> maintained by Apple.</p>
<p>If you find this useful, let me know in the comments. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2012/11/05/libsdl-1-2-adds-support-for-opengl-3-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Variadic Templates in C++ 11 (Part 2 of 2)</title>
		<link>http://www.alejandrosegovia.net/2012/09/24/variadic-templates-in-c-11-part-2-of-2/</link>
		<comments>http://www.alejandrosegovia.net/2012/09/24/variadic-templates-in-c-11-part-2-of-2/#comments</comments>
		<pubDate>Mon, 24 Sep 2012 08:00:45 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=157</guid>
		<description><![CDATA[Last week we started discussing C++11&#8242;s new Variadic Templates. In that article I showed you how to declare a function initialized by a Variadic Template that returns the number of template arguments it was called with. Today, we build on &#8230; <a href="http://www.alejandrosegovia.net/2012/09/24/variadic-templates-in-c-11-part-2-of-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Last week we started discussing C++11&#8242;s new <a href="http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/">Variadic Templates</a>.</p>
<p>In that article I showed you how to declare a function initialized by a Variadic Template that returns the number of template arguments it was called with. Today, we build on those concepts to implement a printf-like function with the properties of being typesafe, don&#8217;t requiring parsing formatting characters and supporting non-POD data types. Let&#8217;s get started.</p>
<p>The first thing I want to do is rewrite the <a href="http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/">example from last week</a>. This will ease introducing this week&#8217;s concepts. Let&#8217;s create a new function <strong>g</strong> that does the same that <strong>f</strong> did, but receives any number of arguments via template instantiation.</p>
<pre class="brush:cpp">
template &lt;class... T&gt;
size_t g(T... args)
{
  return sizeof...(args);
}
</pre>
<p><strong>g</strong> does exactly the same that <strong>f</strong>, the only difference is that we can now call it using the following syntax:</p>
<pre class="brush:cpp">
int main(int argc, char* argv[])
{
  cout &lt;&lt; g(); // prints "0"
  cout &lt;&lt; g(1); // prints "1"
  cout &lt;&lt; g(1,2,3,4,5,6,7) // prints "7"
}
</pre>
<p>It is, in a way, like a variadic function, but written in C++11 style instead of plain C.</p>
<p>It&#8217;s important that you understand how <strong>g</strong> works, if you don&#8217;t, please review the code again and try making changes to it.</p>
<p>Assuming that&#8217;s out of the way, let&#8217;s delve in today&#8217;s article.</p>
<p>We want to develop a <strong>print</strong> function that can receive any number of parameters of any type. So we can call:</p>
<pre class="brush:cpp">

A a; // Create some object...

print(1);
print(1, 2.0f);
print(1, 2.0f, "Hello");
print(1, 2.0f, "Hello", a);

// An so on...

</pre>
<p>Now, you might be guessing that one way to implement this function would be to have a &#8220;base case&#8221; that can print one argument and then have it called with each supplied argument.</p>
<pre class="brush:cpp">
template &lt;class T&gt;
void print(const T&#038; msg)
{
  cout &lt;&lt; msg &lt;&lt; " ";
}
</pre>
<p>That&#8217;s a really good idea and, last time, we saw how to determine how many arguments a Variadic Template has been instanciated with (using the <strong>sizeof&#8230;</strong> operator). </p>
<p>Unfortunately, when it comes to Variadic Templates, we can&#8217;t iterate over the arguments based on the count. We need to find another way.</p>
<p>In an idea that I regard largely borrowed from functional programming, what if we could separate the list of arguments in the &#8220;head&#8221; element and the &#8220;rest&#8221; of the list?</p>
<p>Well, if that was the case, then we could call our base-case print function with the head and then call the general-case function with the rest of the list. Eventually, the list will be empty and we will have printed all elements!</p>
<p>We can do exactly that using C++11 new template syntax:</p>
<pre class="brush:cpp">

// This is our base-case for the print function:

template &lt;class T&gt;
void print(const T&#038; msg)
{
  cout &lt;&lt; msg &lt;&lt; " ";
}


// And this is the recursive case:

template &lt;class A, class... B&gt;
void print(A head, B... tail)
{
  print(head);
  print(tail...);
}

</pre>
<p>Let&#8217;s try this with a simple program:</p>
<pre class="brush:cpp">
int main(int argc, char* argv[])
{

  print(1, "\n");
  print(1, 2.0f, "\n");
  print(1, 2.0f, "Hello", "\n");

  return 0;
}
</pre>
<p>The output should be something like:</p>
<pre class="brush:bash">
 1 
 1 2 
 1 2 Hello
</pre>
<p>And that&#8217;s all there is to it. The C++ compiler will take care of generating the appropriate code to instanciate our functions and to split the parameter list so we can print the arguments one by one. Notice how this is much easier than having to mess with variadic functions, while being typesafe too.</p>
<p>The biggest challenge is assimilating the new syntax, but there are lots of good references around <a href="https://www.ibm.com/developerworks/mydeveloperworks/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/c_templates_what_is_a_variadic_template_function41?lang=en">like this article from IBM</a>, where I got the idea of writing a print function, or even the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2080.pdf">Variadic Template proposal</a> for the ISO committee, another great resource.</p>
<p>Stay tuned for more C++11 goodness next week!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2012/09/24/variadic-templates-in-c-11-part-2-of-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Variadic Templates in C++11 (Part 1 of 2)</title>
		<link>http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/</link>
		<comments>http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/#comments</comments>
		<pubDate>Mon, 17 Sep 2012 08:00:32 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=155</guid>
		<description><![CDATA[This week we are continuing with the C++11 saga, moving on to a new feature called &#8220;Variadic Templates&#8221;. Inspired by the concept of Variadic Functions in C, the idea behind Variadic Templates is to allow a template to be instanciated &#8230; <a href="http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This week we are continuing with the C++11 saga, moving on to a new feature called &#8220;Variadic Templates&#8221;.</p>
<p>Inspired by the concept of Variadic Functions in C, the idea behind Variadic Templates is to allow a template to be instanciated with any number of arguments.</p>
<p>In this article I&#8217;ll cover the new syntax and present a simple example that declares a function that uses a Variadic Template that prints the number of arguments it was intantiated with.</p>
<p>Previous parts of this saga included an overview of new <a href="http://www.alejandrosegovia.net/2012/08/27/playing-with-c11-using-clang-revisited/">iterators and lambda expressions</a> as well as Move Semantics, which was treated in two parts: <a href="http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/">Part 1</a> and <a href="http://www.alejandrosegovia.net/2012/09/10/move-semantics-in-c11-part-2-of-2/">Part 2</a>.</p>
<p>Let&#8217;s get started!</p>
<p>First of all, C++11 had to extend the C++ syntax for templates in order to support Variadic Templates. The new syntax allows annotating a parameter with an ellipsis (&#8230;) to denotate that we may expect receive zero or more parameters in the given place.</p>
<p>This means that the following declaration is now valid C++:</p>
<pre class="brush:cpp">
template &lt;class... T&gt;
void f()
{
}
</pre>
<p><strong>f</strong> is a function that can be expanded with zero or more template parameters.</p>
<p>Now that we know how to declare a Variadic Template, let&#8217;s write a simple program that prints the number of arguments the function <strong>f</strong> template has been expanded with.</p>
<pre class="brush:cpp">
#include &lt;iostream&gt;
using std::cout;
using std::endl;

template &lt;class... T&gt;
size_t f()
{
    return sizeof...(T);
}

int main(int argc, char* argv[])
{
    cout &lt;&lt; "sizeof f&lt;int&gt;" &lt;&lt; f&lt;int&gt;() &lt;&lt; "\n";
    cout &lt;&lt; "sizeof f&lt;int, float&gt;" &lt;&lt; f&lt;int, float&gt;() &lt;&lt; "\n";
    cout &lt;&lt; "sizeof f&lt;int, float, char&gt;" &lt;&lt; f&lt;int, float, char&gt;() &lt;&lt; endl;
    return 0;
}
</pre>
<p>Compiling this program with clang and running it produces the following output:</p>
<pre class="brush:bash">
sizeof f&lt;int&gt;: 1
sizeof f&lt;int, float&gt;: 2
sizeof f&lt;int, float, char&gt;: 3
</pre>
<p>Here, each line of the output corresponds to the number of parameters the function template was instantiated with. As you probably noticed, the new <strong>sizeof&#8230;</strong> takes the packed template arguments and returns their count. If we just called <strong>f</strong> without instantiating its template, the number of arguments printed would be 0.</p>
<p>Now, you might be wondering what Variadic Templates might be used for. In next week&#8217;s article I will show you how to write a typesafe printf-like function in C++11 style. Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2012/09/17/variadic-templates-in-c11-part-1-of-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Move Semantics in C++11 (Part 2 of 2)</title>
		<link>http://www.alejandrosegovia.net/2012/09/10/move-semantics-in-c11-part-2-of-2/</link>
		<comments>http://www.alejandrosegovia.net/2012/09/10/move-semantics-in-c11-part-2-of-2/#comments</comments>
		<pubDate>Mon, 10 Sep 2012 08:00:58 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=150</guid>
		<description><![CDATA[Last week we talked about the problem with passing objects around in the 2003 C++ standard, and mentioned how the new move semantics in C++11 could help us avoid expensive object copies. In this article I continue where I left &#8230; <a href="http://www.alejandrosegovia.net/2012/09/10/move-semantics-in-c11-part-2-of-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/">Last week</a> we talked about the problem with passing objects around in the 2003 C++ standard, and mentioned how the new move semantics in C++11 could help us avoid expensive object copies.</p>
<p>In this article I continue where I left off last week and show an updated version of the code that implements move semantics.</p>
<p>Now, the new code might be generated by a C++11 compiler automatically, just like default copy and assignment operators are generated, but I will show you how to implement these yourself.</p>
<p>Normally, we would just go about adding the new functions to our program, and that&#8217;s the way it should be for new C++11 codebases. Chances are, however, that today you will probably be adding support to an existing project that might need to be built for a platform that doesn&#8217;t have a readily available C++11 compiler.</p>
<p>You wouldn&#8217;t want to break compatibility with that platform, so something you can do is to conditionally compile move semantics into your program. This way, you can have the best of both worlds: a speedy implementation for programs compiled with a state-of-the-art compiler and a (slower, but working) fallback for all other target platforms.</p>
<p>So, bearing this in mind, let&#8217;s add a new move constructor and a new move assignment operator to A, but protected by a MOVE_CTOR macro:</p>
<pre class="brush:cpp">
#include &lt;iostream&gt;
using std::cout;
using std::endl;

class A
{
	public:
		A();
		A(const A&#038; other);
		A&#038; operator=(const A&#038; other);

#ifdef MOVE_CTOR
		A(A&#038;&#038; other);
		A&#038; operator=(A&#038;&#038; other);
#endif //MOVE_CTOR

		float _a;
};

A::A() : _a(0.0f)
{
	cout &lt;&lt; "Running A()" << endl;
}

A::A(const A&#038; other)
{
	cout &lt;&lt; "Running A(const A&#038;)" &lt;&lt; endl;
	_a = other._a;
}

A&#038; A::operator=(const A&#038; other)
{
	cout &lt;&lt; "Running operator=(const A&#038;)" &lt;&lt; endl;
	_a = other._a;
	return *this;
}

#ifdef MOVE_CTOR

A::A(A&#038;&#038; other)
{
	cout &lt;&lt; "Move-constructing A" &lt;&lt; endl;
	_a = other._a;
	other._a = 0.0f;
}

A&#038; A::operator=(A&#038;&#038; other)
{
	if (&#038;other != this)
	{
		cout &lt;&lt; "Move-assigning A" &lt;&lt; endl;
		_a = other._a;
		other._a = 0.0f;
	}

	return *this;
}

#endif //MOVE_CTOR

A getAnA()
{
	A a;
	a._a = 1.0f;
	return a;
}

int main(int argc, char* argv[])
{
	cout &lt;&lt; "==Declaring A a==" &lt;&lt; endl;
	A a; 
	cout &lt;&lt; "==Assigning a=getAnA()==" &lt;&lt; endl;
	a = getAnA();
	cout &lt;&lt; "==done==" &lt;&lt; endl;
	cout &lt;&lt; "a._a = "&lt;&lt; a._a &lt;&lt; endl;
	return 0;
}
</pre>
<p>To build this source file with support for move semantics, use the following command. Older compilers can opt-out of building C++11-specific code. </p>
<pre class="brush:bash">
clang++ -std=c++11 -stdlib=libc++ -DMOVE_CTOR main.cpp
</pre>
<p>If everything's alright, here's the output that should be produced from running this program:</p>
<pre class="brush:bash">
:@~/devel/C++/move_ctor11$ ./a.out 
==Declaring A a==
Running A()
==Assigning a=getAnA()==
Running A()
Move-assigning A
==done==
a._a = 1
</pre>
<p>Here we can immediately notice how we are avoiding running the (expensive) copy assignment operator and we substitute it with a lightweight move assignment that takes the internal data of the source object.</p>
<p>Think how this could help you avoid deep-copying matrices, trees, memory pages, and even how it would help you code safer by preventing having to sacrifice const-correctness and immutable object state in your code as hacky ways to gain performance. C++11 really does feel like a new language.</p>
<p>Stay tuned for more C++11 goodness next week!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2012/09/10/move-semantics-in-c11-part-2-of-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Move Semantics in C++11 (Part 1 of 2)</title>
		<link>http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/</link>
		<comments>http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/#comments</comments>
		<pubDate>Mon, 03 Sep 2012 08:00:43 +0000</pubDate>
		<dc:creator>Alex</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.alejandrosegovia.net/?p=149</guid>
		<description><![CDATA[Continuing with the C++11 saga, this week I&#8217;ve been playing with move semantics. In this post I share my findings regarding using it on Apple&#8217;s Clang version 4.0. Move semantics are a new mechanism built into C++ that allow us &#8230; <a href="http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Continuing with <a href="http://www.alejandrosegovia.net/2012/08/27/playing-with-c11-using-clang-revisited/">the C++11 saga</a>, this week I&#8217;ve been playing with move semantics. In this post I share my findings regarding using it on Apple&#8217;s Clang version 4.0.</p>
<p>Move semantics are a new mechanism built into C++ that allow us to &#8220;move&#8221; data from one object to another. They help avoid full object copies that, today, could occur under different scenarios.</p>
<p>The copy involved in passing in values to a function is a good example that can usually be avoided by receiving parameters as <strong>const</strong> references instead of as values. Other scenarios, like returning an object from a function, are, however, harder to avoid.</p>
<p>Move semantics let us write special functions that can &#8220;steal&#8221; a source object&#8217;s inner data and assign it to a new object. It could help you avoid an expensive copy operation when you know the source object is not going to be used anymore.</p>
<p>I&#8217;ve written a simple example to illustrate the problem. Suppose we have class A and we want to have a function that creates an A instance, then customizes it and finally returns it to the caller.</p>
<pre class="brush:cpp">
#include &lt;iostream&gt;
using std::cout;
using std::endl;

// A's interface:

class A
{
	public:
		// Default ctor:
		A();
		
		// Copy ctor:
		A(const A&#038; other);

		// Copy-assignment operator:
		A&#038; operator=(const A&#038; other);

		// Inner data, should be private...
		float _a;
};

// A's implementation:

A::A() : _a(0.0f)
{
	cout &lt;&lt; "Running A()" << endl;
}

A::A(const A&#038; other)
{
	cout &lt;&lt; "Running A(const A&#038;)" &lt;&lt; endl;
	_a = other._a;
}

A&#038; A::operator=(const A&#038; other)
{
	cout &lt;&lt; "Running operator=(const A&#038;)" &lt;&lt; endl;
	_a = other._a;
	return *this;
}

// Helper function to create and customize an A instance:

A getAnA()
{
	A a;
	a._a = 1.0f;
	return a;
}

// Program entry point:

int main(int argc, char* argv[])
{
	cout &lt;&lt; "==Declaring A a==" &lt;&lt; endl;
	A a; 
	cout &lt;&lt; "==Assigning a=getAnA()==" &lt;&lt; endl;
	a = getAnA();
	cout &lt;&lt; "==done==" &lt;&lt; endl;
	cout &lt;&lt; "a._a = "&lt;&lt; a._a &lt;&lt; endl;
	return 0;
}
</pre>
<p>Running this code yields the following output:</p>
<pre class="brush:cpp">
:@~/devel/C++/move_ctor11$ ./a.out 
==Declaring A a==
Running A()
==Assigning a=getAnA()==
Running A()
Running operator=(const A&#038;)
==done==
a._a = 1
</pre>
<p>The problem here lays in line 6. When the instance is to be returned from function getAnA(), it lives in the called function's stack, so we need to copy it into the caller's stack space in orde to return it. The code that does the copy is generated automatically by the C++ compiler and will incur in a performance penalty.</p>
<p>How slow is it? Well, it depends. For a big object (for instance a memory page, a huge matrix or other gigantic data structure) the performance penalty can be significant, specially when we really start to pass objects around.</p>
<p>This copy, however could completely be avoided by leveraging the fact that the source instance is going to go away. Move semantics allow us to have the destination A steal (or <strong>move</strong>) the source A's inner data.</p>
<p>Next week I'll show you how you can implement move semantics to speed up object passing. Stay tuned!.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alejandrosegovia.net/2012/09/03/move-semantics-in-c11-part-1-of-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
