<?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>db-in&#039;s blog &#187; Cocoa</title>
	<atom:link href="http://db-in.com/blog/category/objective-c/cocoa/feed/" rel="self" type="application/rss+xml" />
	<link>http://db-in.com/blog</link>
	<description></description>
	<lastBuildDate>Mon, 05 Mar 2012 15:15:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Objective-C Singleton</title>
		<link>http://db-in.com/blog/2011/12/objective-c-singleton/</link>
		<comments>http://db-in.com/blog/2011/12/objective-c-singleton/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 08:46:05 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Singleton]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1477</guid>
		<description><![CDATA[Singleton design pattern in Obj-C, the best way to create a Singleton class thread-safe. Includes a Xcode template for Singleton classes.]]></description>
			<content:encoded><![CDATA[<p>Hello fellows,</p>
<p>Due to many emails I have been received on the last months, I decide to create a single article to explain a little bit about the Singleton classes (also known as Singleton Pattern). I&#8217;ll focus here on Objective-C and Cocoa approach, however I&#8217;ll talk a little bit generally, so you can take the concept to other languages as well.</p>
<p>Let&#8217;s start!<br />
<span id="more-1477"></span></p>
<p><br/></p>
<h2><strong>Just Give me the Code!</strong></h2>
<p>Ok, ok. For who of you that just want the final code without protraction, here is it, you can choose a Xcode template or the pure code:</p>
<p><em><br />
<h3>Xcode template (Xcode 4)</h3>
<p></em><br />
A cool template for Xcode 4 that I created to use over my working machines.</p>
<ol>
<li>Download the zipped file bellow.</li>
<li>Unzip and copy the &#8220;db-in&#8221; folder to &#8220;/Library/Developer/Xcode/Templates/File Templates&#8221;</li>
<li>Open an Xcode project and try to add a new file. You will see a category called &#8220;db-in&#8221; on the left side, under the iOS platform.</li>
</ol>
<p><a href="http://db-in.com/downloads/xcode4_singleton_template.zip" onmousedown="_gaq.push(['_trackEvent', 'Singleton iOS', 'Xcode', 'Download']);"><img class="alignleft" title="download" src="http://db-in.com/imgs/download_button.png" alt="Download Xcode template files"/><br />
<strong>Download now</strong><br />
Xcode Singleton Class template<br />
40kb<br />
</a></p>
<p><em><br />
<h3>Pure code</h3>
<p></em><br />
Here is the code for your header and source files:</p>
<table width="675">
<tbody>
<tr>
<th>Header file (.h)</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
@interface MySingleton : NSObject

+ (MySingleton *) instance;

@end
</pre>
<table width="675">
<tbody>
<tr>
<th>Source file (.m)</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
@interface MySingleton()

// Make any initialization of your class.
- (id) initSingleton;

@end

@implementation MySingleton

- (id) initSingleton
{
	if ((self = [super init]))
	{
		// Initialization code here.
	}

	return self;
}

+ (MySingleton *) instance
{
	// Persistent instance.
	static MySingleton *_default = nil;

	// Small optimization to avoid wasting time after the
	// singleton being initialized.
	if (_default != nil)
	{
		return _default;
	}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
	// Allocates once with Grand Central Dispatch (GCD) routine.
	// It's thread safe.
	static dispatch_once_t safer;
	dispatch_once(&#038;safer, ^(void)
				  {
					  _default = [[MySingleton alloc] initSingleton];
				  });
#else
	// Allocates once using the old approach, it's slower.
	// It's thread safe.
	@synchronized([MySingleton class])
	{
		// The synchronized instruction will make sure,
		// that only one thread will access this point at a time.
		if (_default == nil)
		{
			_default = [[MySingleton alloc] initSingleton];
		}
	}
#endif
	return _default;
}

- (id) retain
{
	return self;
}

- (oneway void) release
{
	// Does nothing here.
}

- (id) autorelease
{
	return self;
}

- (NSUInteger) retainCount
{
    return INT32_MAX;
}

@end
</pre>
<p><br/></p>
<h2><strong>At a glance</strong></h2>
<p>First off, Singleton is a Design Patterns, I know you know some patterns and also use some of them every day in your works. Like MVC (Model View Controller) which all of us use to create our App in Xcode, or also the Delegate Pattern, which Cocoa framework uses largely. So the Singleton is one of those patterns. There are hundreds of patterns, if you want to learn more about Design Patterns I suggest you this book:<br />
<a href="http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612" title="Design Pattern" target="_blank">http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612</a></p>
<p>OK, now about Singleton Pattern. It&#8217;s simple the concept of instantiate (allocate the necessary memory) for a class once and share this instance with all other classes/functions that need it, making at this form, a single point of access.</p>
<p>There are many discussion about the Singleton, many criticisms and many enthusiasm. In my humble opinion, the Singleton Pattern is very useful to control/manage some global data. Like the user account, for example, specially when some data need a special treatment, like user imagem data.</p>
<p>Anyway, my objective here is just to show you how to create a real Singleton class, using the minimum code as possible and make it thread-safe. Remember that in Objective-C multithreading is always something that we must be aware and think about.</p>
<p><br/></p>
<h2><strong>Coding the concept</strong></h2>
<p>In theory the code is very simple, instead of allocate and initialize the class, we just call a class method that returns the singleton instance. We can use this approach through all our application:</p>
<table width="675">
<tbody>
<tr>
<th>Simple singleton</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
// Inside a ClassA, for example.
MySingleton *foo = [MySingleton instance];
[foo setSomeValue:1];

// Inside a ClassB, for example.
MySingleton *foo = [MySingleton instance];
[foo someValue]; // gets the value that was set on ClassA.
</pre>
<p>It&#8217;s important to remember that a singleton class SHOULDN&#8217;T BE RELEASED! Using the Cocoa logic, when you call &#8220;instance&#8221; you are not allocating nor copying any memory, so you shouldn&#8217;t release it.</p>
<p>Well, but the memory must be allocated for someone, right? Yes, the memory will be allocated and controlled by the &#8220;instance&#8221; method. Let&#8217;s talk about the singleton lock.</p>
<p><br/></p>
<h2><strong>Singleton Lock</strong></h2>
<p>We create a kind of lock to make sure our instance will be initialized only once. Like this:</p>
<table width="675">
<tbody>
<tr>
<th>Singleton lock</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
+ (MySingleton *) instance
{
	// Persistent instance.
	static MySingleton *_default = nil;

	if (_default == nil)
	{
		_default = [[MySingleton alloc] init];
	}

	return _default;
}
</pre>
<p>This code will work for 99,9% of the time for ALL kind of languages. However, there is a rare kind of situation which this code will fail. We&#8217;re talking about the multithreading behavior where two threads try to access the singleton instance AND the singleton is not initialized yet.</p>
<div id="attachment_1481" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/12/singleton_lock.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/12/singleton_lock.jpg" alt="In a very rare situation, two threads can try to initialize a singleton at the same time." title="singleton_lock" width="600" height="600" class="size-full wp-image-1481" /></a><p class="wp-caption-text">In a very rare situation, two threads can try to initialize a singleton at the same time.</p></div>
<p>Notice that initializing a class is something very fast, could be done in one or two microseconds, however for a multithreading application, this could be time enough to cause a redundant instantiation. As the singleton, usually, is never deallocated, the double memory allocation will represent a leak.</p>
<p>To solve this problem, all that we need is to make sure our singleton lock be thread-safe, that means, only one thread can make the initialization process. At this point, with Objective-C we have many options, let&#8217;s see the best one.</p>
<p><br/></p>
<h2><strong>Thread Safe</strong></h2>
<p>The best and faster approach is using the GCD (Grand Central Dispatch). However the GCD is not available for all iOS versions, just for iOS 4 or later. So we must think in a solution that fits good for all. The &#8220;@synchronized&#8221; instruction is something that works for all iOS versions, it creates a kind of funnel/queue in which only one thread can run at a time.</p>
<p>The problem with &#8220;@synchronized&#8221; is that it&#8217;s very slow and could make threads run at a synchronized way. So, to avoid unnecessarily wasting time with the @synchronized, let&#8217;s create a way to make the things run faster after the singleton being initialized:</p>
<table width="675">
<tbody>
<tr>
<th>Thread safe</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
+ (MySingleton *) instance
{
	// Persistent instance.
	static MySingleton *_default = nil;

	// Small optimization to avoid wasting time after the
	// singleton being initialized.
	if (_default != nil)
	{
		return _default;
	}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
	// Allocates once with Grand Central Dispatch (GCD) routine.
	// It's thread safe.
	static dispatch_once_t safer;
	dispatch_once(&#038;safer, ^(void)
				  {
					  _default = [[MySingleton alloc] init];
					  // private initialization goes here.
				  });
#else
	// Allocates once using the old approach, it's slower.
	// It's thread safe.
	@synchronized([MySingleton class])
	{
		// The synchronized instruction will make sure,
		// that only one thread will access this point at a time.
		if (_default == nil)
		{
			_default = [[MySingleton alloc] init];
			// private initialization goes here.
		}
	}
#endif
	return _default;
}
@end
</pre>
<p>Notice that the &#8220;if (_default != nil)&#8221; is a single check, that runs very very fast and can avoid our code of spending time with unnecessary checks. About the GCD and blocks, it&#8217;s a simple piece of code that makes the same thing as the code without GCD. The only difference is that the GCD approach uses the special data type &#8220;dispatch_once_t&#8221; (a kind of BOOL) to check if the code have been executed before.</p>
<p>If you want more information about GCD and the blocks, here is it:<br />
<a href="http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" title="Blocks guide" target="_blank">http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html</a><br />
<a href="http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html" title="GCD reference" target="_blank">http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html</a><br />
<a href="http://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/_index.html" title="Blocks for beginners" target="_blank">http://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/_index.html</a></p>
<p><br/></p>
<h2><strong>Final adjustments</strong></h2>
<p>OK, we&#8217;re almost done. Now, just to make sure that any other class (including classes from Cocoa framework) will not change the retain count of our singleton class, we can override some methods:</p>
<table width="675">
<tbody>
<tr>
<th>Avoiding changes on memory count</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">
- (id) retain
{
	return self;
}

- (oneway void) release
{
	// Does nothing here.
}

- (id) autorelease
{
	return self;
}

- (NSUInteger) retainCount
{
    return INT32_MAX;
}
</pre>
<p>The dealloc method is not necessary, because the singleton will never be deallocated. But remember to release and retain the memory for internal variables, by the way this is why @property and @synthesize exist.</p>
<p><br/></p>
<h2><strong>Conclusion</strong></h2>
<p>Very well, my friends, that is all about Singleton Pattern for Obj-C. I hope you liked. Enjoy your singletons and feel free to ask anything you want.</p>
<p>Cya!</p>
<p><iframe scrolling="no" src="http://db-in.com/downloads/apple/tribute_to_jobs.html" width="100%" height="130px"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/12/objective-c-singleton/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>All about OpenGL ES 2.x – (part 3/3)</title>
		<link>http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/</link>
		<comments>http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/#comments</comments>
		<pubDate>Thu, 05 May 2011 18:01:35 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1369</guid>
		<description><![CDATA[A full tutorial about OpenGL ES 2.x to iPhone, iPad, iPod using Objective-C and Xcode.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/05/opengl_part3.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/opengl_part3.png" alt="" title="opengl_part3" width="300" height="352" class="alignright size-full wp-image-1417" /></a><br />
Here we are for the final part of this serie of tutorial!<br />
Welcome back, my friends.</p>
<p>Is time to dive in advanced knowledges about OpenGL and 3D world. In this tutorial we&#8217;ll see many things about the 2D graphics, multisampling, textures, render to off-screen surfaces and let&#8217;s try to optimize at maximum our applications&#8217; performance.</p>
<p>Is very important to you already know about all the concepts covered in the other 2 parts of this serie, if you miss something, here is a list:</p>
<p>This serie is composed by 3 parts:</p>
<ul>
<li><a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/" target="_blank">Part 1 &#8211; Basic concepts of 3D world and OpenGL (Beginners)</a></li>
<li><a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/" target="_blank">Part 2 &#8211; OpenGL ES 2.0 in-depth (Intermediate)</a></li>
<li>Part 3 &#8211; Jedi skills in OpenGL ES 2.0 and 2D graphics (Advanced)</li>
</ul>
<p><span id="more-1369"></span></p>
<p>At this time I imagine you know a lot of things about OpenGL and 3D world. You probably already created some applications using OpenGL, discovered many cool things, found some problems, even maybe your own engine/framework is under construction and I&#8217;m very glad in see you coming back.</p>
<p>As I&#8217;ve read once in a book: &#8220;One day you didn&#8217;t know to walk. Then you learned how to stand up and walk. Now is time to run, jump and swim!&#8221;&#8230; and why not &#8220;to fly&#8221;. With OpenGL our imagination has no limits, we can fly.</p>
<p>Let&#8217;s start.</p>
<p><a name="list_contents"></a><br />
Here is a little list of contents to orient your reading:</p>
<table width="675">
<tr>
<th colspan=2>List of Contents to this Tutorial</th>
</tr>
<tr>
<td valign="top">
<ul>
<li><a href="#2d_graphics">2D graphics with OpenGL</a></li>
<li><a href="#grid">The Grid Concept</a></li>
<li><a href="#depth_buffer_2d">The Depth Render Buffer in 2D</a></li>
<li><a href="#cameras_2d">The Cameras with 2D</a></li>
<li><a href="#multisampling">The Multisampling</a></li>
<li><a href="#more_texture">More About Textures</a>
<ul>
<li><a href="#bpp">Bytes per Pixel</a></li>
<li><a href="#pvrtc"> PVRTC</a></li>
</ul>
</li>
<li><a href="#tips_tricks">Tips and Tricks</a>
<ul>
<li><a href="#cache">The Cache</a></li>
<li><a href="#store_values"> Store the Values</a></li>
<li><a href="#c_fastest"> C is Always the Fastest Language</a></li>
</ul>
</li>
<li><a href="#conclusion"> Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p><br/><br />
<h2><strong>At a glance</strong></h2>
<p>Remembering everything until here:</p>
<ol>
<li>OpenGL’s logic is composed by just 3 simple concepts: Primitives, Buffers and Rasterize.</li>
<li>OpenGL ES 2.x works with programmable pipeline, which is synonymous of Shaders.</li>
<li>OpenGL isn&#8217;t aware of the output device, platform or output surface. To make the bridge between OpenGL&#8217;s core and our devices, we must use EGL (or EAGL in iOS).</li>
<li>The textures are crucial and should have a specific pixel format and order to fit within OpenGL.</li>
<li>We start the render process by calling <strong>glDraw*</strong>. The first steps will pass through the Vertex Shader, several checks will conclude if the processed vertex could enter in the Fragment Shader.</li>
<li>The original structure of our meshes should never change. We just create transformations matrices to produce the desired results.</li>
</ol>
<p>First I&#8217;ll talk about 2D graphics, then let&#8217;s see what is the multisampling/antialias filter, personally I don&#8217;t like the cost x benefit of this kind of technique. Many times an application could run nicely without multisampling, but a simple multisampling filter can completely destroy the performance of that application. Anyway, sometimes, it&#8217;s really necessary to make temporary multisampling to produce smooth images.</p>
<p>Later I&#8217;ll talk about textures in deep and its optimization 2 bytes per pixel data format. Also let&#8217;s see PVRTC and how to place it in an OpenGL&#8217;s texture, besides render to an off-screen surface.</p>
<p>And finally I&#8217;ll talk a briefly about some performances gains that I discovered by my self. Some tips and tricks which really help me a lot today and I want to share this with you.</p>
<p>Let&#8217;s go!</p>
<p><br/><a name="2d_graphics"></a></p>
<h2><strong>2D graphics with OpenGL</strong></h2>
<p><a href="#list_contents">top</a><br />
Using 2D graphics with OpenGL is not necessary limited to the use of lines or points primitives. The three primitives (triangles, lines and points) are good to use with 3D and 2D. The first thing about 2D graphics is the Z depth. All our work becomes two dimensions, excluding the Z axis to translations and scales and also excluding X and Y to rotations. It implies that we don&#8217;t need to use the Depth Render Buffer anymore, because everything we draw will be made on the same Z position (usually the 0.0).</p>
<p>A question comes up: &#8220;So how the OpenGL will know which object should be drawn on the front (or top) of the other ones?&#8221; It&#8217;s very simple, by drawing the objects in the order that we want (objects at the background should be drawn first). OpenGL also offers a feature called Polygon Offset, but it&#8217;s more like an adjustment than a real ordering.</p>
<p>OK, now we can think in 2D graphics at three ways:</p>
<ol>
<li>Many squares on the same Z position.</li>
<li>Many points on the same Z position.</li>
<li>All above.</li>
</ol>
<div id="attachment_1372" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/2d_orthographic_example.jpg"><img class="size-full wp-image-1372" title="2d_orthographic_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/2d_orthographic_example.jpg" alt="This is how a 2D graphics looks like for OpenGL using squares." width="600" height="497" /></a><p class="wp-caption-text">This is how a 2D graphics looks like for OpenGL.</p></div>
<div id="attachment_1373" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/2d_scene_example.jpg"><img class="size-full wp-image-1373" title="2d_scene_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/2d_scene_example.jpg" alt="How a 2D scene will appear on the screen." width="600" height="497" /></a><p class="wp-caption-text">How a 2D scene will appear on the screen.</p></div>
<p>You could imagine how easy it&#8217;s to OpenGL, a state machine prepared to work with millions of triangles, to deal with those few triangles. In extreme situations, 2D graphics  works with hundreds of triangles.</p>
<p>With simple words, everything will be textures. So most of our work with 2D will be on the textures. Many people feel compelled to create an API to work with texture Non-POT, that means, work with texture of dimensions like 36 x 18, 51 x 39, etc. My advice here is: &#8220;Don&#8217;t do that!&#8221;. It&#8217;s not a good idea to work with 2D graphics using Non-POT textures. As you&#8217;ve seen in the last image above, it&#8217;s always a good idea work with a imaginary grid, which should be POT, a good choice could be 16&#215;16 or 32&#215;32.</p>
<p>If you are planing to use PVRTC compressed image files, could be good to use a grid of 8&#215;8, because PVRTC minimum size is 8. I don&#8217;t advice make grids less than 8&#215;8, because it&#8217;s unnecessary precise and could increase your work developing, also it compromise your application&#8217;s performance. Grids with 8&#215;8 size are very precise, we&#8217;ll see soon the diferences between the grids and when and how to use them. Let&#8217;s talk a little bit more about the grid.</p>
<p><br/><a name="grid"></a></p>
<h2><strong>The Grid Concept</strong></h2>
<p><a href="#list_contents">top</a><br />
I think this is the most important part in the planing of a 2D application. In a 3D game, for example, to determine where a character can walk we must create a collision detector. This detector could be a box (bounding box) or a mesh (bounding mesh, a simple copy from the original). In both cases, the calculations are very important and expensive. But in a 2D application it&#8217;s very very easy to find the collisions areas if you are using a grid, because you have only a square area using X and Y coordinates!</p>
<p>This is just one reason because the grid is so important. I know you can come up with many other advantages of the grid, like the organization, the precision on the calculations, the precision of the objects on the screen, etc. About 10 year ago (or maybe more) I worked with a tiny program to produce RPG games with 2D graphics. The idea of grid was very well stablished there. The following images show how everything can be fitted into the grid:</p>
<div id="attachment_1374" class="wp-caption alignleft" style="width: 310px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example1.jpg"><img class="size-medium wp-image-1374" title="rpg_maker_example1" src="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example1-300x227.jpg" alt="Grid in the RPG Maker. (click to enlarge)" width="300" height="227" /></a><p class="wp-caption-text">Grid in the RPG Maker. (click to enlarge)</p></div>
<p>I know, I know&#8230; it&#8217;s the &#8220;Fuckwindons&#8221; system, sorry for that&#8230; as I told you, it was a decade ago&#8230; OK, let&#8217;s understand the important features about the grid. You can click on the side image to enlarge it. The first thing I want you notice is the about the overlap of the images. Notice that the left side of the window is reserved to a kind of library. At the top of this library you can see little square images (32&#215;32 in this case). Those squares are reserved to the floor of the scenario (in our OpenGL language, it would be the background). The other images in that library are transparent images (PNG) wich can be placed on top of the floor squares. You can see this difference looking at the big trees placed on the grid.</p>
<p>Now find the &#8220;hero&#8221; on the grid. He&#8217;s at the right side near a tree, it shows a little face with redhead inside a box. This is the second important point about the grid. That hero doesn&#8217;t occupies only one little square on the grid, he could be bigger, but to the grid, the action delimitator represents only one square. Confused? Well, it&#8217;s always a good idea to use only one grid&#8217;s square to deal with the actions, because it let your code much more organized than other approaches. To create areas of actions you can duplicate the action square, just like the exit of the the village on the right top area of the grid in this side image.</p>
<p>I&#8217;m sure you can imagine how easy is to create a control class to deal with the actions in your 2D application and then create view classes referencing the control classes, so you can prepare the view classes to get the collision detection on many squares on the grid. So you have 1 action &#8211; N grid squares detectors. At this way you can take all advantages of the grid and also an incredible boost in your application&#8217;s performance.</p>
<p>By using the grid you can easy define the collision areas which are impossible to the character pass through, like the walls. Another great advantage of using the grid is define &#8220;top areas&#8221;, that means, areas which always will be drawn on top, like the up side of the trees. So if the character pass through these areas, he will be displayed behind.</p>
<p>The following image shows a final scene which uses all these concepts of the grid. Notice how many images can be overlapped by others, pay attention of how the character deals with the action square and its own top areas. And notice the most top effects overlapping everything, like the clouds shadows or the yellow light coming from the sun.</p>
<div id="attachment_1375" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example2.jpg"><img class="size-full wp-image-1375" title="rpg_maker_example2" src="http://db-in.com/blog/wp-content/uploads/2011/04/rpg_maker_example2.jpg" alt="RPG Maker final scene." width="600" height="450" /></a><p class="wp-caption-text">RPG Maker final scene.</p></div>
<p>Summarizing the points taken, the grid is really the most important part of planning a 2D application. The grid is not a real thing in OpenGL, so you have to be careful about using this concept, because everything will be imaginary. Well, just to let you know, an extra information: the grid concept is so important that the OpenGL internally works with a grid concept to construct the Fragments.</p>
<p>Great, this is everything about the grid. Now you would say: &#8220;OK, but this is not what I wanted, I want a game with a projection like Diablo, Sin City or even the We Rule does!&#8221;. Oh right, so let&#8217;s make things more complex and bring back the Depth Render Buffer and Cameras to our 2D application.</p>
<p><br/><a name="depth_buffer_2d"></a></p>
<h2><strong>The Depth Render Buffer in 2D</strong></h2>
<p><a href="#list_contents">top</a><br />
Knowing how the 2D graphics goes with OpenGL, we can think in more refined approach, like use the Depth Buffer even in 2D applications.</p>
<div id="attachment_1376" class="wp-caption alignleft" style="width: 320px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/grid_depth_example.jpg"><img class="size-medium wp-image-1376" title="grid_depth_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/grid_depth_example-300x200.jpg" alt="&quot;2D game&quot; using OpenGL with Depth Render Buffer. (click to enlarge)" width="310" height="205" /></a><p class="wp-caption-text">&quot;2D game&quot; using OpenGL with Depth Render Buffer. (click to enlarge)</p></div>
<div id="attachment_1377" class="wp-caption alignright" style="width: 320px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/grid_normal_example.jpg"><img class="size-medium wp-image-1377" title="grid_normal_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/grid_normal_example-300x200.jpg" alt="&quot;2D game&quot; using OpenGL without Depth Render Buffer. (click to enlarge)" width="310" height="205" /></a><p class="wp-caption-text">&quot;2D game&quot; using OpenGL without Depth Render Buffer. (click to enlarge)</p></div>
<p>By clicking on the images above, you can notice the difference between them. Both screenshot are from famous games from iOS, both use OpenGL and both are known as 2D games. Although they use OpenGL ES 1.1, we can understand the concept of Grid + Depth Render Buffer. The game on the left (<em>Gun Bros</em>) makes use of a very small grid, exactly 8&#215;8 pixels, this kind of grid gives to the game a incredible precision to place the objects on the grid, but to improve the user experience you need to make a set of grid squares to deal with the actions, in this case a good choice could be arranging 4 ou 8 grid squares to each action detector. Now the game on the right, it&#8217;s called <em>Inotia</em>, by the way, Inotia is today in its 3th edition. Since the first edition, Inotia always used a big grid, 32&#215;32 pixels. As Gun Bros, Inotia uses OpenGL ES 1.1.</p>
<p>There are many differences between those two grid types (8&#215;8 and 32&#215;32). The first one (8&#215;8) is much more precisely and could seem to be the best choice, but remember that this choice will increase too much your processing. The Inotia game has a light processing demand, something absolutely unimpressive to the iOS&#8217; hardwares. You need to make the best choice to fit within the application you are planning to use.</p>
<p>Now, talking about the Depth Render Buffer, the great thing about it is that you can use 3D models in your application. Look, without Depth Render Buffer you must use only squares, or another primitive geometric form, with textures. By doing this you must create one different texture to each position of your animation, specially to characters animation, obviously a great idea is make use of texture atlas:</p>
<div id="attachment_1378" class="wp-caption alignleft" style="width: 179px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/texture_atlas_example.png"><img class="size-medium wp-image-1378" title="texture_atlas_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/texture_atlas_example-169x300.png" alt="Character texture atlas from Ragnarok." width="169" height="300" /></a><p class="wp-caption-text">Character texture atlas from Ragnarok.</p></div>
<p>The image of Inotia game above has a similar texture altas to each character that appear in the game. Looking at that image you can see that the three character on the screen can turn just to four directions. Now, take another look to the Gun Bros image above.</p>
<p>Notice that the characters can turn to all directions. Why? Well, by using a Depth Render Buffer you are free to use 3D models in your 2D application. So you can rotate, scale and translate the 3D models respecting the grid and the 2D concepts (no Z translate). The result is much much better, but as any improvements, it has a great cost for performance compared to 2D squares, of couse.</p>
<p>But there is another important thing about mixing 3D and 2D concepts: the use of cameras. Instead of creating a single plane right in front of the screen, locking the Z translations, you can create a great plane along the Z axis, place your objects just as in a 3D application and create a camera with orthographic projection. You remember what it is and how to do it, right? (<a href="http://db-in.com/blog/2011/04/cameras-on-opengl-es-2-x/#projections" target="_blank">click here to check the article about cameras</a>).</p>
<p>Before going further into the cameras and Depth Render Buffer with 2D graphics, it&#8217;s important to know that at this point it has no real difference, at the code level, between 2D and 3D graphics since everything comes from your own planning and organization. So the code to use the Depth buffer is the same we saw in the last part (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/#render_buffers" target="_blank">click here to see the last tutorial</a>).</p>
<p>Now let&#8217;s talk about the cameras with 2D graphics.</p>
<p><br/><a name="cameras_2d"></a></p>
<h2><strong>The Cameras with 2D</strong></h2>
<p><a href="#list_contents">top</a><br />
OK, I&#8217;m sure you know how to create a camera and an orthographic projection now, as you&#8217;ve seen it at the tutorial about cameras, right? (<a href="http://db-in.com/blog/2011/04/cameras-on-opengl-es-2-x/#projections" target="_blank">click here to check the cameras tutorial</a>). Now a question comes up: &#8220;Where is the best place and approach to use cameras and depth render buffer in the 2D graphics?&#8221;. The following image could help more than 1.000 words:</p>
<div id="attachment_1379" class="wp-caption alignright" style="width: 310px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_projection_example.jpg"><img class="size-medium wp-image-1379" title="cameras_projection_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_projection_example-300x240.jpg" alt="Same camera in both projections. (click to enlarge)" width="300" height="240" /></a><p class="wp-caption-text">Same camera in both projections. (click to enlarge)</p></div>
<p>This image shows a scene like Diablo Game style, with a camera in the similar position. You can notice clearly the difference between both projections. Notice the red lines across the picture, with the Orthographic projection those lines are parallels, but with the Perspective projection those lines are not really parallels and can touch at the infinity.</p>
<p>Now focus on the grey scale picture at the bottom right. That is the scene with the objects. As you can see, they are really 3D objects, but with an orthographic projection you can create scenes like Diablo, Sim City, Starcraft and other best sellers, giving a 2D look to your 3D application.</p>
<p>If you take another look at that image of Gun Bros game, you can see that it&#8217;s exactly what they do, there is a camera with orthographic projection and real 3D objects placed on the scene.</p>
<p>So the best approach is to create a camera in your desired position, construct all your scene in a 3D world, set the camera to use orthographic projection and guide your space changes by using the grid concept.</p>
<div id="attachment_1380" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_grid_example.jpg"><img class="size-full wp-image-1380" title="cameras_grid_example" src="http://db-in.com/blog/wp-content/uploads/2011/04/cameras_grid_example.jpg" alt="The grid concept is very important even with cameras and Depth Render Buffer." width="600" height="447" /></a><p class="wp-caption-text">The grid concept is very important even with cameras and Depth Render Buffer.</p></div>
<p>I have one last advice about this subject, well&#8230; it&#8217;s not really an advice, it&#8217;s more like a warning. Perspective and Orthographic projections are completely different. So the same configuration of focal point, angle of view, near and far produces completely different results. So you need to find a configuration to the Orthographic projection different of that you were using with Perspective projection. Probably if you have a perspective projection which is working, when you change to orthographic projection you won&#8217;t see anything. This is not a bug, it&#8217;s just the differences between perspective and orthographic calculations.</p>
<p>OK, these are the most important concepts about 2D graphics with OpenGL. Let&#8217;s make a little review of them.</p>
<ul>
<li>There are two ways of using 2D graphics with OpenGL: by using or not the Depth Render Buffer.</li>
<li>Without Depth Render Buffer you can construct everything like a rectangle on the screen, forget the Z axis position at this way. Your job here will be laborious on textures. Although, by this way, you can have the best performance with OpenGL.</li>
<li>By using the Depth Render Buffer you can use real 3D objects and probably you will want to use a camera with orthographic projection.</li>
<li>Independent of the way you choose, always use the Grid concept when working on 2D graphics. It&#8217;s the best way to organize your world and optimize your application performance.</li>
</ul>
<p>Now is time to go back into the 3D world and talk a little about the multisampling and antialias filter.</p>
<p><br/><a name="multisampling"></a></p>
<h2><strong>The Multisampling</strong></h2>
<p><a href="#list_contents">top</a><br />
I&#8217;m sure you already noticed that every 3D application, which have a real time render, have their objects&#8217; edges aliased. I&#8217;m talking about 3D world in general, like 3D softwares or games, whatever&#8230; the edges always (I mean, in majority of the cases) looks like it&#8217;s kind aliased. That doesn&#8217;t happen due a lack of well developed techniques to fit that but rather it&#8217;s because our hardwares are not so powerful yet to deal with pixel blend in real time too fast.</p>
<p>So, the first thing I want to say about the Anti-Alias filter is: &#8220;it&#8217;s expensive!&#8221;. In the majority of cases this little problem (aliased edges) doesn&#8217;t matter. But there are some situations that your 3D application needs to looks better. The most simple and common example is the render in 3D softwares. When we hit the render button on our 3D software we expect to see gorgeous images, not jagged edges.</p>
<p>With simple words, the OpenGL primitives get rasterized onto a grid (yes, like our grid concept), and their edges may become deformed. OpenGL ES 2.0 supports something called <em>multisampling</em>. It&#8217;s a technique of Anti-Alias filter which each pixel is divided into few samples, each of these samples are treated like a mini-pixel in the rasterization process. Each sample has its own information about color, depth and stencil. When you ask the OpenGL for the final image on the Frame Buffer, it will resolve and mix all the samples. This process produces more smooth edges. OpenGL ES 2.0 is always configured to multisampling technique, even if the number of samples is equal 1, that means 1 pixel = 1 sample. Looks very simple in theory, but remember that OpenGL doesn&#8217;t know anything about the device&#8217;s surface, consequently, anything about device&#8217;s pixel and color.</p>
<p>The bridge between OpenGL and the device is made by the EGL. So the device color informations, pixel informations and surface informations are responsibility of EGL and consequentially the multisampling could not be implemented only by the OpenGL, it needs a plugin, which is responsibility of the vendors. Each vendors must create a plugin to EGL instructing about the necessary information, by doing this the OpenGL can really resolve the multi samples. The default EGL API offers a multisampling configuration, but commonly the vendors make some changes on it.</p>
<p>In the case of Apple, this plugin is called &#8220;Multisample APPLE&#8221; and it&#8217;s located at the OpenGL Extensions Header (glext.h). To correctly implement the Apple Multisample you need 2 Frame Buffer and 4 Render Buffer! 1 Frame Buffer is the normal provided by OpenGL, the another one is the Multisample Framebuffer. The Render Buffers are Color and Depth.</p>
<p>There are three new functions in the glext.h to deal with Multisample APPLE:</p>
<table width="675">
<tr>
<th>Multisample APPLE</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glRenderbufferStorageMultisampleAPPLE(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: The target always will be <strong>GL_RENDERBUFFER</strong>, this is just an internal convention for OpenGL.</li>
<li><strong>samples</strong>: This is the number of samples which the Multisample filter will make.</li>
<li><strong>internalformat</strong>: This specifies what kind of render buffer we want and what color format this temporary image will use. This parameter can be:
<ul>
<li><strong>GL_RGBA4</strong>, <strong>GL_RGB5_A1</strong>, <strong>GL_RGB56</strong>, <strong>GL_RGB8_OES</strong> or <strong>GL_RGBA8_OES</strong> to a render buffer with final colors.</li>
<li><strong>GL_DEPTH_COMPONENT16</strong> or <strong>GL_DEPTH_COMPONENT24_OES</strong> to a render buffer with Z depth.</li>
</ul>
</li>
<li><strong>width</strong>: The final width of a render buffer.</li>
<li><strong>height</strong>: The final height of a render buffer.</li>
</ul>
</td>
</tr>
<tr>
<td>
<h5><strong>GLvoid glResolveMultisampleFramebufferAPPLE(void)</strong></h5>
<p><br/></p>
<ul>
<li>This function doesn&#8217;t need any parameter. This function will just resolve the last two frame buffer bound to <strong>GL_DRAW_FRAMEBUFFER_APPLE</strong> and <strong>GL_READ_FRAMEBUFFER_APPLE</strong>, respectively.</li>
</ul>
</td>
</tr>
<tr>
<td>
<h5><strong>GLvoid glDiscardFramebufferEXT(GLenum target, GLsizei numAttachments, const GLenum *attachments)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: Usually the target will be <strong>GL_READ_FRAMEBUFFER_APPLE</strong>.</li>
<li><strong>numAttachments</strong>: The number of Render Buffer attachments to discard in the target Frame Buffer. Usually this will be 2, to discard the Color and Depth Render Buffers.</li>
<li><strong>attachments</strong>: A pointer to an array containing the type of Render Buffer to discard. Usually that array will be <strong>{GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT}</strong>.</li>
</ul>
</td>
</tr>
</table>
<p>Before checking the code, let&#8217;s understand a little bit more about these new functions. The first function (<strong>glRenderbufferStorageMultisampleAPPLE</strong>) is intended to replace that function that set the properties to the Render Buffer, the <strong>glRenderbufferStorage</strong>. The big new in this function is the number of samples, it will define how many samples each pixel will has.</p>
<p>The second one (<strong>glResolveMultisampleFramebufferAPPLE</strong>) is used to take the informations from the original frame buffer, place it in the Multisample Frame Buffer, resolve the samples of each pixel and then draw the resulting image to our original Frame Buffer again. In simple words, this is the core of Multisample APPLE, this is the function which makes all the job.</p>
<p>The last one (<strong>glDiscardFramebufferEXT</strong>) is another clearing function. As you imagine, after the <strong>glResolveMultisampleFramebufferAPPLE</strong> makes all the processing, the Multisample Frame Buffer will be with many informations in it, so it&#8217;s time to clear all that memory. To do that, we call the <strong>glDiscardFramebufferEXT</strong> informing what we want to clear from where.</p>
<p>Now, here is the full code to use Multisample APPLE:</p>
<table width="675">
<tbody>
<tr>
<th>Multisample Framebuffer APPLE</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// EAGL
// Assume that _eaglLayer is a CAEAGLLayer data type and was already defined.
// Assume that _context is an EAGLContext data type and was already defined.

// Dimensions
int _width, _height;

// Normal Buffers
GLuint _frameBuffer, _colorBuffer, _depthBuffer;

// Multisample Buffers
GLuint _msaaFrameBuffer, _msaaColorBuffer, _msaaDepthBuffer;
int _sample = 4; // This represents the number of samples.

// Normal Frame Buffer
glGenFramebuffers(1, &amp;_frameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);

// Normal Color Render Buffer
glGenRenderbuffers(1, &amp;_colorBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _colorBuffer);
[_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _colorBuffer);

// Retrieves the width and height to the EAGL Layer, just necessary if the width and height was not informed.
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &amp; _width);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &amp; _height);

// Normal Depth Render Buffer
glGenRenderbuffers(1, &amp;_depthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _depthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, _width, _height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthBuffer);
glEnable(GL_DEPTH_TEST);

// Multisample Frame Buffer
glGenFramebuffers(1, &amp;_msaaFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFrameBuffer);

// Multisample  Color Render Buffer
glGenRenderbuffers(1, &amp;_msaaColorBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _msaaColorBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, _samples, GL_RGBA8_OES, _width, _height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _msaaColorBuffer);

// Multisample Depth Render Buffer
glGenRenderbuffers(1, &amp;_msaaDepthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, _msaaDepthBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, _samples, GL_DEPTH_COMPONENT16, _width, _height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _msaaDepthBuffer);
.</pre>
<p>Yes, many lines to a basic configuration. Once all those 6 buffers have been defined, we also need to make the render by a different approach. Here is the necessary code:</p>
<table width="675">
<tbody>
<tr>
<th>Rendering with Multisample APPLE</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
//-------------------------
//	Pre-Render
//-------------------------
// Clears normal Frame Buffer
glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Clears multisample Frame Buffer
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFrameBuffer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//-------------------------
//	Drawing
//-------------------------
//...
// Draw all your content.
//...

//-------------------------
//	Render
//-------------------------
// Resolving Multisample Frame Buffer.
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, _frameBuffer);
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, _msaaFrameBuffer);
glResolveMultisampleFramebufferAPPLE();

// Apple (and the khronos group) encourages you to discard
// render buffer contents whenever is possible.
GLenum attachments[] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT};
glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments);

// Presents the final result at the screen.
glBindRenderbuffer(GL_RENDERBUFFER, _colorBuffer);
[_context presentRenderbuffer:GL_RENDERBUFFER];
.</pre>
<p>If you want to remember something about the EAGL (the EGL implementation by Apple), check it here: <a href="http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/" target="_blank">article about EGL and EAGL</a>. OpenGL also offers some configurations to multisampling, <strong>glSampleCoverage</strong> and few configurations with <strong>glEnable</strong>. I&#8217;ll not talk in deep about these configurations here, because I don&#8217;t believe multisampling is a good thing to spend our time on. As I told you, the result is not a big deal, it&#8217;s just a little bit more refined. In my opinion, the performance cost is too much compared to the final result:</p>
<div id="attachment_1392" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/multisample_result_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/multisample_result_example.jpg" alt="Same 3D model rendered without and with Anti-Alias filter." title="multisample_result_example" width="600" height="470" class="size-full wp-image-1392" /></a><p class="wp-caption-text">Same 3D model rendered without and with Anti-Alias filter.</p></div>
<p>OK, now it&#8217;s time to talk more about the textures in OpenGL.</p>
<p><br/><a name="more_texture"></a></p>
<h2><strong>More About Textures</strong></h2>
<p><a href="#list_contents">top</a><br />
We already know many things about textures from the second part of this serie (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/#textures" target="_blank">All About OpenGL ES 2.x &#8211; Textures</a>).  First, let&#8217;s talk about the optimized types. It&#8217;s a great boost on our application&#8217;s performance and is very easy to implement. I&#8217;m talking about the bytes per pixel of our images.</p>
<p><br/><a name="bpp"></a></p>
<h2>Bytes per Pixel</h2>
<p><a href="#list_contents">top</a><br />
Usually the images has 4 bytes per pixel, one byte for each channel, RGBA. Some images without alpha, like JPG file format, has only 3 bytes per pixel (RGB). Each byte could be represented by an hexadecimal color in the format 0xFF, it&#8217;s called hexadecimal because each decimal house has the range 0 &#8211; F (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F), so when you make a combination of two hexadecimal numbers you get one byte (16 x 16 = 256). As a convention, we describe a hexadecimal color as 0xFFFFFF, where each set of two number represent one color channel (RGB). For images with alpha channel, like PNG format, we are used to say 0xFFFFFF + 0xFF, that means (RGB + A).</p>
<p>My next article will be about binary programming, so I&#8217;ll not talk in deep about binaries here. All that we need for now is to know that 1 byte = 1 color channel. The OpenGL can also work with more compressed format, which uses only 2 bytes per pixel. What that means? It means that each byte will store two color channels, including alpha. In very simple words, let&#8217;s reduce the color&#8217;s range of the image.</p>
<p>The OpenGL offers to us 3 compressed data types: <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong>, <strong>GL_UNSIGNED_SHORT_5_5_5_1</strong>, <strong>GL_UNSIGNED_SHORT_5_6_5</strong>. The first two should be used when you have alpha channel and the last one it&#8217;s only for situations without alpha. These 3 names tell us something about the pixel data. The numbers at the right instruct us about the number of bits (not bytes) that must be used in each channel (RGBA). Oh, and just to make it clear, each byte is composed by 8 bits. So in the first case 4 bits per channel with a total of 2 bytes per pixel. The second one, 5 bits to RGB channels and 1 bit to alpha with a total of 2 bytes per pixel. And the last one, 5 bits to R, 6 bits to G and 5 bits to B with a total of 2 bytes per pixel.</p>
<p>Here I want to make a warning: The type <strong>GL_UNSIGNED_SHORT_5_5_5_1</strong> is not really useful, because only 1 bit to alpha is the same as give it a Boolean data type, I mean, 1 bit to alpha means visible YES or NOT, just it. So this type is not really useful, it has less bits on Green channel than <strong>GL_UNSIGNED_SHORT_5_6_5</strong> and even can&#8217;t produce real transparent effects like <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong>. So if you need the alpha channel, make use of <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong>, if not, make use of <strong>GL_UNSIGNED_SHORT_5_6_5</strong>.</p>
<p>A little thing to know about the <strong>GL_UNSIGNED_SHORT_5_6_5</strong>. As the human eye has more sensibility to the green colors, the channel with more bits is exactly the Green channel. At this way, even with a less color range, the resulting image to the final user will not seem to be that different.</p>
<p>Now let&#8217;s take a look at the difference between both compressions.<br />
<div id="attachment_1393" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/texture_compression_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/texture_compression_example.jpg" alt="OpenGL optimized 2 bytes per pixel (bpp) data types." title="texture_compression_example" width="600" height="470" class="size-full wp-image-1393" /></a><p class="wp-caption-text">OpenGL optimized 2 bytes per pixel (bpp) data types.</p></div></p>
<p>As you saw, by using <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> could really be ugly in some situations. But the <strong>GL_UNSIGNED_SHORT_5_6_5</strong> looks very nice. Why? I&#8217;ll explain in details at the next article about binaries, but in very simple words, by using <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> we have only 16 tonalities for each channel, including 16 tonalities to alpha. But with <strong>GL_UNSIGNED_SHORT_5_6_5</strong> we have 32 tonalities to Red and Blue and 96 tonalities of Green spectrum. It still far from the human eye&#8217;s capacity, but remember that by using these optimizations we reduce 2 bytes per pixel in all our images, this represents much more performance to our renders.</p>
<p>Now it&#8217;s time to learn how to convert our traditional images to these formats. Normally, when you extract the binary informations from an image you get it pixel by pixel, so probably each pixel will be composed by an &#8220;unsigned int&#8221; data type, which has 4 bytes. Each programming language provides a method(s) to extract the binary information from the pixels. Once you have your array of pixel data (array of unsigned int) you can use the following code to convert that data to the <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> or <strong>GL_UNSIGNED_SHORT_5_6_5</strong>.</p>
<table width="675">
<tbody>
<tr>
<th>Converting 4bpp to 2bpp</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
typedef enum
{
	ColorFormatRGB565,
	ColorFormatRGBA4444,
} ColorFormat;

static void optimizePixelData(ColorFormat color, int pixelDataLength, void *pixelData)
{
	int i;
	int length = pixelDataLength;

	void *newData;

	// Pointer to pixel information of 32 bits (R8 + G8 + B8 + A8).
	// 4 bytes per pixel.
	unsigned int *inPixel32;

	// Pointer to new pixel information of 16 bits (R5 + G6 + B5)
	// or (R4 + G4 + B4 + A4).
	// 2 bytes per pixel.
	unsigned short *outPixel16;

	newData = malloc(length * sizeof(unsigned short));
	inPixel32 = (unsigned int *)pixelData;
	outPixel16 = (unsigned short *)newData;

	if(color == ColorFormatRGB565)
	{
		// Using pointer arithmetic, move the pointer over the original data.
		for(i = 0; i < length; ++i, ++inPixel32)
		{
			// Makes the convertion, ignoring the alpha channel, as following:
			// 1 -	Isolates the Red channel, discards 3 bits (8 - 3), then pushes to the final position.
			// 2 -	Isolates the Green channel, discards 2 bits (8 - 2), then pushes to the final position.
			// 3 -	Isolates the Blue channel, discards 3 bits (8 - 3), then pushes to the final position.
			*outPixel16++ = (((( *inPixel32 >> 0 ) &#038; 0xFF ) >> 3 ) << 11 ) |
							(((( *inPixel32 >> 8 ) &#038; 0xFF ) >> 2 ) << 5 ) |
							(((( *inPixel32 >> 16 ) &#038; 0xFF ) >> 3 ) << 0 );
		}
	}
	else if(color == ColorFormatRGBA4444)
	{
		// Using pointer arithmetic, move the pointer over the original data.
		for(i = 0; i < length; ++i, ++inPixel32)
		{
			// Makes the convertion, as following:
			// 1 -	Isolates the Red channel, discards 4 bits (8 - 4), then pushes to the final position.
			// 2 -	Isolates the Green channel, discards 4 bits (8 - 4), then pushes to the final position.
			// 3 -	Isolates the Blue channel, discards 4 bits (8 - 4), then pushes to the final position.
			// 4 -	Isolates the Alpha channel, discards 4 bits (8 - 4), then pushes to the final position.
			*outPixel16++ = (((( *inPixel32 >> 0 ) &#038; 0xFF ) >> 4 ) << 12 ) |
							(((( *inPixel32 >> 8 ) &#038; 0xFF ) >> 4 ) << 8 ) |
							(((( *inPixel32 >> 16 ) &#038; 0xFF ) >> 4 ) << 4 ) |
							(((( *inPixel32 >> 24 ) &#038; 0xFF ) >> 4 ) << 0 );
		}
	}

	free(pixelData);

	pixelData = newData;
}
.</pre>
<p>The routine above assumes the channel order as RGBA. Although is not common, your image could have the pixels composed by another channel order, like ARGB or BGR. In these cases you must change the routine above or change the channel order at when extracting binary informations from each pixel. Another important thing is about the binary order. I don't want to confuse your mind if you don't know too much about binaries, but just as an advice: you probably will get the pixel data in little endian format, the traditional, but if your programming language get the binary informations as a big endian, the above routine will not work properly, so make sure your pixel data is in little endian format.</p>
<p><br/><a name="pvrtc"></a></p>
<h2>PVRTC</h2>
<p><a href="#list_contents">top</a><br />
I sure you've heard about the texture compression format PVRTC, if you already feel confortable about this topic, just skip to the next one. PVRTC is a binary format created by "<a href="http://www.imgtec.com/" target="_blank">Imagination Technology</a>", also called "<em>Imgtec</em>". This format uses the channel order as ARGB instead the traditional RGBA. To say the truth, its optimization is not about the file's size, if we look only to the size, any JPG is more compressed or even a PNG can be lighter. The PVRTC is optimized about its processing, its pixels can be already in the format 2 bytes per pixel (2bpp) or 4 bytes per pixel (4bpp). The data  inside PVRTC is OpenGL friendly and also can store Mipmap levels. So, could it be a good idea to always make use of PVRTC? Well, not exactly... let's see why.</p>
<p>The PVRTC format is not supported by default in OpenGL ES 2.0, there are informations that OpenGL ES 2.1 will come with native support to PVRTC textures, but what we have for now is just the OpenGL ES 2.0. To use PVRTC on it, just as the Multisampling, you need a vendors plug-in. In the case of Apple, this plugin has four new constant values. OpenGL provides a function to upload pixel data from the compressed formats, like PVRTC:</p>
<table width="675">
<tr>
<th>Uploading PVRTC</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: The target always will be GL_TEXTURE_2D, this is just an internal convention for OpenGL.</li>
<li><strong>level</strong>: The number of Mipmap levels in the file.</li>
<li><strong>internalformat</strong>: The format of the PVRTC. This parameter can be:
<ul>
<li><strong>GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG</strong>: Files using the 4bpp without the alpha channel.</li>
<li><strong>GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG</strong>: Files using 4bpp and the alpha channel.</li>
<li><strong>GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</strong>: Files using 2bpp without the alpha channel.</li>
<li><strong>GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</strong>: Files using 2bpp and the alpha channel.</li>
</ul>
</li>
<li><strong>width</strong>: The width of the image.</li>
<li><strong>height</strong>: The height of the image.</li>
<li><strong>border</strong>: This parameter is ignored in OpenGL ES. Always use the value 0. This is just an internal constant to conserve the compatibly with the desktop versions.</li>
<li><strong>imageSize</strong>: The number of the bytes in the binary data.</li>
<li><strong>data</strong>: The binary data for the image.</li>
</td>
</tr>
</table>
<p>As you can imagine, the data format <strong>GL_UNSIGNED_SHORT_4_4_4_4</strong> or <strong>GL_UNSIGNED_SHORT_5_6_5</strong> is chosen based on the file format, RGB or RGBA with 2bpp or 4bpp, depends on.</p>
<p>To generate the PVRTC you have many options. The two most common is the Imgtec Tools or the Apple's Texture Tool. Here you can find the <a href="http://www.imgtec.com/powervr/insider/powervr-utilities.asp" target="_blank">Imgtec Tools</a>.  The Apple tool comes with iPhone SDK, it's located at the path "<em><Xcode Folder>/iPhoneOS.platform/Developer/usr/bin</em>" the name is "<em>texturetool</em>", you can find all informations about it at <a href="http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/TextureTool/TextureTool.html" target="_blank">Apple Texture Tool</a>.</p>
<p>I'll explain how to use the Apple tool here. Follow these steps:</p>
<ul>
<li>Open the Terminal.app (usually it is in /Applications/Utilities/Terminal.app)</li>
<li>Click on <strong>texturetool</strong> in Finder and drag &#038; drop it on Terminal window. Well, you also can write the full path "<em><Xcode Folder>/iPhoneOS.platform/Developer/usr/bin/texturetool</em>", I preffer drag &#038; drop.</li>
<li>Write in front of texture tool path: " -e PVRTC --channel-weighting-linear --bits-per-pixel-2 -o "</li>
<li>Now you should write the output path, again, I prefer drag &#038; drop the file from the Finder to the Terminal window and rename its extension. The extension really doesn't matter, but my advice is to write something that let you identify the file format, like pvrl2 for Channel Weighting Linear with 2bpp.</li>
<li>Finally, add an space and write the input file. Guess... I prefer to drag &#038; drop from the Finder. The input files must be PNG or JPG files only.</li>
<li>Hit "Enter"</li>
</ul>
<table width="675">
<tbody>
<tr>
<th>Terminal Script to Generate PVRTC with Texturetool</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/texturetool
 -e PVRTC --channel-weighting-linear --bits-per-pixel-2 -o
/Texture/Output/Path/Texture.pvrl2 /Texture/Intput/Path/Texture.jpg
.</pre>
<p>Good, now you have a PVRTC file. The problem with the Apple tool is that it doesn't generate the traditional PVRTC binary header. It's composed by 52 bytes at the beginning of the file and gives instructions about the height and width of the image, number of Mipmaps on it, bpp, channels order, alpha, etc. In the traditional PVRTC files, this is the header format:</p>
<ul>
<li><strong>unsigned int (4 bytes)</strong>: Header Length in Bytes. Old PVRTC has a header of 44 bytes instead 52.</li>
<li><strong>unsigned int (4 bytes)</strong>: Height of the image. PVRTC only accepts squared images (width = height) and POT sizes (Power of Two)</li>
<li><strong>unsigned int (4 bytes)</strong>: Width of the image. PVRTC only accepts squared images (width = height) and POT sizes (Power of Two).</li>
<li><strong>unsigned int (4 bytes)</strong>: Number of Mipmaps.</li>
<li><strong>unsigned int (4 bytes)</strong>: Flags.</li>
<li><strong>unsigned int (4 bytes)</strong>: Data Length of the image.</li>
<li><strong>unsigned int (4 bytes)</strong>: The bpp.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Red.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Green.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Blue.</li>
<li><strong>unsigned int (4 bytes)</strong>: Bitmask Alpha.</li>
<li><strong>unsigned int (4 bytes)</strong>: The PVR Tag.</li>
<li><strong>unsigned int (4 bytes)</strong>: Number of Surfaces.</li>
</ul>
<p>But, using the Apple Texture Tool we don't have the file header and without that header we can't find neither the width nor height of the file from our code. So to use PVRTC from Apple tool you should know about bpp, width, height and alpha. Kind of annoying, no?</p>
<p>Well... I have good news for you. I found a way, a trick, to extract informations from the PVRTC generated by Apple tool. This trick works fine, but it can't identify informations about the Mipmap, but this is not a problem, because Apple tool doesn't generate Mipmaps anyway.</p>
<table width="675">
<tbody>
<tr>
<th>Extracting Infos From PVRTC Without Header</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Supposing the bpp of the image is 4, calculates its squared size.
float size = sqrtf([data length] * 8 / 4);

// Checks if the bpp is really 4 by comparing the rest of division by 8,
// the minimum size of PVRTC, if the rest is zero then this image really
// has 4 bpp, otherwise, it has 2 bpp.
bpp = ((int)size % 8 == 0) ? 4 : 2;

// Knowing the bpp, calculates the width and height
// based on the data size.
width = sqrtf([data length] * 8 / bpp);
height = sqrtf([data length] * 8 / bpp);
length = [data length];
.</pre>
<p>The PVRTC files made from Texturetool doesn't have any header, so its image data starts in the first byte of the file. And what about the alpha? Could you ask. Well, the alpha will be more dependent of your EAGL context configuration. If you are using RGBA8, assume the alpha exist and use the <strong>GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG</strong> or <strong>GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</strong>, based on the informations that you extract from the code above. If your EAGL context uses RGB565, so assume <strong>GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG</strong> or <strong>GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG</strong>.</p>
<p>Now to use your PVRTC on OpenGL ES 2.0, it's very simple, you don't need to change almost anything, you will create your texture normally, just replace the call to <strong>glTexImage2D</strong> by <strong>glCompressedTexImage2D</strong> function.</p>
<table width="675">
<tbody>
<tr>
<th>Uploading PVRTC to OpenGL</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// format = one of the GL_COMPRESSED_RGB* constants.
// width = width extract from the code above.
// height = height extract from the code above.
// length = length extract from the code above.
// data = the array of pixel data loaded via NSData or any other binary class.

// You probably will use NSData to load the PVRTC file.
// By using "dataWithContentsOfFile" or similar NSData methods.

glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, length, data);
.</pre>
<p>Well done, this is all about PVRTC. But my last advice about this topic is, always avoid to use PVRTC. The cost X benefit is not so good. Remember you just need to parse an image file once to OpenGL, so PVRTC doesn't offers a great optimization.</p>
<p><br/><a name="off-screen"></a></p>
<h2><strong>The Off-Screen Render</strong></h2>
<p>Until now we've just talked about render to the screen, "on the screen", "on the device", but we also have another surface to render, the off-screen surfaces. You remember it from the EGL article, right? (<a href="http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/" target="_blank">EGL and EAGL article</a>).</p>
<p>What is the utility of  an off-screen render? We can take a snapshot from the current frame and save it as an image file, but the most important thing about off-screen renders is to create an OpenGL texture with the current frame and then use this new internal texture to make a reflection map, a real-time reflection. I'll not talk about the reflections here, this subject is more appropriated to a tutorial specific about the shaders and lights, let's focus only about how to render to an off-screen surface. We'll need to know a new function:</p>
<table width="675">
<tr>
<th>Off-Screen Render</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)</strong></h5>
<p><br/></p>
<ul>
<li><strong>target</strong>: The target always will be <strong>GL_FRAMEBUFFER</strong>, this is just an internal convention for OpenGL.</li>
<li><strong>attachment</strong>: This specifies what kind of render buffer we want to render for This parameter can be:
<ul>
<li><strong>GL_COLOR_ATTACHMENT0</strong> to the Color Render Buffer.</li>
<li><strong>GL_DEPTH_ATTACHMENT</strong> to a Depth Render Buffer.</li>
</ul>
</li>
<li><strong>textarget</strong>: The type of texture, to 2D texture this parameter always will be <strong>GL_TEXTURE_2D</strong>. If your texture is a 3D texture (Cube Map), you can use one of its faces as this parameter: GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y or GL_TEXTURE_CUBE_MAP_NEGATIVE_Z.</li>
<li><strong>texture</strong>: The texture object target.</li>
<li><strong>level</strong>: Specifies the Mipmap level for the texture.</li>
</ul>
</td>
</tr>
</table>
<p>To use this function we need to first create the target texture. We can do it just as before (<a href="http://db-in.com/blog/2011/02/all-about-opengl-es-2-x-part-23/#textures" target="_blank">check out the texture functions here</a>). Then we call <strong>glFramebufferTexture2D</strong> and proceed normally with our render routine. After drawing something (glDraw* callings) that texture object will be filled and you can use it for anything you want. Here is an example:</p>
<table width="675">
<tbody>
<tr>
<th>Drawing to Off-Screen Surface</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// Create and bind the Frame Buffer.
// Create and attach the Render Buffers, except the render buffer which will
// receive the texture as attachment.

GLuint _texture;
glGenTextures(1, &#038;_texture);
glBindTexture(GL_TEXTURE_2D, _texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,  textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture, 0);
.</pre>
<p>Differently than creating a texture for a pixel data, at this time you set the texture data to <strong>NULL</strong>. Because they will be filled up dynamically later on. If you intend to use the output image as a texture for another draw, remember first to draw the objects that will fill the output texture.</p>
<p>Well, as any Frame Buffer operation, it's a good idea to check <strong>glCheckFramebufferStatus</strong> to see if everything was attached OK. A new question comes up: "If I want to save the resulting texture to a file, how could I retrieve the pixel data from the texture?", OpenGL is a good mother, she gives us this function:</p>
<table width="675">
<tr>
<th>Getting Pixel Data from Texture</th>
</tr>
<tr>
<td>
<h5><strong>GLvoid glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels)</strong></h5>
<p><br/></p>
<ul>
<li><strong>x</strong>: The X position to start getting pixel data. Remember that the pixel order in the OpenGL starts in the lower left corner and goes to up right corner.</li>
<li><strong>y</strong>: The Y position to start getting pixel data.  Remember that the pixel order in the OpenGL starts in the lower left corner and goes to up right corner.</li>
<li><strong>width</strong>: The Width to get the pixel data. Can't be greater than the original render buffer.</li>
<li><strong>height</strong>: The Width to get the pixel data. Can't be greater than the original render buffer.</li>
<li><strong>format</strong>: Always use <strong>GL_RGB</strong>, there are other formats, but it is implementation dependent and can vary depending on your vendors. For example, to get Alpha information, it depends on your EGL context configuration, which is vendors dependent.</li>
<li><strong>type</strong>: Always use <strong>GL_UNSIGNED_BYTE,</strong>, there are other formats, but it is implementation dependent and can vary depending on your vendors.</li>
<li><strong>pixels</strong>: A pointer to return the pixel data.</li>
</ul>
</td>
</tr>
</table>
<p>As you've saw, the function is very easy, you can call it any time you want. Just remember a very important thing: "OpenGL Pixel Order!", it starts in the lower left corner and goes to the up right corner. To a traditional image file, that means the image is flipped vertically, so if you want to save to a file, take care with it.</p>
<p>Now you must to do the invert path you are used to when import a texture. Now you have the pixel data and want to construct a file. Fortunately many languages offers a simple way to construct an imagem from pixel data. For example, with Cocoa Touch (Objective-C), we can use NSData + UIImage, at this way:</p>
<table width="675">
<tbody>
<tr>
<th>Drawing to Off-Screen Surface</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
// The pixelData variable is a "void *" initialized with memory allocated.

glReadPixels (0, 0, 256, 256, GL_RGB, GL_UNSIGNED_BYTE, pixelData);
UIImage *image = [UIImage imageWithData:[NSData dataWithBytes:pixelData length:256 * 256]];

// Now you can save the image as JPG or PNG.
[UIImageJPEGRepresentation(image, 100) writeToFile:@"A path to save the file" atomically:YES];
.</pre>
<p>Just a little question, <strong> glReadPixels </strong> will read from where? OpenGL State Machine, do you remember? <strong> glReadPixels </strong> will read the pixels from the "last Frame Buffer bound".</p>
<p>Now it's time to talk more about optimization.</p>
<p><br/><a name="tips_tricks"></a></p>
<h2><strong>Tips and Tricks</strong></h2>
<p><a href="#list_contents">top</a><br />
I want to talk now about some tips and tricks to boost your application. I don't want to talk about little optimizations which make you gain 0.001 secs, no. I want to talk about real optimizations. That ones which can boost 0.5 secs or even increase your render frame rate.</p>
<p><br/><a name="cache"></a></p>
<h3>The Cache</h3>
<p><a href="#list_contents">top</a><br />
This is very important, I really love it, I'm used to use it on everything, it's great! Imagine this situation, the user touch the objects on the screen to make a rotation. Now the user touch another object, but the first doesn't change anything. So it would be great to make the first object's transformation matrix a cached matrix, instead to recalculating the first object's matrix at each frame.</p>
<p>The cached concept extends even to other areas, like cameras, lights and quaternions. Instead to recalculate something at each frame, use a little BOOL data type to check if a matrix or even a value is cached or not. The following pseudo-code shows how is simple to work with cache concept.</p>
<table width="675">
<tbody>
<tr>
<th>Cache Concept</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
bool _matrixCached;
float _changeValue;
float *_matrix;

float *matrix(void)
{
    if (!_matrixCached)
    {
        // Do changes into _matrix.

        _matrixCached = TRUE;
    }

    return _matrix;
}

void setChange(float value)
{
    // Change the _changeValue which will affect the matrix.

    _matrixCached = FALSE;
}
.</pre>
<p><br/><a name="store_values"></a></p>
<h3>Store the Values</h3>
<p><a href="#list_contents">top</a><br />
We are used to change the matrix (or the quaternion) every time that occurs transformation. For example, if our code make the changes: translate X - we change the resulting matrix, translate Y - we change the matrix, rotate Z - change the matrix and scale Y - change the matrix. Some 3D engines and people do not even hold on a value to those transformations, so if the code need to retrieve those values, they extract the values directly from the resulting matrix. But this is not the best approach. A great optimization could be reached if we store the values independently, like translations X,Y and Z, rotations X,Y and Z and scales X,Y and Z.</p>
<p>By storing the values you can make a single change into the resulting matrix, making the calculations once per frame instead of making the calculus at every transformation. The following pseudo-code can help you to understand the Store concept better:</p>
<table width="675">
<tbody>
<tr>
<th>Store Concept</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
float _x;
float _y;
float _z;

float x(void) { return _x; }
float setX(float value)
{
    _x = value;
}

float y(void) { return _y; }
float setY(float value)
{
    _y = value;
}

float z(void) { return _z; }
float setZ(float value)
{
    _z = value;
}

float *matrix(void)
{
    // This function will be called once per frame.
    // Make the changes to the matrix based on _x, _y and _z.
}
.</pre>
<p><br/><a name="c_fastest"></a></p>
<h3>C is always the fast language</h3>
<p><a href="#list_contents">top</a><br />
This tip is just something to remember. You probably know that, but it's very important to reinforce. C is always the fastest language. No other language can be faster than C. It's the most basic language and it's the great father of almost all computer languages. So always try to use C in the most critical parts of the code. Specially for render routines.</p>
<p>String comparisons with C is around 4x faster than Objective-C comparisons. So if you need to check some string value at the render time, prefer to convert it from NSString to C string (char *) and make the comparison, even if you need re-convert from C string to NSString again, even in these cases C string is faster. To compare C strings you know, just use <strong>if (strcmp(string1, string2) == 0)</strong>.</p>
<p>Specially for numbers, always use basic C data types (<strong>float</strong>, <strong>int</strong>, <strong>short</strong>, <strong>char</strong> and their unsigned versions). Besides, avoid at maximum value that use 64 bits, like <strong>long</strong> or <strong>double</strong> data type. Remember that OpenGL ES doesn't support, by default, 64 bits data types.</p>
<p><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
OK dudes, we're at the end of our objective with this serie. I'm sure now you know a lot of things about OpenGL and 3D world. I have covered almost all about the OpenGL in those 3 tutorials of this serie. I hope you learned all the concepts about the subjects covered in these tutorials.</p>
<p>Now, as we are used, let's remember everything:</p>
<ul>
<li>2D graphics with OpenGL can be done by two ways: with or without Depth Render Buffer.</li>
<li>When using Depth Render Buffer, it could also be good to make use of a camera with Orthographic projection.</li>
<li>Independent of the way you choose, always use the Grid concept with 2D graphics.</li>
<li>The Multisampling filter is a plug-in that depends the vendors implementation. Multisampling always has a big cost on performance, use it only in special situations.</li>
<li>Always try to optimize your textures to a 2bpp data format.</li>
<li>You can use PVRTC in your application to save some time when creating an OpenGL texture from a file.</li>
<li>Always try to use the Cache concept when working with matrices.</li>
<li>Make use of the Store Values concept to save CPU processing.</li>
<li>Prefer basic C language on the critical render routines.</li>
</ul>
<p>Well, you know, if you have some doubt, just ask me, let a comment bellow and if I can help I'll be glad.</p>
<p><br/></p>
<h2><strong>From here and beyond</strong></h2>
<p>Well, and now? Is this all? No. It will never be enough! The points and lines deserve a special article. With points in can make particles and some cool effects. As I told at the beginning of this tutorial, you can use points with 2D graphics instead squares, in case of no Depth Render Buffer.</p>
<p>And about the shaders? In deep? The Programmable Pipeline gives us a whole new world of programming. We should talk about the Surface Normals VS Vertex Normals, about the tangent space, the normal bump effect, the reflection and refraction effect. To say the truth... I think we need a new serie of tutorial called "All About OpenGL Shaders". Well, this could be my next serie.</p>
<p>But I want to hear from you, tell me here or on Twitter what you want to know more about.<br />
Just Tweet me:<br />
<a href="http://twitter.com/share" class="twitter-share-button" data-text="Hey @dineybomfim talk more about: " data-count="none" data-url="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></p>
<p>Thanks again for reading.<br />
See you in the next tutorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/05/all-about-opengl-es-2-x-part-33/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Creating Universal Framework to iPhone iOS</title>
		<link>http://db-in.com/blog/2011/05/creating-universal-framework-to-iphone-ios/</link>
		<comments>http://db-in.com/blog/2011/05/creating-universal-framework-to-iphone-ios/#comments</comments>
		<pubDate>Sun, 01 May 2011 19:50:50 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1394</guid>
		<description><![CDATA[Learn how to construct a Custom Framework to iOS Devices and distribute it.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/04/framework_ios.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/framework_ios.png" alt="" title="framework_ios" width="200" height="200" class="alignright size-full wp-image-1396" /></a>Hello my friends,</p>
<p>I felt a good impulse to write a little article about this theme, because there are few poor informations about it around the web. In many cases, are wrong or incomplete informations. So if you want to write a framework to iPhone and distribute it, you are in the right place!</p>
<p>I&#8217;ll treat here about how to construct an Universal Framework to iOS, what are the necessary configurations and everything else related to. We&#8217;ll focus on Xcode 4, but this is also valid to Xcode 3.x.</p>
<p>Let&#8217;s start!<br />
<span id="more-1394"></span></p>
<h2><span style="color:#FF0000">&#8211;WARNING&#8211;</span></h2>
<p><strong>This content is outdated! There is a new version of this article (2.0) teaching how to create an Universal Framework to iOS, much simpler and reliable:</strong><br />
<a href="http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/">http://db-in.com/blog/2011/07/universal-framework-iphone-ios-2-0/</a></p>
<p><a name="list_contents"></a><br />
Here is a little list of contents to orient your reading:</p>
<table width="675">
<tr>
<th colspan=2>List of Contents to this Tutorial</th>
</tr>
<tr>
<td valign="top">
<ul>
<li><a href="#framework_ios">Framework on iOS? Really?</a></li>
<li><a href="#understanding">Understanding Universal, Dynamic and Static concepts</a></li>
<li><a href="#framework_project">Constructing a Framework Project</a>
<ul>
<li><a href="#step_1">1. Create the Project</a></li>
<li><a href="#step_2">2. Framework Classes</a></li>
</ul>
</li>
<li><a href="#compiling_framework">Compiling a Framework</a>
<ul>
<li><a href="#step_3">3. Create a Framework Target</a></li>
<li><a href="#step_4">4. Bundle Setup</a></li>
<li><a href="#step_5">5. Adding code and resources to the Bundle (Framework)</a></li>
<li><a href="#step_6">6. Schemes Setup</a></li>
<li><a href="#step_7">7. Building the Framework</a></li>
</ul>
</li>
<li><a href="#building_universal">Building the Universal Framework</a>
<ul>
<li><a href="#step_8">8. Creating Universal Target</a></li>
<li><a href="#step_9">9. Lipo Tool Script</a></li>
</ul>
</li>
<li><a href="#testing">Testing your Universal Framework</a>
<ul>
<li><a href="#step_10">10. Testing</a></li>
</ul>
</li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
</td>
</tr>
</table>
<p>You can download the project I used in this article:</p>
<p><a href="http://db-in.com/downloads/framework-ios.zip" onmousedown="_gaq.push(['_trackEvent', 'Framework iOS', 'Xcode', 'Download']);"><img class="alignleft" title="download" src="http://db-in.com/imgs/download_button.png" alt="Download Xcode project files to iPhone"/><br />
<strong>Download now</strong><br />
Xcode project files to Framework-iOS<br />
403kb<br />
</a><br/></p>
<p><br/><a name="framework_ios"></a></p>
<h2><strong>Framework on iOS? Really?</strong></h2>
<p><a href="#list_contents">top</a><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/04/framework_icon.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/framework_icon.png" alt="" title="framework_icon" width="128" height="128" class="alignleft size-full wp-image-1397" /></a>Ok buddies, let&#8217;s make something clear, many people had said:&#8221;iOS doesn&#8217;t support custom Frameworks!&#8221;, &#8220;Custom Framework is not allowed at iOS!&#8221;, &#8220;Doesn&#8217;t exist custom Framework on iOS!&#8221; and many other discouraging things like these. Look, I&#8217;ve made many frameworks and worked with many others, I don&#8217;t believe that is really impossible to use a Framework on iOS. According to my experience and knowledge about Frameworks, it&#8217;s absolutely feasible a custom Framework on iOS Devices. If we think more about the issue we can find an elegant solution, right? First, let&#8217;s understand what a Framework really is, here is the definition of framework by Apple&#8217;s eyes:</p>
<blockquote><p>A framework is a hierarchical directory that encapsulates shared resources, such as a dynamic shared library, nib files, image files, localized strings, header files, and reference documentation in a single package.</p></blockquote>
<p>Doesn&#8217;t make many sense something with this description not be allowed in iOS, thinking in architecture and structure. Apple also says:</p>
<blockquote><p>A framework is also a bundle and its contents can be accessed using Core Foundation Bundle Services or the Cocoa NSBundle class. However, unlike most bundles, a framework bundle does not appear in the Finder as an opaque file. A framework bundle is a standard directory that the user can navigate.</p></blockquote>
<p>Good, now thinking about iOS security, performance and size, the only thing in a Framework definition which doesn&#8217;t fit in iOS technology is the &#8220;dynamic shared library&#8221;. The words &#8220;dynamic&#8221; and &#8220;shared&#8221; are not welcome in the iOS architecture. So the Apple allows us to work and distribute something called &#8220;<strong>Static Library</strong>&#8220;. I don&#8217;t like it! It&#8217;s not so easy as a Cocoa Framework, if a developer got your Static Library, he needs to set a header path too, or import the header files&#8230; it&#8217;s not useful, that&#8217;s a shit!</p>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/05/static_library_no.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/static_library_no.png" alt="" title="static_library_no" width="128" height="128" class="alignright size-full wp-image-1403" /></a></p>
<p>Well, so a Framework concept is absolutely compatible with iOS, except by the &#8220;dynamic shared library&#8221;, on the other hand Apple says that a &#8220;static library&#8221; is OK for iOS. So if we replace the &#8220;dynamic shared libraries&#8221; by a &#8220;static library&#8221; we could construct a Custom Framework to iOS, right?</p>
<p>Right!!!!</p>
<p>This is exactly what we&#8217;ll make in this article, let&#8217;s construct a Framework with Static Library, by the way, an Universal Framework.</p>
<p><br/><a name="understanding"></a></p>
<h2><strong>Understanding Universal, Dynamic and Static concepts</strong></h2>
<p><a href="#list_contents">top</a><br />
Simple answer:</p>
<ul>
<li>Universal: Which works perfect on all architectures. iOS devices uses <strong>armv6</strong> and <strong>armv7</strong>, iOS simulator on MacOS X uses <strong>i386</strong>.</li>
<li>Dynamic: The compiler doesn&#8217;t include the target files directly. The classes/libraries are already pre-compiled (binary format) and lies on the system path. Besides, the dynamic libraries can be shared by many applications. This is exactly what Cocoa Framework is.</li>
<li>Static: It represents that classes/libraries which is compiled by the compiler at the build phase. These files can&#8217;t be shared by other applications and relies on application path.</li>
</ul>
<p>Simple as that. If you need more informations about Dynamic VS Static libraries, try this <a href="http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/OverviewOfDynamicLibraries.html" target="_blank">Apple&#8217;s Documentation</a>.</p>
<p>No more concepts, hands at work!</p>
<p><br/><a name="framework_project"></a></p>
<h2><strong>Constructing a Framework Project</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_1"></a><br />
<h3>1. Create the Project:</h3>
<p><a href="#list_contents">top</a><br />
I want to show you step by step of the entire process, so let&#8217;s start with the most basic, create an iOS project. You can choose one application template in Xcode, this is not really so important, but remember to choose one template which could test your Framework code before export it.<br />
<div id="attachment_1399" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_project.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_project.jpg" alt="Create an application project." title="xcode_new_project" width="600" class="size-full wp-image-1399" /></a><p class="wp-caption-text">Create an application project.</p></div></p>
<p><br/><a name="step_2"></a></p>
<h3>2. Framework Classes:</h3>
<p><a href="#list_contents">top</a><br />
<div id="attachment_1400" class="wp-caption alignleft" style="width: 267px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_project_navigator.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_project_navigator.jpg" alt="Create your framework classes." title="xcode_project_navigator" width="257" height="286" class="size-full wp-image-1400" /></a><p class="wp-caption-text">Create your framework classes.</p></div>Now it&#8217;s time to create (or import) your framework classes, just as you are used to in any other application. Remember that organization is 80% of a good framework, so try follow all the Apple advices to create your classes names, methods, properties, functions, etc.</p>
<p>Remember to create an import header to make everything more simple and organized to the user of your framework. Remember to write this header file with a framework notation, just as shown in the image bellow. Also remember to create your classes taking care to hide the classes which should not be visible to the other developers (users of your framework). We will set the public and private headers soon, but it&#8217;s very important to you protect the &#8220;core&#8221; classes, I mean, that classes which you don&#8217;t want to make visible to other developers.</p>
<p>For those private classes, you could import their header inside the &#8220;<strong>.m</strong>&#8221; (or .mm, .cpp, etc) file of a public class, by doing this you protect the header of private classes. Well, I know you probably already know that, I&#8217;m saying just to reinforce.</p>
<p>After you have all the classes (and also other files, like images, sounds, etc.), you are ready to compile a custom framework. In the next step, we&#8217;ll create a target to compile our framework, this will be our first big trick!</p>
<div id="attachment_1401" class="wp-caption aligncenter" style="width: 457px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_header.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_header.jpg" alt="Create your framework header with framework notation." title="xcode_framework_header" width="447" height="157" class="size-full wp-image-1401" /></a><p class="wp-caption-text">Create your framework header with framework notation.</p></div>
<p><br/><a name="compiling_framework"></a></p>
<h2><strong>Compiling a Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_3"></a><br />
<h3>3. Create a Framework Target:</h3>
<p><a href="#list_contents">top</a><br />
OK, let&#8217;s create a target to compile our framework. Click on the icon of your project in the project navigator at the left and hit the button &#8220;Add Target&#8221;. A new window will come up. Now is our first trick. Instead to create a &#8220;Cocoa Touch Static Library&#8221; or a &#8220;Cocoa Framework&#8221; we will create a &#8220;Bundle&#8221; target.</p>
<p>A Bundle? Really? Yes! I can explain. A &#8220;Cocoa Framework&#8221; target can&#8217;t be compiled to armv6/armv7 and Xcode doesn&#8217;t allow us to use &#8220;Static Libraries&#8221; in a &#8220;Cocoa Framework&#8221;, so we can&#8217;t use this target. On the other hand, we can&#8217;t use &#8220;Cocoa Touch Static Library&#8221; either, because it doesn&#8217;t use the framework structure that we want.</p>
<p>Now, the <strong>Bundle</strong> target could be the best choice. It can hold any file we want, we can compile source code inside it and&#8230; we can turn it into a framework. To say the truth, almost all &#8220;Framework &#038; Library&#8221; targets could be turned into a framework too, even the &#8220;Cocoa Touch Static Library&#8221;, throughout this article you probably will figure out why. For now, let&#8217;s create a <strong>Bundle</strong> target.</p>
<div id="attachment_1402" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_target.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_new_target.jpg" alt="Create a Bundle target rather than Cocoa Touch Static Library." title="xcode_new_target" width="600" class="size-full wp-image-1402" /></a><p class="wp-caption-text">Create a Bundle target rather than Cocoa Touch Static Library.</p></div>
<p><br/><a name="step_4"></a></p>
<h3>4. Bundle Setup:</h3>
<p><a href="#list_contents">top</a><br />
<a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_remove_framework.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_remove_framework.jpg" alt="" title="xcode_remove_framework" width="314" height="113" class="alignleft size-full wp-image-1404" /></a>It&#8217;s time to make all the necessary changes to the Bundle target. First of all, make sure you have cleaned up all the default files from the Bundle target. Remove the linked frameworks (you can find it clicking in the &#8220;<strong>Build Phase</strong>&#8221; tab and then they are in the section &#8220;<strong>Link Binary With Libraries</strong>&#8220;) and delete the Preference List file (.plist), the pre-compiled headers (.pch) and the language files.</p>
<p>I&#8217;m sure you already know this, but just to reinforce, here is the Build Setting screen, you can find it by clicking on the project icon in the left project navigator and then clicking in the &#8220;Build Setting&#8221; tab.<br />
<div id="attachment_1405" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_settings-e1304231010699.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_settings-e1304231010699.jpg" alt="You must make a special Build Setting to turn a Bundle into a framework." title="xcode_build_settings" width="600" class="size-full wp-image-1405" /></a><p class="wp-caption-text">You must make a special Build Setting to turn a Bundle into a framework.</p></div></p>
<p>Here is our second great trick, or should be better to say &#8220;tricks&#8221;. Let&#8217;s change the &#8220;<strong>Build Setting</strong>&#8221; following this list:</p>
<ul>
<li><strong><em>Architectures</em></strong>: <span style="color: #3366ff;"><strong>Standard (armv6 armv7)</strong></span> (the values for this property depend on the value of the item bellow).</li>
<li><strong><em>Base SDK</em></strong>: <span style="color: #3366ff;"><strong>Latest iOS (iOS X.X)</strong></span> (in the X.X will appear the number of the lastest iOS SDK installed on your machine).</li>
<li><strong><em>Build Active Architecture Only</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span> (this is a very important set, if it&#8217;s YES then we can&#8217;t compile to armv6 and armv7 at the same time).</li>
<li><strong><em>Supported Platforms</em></strong>: <span style="color: #3366ff;"><strong>iphonesimulator iphoneos</strong></span>.
<li><strong><em>Valid Architecture</em></strong>: <span style="color: #3366ff;"><strong>$(ARCHS_STANDARD_32_BIT)</strong></span> (it&#8217;s very important to be exactly this value, seems there is a bug in Xcode 4, once you set i386 as supported platforms to iOS, it can&#8217;t be removed anymore and it could generate errors in your project. So, to avoid any architectures error, use this value).</li>
<li><strong><em>Installation Directory</em></strong>: [optional change] I like to set this to <span style="color: #3366ff;"><strong>$(BUILT_PRODUCTS_DIR)</strong></span>, but this is not really relevant to our purposes here. You can set it to a path of your choice.</li>
<li><strong><em>Mac OS X Deployment Target</em></strong>: <span style="color: #3366ff;"><strong>Compiler Default</strong></span>.</li>
<li><strong><em>Dead Code Stripping</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Link With Standard Libraries</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Mach-O Type</em></strong>: <span style="color: #3366ff;"><strong>Relocatable Object File</strong></span>. This is the most important change. Here, we instruct the compiler to treat the Bundle as a relocatable file, by doing this, we can turn it into a framework with the wrapper setting.</li>
<li><strong><em>Other Linker Flags</em></strong>: [optional change] <span style="color: #3366ff;"><strong>-ObjC</strong></span>, could be good make sure the compiler understands what&#8217;s the language it is compiling for, this can reduce the warnings at the compilation.</li>
<li><strong><em>Info.plist File</em></strong>: <span style="color: #3366ff;"><em>empty</em></span>, remove any value from this field.</li>
<li><strong><em>Wrapper Extension</em></strong>: <span style="color: #3366ff;"><strong>framework</strong></span>. Here we change the Bundle to a Framework. To Xcode, frameworks is just a folder with the extension <em>.framework</em>, which has inside one or more compiled binary sources, resources and some folders, a folder, usually called Headers, contains all the public headers.</li>
<li><strong><em>Precompile Prefix Header</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span>.</li>
<li><strong><em>Prefix Header</em></strong>: <span style="color: #3366ff;"><em>empty</em></span>, remove any value from this field.</li>
<li><strong><em>Generate Debug Symbols</em></strong>: <span style="color: #3366ff;"><strong>NO</strong></span> (this is a very important setting, otherwise your framework will not work on another computer/profile).</li>
</ul>
<p><br/><a name="step_5"></a></p>
<h3>5. Adding code and resources to the Bundle (Framework)</h3>
<p><a href="#list_contents">top</a><br />
It&#8217;s time to place the content in our framework and define the public headers. To do that, with the Bundle target selected, click on the &#8220;<strong>Build Phase</strong>&#8221; tab. At bottom, hit the button &#8220;<strong>Add Phase</strong>&#8221; and then &#8220;<strong>Add Copy Headers</strong>&#8220;.</p>
<p>Open the recently created &#8220;<strong>Copy Headers</strong>&#8221; section and separate your public headers from the private or project headers. The difference here is:</p>
<ul>
<li>Public: Headers that other developers must know in order to work with your framework. In the final framework product, these headers will be visible even to Xcode.</li>
<li>Private: Headers that is not necessary to other developers, but is good for consult or for reference. These headers will not be visible to Xcode, but will be in the framework folder.</li>
<li>Project: Headers that the other developers nor Xcode have access. In reality these headers will not be placed in the final product, this is just to instruct the compiler to create your custom framework.</li>
</ul>
<p>Now, open the &#8220;<strong>Compile Source</strong>&#8221; section and put there all your <strong>.m</strong>, <strong>.c</strong>, <strong>.mm</strong>, <strong>.cpp</strong> or any other compilable source file. If your framework include not compilable files, like images, sounds and other resources, you can place them in the &#8220;<strong>Copy Bundle Resources</strong>&#8221; section, in the example of this article, I used no resources. This is how your &#8220;<strong>Build Phase</strong>&#8221; will looks like:<br />
<div id="attachment_1406" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_copy_headers.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_copy_headers.jpg" alt="Define your compilable source and the headers." title="xcode_copy_headers" width="600" class="size-full wp-image-1406" /></a><p class="wp-caption-text">Define your compilable source and the headers.</p></div></p>
<p><br/><a name="step_6"></a></p>
<h3>6. Schemes Setup</h3>
<p><a href="#list_contents">top</a><br />
This is an important change to compile our framework. You don&#8217;t need to compile it in the Debug modes, we just need the Release mode, because if you have any Macro in your code which works only in Debug mode, like DEBUG macro, it will assume the configuration of the product that the other developers will make. So to us now, only the Release is important.</p>
<p>You can change it accessing the menu <strong>Product > Manage Schemes&#8230;</strong> or by the schemes short cut: the drop list in front at the Build/Run bottom in the top left corner of the Xcode window.</p>
<p>At this point could be a good idea to delete all the current schemes and then press the button &#8220;<strong>AutoCreate Schemes Now</strong>&#8220;. The important is select your framework target and hit the button &#8220;<strong>Edit</strong>&#8221; at the bottom. In the next window, change the &#8220;<strong>Build Configuration</strong>&#8221; from Debug to Release. Change to Release in all the situations: Run, Test, Profile, Analyze and Archive. By doing this, we ensure that our framework target will always compile the Release version.</p>
<div id="attachment_1407" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_manage_schemes.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_manage_schemes.jpg" alt="Build the custom framework only to Release." title="xcode_manage_schemes" width="600"  class="size-full wp-image-1407" /></a><p class="wp-caption-text">Build the custom framework only to Release.</p></div>
<p><br/><a name="step_7"></a></p>
<h3>7. Building the Framework</h3>
<p><a href="#list_contents">top</a><br />
OK, here is the annoying step of this process. Until now, I don&#8217;t figure out a more easy an elegant way to do this. You must to compile this target twice: one to <strong>iOS Device</strong> (this will compile for the architectures armv6/arvm7) and to <strong>iOS Simulator</strong> (can be iPhone or iPad with any SDK, doesn&#8217;t matter, the simulator always will compile for the architecture i386).</p>
<p>I&#8217;ve tried another way, like create an &#8220;integrator&#8221; and I placed two targets to its &#8220;Target Dependencies&#8221;, but trust me, it&#8217;s worst, because you need to change 2 targets instead 1 in cases when you change the framework content. Besides, the dependencies will assume the architectures of the &#8220;integrator&#8221;, so you need to compile twice too. Anyway&#8230;  the best solution I found until now is use only 1 target and build it twice. If you find a better one, please tell me.</p>
<div id="attachment_1408" class="wp-caption aligncenter" style="width: 380px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_compile_ios_simulator.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_compile_ios_simulator.jpg" alt="Compile the framework target twice: iOS Device and Simulator." title="xcode_compile_ios_simulator" width="370" height="194" class="size-full wp-image-1408" /></a><p class="wp-caption-text">Compile the framework target twice: iOS Device and Simulator.</p></div>
<p>After the compile complete, you can see in the &#8220;<strong>Products</strong>&#8221; folder in the Project Navigator at the left, that your framework product now is active. Right click on it and hit &#8220;<strong>Show in Finder</strong>&#8220;. Take a look at this product, its is your iOS Framework! Great!</p>
<p>But we&#8217;re not done yet. You can test this product in other applications if you want, but it will only work to one architecture. We must to create an Universal version of this product. If you look around your framework product in the Finder, you&#8217;ll see that it is in a folder called &#8220;Release-iphoneos&#8221; (if you didn&#8217;t change the destination folder in the Build Settings). And if you have compiled to Simulator too, you&#8217;ll see another folder called &#8220;Release-iphonesimulator&#8221; which contains the same framework product, but this version is for architecture i386.</p>
<p>So, let&#8217;s join both products into one.</p>
<p><br/><a name="building_universal"></a></p>
<h2><strong>Building the Universal Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_8"></a><br />
<h3>8. Creating Universal Target:</h3>
<p><a href="#list_contents">top</a><br />
To join both architectures products into one, we must to use the <strong>Lipo Tool</strong>. It&#8217;s a tool which comes with iOS SDK, just to know, it is in &#8220;<Xcode Folder>/Platforms/iPhoneOS.platform/Developer/usr/bin&#8221;, its file name is &#8220;lipo&#8221;. But we don&#8217;t need to know this path, Xcode can deal with it to us.</p>
<p>To use the Lipo Tool we&#8217;ll need to create a &#8220;<strong>Run Script</strong>&#8221; at the &#8220;<strong>Build Phase</strong>&#8220;, you can create it in your previously Bundle Target, but my advice is to create another target. I say to create another target to avoid compiling errors. This script will need to use &#8220;Release-iphoneos&#8221; and &#8220;Release-iphonesimulator&#8221; folders, so if the folders or products inside them not exist yet, the compiler will generate errors.</p>
<p>Let&#8217;s add a new target, hit the &#8220;<strong>Add Target</strong>&#8221; button, just as you did with Bundle Target. At this time a good choice is the &#8220;Aggregate&#8221; target. It doesn&#8217;t create any product directly, its purposes is just to aggregate another targets and run some scripts, exactly what we want!</p>
<div id="attachment_1409" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_all.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_build_all.jpg" alt="Use the &quot;Aggregate&quot; target to construct a run script." title="xcode_build_all" width="600" class="size-full wp-image-1409" /></a><p class="wp-caption-text">Use the &quot;Aggregate&quot; target to construct a run script.</p></div>
<p><br/><a name="step_9"></a></p>
<h3>9. Lipo Tool Script:</h3>
<p><a href="#list_contents">top</a><br />
We are almost there, now it&#8217;s time to create the Run Script to use the Lipo Tool. Well, you probably will need to make some changes in the code bellow to fit it to your framework name or folders (if you set different folders to build for). Here is the script to use:</p>
<table width="675">
<tbody>
<tr>
<th>Xcode Script to Lipo Tool</th>
</tr>
</tbody>
</table>
<pre class="brush:cpp">.
if [ "${ACTION}" = "build" ]
then
# Set the target folders and the final framework product.
    INSTALL_DIR=${SYMROOT}/FI.framework
    DEVICE_DIR=${SYMROOT}/Release-iphoneos
    SIMULATOR_DIR=${SYMROOT}/Release-iphonesimulator

# Create and renews the final product folder.
    mkdir -p "${INSTALL_DIR}"
    rm -rf "${INSTALL_DIR}"
    rm -rf "${INSTALL_DIR}/FI"

# Copy the header files to the final product folder.
    ditto "${DEVICE_DIR}/FI.framework/Headers" "${INSTALL_DIR}/Headers"

# Use the Lipo Tool to merge both binary files (i386 + armv6/armv7) into one Universal final product.
    lipo -create "${DEVICE_DIR}/FI.framework/FI" "${SIMULATOR_DIR}/FI.framework/FI" -output "${INSTALL_DIR}/FI"
fi
.</pre>
<div id="attachment_1411" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_run_script.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_run_script.jpg" alt="Lipo script to join products for architectures i386 and armv6/armv7." title="xcode_run_script" width="600" class="size-full wp-image-1411" /></a><p class="wp-caption-text">Lipo script to join products for architectures i386 and armv6/armv7.</p></div>
<p>Now build the Aggregate target. At this time doesn&#8217;t matter if you build for iOS Device or Simulator, because all that it will make is run the script, nothing more. The above script creates the final Universal Framework at the ${SYMROOT} path, this is the same path of your Bundle target. So you can right click on the Framework product in the &#8220;Products&#8221; again and hit &#8220;Show in Finder&#8221;. Move to the level with &#8220;Release-iphoneos&#8221; and &#8220;Release-iphonesimulator&#8221; folders. Now, there is a new folder with the &#8220;.framework&#8221; extension, it&#8217;s your <strong>Universal Framework to iOS</strong>!</p>
<p><strong>Congratulations!</strong></p>
<p><br/><a name="testing"></a></p>
<h2><strong>Testing your Universal Framework</strong></h2>
<p><a href="#list_contents">top</a><br />
<a name="step_10"></a><br />
<h3>10. Testing:</h3>
<p><a href="#list_contents">top</a><br />
To test your Universal Framework could be a good idea take it from that folder and place it in another one more easy to find, like the Desktop or ~/Library/Frameworks. Well, to avoid take it from that folder every time, you can change the Run Script above. Just change the &#8220;<strong>INSTALL_DIR</strong>&#8221; variable and set a path of your choice, make sure you choose a path with the write permissions. A good choice could be use the Xcode variable <strong>${SRCROOT}</strong> which represents your project folder root, so you can set <strong>${SRCROOT}/Products</strong> or something like that.</p>
<p>Anyway, with your Universal Framework in an &#8220;user friendly path&#8221;, create a new Xcode project, select the Application target and go to &#8220;<strong>Build Phase</strong>&#8221; tab. Open the section &#8220;<strong>Link Binary With Libraries</strong>&#8221; and hit the &#8220;<strong>+</strong>&#8221; to add a new Framework. Click the &#8220;<strong>Add Other&#8230;</strong>&#8221; button and select your Universal Framework. Remember, you must to select the &#8220;<strong>.framework</strong>&#8221; folder.</p>
<p>After the importing, Xcode will know everything about your custom framework. So try to write some code using your framework classes. Remember to import your Framework Principal Header as a framework notation. Xcode will use your public headers in the Code Completion.</p>
<div id="attachment_1414" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_active.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/05/xcode_framework_active.jpg" alt="Xcode knows your public headers and can use them in the Code Completion." title="xcode_framework_active" width="600" class="size-full wp-image-1414" /></a><p class="wp-caption-text">Xcode knows your public headers and can use them in the Code Completion.</p></div>
<p>I like to use the Xcode Midnight Color Theme, so the classes of the project are green and the framework classes are blue. I love blue classes! <img src='http://db-in.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p><a href="#list_contents">top</a><br />
Well done, my friends! As we are used, let&#8217;s make a final review and take care with some possible problems.</p>
<ul>
<li>In a common Xcode project, create a Bundle target.</li>
<li>Make the necessary setup, place your sources, headers and resources in it and finally change the its Schemes configuration.</li>
<li>Compile to iOS Device (armv6/armv7) and to Simulator (i386).</li>
<li>Create an Aggreate target and place a <strong>Run Script</strong> in it.</li>
<li>Enjoy your real <strong>Universal Framework to iOS</strong>!</li>
</ul>
<p>To finish I want to talk about some issues that I had:</p>
<ul>
<li>Take special care with the architectures. Don&#8217;t write the i386 directly in the <strong><em>Valid Architectures</em></strong> setting, always use the <strong>$(ARCHS_STANDARD_32_BIT)</strong>. Plus, always set the <strong><em>Build Active Architecture Only</em></strong> to <strong>NO</strong>.</li>
<li>Take care with your classes structure. If you set, for example, the ClassB.h as a Project or Private header, but in your code you import it into a Public header, this will cause conflicts.</li>
<li>Take care with the <strong><em>Install Directory</em></strong> and <strong><em>Skip Install</em></strong> settings. They can generate warning if the folders permissions or paths are not right set.</li>
<li>Finally, take a special care with the Lipo Tool script. It could generate warnings and/or errors if the paths was not found or the folder permissions was not right set.</li>
</ul>
<p>This is all, buddy.<br />
As I told you, the annoying thing is that you need build 3 times to generate a new Universal Framework: 2 x Bundle target (one to iOS Device and other to the Simulator) and 1x to the Aggregate target (which will run a script). But by my experience, this is not to much, you will create the final product only few times. At the great majority, you will test your Framework classes directly with the Application target in your Framework Xcode Project.</p>
<p>Enjoy your real Framework to iOS!</p>
<p>Thanks for reading,<br />
See you soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/05/creating-universal-framework-to-iphone-ios/feed/</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
		<item>
		<title>NinevehGL Features</title>
		<link>http://db-in.com/blog/2011/04/ninevehgl-features/</link>
		<comments>http://db-in.com/blog/2011/04/ninevehgl-features/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 15:12:36 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[Engine]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[NinevehGL]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=1381</guid>
		<description><![CDATA[The time for the NinevehGL is coming. Check now its features and what you could expect from.]]></description>
			<content:encoded><![CDATA[<p><a href="http://db-in.com/blog/wp-content/uploads/2011/04/ngl_feather.png"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/ngl_feather.png" alt="" title="ngl_feather" width="130" height="200" class="alignleft size-full wp-image-1390" /></a>Hello everyone!</p>
<p>Today I want to talk about the NinevehGL. Talk more about the features and about what it can offer to us. NinevehGL is almost done, I want to be as fast as possible, but I don&#8217;t want to launch it without everything seems great: the documentation, the tutorials, the official website and obviously, the NinevehGL itself.</p>
<p>Soon I&#8217;ll start posting videos and many divulgations about it, but right now in this article let&#8217;s see some images taken directly from the NinevehGL running.</p>
<p>Let&#8217;s start!</p>
<p><span id="more-1381"></span><br />
<br/></p>
<h2><strong>At a glance</strong></h2>
<p>The NinevehGL is a 3D engine fully made with the most pure Objective-C, right on top of Cocoa Touch Framework. So at the first moment, the NinevehGL is a 3D engine only for iOS. I intend to port NinevehGL to MacOSX (desktops with Obj-C) and also for ActionScript 3.0, using the new great API code named Molehill. ActionScript is my old programming language, today I don&#8217;t hold much lover for it, but I know that there are many people that still loving Flash. Another important step is to port NinevehGL to JavaScript to work with WebGL. But at the beginning, NinevehGL will work only with OpenGL ES 2.x for iOS.</p>
<p>Now the most important question: &#8220;Why NinevehGL instead of PowerVR, Oolong, SIO2, Torque, Ogre, UDK, Unity, Wolfenstein, Shiva, Galaxy, or any other? Why should I choose NinevehGL instead any other 3D engine?&#8221;.</p>
<p>I always tried to convince everyone to buy what I was selling, trying to convince everybody from my point of view. But not this time, I don&#8217;t want to sell anything, I don&#8217;t want to convince you. If you are using some other engine and glad with that, just continue with it, you don&#8217;t have to change. Also, if you are a great OpenGL programmer and have your very own model and structure, continue with it, don&#8217;t change anything. Because, again, I don&#8217;t want to convince anyone at this time. Just as OpenGL, I&#8217;ll focus on the most important thing to me: development!</p>
<p>I took everything that I&#8217;ve seen of worst in other engines and I&#8217;ve tried to make it better in NinevehGL. I took all my frustations with the actual engines, all my luggage as developer, all my knowledge about 3D world and put all of them in the NinevehGL. So, if you are like me and you have some insatisfaction with the other engines, for you, NinevehGL could really nice for you! I know I&#8217;m telling this every time, but I love this concept:&#8221;Keep it simple!&#8221; This is the NinevehGL&#8217;s main principle, everything was made to be simple. There are no commands that need more than one single line of code. If you want to make one thing, you need one line, nothing else.</p>
<p>Now I&#8217;ll describe in details the most important features of NinevehGL. Remember, I don&#8217;t want to convince you of anything. I&#8217;m sure you are an advanced programmer and can form your own opinion about what&#8217;s coming next. If you like it, great! If don&#8217;t, it&#8217;s great as well! Just tell me why and I&#8217;ll try to make better.</p>
<p>Here is a features&#8217; list.</p>
<table width="675">
<tr>
<th>NinevehGL Features</th>
</tr>
<tr>
<td>Imports OBJ file.</td>
</tr>
<tr>
<td>Imports DAE (COLLADA) file.</td>
</tr>
<tr>
<td>Works with NGL binary file (exclusive of NinevehGL).</td>
</tr>
<tr>
<td>Cache 3D files to optimize the loading in next times (around 95% less loading time).</td>
</tr>
<tr>
<td>Works with OpenGL ES 2.x (programmable pipeline).</td>
</tr>
<tr>
<td>Full integrations with custom Shaders.</td>
</tr>
<tr>
<td>Supports 3D and 2D application.</td>
</tr>
<tr>
<td>Programming interface is 100% User Friendly and totally independent of OpenGL version.</td>
</tr>
<tr>
<td>Absolutely oriented to performance and minimum size (NinevehGL is 10% &#8211; 60% faster than any other engine).</td>
</tr>
<tr>
<td>Full support for PVRTC (even to without header generated by MacOS).</td>
</tr>
<tr>
<td>Automatically calculates normals and tangent space to work with lights and bump maps.</td>
</tr>
</table>
<p><br/><a name="importing"></a></p>
<h2><strong>Importing 3D files</strong></h2>
<p>This is the most problematic topic to me considering other engines. As OpenGL doesn&#8217;t import 3D files directly, you must use an engine that imports a file good for you or use one of the files accepted by that engine, like POD to PowerVR engine.</p>
<p>This is the first problem that NinevehGL works to solve, it can import the two most popular 3D file formats: COLLADA and WaveFront OBJ. You know what a mess the 3D imports with 3D softwares are. Each software has its own file format and implements its importing routines at its own way. So it&#8217;s not hard to export an OBJ from 3DS Max and when you try to import in Maya, BOOM, error! To tell the truth, the incompatibility with the files when exporting from a 3D software to another is common.</p>
<p>The NinevehGL has a full importing routine. What that means? If your OBJ file has informations about the specular, the bump map, the reflection map or anything supported by OBJ file, NinevehGL will import and parse everything for you with no losses. The same is true for COLLADA files.<br />
<div id="attachment_1383" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/importing_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/importing_example.jpg" alt="NinevehGL supports OBJ and DAE files." title="importing_example" width="600" height="600" class="size-full wp-image-1383" /></a><p class="wp-caption-text">NinevehGL supports OBJ and DAE files.</p></div></p>
<p><br/><a name="caching"></a></p>
<h2><strong>Caching 3D files</strong></h2>
<p>This is the greatest feature in my opinion. NinevehGL works with a third kind of file, the NGL binary file. It&#8217;s a binary file containing a full 3D model with all informations necessary to NinevehGL and also OpenGL. This file is loaded through streaming, so it&#8217;s extremely fast. There are no 3D softwares that can export it, it&#8217;s exclusive from NinevehGL. So how you can use it? There are two ways: First, you can convert your OBJ or COLLADA file on-line! Yes, you read it right, on-line convertion! No plugins, no installations, no complex things, you can generate NGL file on-line! Just access the NinevehGL website, choose the files on your machine and hit the button!</p>
<p>The other way, is the most fascinating one. NGL file is generated automatically by NinevehGL at the first time you load a new file from OBJ or COLLADA. This file will be stored locally in the device under the folder <em><Application_Home>/Library/NinevehGL</em>. What is great here, is that this folder is fully backed up by iTunes. So imagine this:</p>
<ol>
<li>You make an APP, which loads OBJ and COLLADA files.</li>
<li>An user make the download of your APP from the APP Store.</li>
<li>The user runs your APP at the first time, the NinevehGL loads around 20 3D file in 12 secs, let&#8217;s suppose.</li>
<li>The next times that this user runs your APP, the loading time will be 0.12 secs, for example.</li>
</ol>
<p>What happened???<br />
It&#8217;s great! At the second run, the NinevehGL automatically identified  that those 20 3D files were already parsed before, so it will use the cached NGL binary files instead the original ones!</p>
<p>But this feature doesn&#8217;t stop here! Remember, NinevehGL was made to make everything be simple! So, let&#8217;s suppose your application loads the 3D files through the internet connection instead loading it locally. No problems! NinevehGL compares the modification date of the files and choose the most recent. Imagine this:</p>
<ol>
<li>Your APP loads the 3D files from the internet, because you want to make updates without submeting a new APP to APP Store.</li>
<li>An User downloads your APP. First run, 20 3D files in 12 secs.</li>
<li>In the next times, NinevehGL will use NGL binary files, loading them in 0.12 secs.</li>
<li>You make an update and upload some new 3D files.</li>
<li>All the users that have your APP will receive the update, with 10 new 3D files replacing the old ones, so NinevehGL will parse the new downloaded files in 10 secs and it&#8217;ll generate new NGL binary files.</li>
<li>In the next runs of your application, NinevehGL will use the new generated NGL files and the loads will happen in 0.08 secs.</li>
</ol>
<p>I cry of happiness every time I explain this routine. It&#8217;s amazing, wonderful, outstanding, great, it&#8217;s&#8230; it&#8217;s&#8230;  &#8220;magical&#8221;! Well, this is just my opinion about it. But I&#8217;m sure you can imagine how great would be to the final user: &#8220;At the first run, a loading of few seconds, next times, no loading? Where is the loading of this APP?&#8221;. The loading happens in a snap.</p>
<div id="attachment_1384" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/importing_ngl_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/importing_ngl_example.jpg" alt="NinevehGL automatically saves NGL binary files locally." title="importing_ngl_example" width="600" height="600" class="size-full wp-image-1384" /></a><p class="wp-caption-text">NinevehGL automatically saves NGL binary files locally.</p></div>
<p>The last thing I want to say about this feature is the optimization. Again, the NinevehGL was made to be EXTREMELY FAST! So, if you load a NGL binary file directly, it will not create a cache file to it, because it is already optimized, it&#8217;ll just create cache from non optimized files (OBJ and COLLADA). Now you know how to convert your 3D models to NGL binary file, you can convert them on-line, at the official NinevehGL website, or can just run your application in the simulator and take the binary file generated at the first run and find the file at <em><Application_Home>/Library/NinevehGL</em>!</p>
<p>In order to avoid confusion, it&#8217;s important to say that NinevehGL will not be responsible to manage the internet connection for the file downloading. So you can&#8217;t inform an URL to load a 3D file. What the NinevehGL will make is manage the files locally.</p>
<p><br/><a name="shaders"></a></p>
<h2><strong>Custom Shaders</strong></h2>
<p>The NinevehGL was made to work with OpenGL programmable pipeline. So obviously it&#8217;ll create its own shaders, based on the materials (loaded from 3D files or materials created directly in the code). Well, the most fun part of the programmable pipeline is exactly the shaders, so will NinevehGL block us of using our own shaders? Of course NOT! NinevehGL is absolutely user friendly, it&#8217;s flexible!</p>
<p>The other engines working with programmable pipeline are used to give to us only two choices. Working only with your very own shaders or working only with their shaders! Well, this is not a choice, but rather it&#8217;s a dilema! But, the NinevehGL offers another way, a third way: &#8220;all of above&#8221;! Yes, your read it right, NinevehGL has an API Shader capable to integrate two or more shaders into only one program. WOW, what that means?</p>
<p>That means you can create your own shaders, just as you are used to, implementing your own lights effects, materials or anything else you want. Then you pass your shaders to the NinevehGL and it&#8217;ll integrate your custom shaders with the shaders generated by the NinevehGL materials. No conflicts, everything works fine together!</p>
<p>This works for Vertex Shader and/or Fragment Shader. An important thing to say is that there are no special constraints, you can even use a shader that you already have, with many variables inside, many functions and the main function. The NinevehGL Shader API will interpretate the code inside the shaders and will fuse all together.</p>
<div id="attachment_1385" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/importing_shaders_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/importing_shaders_example.jpg" alt="NinevehGL can merge your custom shader with its own shaders." title="importing_shaders_example" width="600" height="326" class="size-full wp-image-1385" /></a><p class="wp-caption-text">NinevehGL can merge your custom shader with its own shaders.</p></div>
<p><br/><a name="tangent_space"></a></p>
<h2><strong>Calculating Normals and Tangent Space</strong></h2>
<p>This is the robust side of NinevehGL. It&#8217;s very fast even in the hard processing scopes, like calculations of normals and tangent space for imported models. Normals and tangent space are very important to generate real time lights, reflections, bump effects and many other things. NinevehGL automatically calculates the normals and generates the tangent space for each mesh that needs it.</p>
<div id="attachment_1386" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/tangent_space_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/tangent_space_example.jpg" alt="NinevehGL automatically generates normals and tangent space, if needed." title="tangent_space_example" width="600" height="600" class="size-full wp-image-1386" /></a><p class="wp-caption-text">NinevehGL automatically generates normals and tangent space, if needed.</p></div>
<p>NinevehGL can automatically generate some effects, like specular lights, ambient light, emissive light, bump map, reflections and other ones specified by NinevehGL materials. NinevehGL doesn&#8217;t impose any limitations to you, it just works around the limits of the OpenGL. So, in the iOS, for example, you can work with very high mesh models. Obviously this is not a common situation, but sometimes it could be better to see high mesh models on the screen. Even to these high meshes, NinevehGL will continue to produce the normals, tangent space, specular lights, bump maps, reflections and everything else you need.</p>
<div id="attachment_1388" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/specular_light_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/specular_light_example.jpg" alt="NinevehGL also works with very high mesh models." title="specular_light_example" width="600" height="600" class="size-full wp-image-1388" /></a><p class="wp-caption-text">NinevehGL also works with very high mesh models.</p></div>
<p>Now I want to show you some other features that are also great, but I&#8217;ll not talk in deep here.</p>
<p><br/><a name="textures"></a></p>
<h2><strong>Optimizing Textures</strong></h2>
<p>Just to keep it fresh on our minds, NinevehGL was made to operate in the maximum performance. So even the loaded textures will be optimized. If you choose to work with an opaque OpenGL Layer (the default), the textures could be optimized to the format RGB_5_6_5, which is the best choice without alpha channel. If you choose to work with transparent layer, the textures could be optimized to the format RGBA_4_4_4_4.</p>
<p>The optimization process will happens automatically and you don&#8217;t need to worry about it. Even to PVRTC compressed texture format, these optimization could happen, if needed to. The textures, as any other external file, can be loaded from any path locally and the NinevehGL is ready to manage the local paths to you.</p>
<p>Plus, just as the 3D files, textures has a kind of &#8220;cache&#8221;, that means if you load an image more than one time, the NinevehGL will manage the load locally and will not spend more memory with the same cached image. This is a very important optimization, mostly in cases when a 3D file use the same image for many things, like to the ambient, diffuse and specular maps.</p>
<p><br/><a name="more"></a></p>
<h2><strong>Many other things</strong></h2>
<p>There are in NinevehGL many other important features, but I&#8217;ll just point it because other engines also have these features, so it&#8217;s not that exclusive. Like:</p>
<ul>
<li>Cameras with projections (perspective and orthographic).</li>
<li>Customizations of OpenGL behaviors, like the render buffers.</li>
<li>Simple API to make 3D transformations (like obj.rotateX += 1.0).</li>
<li>Always use OpenGL optimization features, as Buffer Objects, array of structures, optimized texture formats, etc.</li>
</ul>
<p>One great thing to talk a little bit more is about the auto-corrections. It&#8217;s very common that the 3D modelers create their models with different scales, I mean, a 3D file which contains a spoon could has the range of vertices going through -1000.0 to 1000.0 and other file which contains a house with the range of -0.5 to 0.7, for example. By placing both files in a 3D softwares you probably will see a house at the side of the empire state in format of a spoon.</p>
<p>For a 3D softwares this is not a big deal, because there are an infinity work space and you can simply reorganize your objects visually. But for a programming language, this is a problem and gets even bigger if the object is so big or so far that you can&#8217;t even see it on the screen.</p>
<p>The NinevehGL auto-correction can solve this problem for you, because it can normalize the vertices positions to fit on the screen (or in a specific range you want). By doing so you can control the size of your models without having to export it again from the 3D software. So in the case of the house and the spoon you could set the auto-correction to fit the house at the range -10.0 to 10.0 and the spoon to -0.1 and 0.1, simple as that (one line of code).</p>
<p><br/><a name="outside"></a></p>
<h2><strong>Outside the Scope</strong></h2>
<p>What you should not expect from NinevehGL? Here is a list:</p>
<ul>
<li>The NinevehGL is not a game engine, it&#8217;s a 3D engine.</li>
<li>So you shouldn&#8217;t expect physics controllers or sound controllers. You should construct this kind of stuff by yourself.</li>
<li>No animation, YET! Animations is very important in the 3D world, but the first version of NinevehGL will not come with this feature. (Animations = Character Rigging + Bones)</li>
<li>No collisions, YET! There are two techniques to deal with collision, bounding box and bounding mesh. In this version, NinevehGL will not implement any of those.</li>
</ul>
<p>Obviously any item in this list can change, because the NinevehGL is flexible. Consider the above list as an &#8220;out of scope&#8221; list only for the first version of the NinevehGL.</p>
<p><br/><a name="conclusion"></a></p>
<h2><strong>Conclusion</strong></h2>
<p>I&#8217;m sure you have now a solid opinion about NinevehGL, good or not, so let me know what you think, post a comment bellow, send me an email, tweet me&#8230; anything.</p>
<p>Again, I don&#8217;t want to make promisses, but I really want to see this engine released soon. So I&#8217;m sure it will come in the first half of this year (2011). I&#8217;m just finishing some details now and organizing everything for the first release.</p>
<p>Thanks for reading,</p>
<p>And see you very soon!</p>
<div id="attachment_1382" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/04/ninevehgl_featured.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/04/ninevehgl_featured.jpg" alt="NinevehGL will come in the first half of 2011." title="ninevehgl_featured" width="600" height="475" class="size-full wp-image-1382" /></a><p class="wp-caption-text">NinevehGL will come in the first half of 2011.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/04/ninevehgl-features/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Khronos EGL and Apple EAGL</title>
		<link>http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/</link>
		<comments>http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 04:56:20 +0000</pubDate>
		<dc:creator>Diney Bomfim</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[OpenGL ES]]></category>

		<guid isPermaLink="false">http://db-in.com/blog/?p=930</guid>
		<description><![CDATA[Hi again everybody! This will be a little article to give support to my full tutorial about OpenGL. In this article I&#8217;ll talk about the EGL API and the EAGL (the EGL API implemented by Apple). We&#8217;ll see how to set up an OpenGL&#8217;s application to comunicate with the device&#8217;s windowing system. I&#8217;ll focus on&#8230;]]></description>
			<content:encoded><![CDATA[<p>Hi again everybody!</p>
<p>This will be a little article to give support to my full tutorial about OpenGL. In this article I&#8217;ll talk about the EGL API and the EAGL (the EGL API implemented by Apple). We&#8217;ll see how to set up an OpenGL&#8217;s application to comunicate with the device&#8217;s windowing system.</p>
<p>I&#8217;ll focus on Objective-C and iOS, but I&#8217;ll talk about the setup in others devices and languages too. So let&#8217;s start!<br />
<span id="more-930"></span><br />
<br/></p>
<h2><strong>At a glance</strong></h2>
<p>As I said in the first part of my full tutorial about OpenGL (<a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13/">click here to see</a>), OpenGL is not responsible by manage the windowing system of each device that support it. OpenGL relinquished this responsability. So, to make the bridge between OpenGL&#8217;s render output and the device&#8217;s screen, Khronos group created the EGL API.</p>
<p>Remember that EGL can be modified by the vendors to fit exactly what they need to their devices and windowing systems. So my big advice in this article is: ALWAYS CONSULT THE EGL INSTRUCTIONS FROM YOUR VENDORS.</p>
<p><br/></p>
<h2><strong>Setup EGL API</strong></h2>
<p>OK, now we&#8217;ll enter in a EGL&#8217;s comum area, independently to the vendors&#8217;s implementation, the EGL&#8217;s logics is always needed.</p>
<p>The first thing that EGL needs to know is where we want to display our content, normally it is done with the function <strong>eglGetDisplay</strong>, which returns a EGLDisplay data type. A constant EGL_DEFAULT_DISPLAY is always implemented by the vendors to return their default display. Right after this you call <strong>eglInitialize</strong> to initialize the EGL API, this function will return a boolean data type to inform the status. So normally you start with the code:</p>
<pre class="brush:csharp">
EGLDisplay display;

display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

if (eglInitialize(display, NULL, NULL))
{
    // Proceed with your code.
}
</pre>
<p>The NULL, NULL parameters are pointers, which you can get the major and minor version of the current EGL&#8217;s implementation. I don&#8217;t want to go deeply here, the important thing is understand this step. The EGL API need to know where is the display to initialize, just it!</p>
<p>OK, the next step is the configuration. Once EGL know the display, it can prepare the bridge between OpenGL&#8217;s output and the device&#8217;s screen. To start constructing this bridge, the EGL needs some configurations, which involve the color format, colors individually, the sizes, the transparency, the samples per pixel, pixel format and many others. By default EGL provide a lot of functions to this step, like <strong>eglGetConfigs</strong> or <strong>eglChooseConfigs</strong>. Here the interference of the vendors is more intense, because they need to provide a bunch of configurations about their systems and devices. I&#8217;ll not describe it here, there are so many systems and languages. So again, always consult your vendors.</p>
<p>The last step is more simple. After all configurations, you instruct EGL API to create a render surface, this means, the surface on which your OpenGL&#8217;s render output will be placed. You can choose between a On-Screen or a Off-Screen surface. The first means your render output will go directly to the device&#8217;s screen, the Off-Screen means that your render output will go to a buffer or to a image file, a snapshot, or anything like that. You can define the surface by using <strong>eglCreateWindowSurface</strong> or <strong>eglCreatePbufferSurface</strong>, both will return an EGLSurface.</p>
<p>But here a little advice, if you want to place your render&#8217;s output onto a Off-Screen surface, is better you use a frame buffer directly with OpenGL&#8217;s API instead to create a EGL&#8217;s PBuffer. Is faster and cost less for your application.</p>
<p>Are we ready now?</p>
<p>Not yet. This is just the platform&#8217;s side of the bridge, EGL has the other side of the bridge, the OpenGL&#8217;s side.</p>
<p><br/></p>
<h2><strong>EGL Context</strong></h2>
<p>Until now, EGL knows all that it need about the windowing system, but now EGL needs to know all about our OpenGL usage. Deeply, EGL works with 2 frame buffers. Do you remember what is frame buffer from the first part of OpenGL&#8217;s tutorial, right? (<a href="http://db-in.com/blog/2011/01/all-about-opengl-es-2-x-part-13#Buffers">click here if not</a>). The EGL API use these 2 frame buffer to place the OpenGL&#8217;s render output into your desired surface.</p>
<p>To make it properly, EGL needs to know where are the OpenGL&#8217;s buffers which you want to render. This step is very simple. All that we need is create a EGL context and make it the current context (yes, we can create many contexts). Once we made a context the current context, the subsequent Frame Buffer we use in OpenGL will be used by EGL context. Only one Frame Buffer can be used at time (the next part of OpenGL&#8217;s tutorial will talk deeply about this). Usually, the EGL functions to context are:</p>
<table width="675">
<tr>
<th>EGL Context</th>
</tr>
<tr>
<td>
<h5><strong>EGLContext eglCreateContext(EGLDisplay display, EGLConfig config, EGLContext shareContext, const EGLint* attribList)</strong></h5>
<p><br/></p>
<ul>
<li><strong>display</strong>: The previously get display.</li>
<li><strong>config</strong>: The previously set configuration.</li>
<li><strong>shareContext</strong>: Usually is EGL_NO_CONTEXT to share no context.</li>
<li><strong>attribList</strong>: To OpenGL ES, this parameter determines which version of OpenGL ES will be used. Value 1 represent a context of OpenGL ES 1.x and a value of 2 represent a context of OpenGL ES 2.x.</li>
</ul>
</td>
</tr>
<tr>
<td>
<h5><strong>EGLBoolean eglmakeCurrent(EGLDisplay display, EGLSurface draw, EGLSurface read, EGLContext context)</strong></h5>
<p><br/></p>
<ul>
<li><strong>display</strong>: The display obtained previously.</li>
<li><strong>draw</strong>: The surface obtained previously.</li>
<li><strong>read</strong>: The same value as draw.</li>
<li><strong>context</strong>: The context to be the current.</li>
</ul>
</td>
</tr>
</table>
<p>Seems a little confused? Don&#8217;t worry. I&#8217;m talking superficially about this. The point here is to you understand which an EGL&#8217;s Context represent the OpenGL&#8217;s side of the bridge. The most important advice I can give you is: Look for the vendors documentation of EGL API.</p>
<p><br/><a name="rendering"></a></p>
<h2><strong>Rendering with EGL Context</strong></h2>
<p>Once the EGL knows about the windowing system and has a context to know about our OpenGL application, we can make our render&#8217;s output be presented onto the desired surface.</p>
<p>The render step is very very simple. Do you remember I said EGL works with 2 internal frame buffers? Now is time to use that. All that we need is instruct the EGL to swap the buffers. Swap? Why?</p>
<p>While EGL present one frame buffer to your desired surface, the other one stay on back waiting for a new render output. The buffer on the back will be filled with all renders you did until the next call to EGL swap the buffers and when you do this, EGL brings the back buffer to the front and present the final render&#8217;s output onto the desired surface, while the old front buffer goes to the back to reinitiate the process.</p>
<p>This technique is a great boost on our application&#8217;s performance, because the our final surface will not be notified every time we execute a render command. The final surface will be notified only when we finish all the renders commands. Another improvement is because the buffer on the back will receive the render&#8217;s outputs faster than a device&#8217;s screen, for example.</p>
<div id="attachment_944" class="wp-caption aligncenter" style="width: 610px"><a href="http://db-in.com/blog/wp-content/uploads/2011/02/swap_buffers_example.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/02/swap_buffers_example.jpg" alt="EGL API swap the buffers to present the render onto the desired surface." title="swap_buffers_example" width="600" height="600" class="size-full wp-image-944" /></a><p class="wp-caption-text">EGL API swap the buffers to present the render onto the desired surface.</p></div>
<p>This is the function to swap the buffers and present the render output onto the desired surface.</p>
<table width="675">
<tr>
<th>Swap the EGL&#8217;s buffers</th>
</tr>
<tr>
<td>
<h5><strong>EGLBoolean eglSwapBuffers(EGLDisplay display, EGLSurface surface)</strong></h5>
<p><br/></p>
<ul>
<li><strong>display</strong>: The display obtained previously.</li>
<li><strong>surface</strong>: The surface obtained previously.</li>
</ul>
</td>
</tr>
</table>
<p>OK, this is all about the EGL making the bridge between the OpenGL&#8217;s core and the windowing systems. I know that seems many steps to just output a simple render. But look from far, is just a little setup:</p>
<ol>
<li>Initialize the EGL API with the display and surface given by your vendor.</li>
<li>Make the configurations to your desired surface.</li>
<li>Create a context and make it your current context.</li>
<li>Ask for your EGL context to swap its internal buffers.</li>
</ol>
<p>Now I&#8217;ll talk about EGL implementation by Apple, which has a lot of changes from the original, many changes!</p>
<p><br/></p>
<h2><strong>EAGL &#8211; The Apple&#8217;s EGL API</strong></h2>
<p><a href="http://db-in.com/blog/wp-content/uploads/2011/02/egl_eagl_apis.jpg"><img src="http://db-in.com/blog/wp-content/uploads/2011/02/egl_eagl_apis-300x196.jpg" alt="" title="egl_eagl_apis" width="300" height="196" class="alignright size-medium wp-image-978" /></a>The EAGL (which we are used to pronounce Eagle) is the implementation by Apple of EGL API. The most important thing to know about EAGL is which the Apple doesn&#8217;t allow us to render directly to the screen. We must to work with frame and render buffers.</p>
<p>But why the Apple changed EGL so much? Well, you know the Apple&#8217;s approach, Cocoa Framework is almost like another language, it has infinities rules, hard rules! If you change the place of one little screw, all the framework will down! So the Apple made that changes to fit the EGL API into the Cocoa&#8217;s rules.</p>
<p>Using EAGL, we must to create a color render buffer and draw our render&#8217;s output into it. Plus, we must to bind that color render buffer to a special Apple&#8217;s layer called CAEAGLLayer. And finally to make a render, we need to ask the context to present that color render buffer. In deeply, this command will swap the buffer just like original EGL context, but our code changes a lot. Let&#8217;s see.</p>
<p><br/></p>
<h2>Setup EAGL API</h2>
<p>The first thing we need to do is create a sub-class from UIVIew. Inside this new class, we need to change its Core Animation layer. Doing this is equivalent in the original EGL API to initialize the API, take the display from the windowing system and define our surface. So, in this equivalence we&#8217;ll have <strong>EGLDisplay = the UIWindow which has our custom view</strong> and <strong>EGLSurface = our sub-class from UIView</strong>.</p>
<p>Our code will be like this:</p>
<pre class="brush:csharp">
#import &lt;UIKit/UIKit.h&gt;

@interface CustomView : UIView

@end

@implementation CustomView

// Overrides the layerClass from UIView.
+ (Class) layerClass
{
    // Instead to return a normal CALayer, we return the special CAEAGLLayer.
    // Inside this CAEAGLLayer the Apple did the most important part
    // of their custom EGL's implementation.
    return [CAEAGLLayer class];
}

@end
</pre>
<p>Now we need to make the step of configure the EGL API defining the color format, the sizes and others. In EAGL we do this step by setting the properties of our CAEAGLLayer. So let&#8217;s code:</p>
<pre class="brush:csharp">
@implementation CustomView

...

- (id) initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
	{
		// Assign a variable to be our CAEAGLLayer temporary.
		CAEAGLLayer *eaglLayer = (CAEAGLLayer *)[self layer];

		// Construct a dictionary with our configurations.
		NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
							 [NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking,
							 kEAGLColorFormatRGB565, kEAGLDrawablePropertyColorFormat,
							 nil];

		// Set the properties to CAEALLayer.
		[eaglLayer setOpaque:YES];
		[eaglLayer setDrawableProperties:dict];

		// Other initializations...
	}

    return self;
}

...

@end
</pre>
<p><br/></p>
<h2>EAGL Context</h2>
<p>Following the EGL API steps, the next one is about the context. Here again the Apple changes almost all to fit the EGL API into their Cocoa Framework. The EAGL API gives to us only two Objective-C classes, one of then is EAGLContext. The EAGLContext is equivalent to EGLContext.</p>
<p>Here I have to admit, even changing everything the Apple made this step easer than EGL API. All that you need is allocate a new instance of EAGLContext initializing it with your desired OpenGL ES&#8217;s version (1.x or 2.x) and call a method to make that context the current one. Here you don&#8217;t have to inform again the EGLDisplay, the EGLSurface, the EGLContext and the others annoying parameters as in the origial EGL API.</p>
<pre class="brush:csharp">
@interface CustomView : UIView
{
	EAGLContext *_context;
}

@end

@implementation CustomView

...

- (id) initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
	{
		// Other initializations...

		// Create a EAGLContext using the OpenGL ES 2.x.
		_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

		// Make our new context, the current context.
		[EAGLContext setCurrentContext:_context];
	}

    return self;
}

...

@end
</pre>
<p><br/><a name="renderingeagl"></a></p>
<h2>Rendering with EAGL Context</h2>
<p>Next step!<br />
By following the above EGL&#8217;s steps the next one is the swap the buffers (rendering). But here the Apple changed the thing a lot. As I said before, to use EAGL we must to create at least a color render buffer, this necessarily needs a frame buffer too. So in the reality the next step should be the buffers creations. I could describe this step here, but as this article is just a middle point between the first and the second part of my full tutorial, describe it is not my intention here. I&#8217;ll let this discussion to the next part of that tutorial.</p>
<p>So let&#8217;s go to the final EAGL&#8217;s step, the rendering.<br />
I told you Apple uses a color render buffer instead to directly swap the context&#8217;s buffers. By doing this, Apple simplified the last step, the swap of the buffers. Instead to swap the buffers informing the desired display and surface, we just ask our EAGLContext to present its render buffer.</p>
<pre class="brush:csharp">
@interface CustomView : UIView
{
	EAGLContext *_context;
}

- (void) makeRender;

@end

@implementation CustomView

...

- (void) makeRender
{
	[_context presentRenderbuffer:GL_RENDERBUFFER];
}

...

@end
</pre>
<p>The param GL_RENDERBUFFER to <strong>presentRenderbuffer</strong> is a constant and is just for internal usage. This call should occurs just after we perform all our changes to our 3D objects, like translates or rotations.</p>
<p>Well, this is all the basic instructions about EGL and EAGL APIs. Obviously using EAGL, you could take a more OOP approach, by separating your custom UIView of the other class which hold the EAGLContext instance and makes the final presentation.</p>
<p>Now, as we are used to, let&#8217;s remember the steps using the EAGL.</p>
<ol>
<li>Make a sub-class from UIView and override the layerClass method to return an instance of CAEAGLLayer;</li>
<li>Set up the properties to the CAEAGLLayer;</li>
<li>Create an instance from EAGLContext;</li>
<li>Present a color render buffer onto the screen by using the EAGLContext.</li>
</ol>
<p><br/></p>
<h2><strong>Conclusion</strong></h2>
<p>Well done, my friends.<br />
Think in this article like an abstract class! Is a little step, but is also so much annoying to cover this in the second part of my OpenGL&#8217;s tutorial.</p>
<p>If you were to save only a single sentence of this entire article, the phrase would be: &#8220;Consult the EGL instruction from your vendors!&#8221;. The vendors don&#8217;t interfere inside OpenGL, so I can talk about it independently from the system or language. But the EGL API is the bridge between a unified OpenGL API and all the systems which support OpenGL. So the interference from the vendors on the EGL is bigger! Just like the Apple did!</p>
<p>Thanks for reading!</p>
<p>See you in the next part of OpenGL&#8217;s tutorial!</p>
]]></content:encoded>
			<wfw:commentRss>http://db-in.com/blog/2011/02/khronos-egl-and-apple-eagl/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

