<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
	<title>Technical - Articles</title>
	<link>http://www.gamedev.net/page/resources/_/technical/</link>
	<pubDate>Sat, 25 Feb 2012 21:04:36 +0000</pubDate>
	<ttl>43200</ttl>
	<description>Languages, SDKs, engines, engineering, APIs, networking and other technical development resources</description>
	<item>
		<title>Using Animated Pieces in a Board-based Game wit...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/directx-and-xna/using-animated-pieces-in-a-board-based-game-wit-r2884</link>
		<description><![CDATA[This article by <strong class='bbc'>Kurt Jaegers</strong>, author of <a href='http://www.packtpub.com/xna-4-0-game-development-by-example-beginners-guide/book/rk/xna4_abr2/0910?utm_source=rk_xna4_abr2_0910&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>XNA 4.0 Game Development by Example: Beginner's Guide</a>, enhances a board-based puzzle game called <a href='http://www.packtpub.com/article/building-board-based-puzzle-game-with-microsoft-xna-4' class='bbc_url' title='External link' rel='nofollow external'>Flood Control in XNA 4.0</a> using animation. In this article, we will cover:<ul class='bbc'><br /><li>Animating the rotation of pieces when manipulated by the player<br /></li><li>Gradually fading out pieces of completed scoring chains<br /></li><li>Animating the falling of pieces into place on the board<br /></li></ul><br />
All of these enhancements will give the player a better game experience, as well as give us the opportunity to learn more about how the SpriteBatch class can be used for animation.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Animated pieces</strong></span><br />
We will define three different types of animated pieces: rotating, falling, and fading. The animation for each of these types will be accomplished by altering the parameters of the <em class='bbc'>SpriteBatch.Draw()</em> call.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Classes for animated pieces</strong></span><br />
In order to represent the three types of animated pieces, we will create three new classes. Each of these classes will inherit from the GamePiece class, meaning they will contain all of the methods and members of the GamePiece class, but add additional information to support the animation.<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Child classes</strong><br />
Child classes inherit all of their parent's members and methods. The RotatingPiece class can refer to the <em class='bbc'>pieceType</em> and <em class='bbc'>suffix</em> of the piece without recreating them within RotatingPiece itself. Additionally, child classes can extend the functionality of their base class, adding new methods and properties or overriding old ones. In fact, Game1 itself is a child of the <em class='bbc'>Micrsoft.Xna.Game</em> class, which is why all of the methods we use (<em class='bbc'>Update()</em>, <em class='bbc'>Draw()</em>, <em class='bbc'>LoadContent()</em>, and so on) are declared as "override".</em></p><br />
Let's begin by creating the class we will use for rotating pieces.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – rotating pieces</strong></span><br />
Open your existing Flood Control project in Visual C# Express if it is not already active.<br />
<br />
Add a new class to the project called "RotatingPiece".<br />
<br />
Add "<em class='bbc'>using Microsoft.Xna.Framework;</em>" to the <em class='bbc'>using</em> area at the top of the class.<br />
<br />
Update the declaration of the class to read <em class='bbc'>class RotatingPiece : GamePiece</em>.<br />
<br />
Add the following declarations to the <em class='bbc'>RotatingPiece</em> class:<br />
<br />
	<pre class='prettyprint'>public bool clockwise;<br /><br />public static float rotationRate = (MathHelper.PiOver2 / 10);<br />private float rotationAmount = 0;<br />public int rotationTicksRemaining = 10;</pre><br />
Add a property to retrieve the current rotation amount:<br />
<br />
	<pre class='prettyprint'>public float RotationAmount<br />{<br />get<br />{<br />  if (clockwise)<br />	return rotationAmount;<br />  else<br />	return (MathHelper.Pi*2) - rotationAmount;<br />}<br />}</pre><br />
Add a constructor for the RotatingPiece class:<br />
<br />
	<pre class='prettyprint'>public RotatingPiece(string pieceType, bool clockwise)<br />	  : base(pieceType)<br />{<br />  this.clockwise = clockwise;<br />}</pre><br />
Add a method to update the piece:<br />
<br />
	<pre class='prettyprint'>public void UpdatePiece()<br />{<br />   rotationAmount += rotationRate;<br />   rotationTicksRemaining = (int)MathHelper.Max(0,<br />							rotationTicksRemaining-1);<br />}</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
In step 2, we modified the declaration of the RotatingPiece class by adding <em class='bbc'>: GamePiece</em> to the end of it. This indicates to Visual C# that the RotatingPiece class is a child of the GamePiece class.<br />
<br />
The clockwise variable stores a "true" value if the piece will be rotating clockwise and "false" if the rotation is counter-clockwise.<br />
<br />
When a game piece is rotated, it will turn a total of 90 degrees (or pi/2 radians) over <em class='bbc'>10</em> animation frames. The MathHelper class provides a number of constants to represent commonly used numbers, with <em class='bbc'>MathHelper.PiOver2</em> being equal to the number of radians in a 90 degree angle. We divide this constant by <em class='bbc'>10</em> and store the result as the <em class='bbc'>rotationRate</em> for use later. This number will be added to the <em class='bbc'>rotationAmount</em> float, which will be referenced when the animated piece is drawn.<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Working with radians</strong><br />
All angular math is handled in radians from XNA's point of view. A complete (360 degree) circle contains 2*pi radians. In other words, one radian is equal to about 57.29 degrees. We tend to relate to circles more often in terms of degrees (a right angle being 90 degrees, for example), so if you prefer to work with degrees, you can use the <em class='bbc'>MathHelper.ToRadians()</em> method to convert your values when supplying them to XNA classes and methods.</em></p><br />
The final declaration, <em class='bbc'>rotationTicksRemaining</em>, is reduced by one each time the piece is updated. When this counter reaches zero, the piece has finished animating.<br />
<br />
When the piece is drawn, the <em class='bbc'>RotationAmount</em> property is referenced by a <em class='bbc'>spriteBatch</em>. <em class='bbc'>Draw()</em> call and returns either the <em class='bbc'>rotationAmount</em> property (in the case of a clockwise rotation) or 2*pi (a full circle) minus the <em class='bbc'>rotationAmount</em> if the rotation is counter-clockwise.<br />
<br />
The constructor in step 7 illustrates how the parameters passed to a constructor can be forwarded to the class' parent constructor via the <em class='bbc'>:base</em> specification. Since the GamePiece class has a constructor that accepts a piece type, we can pass that information along to its constructor while using the second parameter (clockwise) to update the clockwise member that does not exist in the GamePiece class. In this case, since both the clockwise member and the clockwise parameter have identical names, we specify <em class='bbc'>this.clockwise</em> to refer to the clockwise member of the RotatingPiece class. Simply <em class='bbc'>clockwise</em> in this scope refers only to the parameter passed to the constructor.<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>this notation</strong><br />
You can see that it is perfectly valid C# code to have method parameter names that match the names of class variables, thus potentially hiding the class variables from being used in the method (since referring to the name inside the method will be assumed to refer to the parameter). To ensure that you can always access your class variables even when a parameter name conflicts, you can preface the variable name with <em class='bbc'>this</em>. when referring to the class variable. <em class='bbc'>this</em>. indicates to C# that the variable you want to use is part of the class, and not a local method parameter.</em></p><br />
Lastly, the <em class='bbc'>UpdatePiece()</em> method simply increases the <em class='bbc'>rotationAmount</em> member while decreasing the <em class='bbc'>rotationTicksRemaining</em> counter (using <em class='bbc'>MathHelper.Max()</em> to ensure that the value does not fall below zero).<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – falling pieces</strong></span><br />
Add a new class to the Flood Control project called "FallingPiece".<br />
<br />
Add <em class='bbc'>using Microsoft.Xna.Framework;</em> to the <em class='bbc'>using</em> area at the top of the class.<br />
<br />
Update the declaration of the class to read <em class='bbc'>class FallingPiece : GamePiece</em><br />
<br />
Add the following declarations to the <em class='bbc'>FallingPiece</em> class:<br />
<br />
	<pre class='prettyprint'>public int VerticalOffset;<br />public static int fallRate = 5;</pre><br />
Add a constructor for the FallingPiece class:<br />
<br />
	<pre class='prettyprint'>public FallingPiece(string pieceType, int verticalOffset)<br />	: base(pieceType)<br />{<br />  VerticalOffset = verticalOffset;<br />}</pre><br />
Add a method to update the piece:<br />
<br />
	<pre class='prettyprint'>public void UpdatePiece()<br />{<br />   VerticalOffset = (int)MathHelper.Max(<br />			0,<br />			VerticalOffset - fallRate);<br />}</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
Simpler than a RotatingPiece, a FallingPiece is also a child of the GamePiece class. A falling piece has an offset (how high above its final destination it is currently located) and a falling speed (the number of pixels it will move per update).<br />
<br />
As with a RotatingPiece, the constructor passes the <em class='bbc'>pieceType</em> parameter to its base class constructor and uses the <em class='bbc'>verticalOffset</em> parameter to set the <em class='bbc'>VerticalOffset</em> member. Note that the capitalization on these two items differs. Since <em class='bbc'>VerticalOffset</em> is declared as public and therefore capitalized by common C# convention, there is no need to use the "this" notation, since the two variables technically have different names.<br />
<br />
Lastly, the <em class='bbc'>UpdatePiece()</em> method subtracts <em class='bbc'>fallRate</em> from <em class='bbc'>VerticalOffset</em>, again using the <em class='bbc'>MathHelper.Max()</em> method to ensure the offset does not fall below zero.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – fading pieces</strong></span><br />
Add a new class to the Flood Control project called "FadingPiece".<br />
<br />
Add using <em class='bbc'>Microsoft.Xna.Framework;</em> to the <em class='bbc'>using</em> area at the top of the class.<br />
<br />
Update the declaration of the class to read class <em class='bbc'>FadingPiece : GamePiece</em><br />
<br />
Add the following declarations to the <em class='bbc'>FadingPiece</em> class:<br />
<br />
	<pre class='prettyprint'>public float alphaLevel = 1.0f;<br />public static float alphaChangeRate = 0.02f;</pre><br />
Add a constructor for the <em class='bbc'>FadingPiece</em> class:<br />
<br />
	<pre class='prettyprint'>public FadingPiece(string pieceType, string suffix)<br />	: base(pieceType, suffix)<br />{<br />}</pre><br />
Add a method to update the piece:<br />
<br />
	<pre class='prettyprint'>public void UpdatePiece()<br />{<br />alphaLevel = MathHelper.Max(<br />	   0,<br />	   alphaLevel - alphaChangeRate);<br />}</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The simplest of our animated pieces, the <em class='bbc'>FadingPiece</em> only requires an alpha value (which always starts at 1.0f, or fully opaque) and a rate of change. The <em class='bbc'>FadingPiece</em> constructor simply passes the parameters along to the base constructor.<br />
<br />
When a <em class='bbc'>FadingPiece</em> is updated, <em class='bbc'>alphaLevel</em> is reduced by <em class='bbc'>alphaChangeRate</em>, making the piece more transparent.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Managing animated pieces</strong></span><br />
Now that we can create animated pieces, it will be the responsibility of the GameBoard class to keep track of them. In order to do that, we will define a <em class='bbc'>Dictionary</em> object for each type of piece.<br />
<br />
A <em class='bbc'>Dictionary</em> is a collection object similar to a List, except that instead of being organized by an index number, a dictionary consists of a set of key and value pairs. In an array or a List, you might access an entity by referencing its index as in <em class='bbc'>dataValues[2] = 12;</em> With a <em class='bbc'>Dictionary</em>, the index is replaced with your desired key type. Most commonly this will be a string value. This way, you can do something like <em class='bbc'>fruitColors["Apple"]="red";</em><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – updating GameBoard to support animated pieces</strong></span><br />
In the declarations section of the GameBoard class, add three dictionaries:<br />
<br />
	<pre class='prettyprint'>public Dictionary&lt;string, FallingPiece&gt; fallingPieces =<br />new Dictionary&lt;string, FallingPiece&gt;();<br />public Dictionary&lt;string, RotatingPiece&gt; rotatingPieces =<br />new Dictionary&lt;string, RotatingPiece&gt;();<br />public Dictionary&lt;string, FadingPiece&gt; fadingPieces =<br />new Dictionary&lt;string, FadingPiece&gt;();</pre><br />
Add methods to the GameBoard class to create new falling piece entries in the dictionaries:<br />
<br />
	<pre class='prettyprint'>public void AddFallingPiece(int X, int Y,<br />  string PieceName, int VerticalOffset)<br />{<br />  fallingPieces&#91;X.ToString() + "_" + Y.ToString()&#93; = new<br />	   FallingPiece(PieceName, VerticalOffset);<br />}<br /><br />public void AddRotatingPiece(int X, int Y,<br />string PieceName, bool Clockwise)<br />{<br />  rotatingPieces&#91;X.ToString() + "_" + Y.ToString()&#93; = new<br />	   RotatingPiece(PieceName, Clockwise);<br />}<br /><br />public void AddFadingPiece(int X, int Y, string PieceName)<br />{<br />  fadingPieces&#91;X.ToString() + "_" + Y.ToString()&#93; = new<br />	   FadingPiece(PieceName,"W");<br />}</pre><br />
Add the <em class='bbc'>ArePiecesAnimating()</em> method to the GameBoard class:<br />
<br />
	<pre class='prettyprint'>{<br />if ((fallingPieces.Count == 0) &&<br />	 (rotatingPieces.Count == 0) &&<br />	 (fadingPieces.Count == 0))<br />{<br />   return false;<br />}<br />else<br />{<br />   return true;<br />}<br />}</pre><br />
Add the <em class='bbc'>UpdateFadingPieces()</em> method to the GameBoard class:<br />
<br />
	<pre class='prettyprint'>private void UpdateFadingPieces()<br />{<br />  Queue&lt;string&gt; RemoveKeys = new Queue&lt;string&gt;();<br /><br />  foreach (string thisKey in fadingPieces.Keys)<br />  {<br />	fadingPieces&#91;thisKey&#93;.UpdatePiece();<br />	if (fadingPieces&#91;thisKey&#93;.alphaLevel == 0.0f)<br />		RemoveKeys.Enqueue(thisKey.ToString());<br />  }<br />  while (RemoveKeys.Count &gt; 0)<br />	  fadingPieces.Remove(RemoveKeys.Dequeue());<br />}</pre><br />
Add the <em class='bbc'>UpdateFallingPieces()</em> method to the GameBoard class:<br />
<br />
	<pre class='prettyprint'>private void UpdateFallingPieces()<br />{<br />  Queue&lt;string&gt; RemoveKeys = new Queue&lt;string&gt;();<br />  foreach (string thisKey in fallingPieces.Keys)<br />  {<br />   fallingPieces&#91;thisKey&#93;.UpdatePiece();<br />   if (fallingPieces&#91;thisKey&#93;.VerticalOffset == 0)<br />	   RemoveKeys.Enqueue(thisKey.ToString());<br />  }<br />  while (RemoveKeys.Count &gt; 0)<br />	 fallingPieces.Remove(RemoveKeys.Dequeue());<br />}</pre><br />
Add the <em class='bbc'>UpdateRotatingPieces()</em> method to the GameBoard class:<br />
<br />
	<pre class='prettyprint'>private void UpdateRotatingPieces()<br />{<br />  Queue&lt;string&gt; RemoveKeys = new Queue&lt;string&gt;();<br />  foreach (string thisKey in rotatingPieces.Keys)<br />  {<br />   rotatingPieces&#91;thisKey&#93;.UpdatePiece();<br />   if (rotatingPieces&#91;thisKey&#93;.rotationTicksRemaining == 0)<br />	   RemoveKeys.Enqueue(thisKey.ToString());<br />  }<br />  while (RemoveKeys.Count &gt; 0)<br />	   rotatingPieces.Remove(RemoveKeys.Dequeue());<br />}</pre><br />
Add the <em class='bbc'>UpdateAnimatedPieces()</em> method to the GameBoard class:<br />
<br />
	<pre class='prettyprint'>public void UpdateAnimatedPieces()<br />{<br />  if (fadingPieces.Count == 0)<br />  {<br />	UpdateFallingPieces();<br />	UpdateRotatingPieces();<br />  }<br />  else<br />  {<br />	UpdateFadingPieces();<br />  }<br />}</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
After declaring the three <em class='bbc'>Dictionary</em> objects, we have three methods used by the GameBoard class to create them when necessary. In each case, the key is built in the form "X_Y", so an animated piece in column 5 on row 4 will have a key of "5_4". Each of the three <em class='bbc'>Add...</em> methods simply pass the parameters along to the constructor for the appropriate piece types after determining the key to use.<br />
<br />
When we begin drawing the animated pieces, we want to be sure that animations finish playing before responding to other input or taking other game actions (like creating new pieces). The <em class='bbc'>ArePiecesAnimating()</em> method returns "true" if any of the <em class='bbc'>Dictionary</em> objects contain entries. If they do, we will not process any more input or fill empty holes on the game board until they have completed.<br />
<br />
The <em class='bbc'>UpdateAnimatedPieces()</em> method will be called from the game's <em class='bbc'>Update()</em> method and is responsible for calling the three different update methods above (<em class='bbc'>UpdateFadingPiece()</em>, <em class='bbc'>UpdateFallingPiece()</em>, and <em class='bbc'>UpdateRotatingPiece()</em>) for any animated pieces currently on the board. The first line in each of these methods declares a <em class='bbc'>Queue</em> object called RemoveKeys. We will need this because C# does not allow you to modify a <em class='bbc'>Dictionary</em> (or List, or any of the similar "generic collection" objects) while a <em class='bbc'>foreach</em> loop is processing them.<br />
<br />
A <em class='bbc'>Queue</em> is yet another generic collection object that works like a line at the bank. People stand in a line and await their turn to be served. When a bank teller is available, the first person in the line transacts his/her business and leaves. The next person then steps forward. This type of processing is known as FIFO, or First In, First Out.<br />
<br />
Using the <em class='bbc'>Enqueue()</em> and <em class='bbc'>Dequeue()</em> methods of the Queue class, objects can be added to the <em class='bbc'>Queue</em> (<em class='bbc'>Enqueue()</em>) where they await processing. When we want to deal with an object, we <em class='bbc'>Dequeue()</em> the oldest object in the <em class='bbc'>Queue</em> and handle it. <em class='bbc'>Dequeue()</em> returns the first object waiting to be processed, which is the oldest object added to the <em class='bbc'>Queue</em>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Collection classes</strong></span><br />
C# provides a number of different "collection" classes, such as the Dictionary, Queue, List, and Stack objects. Each of these objects provides different ways to organize and reference the data in them. For information on the various collection classes and when to use each type, see the following MSDN entry: <a href='http://msdn.microsoft.com/en-us/library/6tc79sx1(VS.80).aspx' class='bbc_url' title='External link' rel='nofollow external'>http://msdn.microsof.&#46;&#46;/6tc79sx1(VS.80).aspx</a><br />
<br />
Each of the update methods loops through all of the keys in its own <em class='bbc'>Dictionary</em> and in turn calls the <em class='bbc'>UpdatePiece()</em> method for each key. Each piece is then checked to see if its animation has completed. If it has, its key is added to the <em class='bbc'>RemoveKeys</em> queue. After all of the pieces in the <em class='bbc'>Dictionary</em> have been processed, any keys that were added to <em class='bbc'>RemoveKeys</em> are then removed from the <em class='bbc'>Dictionary</em>, eliminating those animated pieces.<br />
<br />
If there are any FadingPieces currently active, those are the only animated pieces that <em class='bbc'>UpdateAnimatedPieces()</em> will update. When a row is completed, the scoring tiles fade out, the tiles above them fall into place, and new tiles fall in from above. We want all of the fading to finish before the other tiles start falling (or it would look strange as the new tiles pass through the fading old tiles).<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Fading pieces</strong></span><br />
In the discussion of <em class='bbc'>UpdateAnimatedPieces()</em>, we stated that fading pieces are added to the board whenever the player completes a scoring chain. Each piece in the chain is replaced with a fading piece.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – generating fading pieces</strong></span><br />
In the Game1 class, modify the <em class='bbc'>CheckScoringChain()</em> method by adding the following call inside the <em class='bbc'>foreach</em> loop before the square is set to "Empty":<br />
<br />
	<pre class='prettyprint'>gameBoard.AddFadingPiece(<br />(int)ScoringSquare.X,<br />(int)ScoringSquare.Y,<br />gameBoard.GetSquare(<br />  (int)ScoringSquare.X,<br />  (int)ScoringSquare.Y));</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
Adding fading pieces is simply a matter of getting the square (before it is replaced with an empty square) and adding it to the <em class='bbc'>FadingPieces</em> dictionary. We need to use the <em class='bbc'>(int)</em> typecasts because the <em class='bbc'>ScoringSquare</em> variable is a <em class='bbc'>Vector2</em> value, which stores its X and Y components as floats.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Falling pieces</strong></span><br />
Falling pieces are added to the game board in two possible locations: From the <em class='bbc'>FillFromAbove()</em> method when a piece is being moved from one location on the board to another, and in the <em class='bbc'>GenerateNewPieces()</em> method, when a new piece falls in from the top of the game board.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – generating falling pieces</strong></span><br />
Modify the <em class='bbc'>FillFromAbove()</em> method of the GameBoard class by adding a call to generate falling pieces right before the <em class='bbc'>rowLookup = -1;</em> line:<br />
<br />
	<pre class='prettyprint'>AddFallingPiece(x, y, GetSquare(x, y),<br />   GamePiece.PieceHeight *(y-rowLookup));</pre><br />
Update the <em class='bbc'>GenerateNewPieces()</em> method by adding the following call right after the <em class='bbc'>RandomPiece(x,y)</em> line:<br />
<br />
	<pre class='prettyprint'>AddFallingPiece(x, y, GetSquare(x, y),<br />   GamePiece.PieceHeight * GameBoardHeight);</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
When <em class='bbc'>FillFromAbove()</em> moves a piece downward, we now create an entry in the <em class='bbc'>FallingPieces</em> dictionary that is equivalent to the newly moved piece. The vertical offset is set to the height of a piece (40 pixels) times the number of board squares the piece was moved. For example, if the empty space was at location 5,5 on the board, and the piece above it (5,4) is being moved down one block, the animated piece is created at 5,5 with an offset of 40 pixels (5-4 = 1, times 40).<br />
<br />
When new pieces are generated for the board, they are added with an offset equal to the height (in pixels) of the game board, determined by multiplying the <em class='bbc'>GamePiece.PieceHeight</em> value by the <em class='bbc'>GameBoardHeight</em>. This means they will always start above the playing area and fall into it.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Rotating pieces</strong></span><br />
The last type of animated piece we need to deal with adding during play is the rotation piece. This piece type is added whenever the user clicks on a game piece.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – modify Game1 to generate rotating pieces</strong></span><br />
Update the <em class='bbc'>HandleMouseInput()</em> method in the Game1 class to add rotating pieces to the board by adding the following inside the <em class='bbc'>if (mouseState.LeftButton == ButtonState.Pressed)</em> block before <em class='bbc'>gameBoard.RotatePiece()</em> is called:<br />
<br />
	<pre class='prettyprint'>gameBoard.AddRotatingPiece(x, y,<br />	gameBoard.GetSquare(x, y), false);</pre><br />
Still in <em class='bbc'>HandleMouseInput()</em>, add the following in the same location inside the <em class='bbc'>if</em> block for the right mouse button:<br />
<br />
	<pre class='prettyprint'>gameBoard.AddRotatingPiece(x, y,<br />   gameBoard.GetSquare(x, y), true);</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
Recall that the only difference between a clockwise rotation and a counter-clockwise rotation (from the standpoint of the <em class='bbc'>AddRotatingPiece()</em> method) is a true or false in the final parameter. Depending on which button is clicked, we simply add the current square (before it gets rotated, otherwise the starting point for the animation would be the final position) and "true" for right mouse clicks or "false" for left mouse clicks.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Calling UpdateAnimatedPieces()</strong></span><br />
In order for the <em class='bbc'>UpdateAnimatedPieces()</em> method of the GameBoard class to run, the game's <em class='bbc'>Update()</em> method needs to be modified to call it.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – updating Game1 to update animated pieces</strong></span><br />
Modify the <em class='bbc'>Update()</em> method of the Game1 class by replacing the current <em class='bbc'>case</em> statement for the <em class='bbc'>GameState.Playing</em> state with:<br />
<br />
	<pre class='prettyprint'>case GameStates.Playing:<br />  timeSinceLastInput +=<br />	(float)gameTime.ElapsedGameTime.TotalSeconds;<br />  if (gameBoard.ArePiecesAnimating())<br />  {<br />   gameBoard.UpdateAnimatedPieces();<br />  }<br />  else<br />  {<br />   gameBoard.ResetWater();<br /><br />   for (int y = 0; y &lt; GameBoard.GameBoardHeight; y++)<br />   {<br />	CheckScoringChain(gameBoard.GetWaterChain(y));<br />   }<br />   gameBoard.GenerateNewPieces(true);<br /><br />   if (timeSinceLastInput &gt;= MinTimeSinceLastInput)<br />   {<br />	HandleMouseInput(Mouse.GetState());<br />   }<br />  }<br />  break;</pre><br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
This method is very similar to its previous incarnation. In this instance, we check to see if there are outstanding animated pieces to process. If there are, <em class='bbc'>UpdateAnimatedPieces()</em> is run. If no animated pieces currently exist, the previous behaviour of the <em class='bbc'>GameStates</em>. <em class='bbc'>Playing</em> case is executed.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Drawing animated pieces</strong></span><br />
Our animated pieces are almost completed. In fact, they all function right now but you cannot see them because we have not yet updated <em class='bbc'>Draw()</em> to take them into account.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action – update Game1 to draw animated pieces</strong></span><br />
Add methods to the Game1 class to draw each potential type of game piece (animated and non-animated):<br />
<br />
	<pre class='prettyprint'>private void DrawEmptyPiece(int pixelX, int pixelY)<br />{<br />  spriteBatch.Draw(<br />   playingPieces,<br />   new Rectangle(pixelX, pixelY,<br />	GamePiece.PieceWidth, GamePiece.PieceHeight),<br />	EmptyPiece,<br />	Color.White);<br />}<br /><br />private void DrawStandardPiece(int x, int y,<br />  int pixelX, int pixelY)<br />{<br />  spriteBatch.Draw(<br />   playingPieces, new Rectangle(pixelX, pixelY,<br />	 GamePiece.PieceWidth, GamePiece.PieceHeight),<br />   gameBoard.GetSourceRect(x, y),<br />   Color.White);<br />}<br /><br />private void DrawFallingPiece(int pixelX, int pixelY,<br />	string positionName)<br />{<br />  spriteBatch.Draw(<br />   playingPieces,<br />   new Rectangle(pixelX, pixelY -<br />	 gameBoard.fallingPieces&#91;positionName&#93;.VerticalOffset,<br />	  GamePiece.PieceWidth, GamePiece.PieceHeight),<br />	  gameBoard.fallingPieces&#91;positionName&#93;.GetSourceRect(),<br />	 Color.White);<br />}<br /><br />private void DrawFadingPiece(int pixelX, int pixelY,<br />   string positionName)<br />{<br />  spriteBatch.Draw(<br />   playingPieces,<br />   new Rectangle(pixelX, pixelY,<br />	GamePiece.PieceWidth, GamePiece.PieceHeight),<br />   gameBoard.fadingPieces&#91;positionName&#93;.GetSourceRect(),<br />   Color.White *<br />	gameBoard.fadingPieces&#91;positionName&#93;.alphaLevel);<br />}<br /><br />private void DrawRotatingPiece(int pixelX, int pixelY,<br />   string positionName)<br />{<br />  spriteBatch.Draw(<br />   playingPieces,<br />   new Rectangle(pixelX + (GamePiece.PieceWidth / 2),<br />	   pixelY + (GamePiece.PieceHeight / 2),<br />	   GamePiece.PieceWidth,<br />	   GamePiece.PieceHeight),<br />   gameBoard.rotatingPieces&#91;positionName&#93;.GetSourceRect(),<br />   Color.White,<br />   gameBoard.rotatingPieces&#91;positionName&#93;.RotationAmount,<br />   new Vector2(GamePiece.PieceWidth / 2,<br />	 GamePiece.PieceHeight / 2),<br />   SpriteEffects.None, 0.0f);<br />}</pre><br />
Modify the <em class='bbc'>Draw()</em> method of the Game1 class by replacing the <em class='bbc'>for</em> loop that currently draws the playing pieces with:<br />
<br />
	<pre class='prettyprint'>for (int x = 0; x &lt; GameBoard.GameBoardWidth; x++)<br />  for (int y = 0; y &lt; GameBoard.GameBoardHeight; y++)<br />  {<br />   int pixelX = (int)gameBoardDisplayOrigin.X +<br />	   (x * GamePiece.PieceWidth);<br />   int pixelY = (int)gameBoardDisplayOrigin.Y +<br />	   (y * GamePiece.PieceHeight);<br /><br />   DrawEmptyPiece(pixelX, pixelY);<br /><br />   bool pieceDrawn = false;<br /><br />   string positionName = x.ToString() + "_" + y.ToString();<br /><br />   if (gameBoard.rotatingPieces.ContainsKey(positionName))<br />   {<br />	DrawRotatingPiece(pixelX, pixelY, positionName);<br />	pieceDrawn = true;<br />   }<br /><br />   if (gameBoard.fadingPieces.ContainsKey(positionName))<br />   {<br />	DrawFadingPiece(pixelX, pixelY, positionName);<br />	pieceDrawn = true;<br />   }<br /><br />   if (gameBoard.fallingPieces.ContainsKey(positionName))<br />   {<br />	DrawFallingPiece(pixelX, pixelY, positionName);<br />	pieceDrawn = true;<br />   }<br /><br />   if (!pieceDrawn)<br />   {<br />	DrawStandardPiece(x, y, pixelX, pixelY);<br />   }<br />}</pre><br />
Try it out! Run your game and complete a few rows.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>	What just happened?</strong></span><br />
To keep things organized, we have split the drawing of each of the different potential piece types into its own small method. These methods (<em class='bbc'>DrawEmptyPiece()</em>, <em class='bbc'>DrawStandardPiece()</em>, <em class='bbc'>DrawFallingPiece()</em>, <em class='bbc'>DrawFadingPiece()</em>, and <em class='bbc'>DrawRotatingPiece()</em>) each contain only a single statement to draw the piece.<br />
<br />
Before we look at how each of the pieces is actually drawn, let's examine the way we determine which of these methods to call when drawing a piece. The structure of the drawing loop is still the same as it was before we added animated pieces: each square on the board is looped through, with a blank square being drawn first in each position.<br />
<br />
After the blank space, a new Boolean value called <em class='bbc'>pieceDrawn</em> is declared and set to false. If an animated piece occupies a square, only the animated piece will be drawn, and not the underlying game piece.<br />
<br />
The reason for this is that when the user clicks on the mouse button to rotate a piece, in memory the piece is rotated immediately. The animated piece that the user sees is inserted into the drawing process so it looks like the piece is turning. If both the animated piece and the real underlying piece were to be drawn, the final rotation position would be visible overlaid on top of the rotating piece while the rotation animation was playing.<br />
<br />
The <em class='bbc'>positionName</em> string contains the dictionary key for the space we are currently drawing (in "X_Y" format). We use this to check each of the animated piece dictionaries to see if they contain an entry for that key.<br />
<br />
If they do, the animated piece is drawn and the <em class='bbc'>pieceDrawn</em> variable is set to true. If the piece still has not been drawn after all of the dictionaries have been checked, the base piece is drawn just as it was before.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>SpriteBatch overloads</strong></span><br />
Both falling and fading pieces are drawn using the <em class='bbc'>SpriteBatch.Draw()</em> overload that we are already familiar with; where a <em class='bbc'>Texture2D</em>, destination <em class='bbc'>Rectangle</em>, source <em class='bbc'>Rectangle</em>, and <em class='bbc'>Color</em> are specified when drawing. By multiplying our base drawing color (white) by the alpha value for a fading piece, we cause the whole piece to be drawn partially transparent. As the time passes, the alpha value will reach zero, and the piece will be fully transparent.<br />
<br />
However, rotated pieces need to use an extended version of the <em class='bbc'>SpriteBatch.Draw()</em> call. The first four parameters are the same as our existing <em class='bbc'>Draw()</em> calls. To these parameters, we add a float for the rotation amount, a <em class='bbc'>Vector2</em> for the origin around which the rotation takes place, a <em class='bbc'>SpriteEffects</em> property (set to <em class='bbc'>SpriteEffects.None</em> in this case) and a sorting depth (set to 0, or the top level).<br />
<br />
When using a rotation with this form of the <em class='bbc'>SpriteBatch.Draw()</em> call, it is necessary to specify the point around which the sprite should be rotated. If we were to set the origin to <em class='bbc'>Vector2.Zero</em> (equivalent to 0, 0) the sprite would rotate around the upper left corner of the image, swinging into the spaces of other tiles on the board. The center point of the sprite is specified in local sprite coordinates (as opposed to screen coordinates, or even coordinates within the texture the sprite is being pulled from). The local coordinates of the sprite range from 0, 0 in the upper left corner to the height and width of the sprite in the lower right. In our case, the lower right corner of the sprite is <em class='bbc'>GamePiece.PieceWidth</em>, <em class='bbc'>GamePiece.PieceHeight</em>, or 40, 40.<br />
<br />
By specifying <em class='bbc'>new Vector2(GamePiece.PieceWidth/2, GamePiece.PieceHeight/2)</em> we are setting the origin to the center of the sprite, meaning it will rotate in place as expected.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
In the above article we covered:<ul class='bbc'><br /><li>Animating the rotation of pieces when manipulated by the player<br /></li><li>Gradually fading out pieces of completed scoring chains<br /></li><li>Animating the falling of pieces into place on the board<br /></li></ul>]]></description>
		<pubDate>Sat, 25 Feb 2012 04:33:01 +0000</pubDate>
		<guid isPermaLink="false">697782646a61d39ff18134e51fe7db85</guid>
	</item>
	<item>
		<title>How we Built an iOS game on PC</title>
		<link>http://www.gamedev.net/page/resources/_/technical/mobile-development/how-we-built-an-ios-game-on-pc-r2880</link>
		<description><![CDATA[This article chronicles <a href='http://itunes.apple.com/us/app/catch-the-monkey/id495509241' class='bbc_url' title='External link' rel='nofollow external'>Catch the Monkey</a> from ideation to sale worldwide in the <a href='http://itunes.apple.com/us/app/catch-the-monkey/id495509241' class='bbc_url' title='External link' rel='nofollow external'>App Store</a>.<br />
<br />
You can find out more about <a href='http://mirthwerx.com/' class='bbc_url' title='External link' rel='nofollow external'>Mirthwerx</a> and our projects at our <a href='http://mirthwerx.com/' class='bbc_url' title='External link' rel='nofollow external'>website</a>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Intro</strong></span><br />
Many people want to get into making games, specifically mobile games. Well, we were one of you! This series is for anyone who wants to jump in and do it. Our goal is twofold:<br />
1) To demonstrate that it is possible<br />
2) To share lessons we learned that will hopefully benefit those starting out<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_261239.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>About Us</strong></span><br />
We at Mirthwerx are a team of two: Thomas the self taught programmer and Alex the artist who studied classical animation at Sheridan. We met 20 years ago in highschool and have tried to make a game ever since.<br />
<br />
Before we embarked on this project, I had been writing business web/mobile software with Microsoft technologies for about 15 years. With this background, we knew how to build software properly (OOP, design specs, usability concerns). But you will see later how we failed to apply it.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>	Design and Prototyping</strong></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Technology</strong></span><br />
From day one, we knew we wanted two things:<br />
<p class='bbc_indent' style='margin-left: 40px;'>1) Android is the future, but iPhone is the now. We will build for both</p><br />
<p class='bbc_indent' style='margin-left: 40px;'>2) We want to build on a windows platform with familiar environment and tools</p><br />
I started investigating the Mac platform and XCode by buying a mac-mini. After spending a day with ObjectiveC I knew I did not want to work in that language at all, it would drive me batty. Fortunately we could address both goals with one solution: Marmalade (formerly called Airplay before Apple started calling everything Airplay).<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_41468.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Here you can see using VS2008 C++ debugging and tracing in real time with an iOS emulator</em><br />
<br />
Marmalade allows the user to write once in Visual Studio C++ and run anywhere (iOS, Android, Blackberry, Windows Phone, Bada, and more). The simulator is excellent, with all the performance monitoring you’d expect, so it was a total win finding this technology. The pricing for independent developers is also very reasonable.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Design</strong></span><br />
Given this was our first title, we wanted to keep the design of the app simple. The initial concept was this:<br />
The player swipes their finger to tickle monkeys in a farmer’s field. The monkeys come more and faster in each level. The end.<br />
<br />
It seemed so simple at the time, and there were only two of us, that we thought we didn’t need a proper specification &#100;ocument. Instead we used <a href='http://xmind.net/' class='bbc_url' title='External link' rel='nofollow external'>Xmind</a> (free!) for mind mapping all our ideas and kept “the design” in there. The game was intentionally art heavy, as our artist was able to work full time on this project, but I was only able to work after hours/weekends.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_99766.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Mind Mapping is a powerful way to capture ideas quickly and organize them well for later reference. Xmind is a free open source tool for mind mapping.</em><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Prototype</strong></span><br />
In business software an initial prototype for the users is critical. It removes all the guess work that comes from reading and interpreting a Word &#100;ocument.<br />
<br />
Rather than programming a prototype for real, we used an extremely powerful and inexpensive ($40 for a registered version!) game making tool called <a href='http://www.yoyogames.com/gamemaker/windows' class='bbc_url' title='External link' rel='nofollow external'>GameMaker 8</a>. This allowed us to throw together the graphics that had already been drawn with a few play mechanics and see if we had something fun or not. I think all in the first prototype took 20 hours. Since it was running on a windows screen, there was no way to test the actual touch/swipe mechanic, so we just resorted to clicking, each click simulating a swipe. So the big question: Is it fun?<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_106296.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>First prototype of Catch the Monkey made in Game Maker 8</em><br />
<br />
No. It was not fun. We changed around several variables (speed of monkey, clicks to make them laugh, number of monkeys at one time) but it was just too simple. There wasn’t enough to do. We couldn’t see playing it for more than 2 minutes. We had no desire to make a “gag game” so we went back to the drawing board.<br />
<br />
In our design brainstorming session we came up with the idea of using different kinds of tools to interact with the monkeys. Tickling was just the initial tool, a feather, but later you could get other tools. This seemed to have some promise. So we thought up several types of tools, narrowed it down to a few that were easy to put into a prototype, and then made prototype 2. In this version the player has an inventory of each tool. When one ran out, the farmer would call his wife for a refill which would appear in a few moments. It made the player have to think about what tool to use when. We also gave the player control of the farmer, they could direct the farmer to walk to certain areas or pickup a certain monkey. Finally we added the concept of catching stars. Every so often a star would pop out and the player would have to click it to catch it. Stars would be used later for upgrades, though we never built it into the prototype. So: Is it fun?<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_24662.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Prototype 2 Made with Game Maker, notice the inventory counts for the differing tools</em><br />
<br />
Yes and no. There was a kernel of fun in there that was trying to get out, but there were still many things blocking it. We knew choosing (essentially strategizing) between tools was fun and catching stars was fun (it was spontaneous, different, and difficult). We dropped controlling the farmer (too cumbersome), dropped the refill concept (too complex and arbitrary). We needed a game mechanic to allow the player to strategize and manage resource(s).<br />
<br />
<em class='bbc'>I must note that when we prototyped, we didn't just do it amongst ourselves, but with others who were not involved in the project to get their honest feedback. Those working on a project are too biased to give a proper perspective to what they are testing. You’ll see later how this also came to bite us in the butt.</em><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Conclusion</strong></span><br />
At this stage we sat down for our third and final all day brainstorming session. We went through many concepts before considering the mana/cooldown mechanic in WoW. In WoW the player can’t just cast all the spells they want, they have a mana bar limiting the number that can be used in a short period of time. But some spells are so powerful that while they do use up mana, they must cool down for a long time (several minutes) so they cannot be used in a single battle. We felt if every tool required a common energy pool, but had varying cooldowns, we could strike the strategic balance we were looking for. By having enough variables we could keep things fresh and interesting for the player, and therefore they would be engaged and have fun.<br />
<br />
One additional thing we decided was to create Star Powers. Stars to this point were only used as a currency to purchase upgrades, but a Star Power is a special ability that can help you now mid level for a certain cost in stars. By making stars dual purpose, and facing the player with a decision for a momentary benefit now rather than a long term pay off later, is a great mechanic we tried to bring to other aspects. It became a fun challenge for us as designers to make star powers that were really really useful, but the smart player only uses sparingly so they can get all the upgrades.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_92756.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>The final toolbelt design.</em><br />
<br />
With the design phase basically finished (design happens all the way through), we proceeded into building the core game.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>	Building the Core</strong></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Intro</strong></span><br />
In the first article, we covered how Catch the Monkey started from initial simple concept, to the technology we chose, through the prototyping phase. At the end of prototyping we had a greatly increased design, but despite knowing better, we didn’t document it thoroughly. We knew we had 12 tools to create, 10 types of monkeys, and some vague concept of a store which would allow the purchase of upgrades. How many upgrades and what they would do was not finalized. It was time to start coding!<br />
<br />
This article is longer than the previous, I have attempted to keep it of reasonable length by highlighting only the most interesting aspects from the core construction phase. If you have a specific question, just post a comment and I’ll respond.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>We Going to Do this or Not?!</strong></span><br />
As mentioned in the first article, the artist was working full time but I as the programmer was only able to work part time as I was required by other aspects of the business. The project dragged. It finally reached a point where the project would be cancelled due to lack of progress. Instead, I mapped out the time remaining to build the game. About 6 weeks (50hrs x 6 = 300hrs) should do it. I made an extreme decision: I booked a 6 week hiatus from work to go to my cottage and focus 100% on the game. While my wife was less than thrilled, she was supportive of seeing me get the game done. It was time to go “all in”. Hind sight confirms this was the right way to recover the project.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Our Single Biggest Mistake</strong></span><br />
Not having a properly defined design document would appear to be our largest mistake, but we made one that completely dwarfed it.<br />
<br />
If you study the zombies in Plants vs Zombies, you will see there are many types of zombies, but they are made up of several graphical parts (head, body, arm, arm, legs) and several optional decorators (pylon, helmet, paper). By reusing and varying these components you can have many different types of zombie with minimal memory requirements. We wanted a similar approach with many kinds of monkeys each with varying abilities and weaknesses.<br />
<br />
<span rel='lightbox'><img src='http://static-www.ec.popcap.com/www.popcap.com/sites/www.popcap.com/files/games/pvz/screenshots/pvz3.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
However, and we painfully learned this later, if you want to have this kind of reuse, you have to lay down very specific rules of what the characters can and cannot do. Notice in plants verses zombies that the zombies always face the camera (like the 2D South Park animation). No matter what they do, they never turn away from the camera to a profile view.<br />
<br />
Well, early on in our animation and prototyping we decided when the monkey arrives at a plant he will plop down, TURN HIS BACK, and begin digging. Then when he gets a potato, he will TURN BACK and proceed to eat it. We completed all the artwork for the regular monkey before we discovered what a problem this was. When we wanted to have a hat monkey, we thought we would just create a separate hat object, attach it to the monkey, and off we go. Well as we did it we realized the hat (or vest, or sunglasses) has to turn with the monkey as he turns away from the camera. This requires one decorator frame per monkey frame and pixel perfect alignment. This means a whole host of painstakingly researched coordinates per frame to get it all to look right. It was so much work, and we didn’t want to redraw the digging animation, so we made an expedient decision: just duplicate all the frames for the regular monkey to the hat monkey with the hat pasted right into the frame. The artist went ahead and did this for each of the 6 additional types of monkeys.<br />
<br />
Here is the math of why this was such a problem later:<br />
1 monkey has a set of interaction sprite sheets (fear, ducky, laughing, walking, climbing, etc.) taking about 20mb of VRAM memory.<br />
7 monkey types x 20mb = 140mb VRAM<br />
The iPhone 3GS (iPod 3+) only has ~55MB of VRAM available (with a 15MB heap) before it starts crashing.<br />
We had initially wanted to target the iPod Touch 2+, but it has only 30MB of VRAM and it became impossible. So we increased the system requirements to iPod 3+ and scrambled to get the VRAM down. We’ll talk more about this in the next article.<br />
<br />
So the lesson is always map out memory requirements during the design phase, before you build it, rather than in the middle, or after. Had we of known the ramifications of the monkey turning away from the camera we would have gone a different direction with the art and the game wouldn’t be noticeably different.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Cute Monkeys in a Nasty Real-Time World</strong></span><br />
Many business developers I know avoid writing multi-threaded solutions when they can avoid it. Why? Because the race conditions that can occur between two separate threads doing their own thing are a nightmare for testing. There are so many permutations of what could be happening simultaneously in the application that if it crashes, it is difficult to reproduce never mind fix permanently.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_36490.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
When it comes to games, they are already real-time in that the Update() loop is executed every so many milliseconds not matter what. There is no concept of “blocking” calls like there is in Windows Forms development. This is just the way games are, and this is not what I’m referring to.<br />
<br />
I’m talking about a real-time game verses a turn based game. A turn based game waits for user input, then responds accordingly; while waiting for user interaction there may be things happening on screen, nice effects and such, but the actual state of the game doesn’t change. In a real-time system the game state is constantly changing regardless of player interaction.<br />
<br />
For our first time game, we NEVER should have chosen to do a real-time game.<br />
<br />
Catch the Monkey was an incredible amount of effort to make everything work in a constantly changing environment. The number of testing scenarios is probably 20 times greater than a turn based system. The ability to replicate scenarios is extremely difficult, even when programming specific unit tests to occur. There was a point late the construction phase I wasn’t sure I could ever get it to stop crashing. Fortunately Marmalade has some amazing memory monitoring tools built into it I was able to find all the issues (I think!).<br />
<br />
We learned this lesson so bitterly the next title we are currently working on is turn based.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Object Hierarchy</strong></span><br />
Obviously the power of OOP is the ability to build small, focused, encapsulated objects and then work with them at a higher level. My goal was to create an object hierarchy that knew how to instantiate, move, and render itself.<br />
<br />
There was a time in my career where I didn’t do modelling. Once someone showed me Rational Rose, UML, and modelling I never went back. I always model my code, even personal projects no one will ever see, because I find it the best way to think through the problems before the code gets in the way. Rational Rose (or any proper modelling tool) helps you think through the design as you design. I used Rational Rose for several years, but when I went out on my own I couldn’t afford the $2,000/seat license. Fortunately the Open Source community came to the rescue with <a href='http://www.staruml.org/' class='bbc_url' title='External link' rel='nofollow external'>StarUML</a>. StarUML is a powerful free object modeling tool. It is virtually identical to Rational Rose (at least to the last version I used in 2003).<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_62786.jpg' alt='Posted Image' class='bbc_img' /></span><br />
Looking at the class design diagram, notice the two fundamental objects: GameObject and UIObject. Both of these inherit from Graphic. Graphic encapsulates all the Marmalade 2D API interaction, and therefore is necessary for rendering whether it is a monkey, a story slide, or a text object.<br />
<br />
A GameObject is an object used in a GameScene (which is a level you play). It manages its own state, sprite sheets, depth calculation, scaling (based on depth), click handling, and hit detection. All play objects inherit from GameObject. UIObject is similar to GameObject, but is more lightweight and designed for non-play scenes, such as text, buttons, and images in the store or tool selection screens.<br />
<br />
<strong class='bbc'><span style='font-size: 14px;'>Design Patterns</span></strong><br />
We used GoF design patterns as necessary. For example:<ul class='bbc'><br /><li>We used the Factory pattern for our Level class; feed in a week and day, and it spits out a formatted level object, complete with any necessary tutorials.<br /></li><li>We used two singletons for caching image files and sound files called GraphicManager and SoundManager, so even though each object is responsible for loading/unloading it’s assets, it does it through these caches to minimize the actual memory used.We used a singleton for player state (number of stars, current progress, which tutorials have fired, upgrades purchased). This made it extremely simple to serialize/deserialize player progress.<br /></li><li>We used the Decorator pattern for adding graphical effects to any GameObject, such as fade in, fade out, flashing, etc.<br /></li></ul><br />
One of the early conceptual struggles I had was how to bring all the different types of screens (a store, a tool selection, story modes, title screens, option/menu screens, game modes) together into a nice organized OOP paradigm. While researching I found two excellent articles by iPhone game maker rivermanmedia:<br />
<a href='http://www.rivermanmedia.com/programming/6-object-oriented-game-programming-the-scene-system' class='bbc_url' title='External link' rel='nofollow external'>The Scene System</a><br />
<a href='http://www.rivermanmedia.com/programming/5-object-oriented-game-programming-the-gui-stack' class='bbc_url' title='External link' rel='nofollow external'>The GUI Stack</a><br />
<br />
I knew this paradigm was the way forward not just for this game, but probably all future games.<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_18817.jpg' alt='Posted Image' class='bbc_img' /></span><br />
The Scene system breaks down the game into a series of scenes. In Catch the Monkey I ended up with 19, like SceneTitle and SceneDialog. Each of these inherit a common interface from Scene such as: Init(), Update(), Render(), Shutdown(). I created a SceneManager singleton that contains all the logic related to scene creation, shutdown, and transition. Now my code can be blissfully unaware of what else is going on at a higher level. If I want a scene to end and begin a new scene, I call:<br />
<br />
<pre class='prettyprint'>SM-&gt;ChangeScene(new SceneShop());</pre><br />
If I want the new scene to be focused and on top of the current scene, I call:<br />
<br />
<pre class='prettyprint'>SM-&gt;AddScene(new SceneOptions());</pre><br />
The SceneManager knows if there currently are other scenes involved, winding them down appropriately, removing their assets from memory, doing a fading transition, then initializing and firing up the new scene. With this in place the real-time game now behaves more like a Windows Form application, with dialogs able to call dialogs and just let the OS worry about sorting it all out.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_6328.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The second key concept is the GUIStack. The GUI Stack sits inside the SceneManager and replicates “focus” of a scene just like how Windows does for forms and dialogs. By pushing and popping scenes onto the stack, I can control which scene has its Update() and Render() code called. If a scene doesn’t receive the Update() call, it is effectively frozen in time (paused). In pure form, the top scene is the only one to have its Update() called, while all in the stack have their Render() called. Later in testing I removed calling Render() to every scene in the stack for performance improvement. For scenes that require a background scene (such as a dialog window appearing over top of the game screen) I Instead take a screenshot of the current state, then display that as a backdrop to whatever the current scene is.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Using Marmalade in 2D</strong></span><br />
As previously mentioned, we were targeting both iPhone and Android simultaneously with C++ in Visual Studio 2008. While Marmalade is a 3D framework, we knew we were making a 2D title and therefore focused on the Iw2D APIs. I’ll highlight the fundamentals of 2D animation with Marmalade’s 2D API.<br />
<br />
As you you’ll see, Marmalade works at a pretty low level. This isn’t GameSalad here, and that is one of the reasons I chose it. Given the choice, I prefer the flexibility and power of a low level API rather than being limited to what a framework designer decided I should be able to do (or not!).<br />
<br />
Marmalade works it magic by using a custom make file called an MKB. This file allows the user to define Marmalade libraries to pull into the project, source code, assets (sounds), fonts, and texture groups.<br />
<br />
Marmalade has a resource manager that allows the management of image groups (texture groups) by defining them like this in the MKB file:<br />
<br />
<pre class='prettyprint'># Provide access to resource objects via IDE<br />		  &#91;"Resources"&#93;<br />		  (data)		<br />		  fonts.group<br />		  templates.itx<br />		  UI.group<br />		  Loading.group<br />		  Title.group</pre><br />
You then define all your images in custom group files:<br />
<br />
<pre class='prettyprint'>UI.GROUP<br />CIwResGroup<br />{<br />		  name "UI"  <br />		  shared true<br />		  useTemplate "image"	"image_template"<br />		<br />		  "./accountbuttons.png"<br />		  "./account1.png"<br />		  "./account2.png"<br />		  "./account3.png"<br />		  "./black.png"<br />		  "./bluestarbg.png"<br />		  "./pause.png"</pre><br />
Within the code you can test if resource groups are already loaded into memory, and then load/unload them through two simple function calls:<br />
<br />
<pre class='prettyprint'>if (IwGetResManager()-&gt;GetGroupNamed("farm", IW_RES_PERMIT_NULL_F) != NULL)<br />IwGetResManager()-&gt;LoadGroup("farm.group");</pre><br />
Or:<br />
<br />
<pre class='prettyprint'> 		 IwGetResManager()-&gt;DestroyGroup("farm");</pre><br />
Images are loaded (and automatically uploaded to OpenGL VRAM) by asking for the image by name (without the .png extension) by using:<br />
<br />
<pre class='prettyprint'>CIw2DImage* img = Iw2DCreateImageResource(name);		</pre><br />
Once you have an image in memory, it can be rendered simply by calling the image drawing routine with the image you want, and the 2D vector position.<br />
<br />
<pre class='prettyprint'>Iw2DDrawImage(img, CIwSVec2(x,y));</pre><br />
Marmalade automatically queues up all of the drawing calls in the order in which you called them, so this way you can control layering by doing your background draw calls first. So before I would run through my Render() routine I would sort all my objects by depth (lowest to highest) and then draw them in that sequence.<br />
<br />
To complete the rendering I call these two routines, which tells Marmalade I’m finished, show it to the world:<br />
<br />
<pre class='prettyprint'>Iw2DFinishDrawing();<br />Iw2DSurfaceShow();</pre><br />
That’s it. Call those drawing routines each frame and you’ve got yourself a game.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Simplifying Sprite Sheets</strong></span><br />
The game comprises over 4,000 frames of hand drawn animation, most is for the monkeys interacting with their world. To manage all these images, we put them into spritesheets. Two issues needed to be considered:<ul class='bbc'><br /><li>No dimension of the sprite sheet could be larger than 1024 (iPhone doesn’t like textures bigger than this and Marmalade started fuzzing them)<br /></li><li>Sprite sheet dimensions needed to be to the power of 2 (32,64,128,256,512,1024) for the graphics card. If they weren’t, the graphics card would pad them out to make them to the power of 2 anyway.<br /></li></ul><br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_20891.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>An example of a GameMaker strip.</em><br />
<br />
Photoshop does not have an easy way to make a sprite sheet where each frame is universal in height/width. So we discovered a trick that saved us dozens of hours:<ul class='bbc'><br /><li>Save each frame in PNG from photoshop<br /></li><li>Create a sprite in Game Maker to drag and drop each PNG frame from the file system for a given animation<br /></li><li>Export the sprite from Game Maker as an animation strip, which is each frame appended into one long horizontal PNG with the number of frames appended to the file name.<br /></li><li>Run our custom sprite sheet program on the strip, which would break it out into a rectangle of the smallest power of 2 dimension as a PNG.<br /></li></ul><br />
While it sounds involved, we could go from a collection of png frames to a squared sprite sheet in under 2 minutes. Just for its ability to create sprite strips GameMaker is well worth having!<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_782.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>The final spritesheet, power of 2 sized.You can't tell, but we also dropped the color depth from 32bit to 16bit for memory.</em><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Conclusion</strong></span><br />
Who is the harshest critic, the audience or the musician? The musician, for they have the double burden of knowing every note they missed and how much better they played during practice. So while the creator is extremely biased and forgiving of their creation, there is a harsh reality of what they intended and what they ended up making. I would say the music is always much sweeter in the imagination than on the page.<br />
<br />
At the end of the 6 weeks I had finished building the core of the game. I came in around 340hrs. Knowing I have a personal biased, having played the game over a thousand times during build cycles, I concluded this game is actually fun. There was something magical about trying to entertain 3-5 monkeys simultaneously. Because I was away at the cottage, the artist had to take my word for it. And since I hadn’t yet figured out how to deploy it, he had no way to play it other than on my laptop. But, knowing we had a good core, something we were proud of, gave us the determination for the toughest fight yet: Polishing.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>	Balancing and Polishing</strong></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Intro</strong></span><br />
At this point we had a working game, around 90% feature complete. The player could start a new game, play each level, interact with all 7 monkeys, use all 10 tools, save up stars, buy 28 upgrades in the store, use all 4 star powers, and save/resume their game. We declared ourselves feature complete. If we had created a more detailed design document we would have realized how untrue that statement actually was!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Last 10% takes 90% of the Time</strong></span><br />
We didn’t know how long it would take to establish a publisher relationship, so we started showing an early prototype to some publishing agents. One commented that the game core was good, we definitely have a quality AAA title here, but we still have a lot of work left for polishing. We thought that was a rather silly statement, and proceeded to finishing off the loose ends and game balance figuring we would be in the store in about 2 weeks.<br />
<br />
This is where games are vastly different than business software. In business software, when we are feature complete with all unit testing completed, 80%-90% of the work really has been done. Integration testing reveals its issues, but they are generally just misunderstandings between developers and spec that need to be resolved. A real-time game integration testing is about 50% of the work because of the layered interactivity/dependencies of the game elements to each other.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting it on a Device</strong></span><br />
Up until this point, the game could only be played in the Marmalade PC simulator. We still had no idea if performance would be an issue (memory or FPS) on real devices. It also severely hampered unit testing as the artist couldn’t test the game at all. It was time to deploy to a device.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_69482.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Marmalade Deployment Tool for making the IPA file</em><br />
<br />
Apple is extremely careful of what can be put onto their devices. This is good as it cuts down on piracy, but it also creates a whole series of hoops you must jump through to sign your code and get device ids and certificates for deploying test builds to a device.<br />
<br />
If you are using xCode on a mac (especially the latest version of xCode), it is a relatively straight forward process, where xCode takes care of most of it for you. All of apple’s documentation tells you step by step how to do it with xCode. If you are on PC, well prepare for some hassle.<br />
<br />
There are two things you must do: 1) Setup your machine for iOS deployments and 2) Setup your project for iOS distribution. Fortunately, the documentation in Marmalade 5.2 for how to create distribution builds is much improved over previous versions. There is a walk through that explains you to create a certificate, which you then upload to Apple, and download the Apple certificate(s) and where to put them.<br />
<br />
With the PC setup, the project must be setup and signed for distribution. The Apple dev portal is used to assign UDIDs of devices allowable to an application. Apple provides a provisioning certificate used to sign your project. Marmalade has a deployment tool that appears when making a release ARM build of the project. You enter in provisioning and OS specific options into this tool (it saves the settings to the custom MKB file) and it does the magic of making you an IPA that can be deployed through iTunes to your iOS device.<br />
<br />
All in I was able to get the game on my iPod in about 10 hours. This was a vital step, because we needed the touch screen to test our gestures.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting Jiggy with Gestures</strong></span><br />
If you recall, our core design was a player using their finger to tickle a monkey through swiping. After some prototyping, we needed other tools to break up the monotony of constantly swiping back and forth. One of our early influences was a GameLoft game Bailout Wars. The player flicks bankers to their doom, but you also have to make other motions as well.<br />
<br />
<span rel='lightbox'><img src='http://toucharcade.com/wp-content/uploads/2009/10/496754.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
We studied numerous games and came up with this list:<ul class='bbc'><br /><li>Tap<br /></li><li>Tap & hold<br /></li><li>Swipe Horizontal<br /></li><li>Swipe Down<br /></li><li>Flick Up<br /></li><li>Circle (clockwise or counter clockwise)<br /></li></ul><br />
We chose Tap, Swipe Horizontal, Swipe Down, and Flick Up. (We also had Tap & Hold, but cut it later.) We tied these gestures to tools that we felt made sense: the paper bag, for instance, is placed on a monkey’s head, so the player swipes the bag down onto the head.<br />
<br />
iOS and Android support multi-touch (up to 10 points) but we decided to stick to just single touch. A touch is nothing more than a click event, so we inspect the s3ePointerEvent in Marmalade to capture it into a global touch variable like this:<br />
<br />
<pre class='prettyprint'>void SingleTouchButtonCB(s3ePointerEvent* event)<br />{<br />		g_Touches&#91;0&#93;.active = event-&gt;m_Pressed != 0;<br />		g_Touches&#91;0&#93;.x = event-&gt;m_x;<br />		g_Touches&#91;0&#93;.y = event-&gt;m_y;<br />		g_Touches&#91;0&#93;.when = (int32)s3eTimerGetMs();<br />		g_Touches&#91;0&#93;.handled = false;<br />}</pre><br />
While it is all nice to know where a finger currently is, how do you know if they are making a gesture or not? The answer is you have to do that yourself.<br />
<br />
A gesture begins when the finger touches the screen. From then on, the current position of that touch must be tracked at a regular interval until it is released (finger is lifted). The difference in origin, progression across the points, and exit must be analyzed to determine what kind of gesture was made. I used the Strategy Pattern in a generic Tool class with the child class for each tool implementing their own unique gesture recognition.<br />
<br />
So while this explains the technical on how to do gestures, there was a lot of refinement necessary to get it to “feel” right. It is amazing how different each person performs a simple left/right swipe. Some people do very gentle little swipes of 10 pixels, while others go all the way across the screen. Some do it straight across, others on a diagonal. Some do it so slow it didn’t register, and some do it so fast it didn’t register (we found the “right” granularity for the timing interval of each point is 50ms). At the end of the day, we went from a very strict gesture system where a horizontal swipe couldn’t have more than 20 pixels of vertical movement, to a very loose one where just about anything goes!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Saving the Story To Last</strong></span><br />
Catch the Monkey is an action game. While we need some sort of story to set the context for the player’s actions, we knew we didn’t need <em class='bbc'>Crime and Punishment </em>here. From the very beginning, we had a rough story outline:<br />
<br />
<em class='bbc'>A farmer in South Africa has a potato farm. As he sits down to lunch with his wife, a monkey is spotted in the field. He goes outside to take care of the monkey, but more and more keep coming. Eventually he overcomes all the monkeys and returns to a cold lunch. Fin.</em><br />
<br />
Ok, so we aren’t winning any Oscars for screenplay writing, but it was enough to get going so we focused on building the game and then would circle back to the story.<br />
<br />
<strong class='bbc'><span style='color: #b22222'>BIG MISTAKE!</span></strong><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_109408.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
When it came time to do the story sequences, I decided to involve my friend Rob for help. We sat down one evening to hash out the story. He started asking basic background questions for which I had no answer:<ul class='bbc'><br /><li>How well does the farmer do, is he poor or rich?<br /></li><li>How’s his marriage, good or strained?<br /></li><li>What’s his demeanor: happy or surly?<br /></li><li>How long have they lived in this location?<br /></li></ul><br />
This may seem like silly fluffy stuff, but it isn’t. I knew from research in how to write fiction that before you have a story, you have to have a character. It is the characters that drive the story and we didn’t have characters. So Rob and I had to define the characters first.<br />
<br />
Throughout the game the player unlocks new tools. How are these communicated to the player? We decided it was by the farmer’s wife “finding” them and making them available to the farmer in his tool shed. We chose to use a dialog sequence to put the tool arrival into some context. Well, you cannot write effective dialog (even simple monkey catching dialog) without knowing the characters voice. So these “fluffy” questions had to be answered before we could write a single line of dialog.<br />
<br />
We then had to answer the two big questions:<br />
<br />
1) Why are the monkeys coming to the farm in the first place? (Why now and not a year ago, or why not a year from now?)<br />
2) How is it that the player stops the monkeys from coming (by resolving #1)?<br />
<br />
We went through a lot of ideas that night, but everything good we came up with changed the flow of the game, or introduced new characters (like a boss monkey), and we just couldn’t afford to do all those changes this late in the game development. It was overwhelmingly evident we should have had this meeting in the first week of the game, not the last.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_27281.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Before you can write a line of dialog, you have to know the character's voice</em><br />
<br />
We wrote the best story we could without changing the game or requiring a lot of new art assets. The first rule of writing is “write what you know”. In the end, I based the farmer and wife on myself and my wife. The problem the farmer faces of trying to get rid of the monkeys, which seems so simple from the beginning, becomes overwhelming and takes over his whole life. This is actually a metaphor for what the monkey game became to me. When the farmer bemoans the monkeys never ending, that’s how I felt about the amount of work the game kept requiring. But in the background, unfazed, is the wife. Helping where she can, encouraging when needed. Many of the lines in the game are verbatim what my wife said. When the farmer’s wife goes away on a girl’s trip in the middle of it all, this also happened in real life.<br />
<br />
Of course, all this is probably far too sophisticated for a simple action monkey catching game, but it is in there none the less.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Levels and the Game Master</strong></span><br />
I’ll admit this up front: sometimes I’m just plain lazy. But sometimes laziness is the mother of invention. <span rel='lightbox'><img src='http://public.gamedev.net//public/style_emoticons/default/happy.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
When we built the second prototype each level had scripted events: when a monkey is to be released down a tree, the type of monkey, the size of a wave of monkeys at one time. Most of these events were time driven. This is how classic action games, like Capcom’s 1942, are made. Each play through is the same.<br />
<br />
It was a lot of work scripting each level with all the events, and frankly I didn’t want to do it again in the real game. There are also problems with scripting: how do you know if the player is bored or sufficiently challenged? Releasing a monkey every 10 seconds may be fun for me, but too easy/hard for you.<br />
<br />
So we tried to think of an alternative: what if we had a Game Master (to borrow the RPG term) that determines when, where, and type of monkey to release based on how well the player is doing. If a player is doing poorly it won’t become ridiculously intense, and if they are doing well it won’t get boring. We will define rules for the GM to behave by, and vary those rules from level to level. For instance, some levels the GM will be fast and furious, in others a slow build up. Even better, the GM can monitor things in real time, like the players energy level, and make smart decisions at the time of knowledge rather than guessing with scripting.<br />
<br />
This seemed like a radical idea to us, so we weren’t sure what the negatives would be to building this dynamic AI “level designer” just so I didn’t have to do all that scripting.<br />
<br />
I don’t remember why, but for some reason I felt I should play Valve’s Left for Dead FPS zombie game. I generally don’t like zombie shooters so I had never played it before. I got it off steam and noticed somewhere in the description about “The Director”, which is essentially a level AI that responds in real-time to the players to give different experiences each play through. Once I saw Valve did it, I knew we were on the right path!<br />
<br />
<span rel='lightbox'><img src='http://www.legitreviews.com/images/reviews/1161/left4dead2-gameplay.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>If Valve did it, so can we!</em><br />
<br />
It took a few days to build the Level GM, but once it was done it was a total win. No scripting required, all we had to do was define for the GM the resources it has (types of monkeys, total number of each monkey allowed at a time) and the level of intensity we want (earlier levels are easier than later ones).<br />
<br />
In the book <a href='http://books.google.ca/books?id=5SjHsrn_PnUC&lpg=PA169&ots=1QVhM2EwY6&dq=Game%20design%20Andrew%20fillings&pg=PA272#v=onepage&q&f=false' class='bbc_url' title='External link' rel='nofollow external'><em class='bbc'>Andrew Rollings and Ernest Adams on Game Design</em></a> (some of it is free on google ebooks) they explain how it is more fun to have waves of intensity followed by relief followed by intensity rather than constant intensity. Plants vs Zombies follows this formula perfectly by providing big waves of zombies followed by few zombies so you can rebuild. We implemented this concept by adding “moods” to the GM. Based on many factors, the GM will “go evil” on you and break the rules of intensity we set out. But at other times it will “go nice” and give you a chance to catch your breath.<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_16745.jpg' alt='Posted Image' class='bbc_img' /></span><br />
We’ve detailed plenty of our mistakes in these articles, so we’re proud to say this is one where we nailed it! We’ll be using this approach in our future titles.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Game Balancing: Redeeming Features</strong></span><br />
Game balancing is tough stuff! There are no strict rules as to what makes something fun, especially in combinations. In the end we had to go with our personal play experience, and then test on others.<br />
<br />
It took 6 weeks to make the core game, and another 10 weeks to balance it. As I look over my work logs, up until the last day we were changing cooldowns, upgrade costs, and energy costs. I could give many examples from our time of play balancing, but I believe the most valuable lesson I can share is how we took something that wasn’t good and made it great. This at the core is what the balancing phase entails. So here is the brief story of the Paper Bag:<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_780.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
In reading a book on fiction writing it stated every character thinks they are the hero of the story, so give them a chance to shine. Think of how in Lord of the Rings Sam, a tag along character for much of the story, gets to be the hero when he carries Mr. Frodo up Mount Doom. I think this applies to game features, in our case every tool should get to be the hero and legitimate chance of being a player’s favorite.<br />
<br />
Each tool has its own purpose. Some are for taking out individual monkeys, some are for dealing with groups. Some are to prevent them from coming in, some are for dealing with them as they come in. Some require the player’s attention and dexterity, some are great because they don’t require any attention.<br />
<br />
The paper bag is a high cost high impact tool that completely paralyzes one monkey (intended for a high threat monkey) for a long period of time. It also has an Area of Effect (AOE) which causes other monkeys to be distracted and laugh at the silly monkey stumbling around.<br />
<br />
In the first iteration, once the bag was placed onto a monkey’s head it immediately made all monkeys in range laugh. Play testing revealed players preferring other tools over the bag. It’s not that it was bad, but it wasn’t good.<br />
<br />
We played around with the cost, cool down, and range. At one point it made all the monkeys in the field laugh. But still the other tools were better.<br />
<br />
Then we thought: what if instead of a onetime AOE effect it had a continual AOE? For the entire time the target monkey stumbled around any monkeys in range would be influenced. This changed the best time to use a paperbag from where a lot of monkeys are currently, to where a lot of monkeys WOULD BE. By making this AOE effect continuous we now had a very effective crowd control AOE tool while incapacitating one target monkey.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_7098.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
Now the paper bag is fantastic!<br />
<br />
During game balancing some diamonds are in the rough. Some are rougher than others. It requires determination to cut into them to let the inner brilliance shine forth.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Features: Knowing when and how to say NO!</strong></span><br />
A game can be built forever. Should I even mention the obvious example of Duke Nukem Forever? When the goal is to create a rich enjoyable play experience, the temptation is to keep adding more and more features, because more = better, right?<br />
<br />
Sometimes no. In our case we had to ship the game, not just for financial reasons but for psychological ones. After 2 years it is hard to keep up the enthusiasm. As we played and balanced, many ideas would come up. For instance:<ul class='bbc'><br /><li>We needed to add an easy (casual) mode for non-gamers or younger children<br /></li><li>We needed a visual and audio warning to the player that they just lost a plant (seems obvious now, but it wasn’t added until the second last day)<br /></li><li>We needed more sound effects<br /></li><li>We changed the “level complete” requirement from reaching a certain number of monkeys, to reaching a certain number AND clearing the whole field<br /></li></ul><br />
All of the above were implemented, but they were unscheduled tasks and our release date kept being pushed further and further out.<br />
<br />
To decide what HAD to be done we asked ourselves these two simple questions:<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'>1) Is the game broken without it? Meaning it is too hard to play, or doesn’t make sense to the average player, or boring/repetitive</p><br />
<p class='bbc_indent' style='margin-left: 40px;'>2) Would we be embarrassed to release without it? Meaning it is obvious we cut a corner.</p><br />
The second question may sound a little strange. Personal pride and brand reputation are at stake writing a game. If we tried our best and failed, that is ok. Sometimes that is life. But if we cut corners, therefore reducing chance of success, and we failed, that is just being lazy or foolish.<br />
<br />
To reach our timeline some things had to give:<ul class='bbc'><br /><li>Cut a type of monkey<br /></li><li>Cut two tools<br /></li><li>We wanted level ranking and gamecenter integration, but we had to cut it<br /></li></ul><br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_4672.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Watergun didn't make the cut. Maybe there will be a sequel we can put it into!</em><br />
<br />
Finally, the hardest thing we had to do was what I’ll call “compress” the game. Our goal had always been to have 50 levels, each of about 3 minutes (earlier ones are shorter, later ones are longer) for 150 minutes of perfect play.<br />
<br />
Upon play balancing we saw there were fun levels and not as fun levels. Fun levels generally had the player getting something new (a new tool, star power, monkey type). So we decided to compress the game by removing the low fun content; 13 levels. It hurt to see all that work go away. But in the end what the player now experiences is peak to peak fun with no valleys.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Conclusion</strong></span><br />
After spending twice as much time polishing the game as it took to build it, we had a game that was truly feature complete. It was fun, it flowed well, and we are proud of it. It takes some going, but once you hit the sweet spot mid way through the game it is a ton of fun. We were finally ready for testing with others.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>	Testing, Release, Marketing</strong></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Intro</strong></span><br />
We had a game! Hurray! It worked, it played well, it has a beginning, middle, and ending. We were ready to get the sucker out the door. But before release, we had to go through the final stage of development: testing. Wow, what an eye opener!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>No one Knows How to Play Your Game, and They Don’t Care to Learn!</strong></span><br />
I submit I may be the strangest person alive.<br />
<br />
I grew up in the 80’s and early 90’s. This is where many of my early gaming habits formed. Back then when I bought a new computer game, such as Civilization, Ultima, or Wing Commander, I would sit down and read the entire manual cover to cover before attempting to play the game. And this was when manuals were works of art: the civilization manual was over 100 pages and filled with fascinating sidebar historical facts. I continued this practice, though I’ve stopped now that the manuals are nothing more than epilepsy warnings and telling me where the square button is on my controller. (Fortunately board games still have amazing manuals, so I can enjoy those <span rel='lightbox'><img src='http://public.gamedev.net//public/style_emoticons/default/tongue.png' alt='Posted Image' class='bbc_img' /></span> )<br />
<br />
<span rel='lightbox'><img src='http://1.bp.blogspot.com/-_kA8D_pane0/TcKjStr665I/AAAAAAAAAVg/70DTAyUcWkQ/s1600/civilization1.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>The good old days when games were hard and manuals were thicker than your arm!</em><br />
<br />
Apparently no one else read manuals so the gaming industry moved away from them altogether. Players want to play, not learn how to play. I sort of knew this, I read about it in game design books, but I didn’t have the experiential knowledge of it. It quickly came.<br />
<br />
At our pre-release party (unfortunately 3 months before the actual release, but who’s counting) we had several iOS devices with a 4 level demo version of Catch the Monkey installed on them for people to play. We watched people pick up the game and play it for the first time. We learned two things: people enjoyed playing with the monkeys, but they had no clue how to do it. So while they had fun, they were frustrated not knowing how to use the various tools.<br />
<br />
It seems obvious as I write this, but we discovered our need for tutorials built into the game. All I can say is that when you work on something closely for 2 years you lose track of what is “intuitive” and what isn’t. Observe strangers and reality will come crashing in. So, we used our character dialog system to retrofit in a tutorial system.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_50139.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>First Iteration of Tutorials. Nobody reads em. </em><em class='bbc'><span rel='lightbox'><img src='http://public.gamedev.net//public/style_emoticons/default/sad.png' alt='Posted Image' class='bbc_img' /></span></em><br />
<br />
Weeks before release, we tested with a focus group of teenage girls (our demographic) to see how they enjoyed the game. I squirmed in my seat as I watched them tap “next, next, next” and completely bypass the tutorial to get on to the game. Once there, they didn’t know how to use certain features, started losing, and became frustrated.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_40262.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Final version of tutorials. If you can't follow that, there's no helping you!!!<span rel='lightbox'><img src='http://public.gamedev.net//public/style_emoticons/default/angry.png' alt='Posted Image' class='bbc_img' /></span> </em><br />
<br />
We learned valuable lessons as we went through three iterations of tutorials:<ul class='bbc'><br /><li>People assume they already know how to play your game. I can’t for the life of me figure out why they come with this belief, but they do. Work with it, not against it.<br /></li><li>People don’t want to learn (because of the above), they want to play. So teach them <strong class='bbc'>one basic thing</strong> and set them off playing<br /></li><li>When teaching, we observed the average player’s patience is two: Two screens of slides, two steps of interaction, two dialog boxes, then they don’t care anymore and want to skip forward<br /></li><li>After playing, people want to learn. There is a correlation between how long they play and how interested they are in learning to play. In the first 2 minutes, they have 0% interest, at 5 minutes they have 10% interest, at 10 minutes they have 50% interest. You have to space your lessons appropriately<br /></li><li>Remove all flowery “in character” text from the tutorial, they want to learn as quickly and efficiently as possible and could care less if a character starts each sentence with “<gwok>”<br /></li><li>They don’t want to read, they want to do. Make the tutorial visual and interactive<br /></li><li>Pre-plan your tutorials into the main story/progression of the game. Don’t do what we did and try to retrofit it in, it was a lot of work after the fact<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>Testing with Testflight</strong></span><br />
As previously mentioned, iOS locks down the devices to which you can install a binary. This requires the unique UDID of each device, registering it through the apple portal, including the provisioning profile at compile time into the binary, and then copying a provisioning profile to the device through iTunes (which provides zero feedback if it was done successfully) and finally copying the binary to the device through iTunes. I can’t think of a process more antithetical to the apple “it just works” mantra. So, you can do all that OR you can use testflightapp.com.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_114752.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>Testflight for build distribution during testing; epic win!</em><br />
<br />
With testflight, you send testers (family, friends, enemies) an email link and they go to it on their device. Testflight takes care of finding the device UDID, os version, make/model of device, and sending it to you the developer, installing the provisioning certificate. As a developer, all you need to do is register the device id to your binary. Now you can upload a build (with release notes) to testflight, and everyone you autohrize is sent an email a link to download it. It bypasses all the silly itunes file copying. Testflight’s reporting allows you to see who has what installed. Valuable when they start reporting problems as you can definitively say “Oh, that’s because you’re on a build that was so yesterday! That build was terrible! Install the NEW build, it’s wonderful.”<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Testing with Non-Gamers</strong></span><br />
Would you rather know about an issue during development, or once it’s released? Of course during development!<br />
<br />
Testing with people who play similar games as the one you are making is very helpful. You can be sure you are meeting your demographics’ demands and they can often make suggestions or give articulate feedback on issues as they have a frame of reference.<br />
<br />
However, we found great value in testing with people who have never ever played an electronic game in their life. You know who I’m talking &#097;bout: your mother-in-law whose only game experience is yahtzee on the dining room table; the friend who didn’t know brick breaker was pre-installed on his blackberry.<br />
<br />
The official term is blackbox testing. These people can confirm if your tutorials work, but more importantly they do things you never in a million years would do. But make sure you watch them closely, they won’t be able to tell you what they did or did not do. Here is an example:<br />
<br />
<span rel='lightbox'><img src='http://www.techwarelabs.com/wp-content/gallery/news-images/touchscreen.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
We finished our final bug free never crashes build Dec 15. Over the Christmas holidays I showed a non-gamer friend the finished game. Within 2 minutes of playing he crashed it.<br />
<br />
How? He never once lifted his finger from the screen. If you recall from part 3 about our gesture system, it tracks the current finger position every 50ms. Well if the player never ever lifts their finger from the screen, it becomes one giant gesture of 2,400 points after 2 minutes (affecting performance). Even worse, the initial target object of the gesture may be destroyed while waiting for the gesture to finish, resulting in a NULL reference and therefore a crash.<br />
<br />
It was relatively easy to replicate and fix once I saw what he did, but I have to admit I never imagined someone not lifting their finger!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How Do You Know When You are Done Testing?</strong></span><br />
This may seem like a silly question, especially coming from a business software background. In business software you would already have all your test cases written before hand (Right?) and execute them. When they all pass, you know you are good to release. Typically we would then get the customer to test the application in a pilot project, and that is the “real world” test. If it’s good, we release.<br />
<br />
Well in games, it’s different. There is no “customer” to sign off and take responsibility that the application is good, you just have to decide at some point: it’s done.<br />
<br />
Release too early, and the game will crash or misbehave for customers. Release too late, and you’ve squandered valuable effort that could have gone into another title.<br />
<br />
I was listening to the <a href='http://http//ocw.mit.edu/courses/comparative-media-studies/cms-608-game-design-fall-2010/' class='bbc_url' title='External link' rel='nofollow external'>MIT Open Courseware on Game Design</a> and they asked this very question: how do you know testing is done?<br />
<br />
Their answer: When you are out of time.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_67513.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>When you can't take another step forward, you might be done testing.</em><br />
<br />
That seemed like a cheeky answer, but having now lived it, I agree. Now, of course, we made certain all features worked, it was as fun as we could make it, and it didn’t crash. (Of course now as I write this we’ve heard reports of a bug in one of our tutorials, oops!). The game will never be perfect, there is always more to add, more to test. There comes a point where you have to draw a line in the sand and ship it. For perfectionists, this is a very difficult thing to do. I am fortunate that I’m not working solo on this project, both the artist and I together were able to agree the game was ready to go out. That gave me confidence I wasn’t deluding myself or just fed up. J For those soloing it, I recommend you ask a friend to be your “quality control” and help give you the thumbs up for releasing.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Judging the Difficulty</strong></span><br />
I read in the book <a href='http://books.google.ca/books?id=8w_ETFmHrewC&printsec=frontcover&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false' class='bbc_url' title='External link' rel='nofollow external'>Level Up: Guide to Great Game Design</a> that the game makers are the worst people for judging the difficulty. So, I knew this going in, but it is still difficult in practice. Obviously the first people that need to be happy are the ones making the game, that is your first quality control gate.<br />
<br />
We also tested on young children (3, 8, and 9). Why? Because they’ll test for free all day long and they have nothing better to do. <span rel='lightbox'><img src='http://public.gamedev.net//public/style_emoticons/default/tongue.png' alt='Posted Image' class='bbc_img' /></span> (And they are the artist’s children). We found that young kids love to play Catch the Monkey, but the mid game was too hard for them. So thinking this was a secondary market, we created an Easy mode that gives the player more energy and reduces the maximum number of monkeys in the field at a single time. The kids loved the easy mode and were able to finish the game, so we were happy.<br />
<br />
<span rel='lightbox'><img src='http://d24w6bsrhbeh9d.cloudfront.net/photo/1007965_700b_v1.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
Later, when doing focus group testing, two of the teenage girls couldn’t get past a certain level and were getting frustrated. We recommended they restart the game in easy mode. As soon as they started playing in easy mode they said “Oh wow, this is much more fun.”<br />
<br />
At this point we had a dilemma: do we make easy mode normal mode, and normal mode hard mode? We did and made all the code changes to reflect this.<br />
<br />
Then, a few days later, we fixed a bug in the Level GM AI and found it was working much better than previously. So we flipped it all back to Easy and Normal rather than Normal and Hard.<br />
<br />
Big mistake.<br />
<br />
Now that we have released and friends/family have been buying it, the most common complaint we hear from casual gamers is that it is too hard. When we tell them through facebook to try it on easy mode, they always come back with “Oh wow, this is much more fun.” Even post release we’re still learning things the hard way!<br />
<br />
Here are the key lessons we’ve learned:<ul class='bbc'><br /><li>Make the game too easy, rather than too hard. Too easy can still be enjoyable, too hard never is.<br /></li><li>Casual gamers are <strong class='bbc'>not</strong> looking for a challenge, they are looking to pass the time. Easy fits within this expectation.<br /></li><li>Don’t make the game hard with the ability for the player to opt into easy. Make it easy with the ability to opt into hard.<br /></li></ul><br />
<strong class='bbc'>Releasing to the App Store</strong><br />
After making it through the arduous testing phase, we were ready to release this sucker. This has several steps:<br />
<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'>1) Making a build signed for App Store, as opposed to ad-hoc provisioning build</p><br />
<p class='bbc_indent' style='margin-left: 40px;'>2) Uploading the binary to Apple</p><br />
<p class='bbc_indent' style='margin-left: 40px;'>3) Waiting for approval</p><br />
It was time to fire up Visual Studio one last time and create an app store build. It was relatively easy to do, I simply copied the deployment options from my test flight build in Marmalade and off I went. Now here’s the thing: you cannot test your app store build before you upload it. Why? Because it can only be installed on a device <strong class='bbc'>through</strong> the app store. So better get it right!<br />
<br />
And we didn’t. <span rel='lightbox'><img src='http://public.gamedev.net//public/style_emoticons/default/blink.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_19389.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>iTunes Connect is how you control your app in the app store</em><br />
<br />
I made two blunders when doing the final build. The first was somehow I didn’t copy the proper icon image settings from the internal build to the final build, so it went to the app store with the default app icon. Doh! The second was far, far worse.<br />
<br />
We knew our game didn’t work on anything below iPhone 3GS or iPod 3. I saw other games show this requirement in the app store along the left column. I didn’t see any way to set this through marmalade deployment, so I assumed it was done in the app store itself.<br />
<br />
Well when you upload an app, especially your first, iTunes Connect walks you through a wizard. The answers you provide can never be changed, you got one shot to do it right. These we did right. Again, I didn’t see anywhere I could set the requirements, so I figured it was after I uploaded the binary. I uploaded the binary and it went into the queue for review and approval.<br />
<br />
Well, 8 days later, it was approved. But still no way to set the system requirements. It wasn’t until later that I found out you need to modify the plist.info file to include the OpenGL ES version to 2.0 to target the devices we wanted.<br />
<br />
No biggie, I modified the plist.info file and proceeded to upload the new binary.<br />
<strong class='bbc'>ERROR!</strong><br />
<br />
Apple does not allow a developer to set more narrow restrictions on an application update than the app first had. So in short: if your initial version says it will run on iPod 2, you can’t later do an update that makes it no longer run on iPod 2. We screwed up the one thing you cannot correct through an app update. After much back and forth with apple support we had to resort to putting the requirement right into the app description. We already know people don’t read, but it’s the best we can do at this point.<br />
<br />
And one final thing to know about releasing to the app store when you make your app on a PC: you REQUIRE a mac to upload the binary to apple.<br />
<br />
ITunes Connect used to allow you to upload through http, but no longer. There is a binary uploader program in the iOS SDK that checks and uploads your binary to apple. That uploader program only works on a mac. So while you can build and test the entire app on a PC, you need a mac for 10 minutes to upload your final binary. I’ve seen someone suggest just going to an apple store and using a demo mac to upload. In my case I already had the mac mini, so it wasn’t terribly inconvenient, but it was a real surprise.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Releasing to the World</strong></span><br />
By default, all apps uploaded to apple are released to every itunes store in the world, unless you specifically turn a store off.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_31519.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>There be a lot of iTunes Stores. Fortunately you only need 6 translations to cover them all.</em><br />
<br />
We had always intended to release to multiple countries, so we tried to minimize the amount of text in game and use symbols where we could (the monkey story sequences use icons rather than text for this reason, although it actually made more sense conceptually too: how do you write “monkey speak” anyway?!).<br />
<br />
The key is to get your app description translated from your native language into the various app store languages. It costs about $100 per language to use a translation service to translate our app description. Of course, the difficulty is we have no way to judge how good the translation is!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Initial Marketing</strong></span><br />
As I write this fourth part, our game has been out in the world for 22 days. Sales haven’t skyrocketed, so we’re in no position to advise on how to market a game. However, there are two things we can share.<br />
<br />
First, Apple controls the app store. They make their decisions based on volume. The sections like “What’s Hot” and “New and Noteworthy” are driven by volume. The more volume you can drive in the initial days, the more likely you are to appear in those sections. Obviously the key is to get into the “Top 100 Free” or “Top 100 Paid”. The only way you get there is through volume.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev5.net/gallery/album_371/gallery_25962_371_117000.png' alt='Posted Image' class='bbc_img' /></span><br />
<em class='bbc'>We've made it to #45 in the Family What's Hot. Go little monkey! Go!</em><br />
<br />
Secondly, we knew review sites are important to get initial buzz going, but how do you find all the review sites out there? A google search will return some of the biggies, but also blogs that haven’t been updated in 2 years. So we devised a clever way to make a short list of review sites: most games put their reviews or quotes from review sites in the top part of their app description. By clicking through about 20 apps we were able to compile a list of 41 respectable mobile game review sites.<br />
<br />
Most if not all review sites work from a backlog of about 3-4 weeks. And they all want a promo code to get the game for free, they won’t pay money for your app. Apple allows you 50 promo codes per release. Once you make a new release, the unused promo codes are invalidated.<br />
<br />
In the 3 weeks we’ve been waiting, we’ve had 1 review come back. Fortunately it was a good one.<br />
<br />
For our next title we’ll be doing more on the pre-release marketing side to get the game buzz out before release. As we were taking so long on Catch the Monkey and we didn’t really know if or when we would be done, we had to forgo pre-release marketing.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Conclusion</strong></span><br />
Well, there you have it: a summary of our ups and downs over roughly 2 years trying to make an iphone game.<br />
<br />
We set a goal, and despite great difficulties, achieved it. Beyond this, three things have brought great satisfaction:<br />
<br />
1. Our first review came in:<br />
<span rel='lightbox'><img src='http://cdn.famigo.com/static/images/famigo-approved.png' alt='Posted Image' class='bbc_img' /></span><br />
We received <a href='http://mirthwerx.com/2012/02/03/catch-the-monkey-scores-45-stars-from-famigo-com/' class='bbc_url' title='External link' rel='nofollow external'>4/5 stars</a> and an editor’s choice award from the family mobile gaming site <a href='http://mirthwerx.com/2012/02/03/catch-the-monkey-scores-45-stars-from-famigo-com/' class='bbc_url' title='External link' rel='nofollow external'>famigo.com</a>. It’s nice to know someone objective thinks what we made is good!<br />
<br />
2. A review someone wrote on the US store:<br />
<em class='bbc'>How fun can catching monkeys be? Hours of fun! I love this game because it's something for my kids to do that's different from princess games and phonics—and it’s something that I can do when I’m commuting, waiting for my next appointment, or just to relax. This has got to be one of the best non-violent games I’ve ever seen. Great graphics, good story, and entertaining for everyone.</em><br />
<br />
3. The popularity of these articles.<br />
When we first set out to talk about our experience, we didn’t know who would be interested. Over 3,000 reads and counting on the first article makes all this writing effort worthwhile! Thanks!<br />
<br />
<strong class='bbc'>What’s next for <a href='http://mirthwerx.com/' class='bbc_url' title='External link' rel='nofollow external'>Mirthwerx</a>?</strong><br />
We’re currently working on a few things:<ul class='bbc'><br /><li>Playbook version (taking full advantage of having used Marmalade)<br /></li><li>Android version (dido)<br /></li><li>Free version (different from a lite version, it’s a different but similar game)<br /></li><li>And our second title which is a puzzle game for the masses (remember, turn based!)<br /></li></ul><br />
I’ve enjoyed writing these articles, I hope they’ve been of benefit. I have some ideas for maybe doing an “encore” 5<sup class='bbc'>th</sup> article next week, but I’d be looking for questions or comments from people before I decide to do it.<br />
<br />
Until next we meet,<br />
Lord Yabo]]></description>
		<pubDate>Thu, 23 Feb 2012 20:54:34 +0000</pubDate>
		<guid isPermaLink="false">003a8eb4813be2f8c5ad692ff1866162</guid>
	</item>
	<item>
		<title>3D Animation Techniques with XNA Game Studio 4.0</title>
		<link>http://www.gamedev.net/page/resources/_/technical/directx-and-xna/3d-animation-techniques-with-xna-game-studio-40-r2879</link>
		<description><![CDATA[In this article, we will look at several ways to make the objects in our scene move. First, we will look at the animation of objects as a whole. We will do this through simple linear interpolation between start and end values, and through a more complex curve interpolation. We will also look at more complex animations through keyframed animation.<br />
<br />
This article by <strong class='bbc'>Sean James</strong>, author of <a href='http://www.packtpub.com/3d-graphics-with-xna-game-studio-4-0/book/rk/3dxna-abr4/0111?utm_source=rk_3dxna_abr4_0111&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>3D Graphics with XNA Game Studio 4.0</a>, covers:<ul class='bbc'><br /><li>Object animation<br /></li><li>Keyframed animation<br /></li><li>Curve interpolation<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Object animation</strong></span><br />
We will first look at the animation of objects as a whole. The most common ways to animate an object are rotation and translation (movement). We will begin by creating a class that will interpolate a position and rotation value between two extremes over a given amount of time. We could also have it interpolate between two scaling values, but it is very uncommon for an object to change size in a smooth manner during gameplay, so we will leave it out for simplicity's sake.<br />
<br />
The <em class='bbc'>ObjectAnimation</em> class has a number of parameters—starting and ending position and rotation values, a duration to interpolate during those values, and a Boolean indicating whether or not the animation should loop or just remain at the end value after the duration has passed:<br />
<br />
<pre class='prettyprint'>public class ObjectAnimation<br />{<br />  Vector3 startPosition, endPosition, startRotation, endRotation;<br />  TimeSpan duration;<br />  bool loop;<br />}</pre><br />
We will also store the amount of time that has elapsed since the animation began, and the current position and rotation values:<br />
<br />
<pre class='prettyprint'>TimeSpan elapsedTime = TimeSpan.FromSeconds(0);<br /><br />public Vector3 Position { get; private set; }<br />public Vector3 Rotation { get; private set; }</pre><br />
The constructor will initialize these values:<br />
<br />
<pre class='prettyprint'>public ObjectAnimation(Vector3 StartPosition, Vector3 EndPosition,<br />  Vector3 StartRotation, Vector3 EndRotation, TimeSpan Duration,<br />  bool Loop)<br />{<br />  this.startPosition = StartPosition;<br />  this.endPosition = EndPosition;<br />  this.startRotation = StartRotation;<br />  this.endRotation = EndRotation;<br />  this.duration = Duration;<br />  this.loop = Loop;<br />  Position = startPosition;<br />  Rotation = startRotation;<br />}</pre><br />
Finally, the <em class='bbc'>Update()</em> function takes the amount of time that has elapsed since the last update and updates the position and rotation values accordingly:<br />
<br />
<pre class='prettyprint'>public void Update(TimeSpan Elapsed)<br />{<br />  // Update the time<br />  this.elapsedTime += Elapsed;<br /><br />  // Determine how far along the duration value we are (0 to 1)<br />  float amt = (float)elapsedTime.TotalSeconds / (float)duration.<br />TotalSeconds;<br /><br />  if (loop)<br />	 while (amt &gt; 1) // Wrap the time if we are looping<br />		   amt -= 1;<br />  else // Clamp to the end value if we are not<br />	 amt = MathHelper.Clamp(amt, 0, 1);<br /><br />  // Update the current position and rotation<br />  Position = Vector3.Lerp(startPosition, endPosition, amt);<br />  Rotation = Vector3.Lerp(startRotation, endRotation, amt);<br />}</pre><br />
As a simple example, we'll create an animation (in the <em class='bbc'>Game1</em> class) that rotates our spaceship in a circle over a few seconds:<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0041OT_09_01.png' alt='Posted Image' class='bbc_img' /></span></p><br />
We'll also have it move the model up and down for demonstration's sake:<br />
<br />
<pre class='prettyprint'>ObjectAnimation anim;</pre><br />
We initialize it in the constructor:<br />
<br />
<pre class='prettyprint'>models.Add(new CModel(Content.Load("ship"),<br />  Vector3.Zero, Vector3.Zero, new Vector3(0.25f), GraphicsDevice));<br /><br />anim = new ObjectAnimation(new Vector3(0, -150, 0),<br />	   new Vector3(0, 150, 0),<br />	   Vector3.Zero, new Vector3(0, -MathHelper.TwoPi, 0),<br />	   TimeSpan.FromSeconds(10), true);</pre><br />
We update it as follows:<br />
<br />
<pre class='prettyprint'>anim.Update(gameTime.ElapsedGameTime);<br /><br />models&#91;0&#93;.Position = anim.Position;<br />models&#91;0&#93;.Rotation = anim.Rotation;</pre><br />
<span style='font-size: 18px;'><strong class='bbc'>Keyframed animation</strong></span><br />
Our <em class='bbc'>ObjectAnimation</em> class allows us to create simple linear animations, but we can't create anything more complex. For example, we can't make our spaceship move in a circle with this class. To achieve more complex animations, we will use what is called <strong class='bbc'>keyframed animation</strong>. In this method, we specify "key" frames where we want the object to be in a specific position and orientation. We then rely on the code to interpolate between those values to fill in the frames between the key frames.<br />
<br />
The following screenshot shows our spaceship at the keyframed positions along a path, and the black line shows the path that would be taken by interpolating between keyframes:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0041OT_09_02.png' alt='Posted Image' class='bbc_img' /></span></p><br />
Keyframed animation is useful because it is a fast way to create somewhat complex animations without having to animate each frame. For example, birds flying through the air, soldiers on patrol, or even a camera flying through a scene, can all be animated through keyframes. This is probably the easiest way to move the camera during a cutscene, for example. We represent a key frame with the <em class='bbc'>ObjectAnimationFrame</em> class. Like the previous class, it contains position and rotation values. It also, however, contains a time value, marking this frame's time offset from the beginning of the animation.<br />
<br />
<pre class='prettyprint'>public class ObjectAnimationFrame<br />{<br />  public Vector3 Position { get; private set; }<br />  public Vector3 Rotation { get; private set; }<br />  public TimeSpan Time { get; private set; }<br /><br />  public ObjectAnimationFrame(Vector3 Position, Vector3 Rotation,<br />   TimeSpan Time)<br />  {<br />	this.Position = Position;<br />	this.Rotation = Rotation;<br />	this.Time = Time;<br />  }<br />}</pre><br />
We can now create a new animation class that uses key frames:<br />
<br />
<pre class='prettyprint'>public class KeyframedObjectAnimation<br />{<br />List frames = new List();<br />bool loop;<br />TimeSpan elapsedTime = TimeSpan.FromSeconds(0);<br /><br />public Vector3 Position { get; private set; }<br />public Vector3 Rotation { get; private set; }<br /><br />public KeyframedObjectAnimation(List Frames,<br />  bool Loop)<br />{<br />  this.frames = Frames;<br />   this.loop = Loop;<br />  Position = Frames&#91;0&#93;.Position;<br />  Rotation = Frames&#91;0&#93;.Rotation;<br />}<br />}</pre><br />
Finally, the <em class='bbc'>Update()</em> function fï»¿igures out which frame we are on and interpolates between its values and the next frame's values, based on how far between them we are:<br />
<br />
<pre class='prettyprint'>public void Update(TimeSpan Elapsed)<br />{<br />  // Update the time<br />  this.elapsedTime += Elapsed;<br /><br />  TimeSpan totalTime = elapsedTime;<br />  TimeSpan end = frames&#91;frames.Count - 1&#93;.Time;<br /><br />  if (loop) // Loop around the total time if necessary<br />	while (totalTime &gt; end)<br />	   totalTime -= end;<br />  else // Otherwise, clamp to the end values<br />  {<br />	Position = frames&#91;frames.Count - 1&#93;.Position;<br />	Rotation = frames&#91;frames.Count - 1&#93;.Rotation;<br />	return;<br />  }<br /><br />  int i = 0;<br />  // Find the index of the current frame<br />  while(frames&#91;i + 1&#93;.Time	  i++;<br />  // Find the time since the beginning of this frame<br />  totalTime -= frames&#91;i&#93;.Time;<br /><br />  // Find how far we are between the current and next frame (0 to 1)<br />  float amt = (float)((totalTime.TotalSeconds) /<br />	 (frames&#91;i + 1&#93;.Time - frames&#91;i&#93;.Time).TotalSeconds);<br /><br />  // Interpolate position and rotation values between frames<br />  Position = Vector3.Lerp(frames&#91;i&#93;.Position, frames&#91;i + 1&#93;.Position,<br />   amt);<br />  Rotation = Vector3.Lerp(frames&#91;i&#93;.Rotation, frames&#91;i + 1&#93;.Rotation,<br />   amt);<br />}</pre><br />
For example, we can now create a new animation to move our spaceship in a square:<br />
<br />
<pre class='prettyprint'>KeyframedObjectAnimation anim;</pre><br />
We set it up as follows:<br />
<br />
<pre class='prettyprint'>List frames = new List();<br /><br />frames.Add(new ObjectAnimationFrame(new Vector3(-1000, 100, -1000),<br />  new Vector3(0, MathHelper.ToRadians(-90), 0),<br />  TimeSpan.FromSeconds(0)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(1000, 100, -1000),<br />  new Vector3(0, MathHelper.ToRadians(-90), 0),<br />  TimeSpan.FromSeconds(3)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(1000, 100, -1000),<br />  new Vector3(0, MathHelper.ToRadians(-180), 0),<br />  TimeSpan.FromSeconds(6)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(1000, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(-180), 0),<br />  TimeSpan.FromSeconds(9)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(1000, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(-270), 0),<br />  TimeSpan.FromSeconds(12)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-1000, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(-270), 0),<br />  TimeSpan.FromSeconds(15)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-1000, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(-360), 0),<br />  TimeSpan.FromSeconds(18)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-1000, 100, -1000),<br />  new Vector3(0, MathHelper.ToRadians(-360), 0),<br />  TimeSpan.FromSeconds(21)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-1000, 100, -1000),<br />  new Vector3(0, MathHelper.ToRadians(-450), 0),<br />  TimeSpan.FromSeconds(24)));<br /><br />anim = new KeyframedObjectAnimation(frames, true);</pre><br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0041OT_09_03.png' alt='Posted Image' class='bbc_img' /></span></p><br />
The <em class='bbc'>Update</em> code remains the same. Running the game, you will see the spaceship move from corner to corner of a box, turning towards the next corner at each stop.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Curve interpolation</strong></span><br />
We now have the ability to make animations with multiple key frames, which allows us to create more complex animations. However, we are still interpolating linearly between those key frames. This looks good for rotations, for example, but it would not look good for an object following a path, as the object would abruptly change direction after reaching a key frame in its animation. Instead, we want to be able to have our objects follow a smooth curve through the positions defined in the key frames. We will do this with what is called <strong class='bbc'>Catmull-Rom interpolation</strong>. This is a process that will create a curve through our key frame positions, allowing for much smoother object animation:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0041OT_09_04.png' alt='Posted Image' class='bbc_img' /></span></p><br />
Let's modify the <em class='bbc'>KeyframedObjectAnimation</em> class to use Catmull-Rom interpolation for the position value. XNA has a built-in function to calculate an interpolated position between the second and third points in a set of four points using Catmull-rom interpolation. However, it works only in one dimension, so we'll need to create a function that will interpolate between a set of instances of <em class='bbc'>Vector3</em>:<br />
<br />
<pre class='prettyprint'>Vector3 catmullRom3D(Vector3 v1, Vector3 v2, Vector3 v3,<br />Vector3 v4, float amt)<br />{<br />return new Vector3(<br />  MathHelper.CatmullRom(v1.X, v2.X, v3.X, v4.X, amt),<br />  MathHelper.CatmullRom(v1.Y, v2.Y, v3.Y, v4.Y, amt),<br />  MathHelper.CatmullRom(v1.Z, v2.Z, v3.Z, v4.Z, amt));<br />}</pre><br />
The <em class='bbc'>amt</em> argument specifies how far (0 to 1) between the second and third vectors the new position should be. We can now modify the position calculation to use this new function:<br />
<br />
<pre class='prettyprint'>// Interpolate position and rotation values between frames<br />Position = catmullRom3D(frames&#91;wrap(i - 1, frames.Count - 1)&#93;.<br />Position,<br />  frames&#91;wrap(i, frames.Count - 1)&#93;.Position,<br />  frames&#91;wrap(i + 1, frames.Count - 1)&#93;.Position,<br />  frames&#91;wrap(i + 2, frames.Count - 1)&#93;.Position, amt);</pre><br />
The <em class='bbc'>wrap()</em> function wraps the value that it is given around a certain interval—in this case [0, <em class='bbc'>frames.Count</em> – 1]. This means that we will not have to worry about our indices going out of range when finding the last point, next point, and so on, but it does mean that this type of interpolation will work best with a closed curve—a circle, for example:<br />
<br />
<pre class='prettyprint'>// Wraps the "value" argument around &#91;0, max&#93;<br />int wrap(int value, int max)<br />{<br />  while (value &gt; max)<br />	value -= max;<br /><br />  while (value	 value += max;<br />  return value;<br />}</pre><br />
We could now create the following keyframed animation with a curved path to demonstrate our new interpolation method:<br />
<br />
<pre class='prettyprint'>List frames = new List();<br /><br />frames.Add(new ObjectAnimationFrame(new Vector3(-500, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(0), 0),<br />  TimeSpan.FromSeconds(0)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(500, 100, 500),<br />  new Vector3(0, MathHelper.ToRadians(0), 0),<br />  TimeSpan.FromSeconds(3)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-500, 100, 0),<br />  new Vector3(0, MathHelper.ToRadians(0), 0),<br />  TimeSpan.FromSeconds(6)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(500, 100, -500),<br />  new Vector3(0, MathHelper.ToRadians(0), 0),<br />  TimeSpan.FromSeconds(9)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-500, 100, -1000),<br />  new Vector3(0, MathHelper.ToRadians(180), 0),<br />  TimeSpan.FromSeconds(12)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-500, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(180), 0),<br />  TimeSpan.FromSeconds(15)));<br />frames.Add(new ObjectAnimationFrame(new Vector3(-500, 100, 1000),<br />  new Vector3(0, MathHelper.ToRadians(360), 0),<br />  TimeSpan.FromSeconds(18)));<br /><br />anim = new KeyframedObjectAnimation(frames, true);</pre><br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0041OT_09_05.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
In this article we have covered the following concepts:<ul class='bbc'><br /><li>Object animation<br /></li><li>Keyframed animation<br /></li><li>Curve interpolation<br /></li></ul>]]></description>
		<pubDate>Thu, 23 Feb 2012 20:34:11 +0000</pubDate>
		<guid isPermaLink="false">1ada62a8c0df8c2909a8669d78a338cb</guid>
	</item>
	<item>
		<title>Producer Consumer Using Double Queues</title>
		<link>http://www.gamedev.net/page/resources/_/technical/general-programming/producer-consumer-using-double-queues-r2878</link>
		<description><![CDATA[<ul class='bbc'><br /><li><a href='http://uploads.gamedev.net/cp/1329923428-DoubleQueue.zip' class='bbc_url' title='External link' rel='nofollow external'>Download source - 4.02 KB</a><br /></li></ul><br />
License: <a href='http://www.opensource.org/licenses/zlib-license.php' class='bbc_url' title='External link' rel='nofollow external'><span class='bbc_underline'><strong class='bbc'>Zlib</strong></span></a><br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Introduction</strong></span><br />
<br />
Producer consumer is an old computer science problem. Many solutions have been proposed to solve this problem. The general approach is using a common queue. A single queue to which the producer writes data to and the consumer reads data from. Avoiding race conditions is done by locking the queue so that when the producer is writing, the consumer is not reading and vice versa.<br />
<br />
The problem with this approach is that whenever the producer puts data to the queue, it has to acquire a lock. Similarly whenever the consumer gets data, it has to lock the queue. This solution is inadequate on systems where the producer generates data in excess of a hundred thousand updates per second. In my opinion, a hundred thousand locks on the queue in one second is a huge performance penalty.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Background</strong></span><br />
<br />
Once while going over this conundrum with my better half, I was introduced to the concept of double queuing. Something similar to the double buffering used in graphics applications to avoid flicker. As far as my research goes, I was not able to find a similar solution to the producer consumer problem. In case this is duplication, my apologies. I would be indebted if you can point me to the original work.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Double Queuing</strong></span><br />
<br />
The solution proposed is very simple and elegant. Instead of using a single queue, we use two queues. At a given time, one queue is designated write queue and the other, the read queue. This helps us to avoid locking the queue while reading and writing to it. The producer is free to fill the write queue and the consumer is free to empty the read queue.<br />
<br />
When the consumer is done reading the read queue, the producer is blocked briefly and the queues are switched. Now the old read queue becomes the new write queue and the old write queue becomes the new read queue. After switching, if there is no data in the new read queue, the consumer is blocked. When the producer gets more data, it unblocks the consumer.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Code</strong></span><br />
<br />
This solution makes use of Events for synchronization between the consumer and the producer. The producer code looks like this:<br />
<pre class='prettyprint'><br /><br />public void ProducerFunc()<br />{<br />	int data = 0;<br /><br />	for (int i = 0; i &lt; 10000; i++)<br />	{<br />		data += 1;<br />		MessageHandler(data);<br />		Thread.Sleep(m_Random.Next(0, 2));<br />	}<br />}<br /><br />private void MessageHandler(int data)<br />{<br />	m_UnblockHandlerEvent.WaitOne();<br />	m_HandlerFinishedEvent.Reset();<br /><br />	m_CurrentWriteQueue.Enqueue(data);<br />	m_ProducerData.WriteLine(data); // logging<br /><br />	m_DataAvailableEvent.Set();<br />	m_HandlerFinishedEvent.Set();<br />}<br /></pre><br />
<br />
<br />
<br />
The ProducerFunc() is a thread function that is invoked 10,000 times. Every time MessageHandler() is called, it checks to see if it has been blocked by the consumer. If not, it resets the ManualResetEvent to indicate to the consumer that the producer has not yet finished. This is useful when the consumer is trying to switch the queues and wants to know if the producer is finished writing to the queue. The rest of the code is straight forward. Data is written to queue and an event is set to wake up the consumer incase it was blocked. Finally, an event is set to indicate that the producer is finished writing to queue.<br />
<br />
This is the consumer code:<br />
<pre class='prettyprint'><br /><br />public void ConsumerFunc()<br />{<br />	int count;<br />	int data;<br />	Queue&lt;int&gt; readQueue;<br /><br />	while (true)<br />	{<br />		m_DataAvailableEvent.WaitOne();<br /><br />		m_UnblockHandlerEvent.Reset(); // block the producer<br />		m_HandlerFinishedEvent.WaitOne(); // wait for the producer to finish<br />		readQueue = m_CurrentWriteQueue;<br />		// switch the write queue<br />		m_CurrentWriteQueue = (m_CurrentWriteQueue == m_Q1) ? m_Q2 : m_Q1;<br />		m_UnblockHandlerEvent.Set(); // unblock the producer<br /><br />		count = ;<br />		while (readQueue.Count &gt; )<br />		{<br />			count += 1;<br /><br />			data = readQueue.Dequeue();<br />			m_ConsumerData.WriteLine(data); // logging<br /><br />			Thread.Sleep(m_Random.Next(0, 2));<br />		}<br />		Console.WriteLine("Removed {0} items from queue: {1}",<br />					count, readQueue.GetHashCode());<br />	}<br />}<br /></pre><br />
<br />
<br />
<br />
The ConsumerFunc() is a separate thread function. When the function starts, it checks to see if the data present event has been set. If not, then it is blocked till we get data written by the producer. Once data is present in the queue, the consumer resets the event to block the producer and waits for the producer to finish. The current write queue is now cached for reading and the current write queue is switched. After the queue is switched, the producer is unblocked to enable it to start writing to the new write queue. Meanwhile the consumer is busy reading from the read queue. Once the queue is empty, the entire process is repeated.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Points of Interest</strong></span><br />
<br />
On further discussing this solution with others, I was told using synchronization events causes more performance problems than using lock. What do you think about that argument? Can you shed some light on this from your experiences with lock and synchronization events?<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>About the Author</strong></span><br />
<br />
	Nothing to brag about! Just another passionate software developer!<br />
<br />
Work to make a living, don't live to work!	<br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>License</strong></span><br />
<br />
This article was authored by Ram Mohan Raja and reproduced for the benefit of our viewers under the terms of the <a href='http://www.opensource.org/licenses/zlib-license.php' class='bbc_url' title='External link' rel='nofollow external'>Zlib</a> license.]]></description>
		<pubDate>Wed, 22 Feb 2012 15:11:21 +0000</pubDate>
		<guid isPermaLink="false">cb4b635a95a5e567747155f54a000542</guid>
	</item>
	<item>
		<title>Introducing Xcode Tools for iPhone Development</title>
		<link>http://www.gamedev.net/page/resources/_/technical/mobile-development/introducing-xcode-tools-for-iphone-development-r2877</link>
		<description><![CDATA[In this article by <strong class='bbc'>Steven F. Daniel</strong>, author of <a href='http://www.packtpub.com/xcode-4-ios-iphone-development-beginners-guide/book/kb/xcode4ios-abr2/0911?utm_source=kb_xcode4ios_abr2_0911&utm_medium=content&utm_campaign=kedar' class='bbc_url' title='External link' rel='nofollow external'>Xcode 4 iPhone Development</a> , we shall:<ul class='bbc'><br /><li>Learn about the features and components of the Xcode development tools.<br /></li><li>Lean about Xcode, Cocoa, Cocoa-Touch, and Objective-C.<br /></li><li>Take a look into each of the iOS Technology Layers and their Components.<br /></li><li>Take a look into what comprises the Xcode Developer set of Tools.<br /></li><li>Take a look at the new features within the iOS4 SDK.<br /></li></ul><br />
There is a lot of fun stuff to cover, so let's get started.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Development using the Xcode Tools</strong></span><br />
If you are running Mac OSX 10.5, chances are your machine is already running Xcode. These are located within the <strong class='bbc'>/Developer/Applications</strong> folder. Apple also makes this freely available through the Apple Developer Connection at <a href='http://developer.apple.com/' class='bbc_url' title='External link' rel='nofollow external'>http://developer.apple.com/</a>.<br />
<br />
The iPhone SDK includes a suite of development tools to assist you with your development of your iPhone, and other iOS device applications. We describe these in the following table.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>iPhone SDK Core Components</strong></span>										This is the main Integrated Development Environment (IDE) that enables you to manage, edit, and debug your projects.											This enables you to develop web-based iPhone and iPad applications, and Dashboard widgets.											The iPhone Simulator is a Cocoa-based application, which provides a software simulator to simulate an iPhone or iPad on your Mac OSX.											These are the Analysis tools, which help you optimize your applications and monitor for memory leaks in real-time.			<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>The Xcode tools require an Intel-based Mac running Mac OS X version 10.6.4 or later in order to function correctly.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Inside Xcode, Cocoa, and Objective-C</strong></span><br />
Xcode 4 is a complete toolset for building Mac OSX (Cocoa-Based) and iOS applications. The new single-windowed development interface has been redesigned to be a lot easier and even more helpful to use than it has been in previous releases. It can now also identify mistakes in both syntax and logical errors, and will even fix your code for you.<br />
<br />
It provides you with the tools to enable you to speed up your development process, therefore becoming more productive. It also takes care of the deployment of both your Mac OSX and iOS applications.<br />
<br />
The Integrated Development Interface (IDE) allows you to do the following:<br />
<ul class='bbc'><br /><li>Create and manage projects, including specifying platforms, target requirements, dependencies, and build configurations.<br /></li><li>Supports Syntax Colouring and automatic indenting of code.<br /></li><li>Enables you to navigate and search through the components of a project, including header files and documentation.<br /></li><li>Enables you to Build and Run your project.<br /></li><li>Enables you to debug your project locally, run within the iOS simulator, or remotely, within a graphical source-level debugger.<br /></li></ul><br />
Xcode incorporates many new features and improvements, apart from the redesigned user interface; it features a new and improved <strong class='bbc'>LLVM</strong> (<strong class='bbc'>Low Level Virtual Machine</strong>) debugger, which has been supercharged to run 3 times faster and 2.5 times more efficient.<br />
<br />
This new compiler is the next generation compiler technology designed for high-performance projects and completely supports C, Objective-c, and now C++. It is also incorporated into the Xcode IDE and compiles twice as fast and quickly as GCC and your applications will run faster.<br />
<br />
The following list includes the many improvements made to this release.<ul class='bbc'><br /><li>The interface has been completely redesigned and features a single-window integrated development interface.<br /></li><li>Interface Builder has now been fully integrated within the Xcode development IDE.<br /></li><li>Code Assistant opens in a second window that shows you the file that you are working on, and can automatically find and open the corresponding header file(s).<br /></li><li>Fix-it checks the syntax of your code and validates symbol names as you type. It will even highlight any errors that it finds and will even fix them for you.<br /></li><li>The new Version Editor works with GIT (Free Open-Source) version control software or Subversion. This will show you the files entire SCM (software configuration management) history and will even compare any two versions of the file.<br /></li><li>The new LLVM 2.0 compiler includes full support for C, Objective-C, and C++<br /></li><li>The LLDB debugger has now been improved to be even faster, it uses less memory than the GDB debugging engine.<br /></li><li>The new Xcode 4 development IDE now lets you work on several interdependent projects within the same wind&#111;w. It automatically determines its dependencies so that it builds the projects in the right order.<br /></li></ul><br />
Xcode allows you to customize an unlimited number of build and debugging tools, and executable packaging. It supports several source-code management tools, namely, CVS "<em class='bbc'>Version control software which is an important component of the Source Configuration Management (SCM)</em>" and Subversion, which allows you to add files to a repository, commit changes, get updated versions and compare versions using the Version Editor tool.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>The iPhone Simulator</strong></span><br />
The iPhone Simulator is a very useful tool that enables you to test your applications without using your actual device, whether this being your iPhone or any other iOS device. You do not need to launch this application manually, as this is done when you Build and run your application within the Xcode Integrated Development Environment (IDE). Xcode installs your application on the iPhone Simulator for you automatically.<br />
<br />
The iPhone Simulator also has the capability of simulating different versions of the iPhone OS, and this can become extremely useful if your application needs to be installed on different iOS platforms, as well as testing and debugging errors reported in your application when run under different versions of the iOS.<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>While the iPhone Simulator acts as a good test bed for your applications, it is recommended to test your application on the actual device, rather than relying on the iPhone Simulator for testing. The iPhone Simulator can be found at the following location <strong class='bbc'>/Developer/Platforms/iPhoneSimulator.Platform/Developer/Applications</strong>.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Layers of the iOS Architecture</strong></span><br />
According to Apple, they describe the set of frameworks and technologies that are currently implemented within the iOS operating system as a series of layers. Each of these layers is made up of a variety of different frameworks that can be used and incorporated into your applications.<br />
<br />
Layers of the iOS Architecture<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1307_01_01.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
We shall now go into detail and explain each of the different layers of the iOS Architecture; this will give you a better understanding of what is covered within each of the Core layers.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>The Core OS Layer</strong></span><br />
This is the bottom layer of the hierarchy and is responsible for the foundation of the Operating system, which the other layers sit on top of. This important layer is in charge of managing memory - allocating and releasing of memory once it has finished with it, taking care of file system tasks, handles networking, and other Operating System tasks. It also interacts directly with the hardware.<br />
<br />
The Core OS Layer consists of the following components:<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Core Services Layer</strong></span><br />
The Core Services layer provides an abstraction over the services provided in the Core OS layer. It provides fundamental access to the iPhone OS services. The Core Services Layer consists of the following components:<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Media Layer</strong></span><br />
The Media Layer provides Multimedia services that you can use within your iPhone, and other iOS devices. The Media Layer is made up of the following components:<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Cocoa-Touch Layer</strong></span><br />
The Cocoa-Touch layer provides an abstraction layer to expose the various libraries for programming the iPhone, and other IOS devices. You probably can understand why Cocoa-Touch is located at the top of the hierarchy due to its support for Multi-Touch capabilities. The Cocoa-Touch Layer is made up of the following components:<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Understanding Cocoa, the language of the Mac</strong></span><br />
Cocoa is defined as the development framework used for the development of most native Mac OSX applications. A good example of a Cocoa related application is Mail or Text Edit.<br />
<br />
This framework consists of a collection of shared object code libraries known as the Cocoa frameworks. It consists of a runtime system and a development environment. These set of frameworks provide you with a consistent and optimized set of prebuilt code modules that will speed up your development process.<br />
<br />
Cocoa provides you with a rich-layer of functionality, as well as a comprehensive object-oriented like structure and APIs on which you can build your applications. Cocoa uses the Model-View-Controller (MVC) design pattern.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>What are Design Patterns?</strong></span><br />
Design Patterns represent and handle specific solutions to problems that arise when developing software within a particular context. These can be either a description or a template, on how to go about to solve a problem in a variety of different situations.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>What is the difference between Cocoa and Cocoa-Touch?</strong></span><br />
Cocoa-Touch is the programming language framework that drives user interaction on iOS. It consists and uses technology derived from the cocoa framework and was redesigned to handle multi-touch capabilities. The power of the iPhone and its User Interface are available to developers throughout the Cocoa-Touch frameworks.<br />
<br />
Cocoa-Touch is built upon the Model-View-Controller structure; it provides a solid stable foundation for creating mind blowing applications. Using the Interface builder developer tool, developers will find it both very easy and fun to use the new drag-and-drop method when designing their next great masterpiece application on iOS.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>The Model-View-Controller</strong></span><br />
The <strong class='bbc'>Model-View-Controller</strong> (or <strong class='bbc'>MVC</strong>) comprises a logical way of dividing up the code that makes up the <strong class='bbc'>GUI</strong> (<strong class='bbc'>Graphical User Interface</strong>) of an application. Object-Oriented applications like Java and .Net have adopted the MVC design pattern.<br />
<br />
The MVC model comprises three distinctive categories:Model : This part defines your application's underlying data engine. It is responsible for maintaining the integrity of that data.<ul class='bbc'><br /><li>View : This part defines the user interface for your application and has no explicit knowledge of the origin of data displayed in that interface. It is made up of Windows, controls, and other elements that the user can see and interact with.<br /></li><li>Controller : This part acts as a bridge between the model and view and facilitates updates between them. It binds the Model and View together and the application logic decides how to handle the user's inputs.<br /></li></ul><br />
<br />
<br />
<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>What is Object-Oriented Programming?</strong></span><br />
Object-Oriented programming (or formally known as "OOP"), provides an abstraction layer of the data on which you operate, it provides a concrete foundation between the data and the operations you perform with the data, in effect giving the data behavior.<br />
<br />
By using the power of Object-Oriented programming, it allows us to create classes and later extend its characteristics to incorporate additional functionality. Objects within a class can be protected to prevent those elements being exposed; this is called "Data Hiding".<br />
<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>If you are interested in learning more about Object-Oriented Programming, please consult the Apple Developer documentation or via the following link <a href='https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/OOP_ObjC/Articles/ooOOP.html' class='bbc_url' title='External link' rel='nofollow external'>https://developer.ap...cles/ooOOP.html</a>.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>What is Objective-C?</strong></span><br />
When I first started to develop for the iPhone, I realised that I needed to learn Objective-C, as this is the development language for Mac and iOS. I found it to be one of the strangest looking languages I had ever come across. Today, I really enjoy developing and working with it, so will you too.<br />
<br />
Objective-C is an object-oriented programming language used by Apple primarily for programming Mac OSX, iPhone, and other iOS applications. It is an extension of the C-Programming Language. If you have not done any OOP programming before, I would seriously recommend that you read the OOP document from the Apple Developer website.<br />
<br />
On the other hand, if you have used and are familiar with C, .Net or Java, learning Objective-C should be relatively easy for you to understand.<br />
<br />
Objective-C consists of two types of files:<br />
<ul class='bbc'><br /><li>.h : These types of files are called 'Header' or 'Interface files'<br /></li><li>.m: These types of files are those which contain your program code logic and make use of the 'Header' files. These are also referred to as 'implementation' files.<br /></li></ul><br />
Most Object-Oriented development environments consist of several parts:<ul class='bbc'><br /><li>An Object-Oriented programming language.<br /></li><li>An extensive library consisting of objects.<br /></li><li>A development suite of developer tools.<br /></li><li>A runtime environment.<br /></li></ul><br />
For example, here is a piece of code written in Objective-C<br />
<br />
<pre class='prettyprint'><br />-(int)method:(int)i {<br />	return &#91;self square_root: i&#93;;<br />}<br /><br /></pre><br />
If we were to compare this same code to how it would be written within C, it would look like this:<br />
<br />
<pre class='prettyprint'><br />int function(int i) {<br />	return square_root(i);<br />}<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>Let's investigate the code</strong></span><br />
Now, let's examine the code line by line to understand what is happening.<br />
<br />
<pre class='prettyprint'><br />-(int)method:(int)i {<br /><br /></pre><br />
We declare a function called <strong class='bbc'>method</strong> and a variable <strong class='bbc'>i</strong>, which is passed in as a parameter. We then pass the value to a function called <strong class='bbc'>square_root</strong> to calculate the value and the calculated result is returned.<br />
<br />
<pre class='prettyprint'><br />return &#91;self square_root: i&#93;;<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>Directives</strong></span><br />
In C/C++, we use directives to include any other header files that our application will need to access, this is done by using <strong class='bbc'>#include</strong>. In Objective-C, we use the <strong class='bbc'>#import</strong> directive. If you observe the content of the MyClass.h file, you will notice that at the top of the file is a <strong class='bbc'>#import</strong> statement.<br />
<br />
<pre class='prettyprint'><br />#import<br />@Interface myClass : NSObject{<br />}<br />@end<br /><br /></pre><br />
The #import statement is known as a "<em class='bbc'>pre-processor directive</em>". As I mentioned previously, in C/C++, you use the <strong class='bbc'>#include</strong> pre-processor directive to include a files content with the current source file. In Objective-C, you use the #import statement to do the same, with the exception that the compiler ensures that the file is only included once.<br />
<br />
To import a header file from one of the framework libraries, you would specify the header filename using the angle brackets (), within the #import statement. If you were wanting to import one of your own header files to be used within your project, you would specify and make use of the (" "), as you can see from our code file, <strong class='bbc'>MyClass.m</strong>.<br />
<br />
<pre class='prettyprint'><br />#import "MyClass.h"<br />@implementation MyClass<br />@end<br /><br /></pre><br />
<span style='font-size: 18px;'><strong class='bbc'>Objective-C Classes</strong></span><br />
A <strong class='bbc'>Class</strong> can be simply be defined as a representation of a type of object; think of it as a blueprint that describes the object. Just as a single blueprint can be used to build multiple versions of a car engine, a class can be used to create multiple copies of an object. In Objective-C, you will spend most of your time dealing with classes and class objects. An example of a class object is the <strong class='bbc'>NSObject</strong> class. <strong class='bbc'>NSObject</strong> is the root class of most of the Objective-C classes. It defines the basic interface of a class and contains methods that are common to all classes that inherit from it.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>@interface</strong></span><br />
To declare a class, you use the <strong class='bbc'>@interface</strong> compiler directive, as follows:<br />
<br />
<pre class='prettyprint'><br />@interface MyClass : NSObject {<br />}<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>@implementation</strong></span><br />
To implement a class declared within a header file, you use the <strong class='bbc'>@implementation</strong> compiler directive, as follows:<br />
<br />
<pre class='prettyprint'><br />#import "MyClass.h"<br />@implementation MyClass<br />@end<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>Class Instantiation</strong></span><br />
In Objective-C, in order for us to create an instance of a class, you would typically use the <strong class='bbc'>alloc</strong> keyword to allocate memory for the object and then return the variable in a class type This is shown in the following example:<br />
<br />
<pre class='prettyprint'><br />MyClass *myClass = &#91;MyClass alloc&#93;;<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>Class Access Privileges</strong></span><br />
In OOP, when you are defining your classes, bear in mind that by default, the access privilege of all fields within a class are <strong class='bbc'>@protected</strong>. These fields can also be defined as <strong class='bbc'>@public</strong>, or <strong class='bbc'>@private</strong>.<br />
<br />
The following table shows the various access privileges that a class can contain.<br />
										A class member is made visible to all classes that instantiate this class.											Class members are made visible to the class that declares it as well as other classes which inherit from the base class.			<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>We have only covered a small part of the Objective-C programming concepts. If you are interested in reading a bit more about this area, please refer to the following website: http:// developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Introducing the Xcode Developer set of Tools</strong></span><br />
The Xcode developer set of tools comprise the Xcode Development Environment (IDE), Interface Builder, iPhone Simulator, and Instruments for Performance Analysis. These tools have been designed to integrate and work harmoniously together.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Introducing the Core Tools</strong></span><br />
The Xcode IDE is a complete full-featured development environment, which has been redesigned and built around to allow for a better smoother workflow development environment. With the integration of the GUI designer (Interface Builder), it allows a better way to integrate the editing of source code, building, compiling and debugging.<br />
<br />
The Interface Builder is an easy to use GUI designer, which enables you to design every aspect of your applications UI, for Mac OSX and iOS applications.<br />
<br />
All of your form objects are stored within one or more resource files, these files contain the associated relationships to each of the objects. Any changes that you make to the form design; these are automatically synchronized back to your code.<br />
<br />
The iPhone Simulator provides you with a means of testing your application out, and to see how it will appear on the actual phone device. The Simulator makes it a perfect choice to ensure that your user interface works and behaves they way you intended it to and makes it easier for you to debug your application. The iPhone Simulator does contain some limitations, which cannot be used to test certain features, so it is always better to deploy your app to your iOS device.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Welcome to Xcode Screen</strong></span><br />
To launch Xcode, double-click the Xcode icon located in the <strong class='bbc'>/Developer/Applications</strong> folder. Alternatively, you can use Spotlight to search for this: simply type Xcode into the search box and Xcode should be displayed in the list at the top.<br />
<br />
When Xcode is launched, you should see the Welcome to Xcode Screen as shown in the following screenshot below. From this screen, you are able to create new projects, check out existing projects from the SCM and modify those files within the Xcode integrated development environment. It also contains some information about learning Xcode as well as Apple Developer resources.<br />
<br />
The panel to the right-hand side of the screen will display any recent projects that you have opened. These can be opened and loaded into the IDE by clicking on them.<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1307_01_02.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Xcode – Integrated Development Environment</strong></span><br />
The Xcode Integrated Development Environment is what you will be using to start to code your iPhone applications.<br />
<br />
This consists of a single-window user interface, consisting of the Project Window, Jump and Navigation Bars, and the newly integrated Interface Builder designer.<br />
<br />
<br />
<p class='bbc_center'><a class='resized_img' rel='lightbox[0d4a5041158195ee04c1dedc25318e4a]' id='ipb-attach-url-7393-0-06650500-1330203877' href="http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=7393" title="1307_01_03(2).png - Size: 329.22K, Downloads: 10"><img src="http://public.gamedev.net/uploads/monthly_02_2012/ccs-5-0-10820500-1329881898_thumb.png" id='ipb-attach-img-7393-0-06650500-1330203877' style='width:480;height:302' class='attach' width="480" height="302" alt="Attached Image: 1307_01_03(2).png" /></a></p><br />
<br />
<p class='bbc_center'><em class='bbc'>(Move the mouse over the image to enlarge.)</em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Features of the iPhone Simulator</strong></span><br />
The"iPhone Simulator", simulates various features of a real iOS device. Although the iPhone simulator is just a simulator to simulate certain tasks, it does come with some limitations.<br />
<br />
Following is the list of some of the features which you are able to test using the iPhone Simulator. The following screenshot below displays the iPhone 4 simulator.<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1307_01_04.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>Please bear in mind, that being the "iPhone Simulator", it is just only a simulator. It does, however, pose some features which are impossible to handle. These have been defined as follows:</em></p><ul class='bbc'><br /><li>Making Phone calls<br /></li><li>Accessing the Accelerometer/Gyroscope<br /></li><li>Sending and Receiving SMS messages<br /></li><li>Installing applications from the App Store<br /></li><li>Accessibility to the Camera<br /></li><li>Use of the Microphone<br /></li><li>Several Core OpenGL ES Features<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Companion Tools and Features</strong></span><br />
These tools are classified as profiling tools which are the instruments that handle the following:<br />
<ul class='bbc'><br /><li>Performance and Power Analysis Tools<br /></li><li>Unit testing tools<br /></li><li>Source Code Management (SCM) / Subversion<br /></li><li>Version Comparison Tool<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Instruments</strong></span><br />
The Xcode instruments allow you to dynamically trace and profile the performance of your Mac OSX, iPhone, and iPad applications. You can also create your own Instruments using DTrace and the Instruments custom builder.<br />
<br />
Through the use of instruments, you can achieve the following:<br />
<ul class='bbc'><br /><li>Ability to perform Stress-tests on your applications.<br /></li><li>Monitor your applications for memory leaks, which can cause unexpected results.<br /></li><li>Gain a deeper understanding of the execution behavior of your applications.<br /></li><li>Track down difficult to reproduce problems in your applications.<br /><br /><br /><p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1307_01_05.png' alt='Posted Image' class='bbc_img' /></span></p><br /></li><li>In the following figure, we display the Instruments environment where you can start to create your robust test harness for your application to ensure that any memory leaks and resource intensive tasks are rectified to avoid problems later when your users download your app and experience issues.<br /><br /><br /><p class='bbc_center'><a class='resized_img' rel='lightbox[0d4a5041158195ee04c1dedc25318e4a]' id='ipb-attach-url-7394-0-06717000-1330203877' href="http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=7394" title="1307_01_06(2).png - Size: 75.28K, Downloads: 9"><img src="http://public.gamedev.net/uploads/monthly_02_2012/ccs-5-0-78702700-1329881930_thumb.png" id='ipb-attach-img-7394-0-06717000-1330203877' style='width:480;height:323' class='attach' width="480" height="323" alt="Attached Image: 1307_01_06(2).png" /></a></p><br /></li></ul><br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>If you are interested in learning more about the instruments that are included with Xcode and the iOS 4 SDK, please consult the Apple Developer documentation.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>iPhone OS4 SDK New Features</strong></span><br />
The iOS4 SDK comes jam-packed and is loaded with as many as 1,500 APIs. It contains some high quality enhancements and improvements, which allows endless possibilities for developers to create some stunning applications.<br />
										This is perhaps the most awaited feature everyone has been waiting for. It is an assortment of seven different services: Audio, VoIP, location, local and push notifications, task completions and fast app switching that will make it possible and simple enough to use many applications at the same time. This will allow you to play the audio continuously, receive calls while your device is locked or other apps are being used, location based applications will continue to guide you, and receiving alerts will be possible without the app running and the app will finish even when the customer leaves in the middle of it.											Another important feature in iOS4 is the Apps Folder, this feature allows you to drag an icon on top of another one and a new folder will be automatically created. It will be named according to the name of the category the particular icon or application comes from.											This has been vastly improved to allow for an organized approach of grouping various mails into one particular folder according to the conversation thread. Added support to handle more than one exchange account, which can also be opened through many third-party applications.											Game Center provides social networking services, where you can take part in leader boards and participate in other online activities with other players.											iAd is a mobile advertising platform to allow developers to incorporate advertisements into their application. It is currently supported on iPhone, iPod Touch, and iPad.			<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>The previous list contains some of the important new features of iOS 4. If you are interested in a more detailed listing of all of the features in each of the releases; check out the following <a href='http://en.wikipedia.org/wiki/iPhone_OS_Version_History' class='bbc_url' title='External link' rel='nofollow external'>http://en.wikipedia....Version_History</a>.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
In this article, hopefully you have gained a good understanding of the Xcode and the development tools and the new and improved Single-Windowed development IDE. We have also covered some of the basics relating to Object-Oriented Programming and Objective-C. It will soon become apparent why Objective-C was chosen as the language of choice for developing Mac OSX and iOS applications.]]></description>
		<pubDate>Wed, 22 Feb 2012 03:36:41 +0000</pubDate>
		<guid isPermaLink="false">06d77b5b9334a3747200e0e617cb73d5</guid>
	</item>
	<item>
		<title>Cocos2d: Working with Sprites</title>
		<link>http://www.gamedev.net/page/resources/_/technical/mobile-development/cocos2d-working-with-sprites-r2876</link>
		<description><![CDATA[Cocos2d is first and foremost a rich graphical API which allows a game developer easy access to a broad range of functionality. In this article, we will take a look at the basic uses of sprites.<br />
<br />
In this article by <strong class='bbc'>Nathan Burba</strong>, author of <a href='http://www.packtpub.com/cocos2d-for-iphone-1-game-development-cookbook/book/ns/cocos2d1-abr1/1211?utm_source=ns_cocos2d1_abr1_1211&utm_medium=content&utm_campaign=naheed' class='bbc_url' title='External link' rel='nofollow external'>Cocos2d for iPhone 1 Game Development Cookbook</a>, we will cover the following topics:<br />
<br />
 <br />
<span style='font-size: 18px;'><strong class='bbc'>Drawing sprites</strong></span><br />
The most fundamental task in 2D game development is drawing a <strong class='bbc'>sprite</strong>. Cocos2d provides the user with a lot of flexibility in this area. In this recipe we will cover drawing sprites using <em class='bbc'>CCSprite</em>, spritesheets, <em class='bbc'>CCSpriteFrameCache</em>, and <em class='bbc'>CCSpriteBatchNode</em>. We will also go over <strong class='bbc'>mipmapping</strong>. In this recipe we see a scene with Alice from Through The Looking Glass.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4002exp_abr1_1.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
Please refer to the project <a href='http://www.packtpub.com/code_download/8381' class='bbc_url' title='External link' rel='nofollow external'>RecipeCollection01</a> for the full working code of this recipe.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
Execute the following code:<br />
<br />
<pre class='prettyprint'><br />@implementation Ch1_DrawingSprites<br />-(CCLayer*) runRecipe {<br />  /*** Draw a sprite using CCSprite ***/<br />  CCSprite *tree1 = &#91;CCSprite spriteWithFile:@"tree.png"&#93;;<br /><br />  //Position the sprite using the tree base as a guide (y anchor <br />point = 0)<br />&#91;tree1 setPosition:ccp(20,20)&#93;;<br />  tree1.anchorPoint = ccp(0.5f,0);<br />  &#91;tree1 setScale:1.5f&#93;;<br />  &#91;self addChild:tree1 z:2 tag:TAG_TREE_SPRITE_1&#93;;<br /><br />  /*** Load a set of spriteframes from a PLIST file and draw one by<br />name ***/<br /><br />  //Get the sprite frame cache singleton<br />  CCSpriteFrameCache *cache = &#91;CCSpriteFrameCache<br />sharedSpriteFrameCache&#93;;<br /><br />  //Load our scene sprites from a spritesheet<br />  &#91;cache addSpriteFramesWithFile:@"alice_scene_sheet.plist"&#93;;<br /><br />  //Specify the sprite frame and load it into a CCSprite<br />  CCSprite *alice = &#91;CCSprite spriteWithSpriteFrameName:@"alice.png"&#93;;<br /><br />  //Generate Mip Maps for the sprite<br />  &#91;alice.texture generateMipmap&#93;;<br />  ccTexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_<br />CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE };<br />  &#91;alice.texture setTexParameters:&texParams&#93;;<br /><br />  //Set other information.<br />  &#91;alice setPosition:ccp(120,20)&#93;;<br />  &#91;alice setScale:0.4f&#93;;<br />  alice.anchorPoint = ccp(0.5f,0);<br /><br />  //Add Alice with a zOrder of 2 so she appears in front of other<br />sprites<br />  &#91;self addChild:alice z:2 tag:TAG_ALICE_SPRITE&#93;;<br /><br />  //Make Alice grow and shrink.<br />  &#91;alice runAction: &#91;CCRepeatForever actionWithAction:<br />   &#91;CCSequence actions:&#91;CCScaleTo actionWithDuration:4.0f scale<br />:0.7f&#93;, &#91;CCScaleTo actionWithDuration:4.0f scale:0.1f&#93;, nil&#93; &#93; &#93;;<br /><br />  /*** Draw a sprite CGImageRef ***/<br />  UIImage *uiImage = &#91;UIImage imageNamed: @"cheshire_cat.png"&#93;;<br />  CGImageRef imageRef = &#91;uiImage CGImage&#93;;<br />  CCSprite *cat = &#91;CCSprite spriteWithCGImage:imageRef key:@<br />"cheshire_cat.png"&#93;;<br />  &#91;cat setPosition:ccp(250,180)&#93;;<br />  &#91;cat setScale:0.4f&#93;;<br />  &#91;self addChild:cat z:3 tag:TAG_CAT_SPRITE&#93;;<br /><br />  /*** Draw a sprite using CCTexture2D ***/<br />  CCTexture2D *texture = &#91;&#91;CCTextureCache sharedTextureCache&#93;<br />addImage:@"tree.png"&#93;;<br />  CCSprite *tree2 = &#91;CCSprite spriteWithTexture:texture&#93;;<br />  &#91;tree2 setPosition:ccp(300,20)&#93;;<br />  tree2.anchorPoint = ccp(0.5f,0);<br />  &#91;tree2 setScale:2.0f&#93;;<br />  &#91;self addChild:tree2 z:2 tag:TAG_TREE_SPRITE_2&#93;;<br /><br />  /*** Draw a sprite using CCSpriteFrameCache and CCTexture2D ***/<br />  CCSpriteFrame *frame = &#91;CCSpriteFrame frameWithTexture:texture<br />rect:tree2.textureRect&#93;;<br />  &#91;&#91;CCSpriteFrameCache sharedSpriteFrameCache&#93; addSpriteFrame:<br />frame name:@"tree.png"&#93;;<br />  CCSprite *tree3 = &#91;CCSprite spriteWithSpriteFrame:&#91;&#91;CCSpriteFrame<br />Cache sharedSpriteFrameCache&#93; spriteFrameByName:@"tree.png"&#93;&#93;;<br />  &#91;tree3 setPosition:ccp(400,20)&#93;;<br />  tree3.anchorPoint = ccp(0.5f,0);<br />  &#91;tree3 setScale:1.25f&#93;;<br />  &#91;self addChild:tree3 z:2 tag:TAG_TREE_SPRITE_3&#93;;<br /><br />  /*** Draw sprites using CCBatchSpriteNode ***/<br /><br />  //Clouds<br />  CCSpriteBatchNode *cloudBatch = &#91;CCSpriteBatchNode<br />batchNodeWithFile:@"cloud_01.png" capacity:10&#93;;<br />  &#91;self addChild:cloudBatch z:1 tag:TAG_CLOUD_BATCH&#93;;<br />  for(int x=0; x   CCSprite *s = &#91;CCSprite spriteWithBatchNode:cloudBatch<br />rect:CGRectMake(0,0,64,64)&#93;;<br />   &#91;s setOpacity:100&#93;;<br />   &#91;cloudBatch addChild:s&#93;;<br />   &#91;s setPosition:ccp(arc4random()%500-50, arc4random()%150+200)&#93;;<br />  }<br /><br />  //Middleground Grass<br />  int capacity = 10;<br />  CCSpriteBatchNode *grassBatch1 = &#91;CCSpriteBatchNode<br />batchNodeWithFile:@"grass_01.png" capacity:capacity&#93;;<br />  &#91;self addChild:grassBatch1 z:1 tag:TAG_GRASS_BATCH_1&#93;;<br />  for(int x=0; x   CCSprite *s = &#91;CCSprite spriteWithBatchNode:grassBatch1<br />rect:CGRectMake(0,0,64,64)&#93;;<br />   &#91;s setOpacity:255&#93;;<br />   &#91;grassBatch1 addChild:s&#93;;<br />   &#91;s setPosition:ccp(arc4random()%500-50, arc4random()%20+70)&#93;;<br />  }<br /><br />  //Foreground Grass<br />  CCSpriteBatchNode *grassBatch2 = &#91;CCSpriteBatchNode<br />batchNodeWithFile:@"grass_01.png" capacity:10&#93;;<br />  &#91;self addChild:grassBatch2 z:3 tag:TAG_GRASS_BATCH_2&#93;;<br />  for(int x=0; x   CCSprite *s = &#91;CCSprite spriteWithBatchNode:grassBatch2<br />rect:CGRectMake(0,0,64,64)&#93;;<br />   &#91;s setOpacity:255&#93;;<br />   &#91;grassBatch2 addChild:s&#93;;<br />   &#91;s setPosition:ccp(arc4random()%500-50, arc4random()%40-10)&#93;;<br />  }<br /><br />  /*** Draw colored rectangles using a 1px x 1px white texture ***/<br /><br />  //Draw the sky using blank.png<br />  &#91;self drawColoredSpriteAt:ccp(240,190) withRect:CGRectMa<br />ke(0,0,480,260) withColor:ccc3(150,200,200) withZ:0&#93;;<br /><br />  //Draw the ground using blank.png<br />  &#91;self drawColoredSpriteAt:ccp(240,30)<br />withRect:CGRectMake(0,0,480,60) withColor:ccc3(80,50,25) withZ:0&#93;;<br /><br />  return self;<br />}<br /><br />-(void) drawColoredSpriteAt:(CGPoint)position withRect:(CGRect)rect<br />withColor:(ccColor3B)color withZ:(float)z {<br />  CCSprite *sprite = &#91;CCSprite spriteWithFile:@"blank.png"&#93;;<br />  &#91;sprite setPosition:position&#93;;<br />  &#91;sprite setTextureRect:rect&#93;;<br />  &#91;sprite setColor:color&#93;;<br />  &#91;self addChild:sprite&#93;;<br /><br />  //Set Z Order<br />  &#91;self reorderChild:sprite z:z&#93;;<br />}<br /><br />@end<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
This recipe takes us through most of the common ways of drawing sprites:<br />
<ul class='bbc'><br /><li>Creating a CCSprite from a file:<br />First, we have the simplest way to draw a sprite. This involves using the <em class='bbc'>CCSprite</em> class method as follows:<br /><pre class='prettyprint'><br />+(id)spriteWithFile:(NSString*)filename;<br /></pre><br /><br />This is the most straightforward way to initialize a sprite and is adequate for many situations.<br /></li><li>Other ways to load a sprite from a file:<br />After this, we will see examples of <em class='bbc'>CCSprite</em> creation using <em class='bbc'>UIImage</em>/<em class='bbc'>CGImageRef</em>, <em class='bbc'>CCTexture2D</em>, and a <em class='bbc'>CCSpriteFrame</em> instantiated using a <em class='bbc'>CCTexture2D</em> object. CGImageRef support allows you to tie Cocos2d into other frameworks and toolsets. CCTexture2D is the underlying mechanism for texture creation.<br /></li><li>Loading spritesheets using <em class='bbc'>CCSpriteFrameCache</em>:<br />Next, we will see the most powerful way to use sprites, the <em class='bbc'>CCSpriteFrameCache</em> class. Introduced in <em class='bbc'>Cocos2d-iPhone v0.99</em>, the <em class='bbc'>CCSpriteFrameCache</em> singleton is a cache of all sprite frames. Using a <strong class='bbc'>spritesheet</strong> and its associated <em class='bbc'>PLIST</em> file we can load multiple sprites into the cache. From here we can create <em class='bbc'>CCSprite</em> objects with sprites from the cache:<br /><pre class='prettyprint'><br />+(id)spriteWithSpriteFrameName:(NSString*)filename;<br /></pre><br /></li><li><strong class='bbc'>Mipmapping</strong>:<br />Mipmapping allows you to scale a texture or to zoom in or out of a scene without aliasing your sprites. When we scale Alice down to a small size, aliasing will inevitably occur. With mipmapping turned on, Cocos2d dynamically generates lower resolution textures to smooth out any pixelation at smaller scales. Go ahead and comment out the following lines:<br /><pre class='prettyprint'><br />&#91;alice.texture generateMipmap&#93;;<br />  ccTexParams texParams = { GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR,<br />GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE };<br />  &#91;alice.texture setTexParameters:&texParams&#93;;<br /></pre><br /><br />Now you should see this pixelation as Alice gets smaller.<br /></li><li>Drawing many derivative sprites with <em class='bbc'>CCSpriteBatchNode</em>:<br />The <em class='bbc'>CCSpriteBatchNode</em> class, added in <em class='bbc'>v0.99.5</em>, introduces an efficient way to draw and re-draw the same sprite over and over again. A batch node is created with the following method:<br /><pre class='prettyprint'><br />CCSpriteBatchNode *cloudBatch = &#91;CCSpriteBatchNode<br />batchNodeWithFile:@"cloud_01.png" capacity:10&#93;;<br /></pre><br /><br />Then, you create as many sprites as you want using the follow code:<br /><pre class='prettyprint'><br />CCSprite *s = &#91;CCSprite spriteWithBatchNode:cloudBatch<br />rect:CGRectMake(0,0,64,64)&#93;;<br />  &#91;cloudBatch addChild:s&#93;;<br /></pre><br /><br />Setting the capacity to the number of sprites you plan to draw tells Cocos2d to allocate that much space. This is yet another tweak for extra efficiency, though it is not absolutely necessary that you do this. In these three examples we draw 10 randomly placed clouds and 60 randomly placed bits of grass.<br /></li><li>Drawing colored rectangles:<br />Finally, we have a fairly simple technique that has a variety of uses. By drawing a sprite with a blank 1px by 1px white texture and then coloring it and setting its <em class='bbc'>textureRect</em> property we can create very useful colored bars:<br /><pre class='prettyprint'><br />CCSprite *sprite = &#91;CCSprite spriteWithFile:@"blank.png"&#93;;<br />&#91;sprite setTextureRect:CGRectMake(0,0,480,320)&#93;;<br />&#91;sprite setColor:ccc3(255,128,0)&#93;;<br /></pre><br /><br />In this example we have used this technique to create very simple ground and sky backgrounds.<br /></li></ul><br />
<br />
<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Coloring sprites</strong></span><br />
In the previous recipe we used colored rectangles to draw both the ground and the sky. The ability to set texture color and opacity are simple tools which, if used properly, can create very cool effects. In this recipe we will create a cinematic scene where two samurai face each other with glowing swords.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4002exp_abr1_2.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
Please refer to the project <em class='bbc'>RecipeCollection01</em> for full working code of this recipe. Also, note that some code has been omitted for brevity.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
Execute the following code:<br />
<br />
<pre class='prettyprint'><br />#import "CCGradientLayer.h<br /><br />@implementation Ch1_ColoringSprites<br /><br />-(CCLayer*) runRecipe {<br />  &#91;self initButtons&#93;;<br /><br />  //The Fade Scene Sprite<br />  CCSprite *fadeSprite = &#91;CCSprite spriteWithFile:@"blank.png"&#93;;<br />  &#91;fadeSprite setOpacity:0&#93;;<br />  &#91;fadeSprite setPosition:ccp(240,160)&#93;;<br />  &#91;fadeSprite setTextureRect:CGRectMake(0,0,480,320)&#93;;<br />  &#91;self addChild:fadeSprite z:3 tag:TAG_FADE_SPRITE&#93;;<br /><br />  //Add a gradient below the mountains<br />//CCGradientDirectionT_B is an enum provided by CCGradientLayer<br />  CCGradientLayer *gradientLayer = &#91;CCGradientLayer layerWithColor:<br />ccc4(61,33,62,255) toColor:ccc4(65,89,54,255) withDirection:<br />CCGradient DirectionT_B width:480 height:100&#93;;<br />  &#91;gradientLayer setPosition:ccp(0,50)&#93;;<br />  &#91;self addChild:gradientLayer z:0 tag:TAG_GROUND_GRADIENT&#93;;<br /><br />  //Add a sinister red glow gradient behind the evil samurai<br />  CCGradientLayer *redGradient = &#91;CCGradientLayer<br />layerWithColor:ccc4(0,0,0,0) toColor:ccc4(255,0,0,100) withDirection<br />:CCGradientDirectionT_B width:200 height:200&#93;;<br />  &#91;redGradient setPosition:ccp(280,60)&#93;;<br />  &#91;redGradient setRotation:-90&#93;;<br />  &#91;self addChild:redGradient z:2 tag:TAG_RED_GRADIENT&#93;;<br /><br />  // Make the swords glow<br />  &#91;self glowAt:ccp(230,280) withScale:CGSizeMake(3.0f, 11.0f)<br />withColor:ccc3(0,230,255) withRotation:45.0f withSprite:goodSamurai&#93;;<br />  &#91;self glowAt:ccp(70,280) withScale:CGSizeMake(3.0f, 11.0f)<br />withColor:ccc3(255,200,2) withRotation:-45.0f withSprite:evilSamurai&#93;;<br /><br />  return self;<br />}<br /><br />-(void) initButtons {<br />  &#91;CCMenuItemFont setFontSize:16&#93;;<br /><br />  //'Fade To Black' button<br />  CCMenuItemFont* fadeToBlack = &#91;CCMenuItemFont itemFromString:@<br />"FADE TO BLACK" target:self selector:@selector(fadeToBlackCallback:)&#93;;<br />  CCMenu *fadeToBlackMenu = &#91;CCMenu menuWithItems:fadeToBlack, nil&#93;;<br />   fadeToBlackMenu.position = ccp( 180 , 20 );<br />   &#91;self addChild:fadeToBlackMenu z:4 tag:TAG_FADE_TO_BLACK&#93;;<br />}<br /><br />/* Fade the scene to black */<br />-(void) fadeToBlackCallback:(id)sender {<br />  CCSprite *fadeSprite = &#91;self getChildByTag:TAG_FADE_SPRITE&#93;;<br />  &#91;fadeSprite stopAllActions&#93;;<br />  &#91;fadeSprite setColor:ccc3(0,0,0)&#93;;<br />  &#91;fadeSprite setOpacity:0.0f&#93;;<br />  &#91;fadeSprite runAction:<br />  &#91;CCSequence actions:&#91;CCFadeIn actionWithDuration:2.0f&#93;, &#91;CCFadeOut<br />actionWithDuration:2.0f&#93;, nil&#93; &#93;;<br />}<br /><br />/* Create a glow effect */<br />-(void) glowAt:(CGPoint)position withScale:(CGSize)size<br />withColor:(ccColor3B)color withRotation:(float)rotation<br />withSprite:(CCSprite*)sprite {<br />  CCSprite *glowSprite = &#91;CCSprite spriteWithFile:@"fire.png"&#93;;<br />  &#91;glowSprite setColor:color&#93;;<br />  &#91;glowSprite setPosition:position&#93;;<br />  &#91;glowSprite setRotation:rotation&#93;;<br />  &#91;glowSprite setBlendFunc: (ccBlendFunc) { GL_ONE, GL_ONE }&#93;;<br />  &#91;glowSprite runAction: &#91;CCRepeatForever actionWithAction:<br />   &#91;CCSequence actions:&#91;CCScaleTo actionWithDuration:0.9f<br />scaleX:size.width scaleY:size.height&#93;, &#91;CCScaleTo<br />actionWithDuration:0.9f scaleX:size.width*0.75f scaleY:size.<br />height*0.75f&#93;, nil&#93; &#93; &#93;;<br />  &#91;glowSprite runAction: &#91;CCRepeatForever actionWithAction:<br />   &#91;CCSequence actions:&#91;CCFadeTo actionWithDuration:0.9f<br />opacity:150&#93;, &#91;CCFadeTo actionWithDuration:0.9f opacity:255&#93;, nil&#93; &#93;<br />&#93;;<br />  &#91;sprite addChild:glowSprite&#93;;<br />}<br /><br />@end<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
This recipe shows a number of color based techniques.<br />
<ul class='bbc'><br /><li>Setting sprite color:<br />The simplest use of color involves setting the color of a sprite using the following method:<br /><pre class='prettyprint'><br />-(void) setColor:(ccColor3B)color;<br /></pre><br /><br />Setting sprite color effectively reduces the color you can display but it allows some programmatic flexibility in drawing. In this recipe we use <em class='bbc'>setColor</em> for a number of things, including drawing a blue sky, a yellow sun, black "dramatic movie bars", and more.<br /><em class='bbc'>ccColor3B</em> is a C struct which contains three <em class='bbc'>GLubyte</em> variables. Use the following helper macro to create <em class='bbc'>ccColor3B</em> structures:<br /><pre class='prettyprint'><br />ccColor3B ccc3(const GLubyte r, const GLubyte g, const GLubyte<br />b);<br /></pre><br /><br />Cocos2d also specifies a number of pre-defined colors as constants. These include the following:<br /><pre class='prettyprint'><br />ccWHITE, ccYELLOW, ccBLUE, ccGREEN, ccRED,<br />ccMAGENTA, ccBLACK, ccORANGE, ccGRAY<br /></pre><br /></li><li>Fading to a color:<br />To fade a scene to a specific color we use the <em class='bbc'>blank.png</em> technique we went over in the last recipe. We first draw a sprite as large as the screen, then color the sprite to the color we want to fade to, and then finally run a <em class='bbc'>CCFadeIn</em> action on the sprite to fade to that color:<br /><pre class='prettyprint'><br />&#91;fadeSprite setColor:ccc3(255,255,255)&#93;;<br />&#91;fadeSprite setOpacity:0.0f&#93;;<br />&#91;fadeSprite runAction: &#91;CCFadeIn actionWithDuration:2.0f&#93; &#93;;<br /></pre><br /></li><li>Using <em class='bbc'>CCGradientLayer</em>:<br />Using the <em class='bbc'>CCGradientLayer</em> class we can programmatically create gradients. To make the mountains in the background fade into the ground the two samurai are standing on we created a gradient using this method:<br /><pre class='prettyprint'><br />  CCGradientLayer *gradientLayer = &#91;CCGradientLayer layerWithColor<br />:ccc4(61,33,62,255) toColor:ccc4(65,89,54,255) withDirection:CCGra<br />dientDirectionT_B width:480 height:100&#93;;<br />  &#91;gradientLayer setPosition:ccp(0,50)&#93;;<br />  &#91;self addChild:gradientLayer z:0 tag:TAG_GROUND_GRADIENT&#93;;<br /></pre><br /><br />Because <em class='bbc'>CCGradientLayer</em> lets you control opacity as well as color, it has many uses. As you can see there is also a sinister red glow behind the evil samurai.<br /></li><li>Making a sprite glow: To make the swords in the demo glow we use subtle color manipulation, additive blending and fading and scaling actions. First we load the <strong class='bbc'>fire.png</strong> sprite supplied by Cocos2d. By changing its X and Y scale independently we can make it thinner or fatter. Once you have the desired scale ratio (in this demo we use x:y 3:11 because the sword is so thin) you can constantly scale and fade the sprite in and out to give some life to the effect. You also need to set the blend function to <em class='bbc'>{ GL_ONE, GL_ONE }</em> for additive blending. Finally this effect sprite is added to the actual sprite to make it seem like it glows.<br /><pre class='prettyprint'><br />CCSprite *glowSprite = &#91;CCSprite spriteWithFile:@"fire.png"&#93;;<br />  &#91;glowSprite setColor:color&#93;;<br />  &#91;glowSprite setPosition:position&#93;;<br />  &#91;glowSprite setRotation:rotation&#93;;<br />  &#91;glowSprite setBlendFunc: (ccBlendFunc) { GL_ONE, GL_ONE }&#93;;<br />  &#91;glowSprite runAction: &#91;CCRepeatForever actionWithAction:<br />  &#91;CCSequence actions:&#91;CCScaleTo actionWithDuration:0.9f<br />scaleX:size.width scaleY:size.height&#93;, &#91;CCScaleTo<br />actionWithDuration:0.9f scaleX:size.width*0.75f scaleY:size.<br />height*0.75f&#93;, nil&#93; &#93; &#93;;<br />  &#91;glowSprite runAction: &#91;CCRepeatForever actionWithAction:<br />  &#91;CCSequence actions:&#91;CCFadeTo actionWithDuration:0.9f<br />opacity:150&#93;, &#91;CCFadeTo actionWithDuration:0.9f opacity:255&#93;, nil&#93;<br />&#93; &#93;;<br />  &#91;sprite addChild:glowSprite&#93;;<br /></pre><br /></li></ul><br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Animating sprites</strong></span><br />
Now it is time to add some animation to our sprites. One thing that should be stressed about animation is that it is only as complicated as you make it. In this recipe we will use very simple animation to create a compelling effect. We will create a scene where bats fly around a creepy looking castle. I've also added a cool lightning effect based on the technique used to make the swords glow in the previous recipe.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4002exp_abr1_3.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
Please refer to the project <em class='bbc'>RecipeCollection01</em> for full working code of this recipe. Also note that some code has been omitted for brevity.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
Execute the following code:<br />
<br />
<pre class='prettyprint'><br />//SimpleAnimObject.h<br />@interface SimpleAnimObject : CCSprite {<br />  int animationType;<br />  CGPoint velocity;<br />}<br /><br />@interface Ch1_AnimatingSprites {<br />  NSMutableArray *bats;<br />  CCAnimation *batFlyUp;<br />  CCAnimation *batGlideDown;<br />  CCSprite *lightningBolt;<br />  CCSprite *lightningGlow;<br />  int lightningRemoveCount;<br />}<br /><br />-(CCLayer*) runRecipe {<br />  //Add our PLIST to the SpriteFrameCache<br />  &#91;&#91;CCSpriteFrameCache sharedSpriteFrameCache&#93; <br />addSpriteFramesWithFile:@"simple_bat.plist"&#93;;<br /><br />  //Add a lightning bolt<br />  lightningBolt = &#91;CCSprite spriteWithFile:@"lightning_bolt.png"&#93;;<br />  &#91;lightningBolt setPosition:ccp(240,160)&#93;;<br />  &#91;lightningBolt setOpacity:64&#93;;<br />  &#91;lightningBolt retain&#93;;<br /><br />  //Add a sprite to make it light up other areas.<br />  lightningGlow = &#91;CCSprite spriteWithFile:@"lightning_glow.png"&#93;;<br />  &#91;lightningGlow setColor:ccc3(255,255,0)&#93;;<br />  &#91;lightningGlow setPosition:ccp(240,160)&#93;;<br />  &#91;lightningGlow setOpacity:100&#93;;<br />  &#91;lightningGlow setBlendFunc: (ccBlendFunc) { GL_ONE, GL_ONE }&#93;;<br />  &#91;lightningBolt addChild:lightningGlow&#93;;<br /><br />  //Set a counter for lightning duration randomization<br />  lightningRemoveCount = 0;<br /><br />  //Bats Array Initialization<br />  bats = &#91;&#91;NSMutableArray alloc&#93; init&#93;;<br /><br />  //Add bats using a batch node.<br />  CCSpriteBatchNode *batch1 = &#91;CCSpriteBatchNode<br />batchNodeWithFile:@"simple_bat.png" capacity:10&#93;;<br />  &#91;self addChild:batch1 z:2 tag:TAG_BATS&#93;;<br /><br />  //Make them start flying up.<br />  for(int x=0; x   //Create SimpleAnimObject of bat<br />   SimpleAnimObject *bat = &#91;SimpleAnimObject<br />spriteWithBatchNode:batch1 rect:CGRectMake(0,0,48,48)&#93;;<br />  &#91;batch1 addChild:bat&#93;;<br />  &#91;bat setPosition:ccp(arc4random()%400+40, arc4random()%150+150)&#93;;<br /><br />  //Make the bat fly up. Get the animation delay (flappingSpeed).<br />  float flappingSpeed = &#91;self makeBatFlyUp:bat&#93;;<br /><br />  //Base y velocity on flappingSpeed.<br />  bat.velocity = ccp((arc4random()%1000)/500 + 0.2f, 0.1f/<br />flappingSpeed);<br /><br />  //Add a pointer to this bat object to the NSMutableArray<br />  &#91;bats addObject:&#91;NSValue valueWithPointer:bat&#93;&#93;;<br />  &#91;bat retain&#93;;<br /><br />  //Set the bat's direction based on x velocity.<br />  if(bat.velocity.x &gt; 0){<br />   bat.flipX = YES;<br />  }<br /> }<br /><br />  //Schedule physics updates<br />  &#91;self schedule:@selector(step:)&#93;;<br /><br />  return self;<br />}<br /><br />-(float)makeBatFlyUp:(SimpleAnimObject*)bat {<br />  CCSpriteFrameCache * cache = &#91;CCSpriteFrameCache<br />sharedSpriteFrameCache&#93;;<br /><br />  //Randomize animation speed.<br />  float delay = (float)(arc4random()%5+5)/80;<br />  CCAnimation *animation = &#91;&#91;CCAnimation alloc&#93; initWithName:@<br />"simply_bat_fly" delay:delay&#93;;<br /><br />  //Randomize animation frame order.<br />  int num = arc4random()%4+1;<br />  for(int i=1; i   &#91;animation addFrame:&#91;cache spriteFrameByName:&#91;NSString<br />stringWithFormat:@"simple_bat_0%i.png",num&#93;&#93;&#93;;<br />   num++;<br />   if(num &gt; 4){ num = 1; }<br />  }<br /><br />  //Stop any running animations and apply this one.<br />  &#91;bat stopAllActions&#93;;<br />  &#91;bat runAction:&#91;CCRepeatForever actionWithAction: &#91;CCAnimate <br />actionWithAnimation:animation&#93;&#93;&#93;;<br /><br />  //Keep track of which animation is running.<br />  bat.animationType = BAT_FLYING_UP;<br /><br />  return delay; //We return how fast the bat is flapping.<br />}<br /><br />-(void)makeBatGlideDown:(SimpleAnimObject*)bat {<br />  CCSpriteFrameCache * cache = &#91;CCSpriteFrameCache<br />sharedSpriteFrameCache&#93;;<br /><br />  //Apply a simple single frame gliding animation.<br />  CCAnimation *animation = &#91;&#91;CCAnimation alloc&#93; initWithName:@<br />"simple_bat_glide" delay:100.0f&#93;;<br /> &#91;animation addFrame:&#91;cache spriteFrameByName:@"simple_bat_01.png"&#93;&#93;;<br /><br />  //Stop any running animations and apply this one.<br />  &#91;bat stopAllActions&#93;;<br />  &#91;bat runAction:&#91;CCRepeatForever actionWithAction: &#91;CCAnimate <br />actionWithAnimation:animation&#93;&#93;&#93;;<br /><br />  //Keep track of which animation is running.<br />  bat.animationType = BAT_GLIDING_DOWN;<br />}<br /><br />-(void)step:(ccTime)delta {<br />  CGSize s = &#91;&#91;CCDirector sharedDirector&#93; winSize&#93;;<br /><br />for(id key in bats){<br />  //Get SimpleAnimObject out of NSArray of NSValue objects.<br />  SimpleAnimObject *bat = &#91;key pointerValue&#93;;<br /><br />  //Make sure bats don't fly off the screen<br />  if(bat.position.x &gt; s.width){<br />   bat.velocity = ccp(-bat.velocity.x, bat.velocity.y);<br />   bat.flipX = NO;<br />  }else if(bat.position.x	bat.velocity = ccp(-bat.velocity.x, bat.velocity.y);<br />   bat.flipX = YES;<br />  }else if(bat.position.y &gt; s.height){<br />   bat.velocity = ccp(bat.velocity.x, -bat.velocity.y);<br />   &#91;self makeBatGlideDown:bat&#93;;<br />  }else if(bat.position.y	bat.velocity = ccp(bat.velocity.x, -bat.velocity.y);<br />   &#91;self makeBatFlyUp:bat&#93;;<br />  }<br /><br />  //Randomly make them fly back up<br />  if(arc4random()%100 == 7){<br />   if(bat.animationType == BAT_GLIDING_DOWN){ &#91;self<br />makeBatFlyUp:bat&#93;; bat.velocity = ccp(bat.velocity.x, -bat.<br />velocity.y); }<br />   else if(bat.animationType == BAT_FLYING_UP){ &#91;self<br />makeBatGlideDown:bat&#93;; bat.velocity = ccp(bat.velocity.x, -bat.<br />velocity.y); }<br />  }<br /><br />  //Update bat position based on direction<br />  bat.position = ccp(bat.position.x + bat.velocity.x, bat.position.y<br />+ bat.velocity.y);<br />  }<br /><br />  //Randomly make lightning strike<br />  if(arc4random()%70 == 7){<br />  if(lightningRemoveCount	&#91;self addChild:lightningBolt z:1 tag:TAG_LIGHTNING_BOLT&#93;;<br />   lightningRemoveCount = arc4random()%5+5;<br />   }<br />  }<br /><br />  //Count down<br />  lightningRemoveCount -= 1;<br /><br />  //Clean up any old lightning bolts<br />  if(lightningRemoveCount == 0){<br />   &#91;self removeChildByTag:TAG_LIGHTNING_BOLT cleanup:NO&#93;;<br />  }<br />}<br /><br />@end<br /><br /></pre><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
This recipe shows us how to structure animation based classes through the use of <em class='bbc'>SimpleAnimObject</em>:<br />
<ul class='bbc'><br /><li>Animated object class structure:<br />When switching from one animation to another it is often important to keep track of what state the animated object is in. In our example we use <em class='bbc'>SimpleAnimObject</em>, which keeps an arbitrary <em class='bbc'>animationType</em> variable. We also maintain a velocity variable that has a Y scalar value that is inversely proportional to the animation frame delay:<br /><pre class='prettyprint'><br />@interface SimpleAnimObject : CCSprite {<br />  int animationType;<br />  CGPoint velocity;<br />}<br /></pre><br /><br />Depending on how in-depth you want your animation system to be you should maintain more information such as, for example, a pointer to the running <em class='bbc'>CCAnimation</em> instance, frame information, and physical bodies.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
As you get more involved with Cocos2d game development you will become more and more tempted to use <strong class='bbc'>asynchronous actions</strong> for gameplay logic and AI. Derived from the <em class='bbc'>CCAction</em> class, these actions can be used for everything from moving a <em class='bbc'>CCNode</em> using <em class='bbc'>CCMoveBy</em> to animating a <em class='bbc'>CCSprite</em> using <em class='bbc'>CCAnimate</em>. When an action is run, an asynchronous timing mechanism is maintained in the background. First time game programmers often over-rely on this feature. The extra overhead required by this technique can multiply quickly when multiple actions are being run. In the following example we have used a simple integer timer that allows us to regulate how long lightning lasts onscreen:<br />
<br />
<pre class='prettyprint'><br />//Randomly make lightning strike<br />if(arc4random()%70 == 7){<br /> if(lightningRemoveCount   &#91;self addChild:lightningBolt z:1 tag:TAG_LIGHTNING_BOLT&#93;;<br />  lightningRemoveCount = arc4random()%5+5;<br /> }<br />}<br /><br />//Count down<br />lightningRemoveCount -= 1;<br /><br />//Clean up any old lightning bolts<br />if(lightningRemoveCount == 0){<br /> &#91;self removeChildByTag:TAG_LIGHTNING_BOLT cleanup:NO&#93;;<br />}<br /><br /></pre><br />
<strong class='bbc'>Synchronous timers</strong> like the one shown in the preceding code snippet are often, but not always, preferable to asynchronous actions. Keep this in mind as your games grow in size and scope.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
In this article we took a look at the basic uses of sprites.]]></description>
		<pubDate>Wed, 22 Feb 2012 03:33:53 +0000</pubDate>
		<guid isPermaLink="false">5e056558ced8fa424facc20b1ba2369c</guid>
	</item>
	<item>
		<title>Introduction to Game Development Using Unity 3D</title>
		<link>http://www.gamedev.net/page/resources/_/technical/game-programming/introduction-to-game-development-using-unity-3d-r2875</link>
		<description><![CDATA[This article by <strong class='bbc'>Ryan Henson Creighton</strong>, author of <a href='http://www.packtpub.com/unity-3d-game-development-by-example-beginners-guide/book/rk/unity3d_abr1/0910?utm_source=rk_unity3d_abr1_0910&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>Unity 3D Game Development by Example</a>, introduces you to Unity 3D—an amazing game engine that enables you to create games and deploy them to a number of different devices, including (at the time of writing) the Web, PCs, iOS platforms, and WiiWare, with modules for Android and Xbox Live Arcade deployment in the works. You'll play a number of browser-based Unity 3D games to get a sense of what the engine can handle, from a massively-multiplayer online game all the way down to a simple kart racer. You'll download and install your own copy of Unity 3D, and mess around with the beautiful Island Demo that ships with the product.<br />
<br />
Technology is a tool. It helps us accomplish amazing things, hopefully more quickly and more easily and more amazingly than if we hadn't used the tool. Before we had newfangled steam-powered hammering machines, we had hammers. And before we had hammers, we had the painful process of smacking a nail into a board with our bare hands. Technology is all about making our lives better and easier. And less painful.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Introducing Unity 3D</strong></span><br />
Unity 3D is a new piece of technology that strives to make life better and easier for game developers. Unity is a game engine or a game authoring tool that enables creative folks like you to build video games.<br />
<br />
By using Unity, you can build video games more quickly and easily than ever before. In the past, building games required an enormous stack of punch cards, a computer that filled a whole room, and a burnt sacrificial offering to an ancient god named Fortran. Today, instead of spanking nails into boards with your palm, you have Unity. Consider it your hammer—a new piece of technology for your creative tool belt.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Unity takes over the world</strong></span><br />
We'll be distilling our game development dreams down to small, bite-sized nuggets instead of launching into any sweepingly epic open-world games. The idea here is to focus on something you can actually finish instead of getting bogged down in an impossibly ambitious opus. When you're finished, you can publish these games on the Web, Mac, or PC.<br />
<br />
The team behind Unity 3D is constantly working on packages and export opinions for other platforms. At the time of this writing, Unity could additionally create games that can be played on the iPhone, iPod, iPad, Android devices, Xbox Live Arcade, PS3, and Nintendo's WiiWare service. Each of these tools is an add-on functionality to the core Unity package, and comes at an additional cost. As we're focusing on what we can do without breaking the bank, we'll stick to the core Unity 3D program for the remainder of this article. The key is to start with something you can finish, and then for each new project that you build, to add small pieces of functionality that challenge you and expand your knowledge. Any successful plan for world domination begins by drawing a territorial border in your backyard.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Browser-based 3D? Welcome to the future</strong></span><br />
Unity's primary and most astonishing selling point is that it can deliver a full 3D game experience right inside your web browser. It does this with the Unity Web Player—a free plugin that embeds and runs Unity content on the Web.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Time for action – install the Unity Web Player</strong></span><br />
Before you dive into the world of Unity games, download the Unity Web Player. Much the same way the Flash player runs Flash-created content, the Unity Web Player is a plugin that runs Unity-created content in your web browser.<br />
<br />
Go to <a href='http://unity3d.com/' class='bbc_url' title='External link' rel='nofollow external'>http://unity3D.com</a>.<br />
Click on the <strong class='bbc'>install now!</strong> button to install the Unity Web Player.<br />
<br />
<a class='resized_img' rel='lightbox[ea0631f50009395747ddb8e9965a026f]' id='ipb-attach-url-7385-0-38334200-1330203877' href="http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=7385" title="0546OT_01_01.png - Size: 12.33K, Downloads: 21"><img src="http://public.gamedev.net/uploads/monthly_02_2012/ccs-8549-0-46524000-1329846631.png" id='ipb-attach-img-7385-0-38334200-1330203877' style='width:216;height:131' class='attach' width="216" height="131" alt="Attached Image: 0546OT_01_01.png" /></a><br />
<br />
Click on <strong class='bbc'>Download Now!</strong><br />
Follow all of the on-screen prompts until the Web Player has finished installing.<br />
<br />
<a class='resized_img' rel='lightbox[ea0631f50009395747ddb8e9965a026f]' id='ipb-attach-url-7386-0-38357200-1330203877' href="http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=7386" title="0546OT_01_02.png - Size: 48.36K, Downloads: 23"><img src="http://public.gamedev.net/uploads/monthly_02_2012/ccs-8549-0-89226600-1329846631_thumb.png" id='ipb-attach-img-7386-0-38357200-1330203877' style='width:480;height:376' class='attach' width="480" height="376" alt="Attached Image: 0546OT_01_02.png" /></a><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Welcome to Unity 3D!</strong></span><br />
Now that you've installed the Web Player, you can view the content created with the Unity 3D authoring tool in your browser.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>What can I build with Unity?</strong></span><br />
In order to fully appreciate how fancy this new hammer is, let's take a look at some projects that other people have created with Unity. While these games may be completely out of our reach at the moment, let's find out how game developers have pushed this amazing tool to its very limits.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>FusionFall</strong></span><br />
The first stop on our whirlwind Unity tour is FusionFall—a <strong class='bbc'>Massively Multiplayer Online Role-Playing Game (MMORPG)</strong>. You can find it at <a href='http://fusionfall.com' class='bbc_url' title='External link' rel='nofollow external'>fusionfall.com</a>. You may need to register to play, but it's definitely worth the extra effort!<br />
 <br />
<p class='bbc_center'><a class='resized_img' rel='lightbox[ea0631f50009395747ddb8e9965a026f]' id='ipb-attach-url-7387-0-38374900-1330203877' href="http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=7387" title="0546OT_01_03.png - Size: 481.21K, Downloads: 16"><img src="http://public.gamedev.net/uploads/monthly_02_2012/ccs-8549-0-45626200-1329846633_thumb.png" id='ipb-attach-img-7387-0-38374900-1330203877' style='width:480;height:275' class='attach' width="480" height="275" alt="Attached Image: 0546OT_01_03.png" /></a></p><br />
FusionFall was commissioned by the Cartoon Network television franchise, and takes place in a re-imagined, anime-style world where popular Cartoon Network characters are all grown up. Darker, more sophisticated versions of the Powerpuff Girls, Dexter, Foster and his imaginary friends, and the kids from Codename: Kids Next Door run around battling a slimy green alien menace.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Completely hammered</strong></span><br />
<strong class='bbc'>FusionFall</strong> is a very big and very expensive high-profile game that helped draw a lot of attention to the then-unknown Unity game engine when the game was released. As a tech demo, it's one of the very best showcases of what your new technological hammer can really do! FusionFall has real-time multiplayer networking, chat, quests, combat, inventory, NPCs (non-player characters), basic AI (artificial intelligence), name generation, avatar creation, and costumes. And that's just a highlight of the game's feature set. This game packs a lot of depth.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Should we try to build FusionFall?</strong></span><br />
At this point, you might be thinking to yourself, "Heck YES! FusionFall is exactly the kind of game I want to create with Unity, and this article is going to show me how!"<br />
<br />
Unfortunately, a step-by-step guide to creating a game the size and scope of FusionFall would likely require its own flatbed truck to transport, and you'd need a few friends to help you turn each enormous page. It would take you the rest of your life to read, and on your deathbed, you'd finally realize the grave error that you had made in ordering it online in the first place, despite having qualified for free shipping.<br />
<br />
Here's why: check out the game credits link on the FusionFall website: <a href='http://www.fusionfall.com/game/credits.php' class='bbc_url' title='External link' rel='nofollow external'>http://www.fusionfal...ame/credits.php</a>.<br />
<br />
This page lists all of the people involved in bringing the game to life. Cartoon Network enlisted the help of an experienced Korean MMO developer called Grigon Entertainment. There are over 80 names on that credits list! Clearly, only two courses of action are available to you:<ul class='bbc'><br /><li>Build a cloning machine and make 79 copies of yourself. Send each of those copies to school to study various disciplines, including marketing, server programming, and 3D animation. Then spend a year building the game with your clones. Keep track of who's who by using a sophisticated armband system.<br /></li><li>Give up now because you'll never make the game of your dreams.<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Another option</strong></span><br />
Before you do something rash and abandon game development for farming, let's take another look at this. FusionFall is very impressive, and it might look a lot like the game that you've always dreamed of making. This article is not about crushing your dreams. It's about dialing down your expectations, putting those dreams in an airtight jar, and taking baby steps. Confucius said: "A journey of a thousand miles begins with a single step." I don't know much about the man's hobbies, but if he was into video games, he might have said something similar about them—creating a game with a thousand awesome features begins by creating a single, less feature-rich game.<br />
<br />
So, let's put the FusionFall dream in an airtight jar and come back to it when we're ready. We'll take a look at some smaller Unity 3D game examples and talk about what it took to build them.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Off-Road Velociraptor Safari</strong></span><br />
No tour of Unity 3D games would be complete without a trip to <a href='http://blurst.com/' class='bbc_url' title='External link' rel='nofollow external'>Blurst.com</a>—the game portal owned and operated by indie game developer Flashbang Studios. In addition to hosting games by other indie game developers, Flashbang has packed Blurst with its own slate of kooky content, including Off-Road Velociraptor Safari. (Note: Flashbang Studios is constantly toying around with ways to distribute and sell its games. At the time of this writing, Off-Road Velociraptor Safari could be played for free only as a Facebook game. If you don't have a Facebook account, try playing another one of the team's creations, like Minotaur China Shop or Time Donkey).<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_04.png' alt='Posted Image' class='bbc_img' /></span></p><br />
In Off-Road Velociraptor Safari, you play a dinosaur in a pith helmet and a monocle driving a jeep equipped with a deadly spiked ball on a chain (just like in the archaeology textbooks). Your goal is to spin around in your jeep doing tricks and murdering your fellow dinosaurs (obviously).<br />
<br />
For many indie game developers and reviewers, Off-Road Velociraptor Safari was their first introduction to Unity. Some reviewers said that they were stunned that a fully 3D game could play in the browser. Other reviewers were a little bummed that the game was sluggish on slower computers. We'll talk about optimization a little later, but it's not too early to keep performance in mind as you start out.<br />
<br />
<strong class='bbc'>	Fewer features, more promise</strong><br />
<br />
If you play Off-Road Velociraptor Safari and some of the other games on the Blurst site, you'll get a better sense of what you can do with Unity without a team of experienced Korean MMO developers. The game has 3D models, physics (code that controls how things move around somewhat realistically), collisions (code that detects when things hit each other), music, and sound effects. Just like FusionFall, the game can be played in the browser with the Unity Web Player plugin. Flashbang Studios also sells downloadable versions of its games, demonstrating that Unity can produce standalone executable game files too.<br />
<br />
<strong class='bbc'>	Maybe we should build Off-Road Velociraptor Safari?</strong><br />
<br />
Right then! We can't create FusionFall just yet, but we can surely create a tiny game like Off-Road Velociraptor Safari, right? Well... no. Again, this article isn't about crushing your game development dreams. But the fact remains that Off-Road Velociraptor Safari took five supremely talented and experienced guys eight weeks to build on full-time hours, and they've been tweaking and improving it ever since. Even a game like this, which may seem quite small in comparison to full-blown MMO like FusionFall, is a daunting challenge for a solo developer. Put it in a jar up on the shelf, and let's take a look at something you'll have more success with.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>I bent my Wooglie</strong></span><br />
<a href='http://www.wooglie.com/' class='bbc_url' title='External link' rel='nofollow external'>Wooglie.com</a> is a Unity game portal hosted by M2H Game Studio in the Netherlands. One glance at the front page will tell you that it's a far different portal than <a href='http://blurst.com/' class='bbc_url' title='External link' rel='nofollow external'>Blurst.com</a>. Many of the Wooglie games are rough around the edges, and lack the sophistication and the slick professional sheen of the games on Blurst. But here is where we'll make our start with Unity. This is exactly where you need to begin as a new game developer, or as someone approaching a new piece of technology like Unity.<br />
<br />
Play through a selection of games on Wooglie. I'll highlight a few of them for your interest:<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Big Fun Racing</strong></span><br />
<strong class='bbc'>Big Fun Racing</strong> is a simple but effective game where you zip around collecting coins in a toy truck. It features a number of different levels and unlockable vehicles. The game designer sunk a few months into the game in his off-hours, with a little help from outsource artists to create the vehicle models.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_05.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<span style='font-size: 14px;'><strong class='bbc'>Diceworks</strong></span><br />
<strong class='bbc'>Diceworks</strong> is a very simple, well-polished game designed for the iPhone in Unity 3D. We won't be covering any iPhone development, but it's good to know that your Unity content can be deployed to a number of other devices and platforms, including the Apple iPhone or iPod touch, and the Nintendo Wii. The iPhone and Wii versions of the software cost an additional fee, but you can deploy your games to the Web, to the Mac, and to the PC for free using the indie version of Unity.<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_06.png' alt='Posted Image' class='bbc_img' /></span></p><br />
Diceworks was created by one artist and one programmer working together as a team. It's rare to find a single person who possesses both programming and artistic talent simultaneously; scientists say that these disciplines are split between two different lobes in our brains, and we tend to favor one or the other. The artist-programmer pairing that produced Diceworks is a common setup in game development. What's your own brain telling you? Are you more comfy with visuals or logic? Art or programming? Once you discover the answer, it's not a bad plan to find someone to make up the other half of your brain so that your game handles both areas competently.<br />
<br />
At any event, with Diceworks we're definitely getting closer to the scope and scale that you can manage on your own as you start out with Unity.<br />
<br />
It's also interesting to note that Diceworks is a 2D game created in a 3D engine. The third "D" is largely missing, and all of the game elements appear to exist on a flat plane. Nixing that extra dimension when you're just starting out isn't a half bad idea. Adding depth to your game brings a whole new dimension of difficulty to your designs, and it will be easier to get up and running with Unity by focusing on the X and Y axes, and leaving the Z-axis in one of those dream jars. With a few sturdy working game examples under your belt, it won't be long before you can take that Z-jar down off the shelf and pop it open. The games that we'll be dealing with in this article will stick to a two-dimensional plane, using three-dimensional models. Even so, certain games have taken this concept and ran with it: New Super Mario Bros. Wii locked its 3D characters to a 2D plane and wound up an extremely complex and satisfying platformer.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Walk before you can run (or double jump)</strong></span><br />
A common mistake that new game developers make is biting off more than they can chew. Even experienced game developers make this mistake when they get really excited about a project, or when they approach a new technology and expect to be immediately proficient at using it. The real danger here is that you'll sit down and try to create your dream—let's say it's a sword and sorcery RPG epic that combines all the best parts of Diablo, ChuChu Rocket!, and Microsoft Excel. When you've sunk days and weeks and months into it and it still looks nothing like the game you envisioned, you give up. You figure that since you failed at creating your dream game, you were never really cut out to be a game developer to begin with.<br />
<br />
You owe it to yourself to start small! Rome wasn't built in a day, and neither was your dream kart racing game starring famous figures from Roman history. By taking smaller steps, you can experience success with a number of smaller games. Then you can take what you learn and add to it, slowly building your expertise until you're in a position to take that dream game jar off the shelf.<br />
<br />
For now, let's keep our dream shelf fully stocked, and turn our attention to something small and achievable. Best would be to have a collection of working games that started out simply, and grew more and more complex as you got smarter.<br />
<br />
There are real-world examples of games that began as simple, effective ideas and later grew into enormously complex and feature-rich titles. From small acorns, mighty multiplayer oak tree games grow.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>There's no such thing as "finished"</strong></span><br />
Some game developers who produce content for fixed media such as game discs and cartridges are used to producing a gold master—the final build of the game—and calling it a day. One of the joys of deploying games to the Web is that they're never truly finished. You can continue tweaking your web games and modifying them until you end up with a far more fun and polished game than you started with.<br />
<br />
If you follow Flashbang Studios on Twitter or if you read the studio's blog, you'll see that they're constantly modifying and improving their games, even years after they were "finished". At the time of this writing, Off-Road Velociraptor Safari was two years old, and the studio's Twitter stream revealed that they're still actively tweaking the game.<br />
<br />
Likewise, we may start with some games that are really raw and unfinished at first. But as we learn more about how to program the crucial bits and pieces common to many games, we'll keep revisiting our rough, early games to add those pieces and improve them.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Stop! Hammer time</strong></span><br />
Now that you've seen some of what Unity can do, it's time to download the program and kick the tires! Unity indie version is available for the low price of free (at the time of this writing) from the Unity 3D website.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Explore Demo island</strong></span><br />
When Unity first opens, you should see a splash screen referring you to different tutorial resources and language guides. How helpful! Now close it. (Don't worry, it'll be there next time, unless you uncheck the <strong class='bbc'>Show at Startup</strong> box).<br />
<br />
Because you chose to download the sample project, it should automatically load the first time you run Unity. Navigate to <strong class='bbc'>Window | Layouts | 2 by 3</strong> to see the different panels that we're about to tour.<br />
 <br />
<p class='bbc_center'><a class='resized_img' rel='lightbox[ea0631f50009395747ddb8e9965a026f]' id='ipb-attach-url-7388-0-38392200-1330203877' href="http://www.gamedev.net/index.php?app=core&module=attach&section=attach&attach_rel_module=ccs&attach_id=7388" title="0546OT_01_07.png - Size: 219.3K, Downloads: 20"><img src="http://public.gamedev.net/uploads/monthly_02_2012/ccs-8549-0-59480600-1329846754_thumb.png" id='ipb-attach-img-7388-0-38392200-1330203877' style='width:480;height:321' class='attach' width="480" height="321" alt="Attached Image: 0546OT_01_07.png" /></a></p><br />
To try out the demo, click on the <strong class='bbc'>Play</strong> button at the top-center of the screen.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_08.png' alt='Posted Image' class='bbc_img' /></span></p><br />
You can walk around the Island Demo using the <em class='bbc'>WASD</em> keys on your keyboard. Jump by pressing the Space bar. When you're finished exploring, click on the <strong class='bbc'>Play</strong> button again to end the demo.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_09.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<span style='font-size: 18px;'><strong class='bbc'>The wonders of technology!</strong></span><br />
Unity contains all of the tools that you need to create an island similar to the one you see in this demo. It has terrain tools that let you model your level right inside the software. It contains a ready-made <strong class='bbc'>First Person Controller Prefab</strong> object you can plunk into the world with automatic <em class='bbc'>WASD</em> keyboard controls that will allow you to explore the terrain. Unity automatically takes care of the rendering (drawing), collisions, physics, and sound effects. That's one fancy hammer!<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Wide-open worlds with Will</strong><br />
If you'd like to learn how to sculpt your own terrain in Unity, and to add 3D models, sounds, and interactivity to create a simple but functional 3D open-world game, check out, "Unity Game Development Essentials", Will Goldstone, Packt Publishing.</em></p><br />
<br />
Much of what you see in the Island Demo can be built directly in Unity using the engine's terrain sculpting tools. The demo contains special models, like the bridge, which were imported from 3D software packages, including 3D Studio Max, Maya, or Blender. Certain elements, like the birds, have scripts attached to them that teach them how to fly. <strong class='bbc'>Scripts</strong> are lists of instructions that tell the items in the game world how to behave.<br />
<br />
Let's take a quick look around the Unity interface and note a few points of interest.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>The Scene window</strong></span><br />
The <strong class='bbc'>Scene</strong> window is where you can position your Game Objects and move things around. This window has various controls to change its level of detail. Use these controls to toggle lighing on and off, and to display the window contents with textures, wireframes, or a combination of both. You can use the colorful gizmo in the top-right corner to constrain the window to the X, Y, and Z axes to view the top and sides of your <strong class='bbc'>scene</strong>. Click on the white box in the middle to return to perspective view. This is what the <strong class='bbc'>Scene</strong> window looks like when you start a new project or create a new <strong class='bbc'>Scene</strong>. You can think of scenes as levels or stages in your game.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_10.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<span style='font-size: 14px;'><strong class='bbc'>The Game window</strong></span><br />
The <strong class='bbc'>Game</strong> window shows you what your players will see. When you click on the <strong class='bbc'>Play</strong> button to test your game (as you just did with the Island Demo), the results of your efforts play out in this wind&#111;w. Toggle the <strong class='bbc'>Maximize on Play</strong> button to test your game in full-screen mode.<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_11.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<span style='font-size: 14px;'><strong class='bbc'>The Hierarchy</strong></span><br />
The <strong class='bbc'>Hierarchy</strong> panel lists all of the <strong class='bbc'>Game Objects</strong> in your <strong class='bbc'>Scene</strong>. <strong class='bbc'>Game Objects</strong>—cameras, lights, models, and prefabs—are the things that make up your game. They can be "tangible" things like the birds and the bridge in the Island Demo. They can also include intangible things, which only you as the game developer get to see and play with, such as the cameras, the lights, and colliders, which are special invisible shapes that tell the game engine when two <strong class='bbc'>Game Objects</strong> are touching.<br />
<br />
The Island Demo <strong class='bbc'>Hierarchy</strong> contains <strong class='bbc'>Game Objects</strong> for the birds, the sea foam, the terrain, and the sun, to name a few. It also lists something called the <strong class='bbc'>First Person Controller Prefab</strong>, which has one of those invisible <strong class='bbc'>Colliders</strong> with a camera stuck to it. That's how the player can see the island. The demo lists something called <strong class='bbc'>Performance</strong>—an empty <strong class='bbc'>Game Object</strong> with a special script at  ached to it that helps the demo run more quickly depending on the player's computer specs. So, <strong class='bbc'>Game Objects</strong> can include touchy-feely "physical" objects like birds and bridges, as well as behind-the-scenes intangible things like lights, cameras, and actions (scripts).<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_12.png' alt='Posted Image' class='bbc_img' /></span></p><br />
Click on a <strong class='bbc'>Game Object</strong> in the <strong class='bbc'>Hierarchy</strong> panel, and then hover your mouse over the <strong class='bbc'>Scene</strong> wind&#111;w. Press the <em class='bbc'>F</em> key on your keyboard, and the <strong class='bbc'>Scene</strong> window will automatically pan and zoom directly to that object. Alternatively, you can go to <strong class='bbc'>Edit | Frame Selected</strong>, which can be more reliable than using the keyboard shortcut. (I like to think of the <em class='bbc'>F</em> as standing for <em class='bbc'>Focus</em> to help me remember what this shortcut does).<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Project panel</strong></span><br />
he <strong class='bbc'>Project</strong> panel lists all of the elements that you'll use to create <strong class='bbc'>Game Objects</strong> in your project. For example, the Island Demo seagull <strong class='bbc'>Game Object</strong> is made up of a mesh that represents the seagull's shape, a material to depict its "skin" or coloring, and a script that controls its flight behavior. The seagull material itself could include a texture (image) file. All of these goodies are listed in the <strong class='bbc'>Project</strong> panel.<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>You got a lot of gull</strong><br />
The actual seagulls in the Island Demo are actually more complex than the ones in our simple example. To see what went into creating them, click on the gray arrow next to <strong class='bbc'>Birds</strong> in the <strong class='bbc'>Project</strong> panel. Then click on the arrow next to <strong class='bbc'>Seagull</strong>. Don't worry if you don't understand what you're seeing—the key here is to understand that the <strong class='bbc'>Project</strong> panel contains many of the elements, or ingredients, that go into making our <strong class='bbc'>Game Objects</strong>.</em></p><br />
<br />
The <strong class='bbc'>Project</strong> panel displays the contents of a special folder called <em class='bbc'>Assets</em>. Unity automatically creates the <em class='bbc'>Assets</em> folder for you when you create a new project. If you drag a compatible file, like a 3D model, a sound effect, or an image into the <strong class='bbc'>Project</strong> panel, Unity copies it to the <em class='bbc'>Assets</em> folder behind the scenes, and displays it in the <strong class='bbc'>Project</strong> panel.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_13.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Don't mess with the Assets folder!</strong><br />
Unity stores metadata about the folder, and by moving stuff around or deleting things through your operating system, you may break your project. If you need to make changes, make them right inside Unity in the <strong class='bbc'>Project</strong> panel.</em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Inspector</strong></span><br />
The <strong class='bbc'>Inspector</strong> is a context-sensitive panel, which means that it changes depending on what you select elsewhere in Unity. This is where you can adjust the position, rotation, and scale of <strong class='bbc'>Game Objects</strong> listed in the <strong class='bbc'>Hierarchy</strong> panel. The <strong class='bbc'>Inspector</strong> can also display controls to configure components that add functionality to Game Objects. Between the three main panels in Unity (<strong class='bbc'>Hierarchy</strong>, <strong class='bbc'>Project</strong>, and <strong class='bbc'>Inspector</strong>), the <strong class='bbc'>Inspector</strong> is where you'll likely spend most of your time because that's where you'll be tweaking and fiddling with every aspect of the elements that comprise your game projects.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_14.png' alt='Posted Image' class='bbc_img' /></span></p><br />
This screenshot of the <strong class='bbc'>Inspector</strong> shows the components attached to the <strong class='bbc'>First Person Controller Prefab</strong> in the Island Demo: two scripts (<strong class='bbc'>FPSWalker and Mouse Look</strong>) and a <strong class='bbc'>Character Controller</strong> component. To see the same content on your computer, click to select the <strong class='bbc'>First Person Controller Prefab</strong> in the <strong class='bbc'>Hierarchy</strong> panel.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Invade Island Demo as a paratrooper</strong></span><br />
Let's use the <strong class='bbc'>Inspector</strong> panel to make a quick change to the start position of the player character. We'll begin the demo with the player 400 feet in midair, giving the player a beautiful bird's eye view of the action as he parachutes into the island.<br />
<br />
The <strong class='bbc'>First Person Controller Prefab</strong> that you just clicked on represents the player in the game. It has a camera embedded in it that the player looks through, and a pill-shaped <strong class='bbc'>Character collider</strong> that tells the game engine when the player is touching other things in the <strong class='bbc'>Scene</strong>. The <strong class='bbc'>Character collider</strong> is what keeps the player from falling through the ground.<br />
<br />
We can use the <strong class='bbc'>Inspector</strong> panel to change the start position of the player. In the <strong class='bbc'>Scene</strong> view, you should see the <strong class='bbc'>First Person Controller Prefab</strong>—it looks like a green pill with what looks like a speaker icon on top of it (this is blocking the <strong class='bbc'>Camera</strong> icon). If you don't see it, follow these steps:<ul class='bbcol decimal'><br /><li>Click to select the <strong class='bbc'>First Person Controller Prefab</strong> in the <strong class='bbc'>Hierarchy</strong> panel.<br /></li><li>Navigate to <strong class='bbc'>Edit | Frame Selected</strong> to focus on the Game Object. Alternatively, you can hover your mouse over the <strong class='bbc'>Scene</strong> view and press the <em class='bbc'>F</em> key on your keyboard. The <strong class='bbc'>First Person Controller Prefab</strong> should swing into view.<br /></li><li>Click on the <strong class='bbc'>Move</strong> button, which looks like four connected arrows.<br />		<br />	<br /><p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_15.png' alt='Posted Image' class='bbc_img' /></span></p>	   <br />	A tripod of three arrows appears at the center of the <strong class='bbc'>Game Object</strong>. The blue Z- axis runs through where the player's belly button would be. The red X-axis runs perpendicular to the X-axis. And the green Y-axis runs straight up and down through the player as if the player was hanging by a piece of string tied to the top of her head. The Y-axis is the up or down axis that we want to adjust.	<br />		<br />	<br /><p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_16.png' alt='Posted Image' class='bbc_img' /></span></p><br /></li><li>You can click-and-drag the green Y-axis arrow to move the player up into the sky, but a better method is to change the Y-axis position in the <strong class='bbc'>Inspector</strong> panel. Expand the gray arrow next to <strong class='bbc'>Transform</strong> in the <strong class='bbc'>Inspector</strong> panel if it's not already open, and change the Y value under <strong class='bbc'>Position</strong> to <strong class='bbc'>400</strong>.<br />		<br />	<br /><p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_17.png' alt='Posted Image' class='bbc_img' /></span></p><br /></li><li>Now, when you press <strong class='bbc'>Play</strong> to test the game, your character will start way up in the sky, floating down to the island before making a soft, quiet landing. It's a good thing that the Unity people didn't write a fall damage script, otherwise we might have some crumpled legs to contend with!<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>Layers and layout dropdowns</strong></span><br />
Above the <strong class='bbc'>Inspector</strong> panel, you'll see the <strong class='bbc'>Layers</strong> and <strong class='bbc'>Layout</strong> dropdowns. <strong class='bbc'>Game Objects</strong> can be grouped into layers, much like in Photoshop or Flash. Unity stores a few commonly used layouts in the <strong class='bbc'>Layout</strong> dropdown. You can also save and load your own custom layouts.<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_18.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<span style='font-size: 14px;'><strong class='bbc'>Playback controls</strong></span><br />
These three buttons help you test your game and control playback. As you've seen, the <strong class='bbc'>Play</strong> button starts and stops your game. The <strong class='bbc'>Pause</strong> button works as expected—it pauses your game so that you can make changes to it on the fly. The third button is a <strong class='bbc'>Step-Through</strong> control; use it to advance frame-by-frame through your game so that you can more tightly control what's going on.<br />
<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_19.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Changes you make while testing don't stick!</strong><br />
One of the more surprising features of Unity is that you can make changes to <strong class='bbc'>Game Objects</strong> and variables on the fly while you're testing your game. But it's important to know that the changes you make during testing will not "stick". Once you stop testing your game, the changes that you made during testing will revert to the state they were in before you clicked on the <strong class='bbc'>Play</strong> button. It's disheartening to make a number of changes to your game, only to realize that the <strong class='bbc'>Play</strong> button was on the entire time, and your changes will be lost. One way to avoid this problem is to toggle the <strong class='bbc'>Maximize on Play</strong> button in the <strong class='bbc'>Game</strong> window so that you'll be more aware of when you're testing and when you're not.</em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Scene controls</strong></span><br />
At the top-left of your screen, you'll see four controls that help you move around your <strong class='bbc'>Scene</strong>, and position <strong class='bbc'>Game Objects</strong> within it. These controls are mapped to the <em class='bbc'>Q, W, E, and R</em> keys on your keyboard. From left to right, they are:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0546OT_01_20.png' alt='Posted Image' class='bbc_img' /></span></p><ul class='bbc'><br /><li><strong class='bbc'>The Hand tool (Q)</strong>: Use it to click-and-drag around your scene. Hold down the <em class='bbc'>Alt</em> key on your keyboard to rotate the view. Hold down the <em class='bbc'>Ctrl</em> key (Windows) or the <em class='bbc'>Command</em> key (Apple) to zoom in and out. Your mouse wheel will also zoom the scene. Hold down the <em class='bbc'>Shift</em> key to pan, zoom, and rotate in larger increments to speed things up. This is a way for you to navigate around the game world. It doesn't actually impact the way the player sees the game. To modify the <strong class='bbc'>Game</strong> view, you need to use the <strong class='bbc'>Move</strong> or <strong class='bbc'>Rotate</strong> tools to modify the <strong class='bbc'>Camera</strong> position.<br /></li><li><strong class='bbc'>The Move tool (W)</strong>: This tool lets you move the Game Objects around your scene. You can either drag the object(s) around by the X, or Y, or Z-axis handles, or by the square in the center for freeform movement. Holding down the <em class='bbc'>Ctrl</em> key will snap movement to set grid increments. We saw this tool when we were positioning the <strong class='bbc'>First Person Controller Prefab</strong> in the middle of the sky.<br /></li><li><strong class='bbc'>Rotate tool (E)</strong>: Use it to spin your objects around using a neat spherical gizmo. The red, green, and blue lines map to the X, Y, and Z axes.<br /></li><li><strong class='bbc'>Scale tool ®</strong>: This tool works much the same as the <strong class='bbc'>Move</strong> and <strong class='bbc'>Rotate</strong> tools. Use it to make your Game Objects larger or smaller. Dragging an X, Y, or Z handle will non-uniformly scale (squash and stretch) the object, while dragging the gray cube in the center will uniformly scale it.<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Don't stop there—live a little!</strong></span><br />
We've glanced briefly at the key elements of the Unity interface, but there's no need to stop poking around. Far beyond the scope of this article, there is a wealth of menu options, buttons, and controls that we haven't covered. Why not explore those menus or start randomly clicking on things that you don't yet understand? Now is the time to safely break stuff. You didn't work hard to create the Island Demo, so why not mess around with it a little bit?<br />
<br />
Here are some things to try:<ul class='bbc'><br /><li>Select some of the Game Objects in the <strong class='bbc'>Hierarchy</strong> panel and move them around in the <strong class='bbc'>Scene</strong> window using the <strong class='bbc'>Scene</strong> controls. What happens when you put the bridge in the middle of the sky? Can you make one of the birds fly into a tree? What happens when you walk way out into the ocean while testing the game?<br /></li><li>Randomly right-click in the three different panels and read through the context menu options to see what you're getting yourself into.<br /></li><li>Poke around in the <strong class='bbc'>GameObject | Create Other</strong> menu. There's a whole list of interesting things that you can add to this scene without even touching the 3D modeling program.<br /></li><li>What happens when you delete the lights from the scene? Or the camera? Can you add another camera? More lights? How does that affect the <strong class='bbc'>Scene</strong>?<br /></li><li>Can you move the <strong class='bbc'>First Person Controller Prefab</strong> to another part of the island to change your starting position? How about starting on top of those two gigantic rocks on the beach?<br /></li><li>Can you replace the audio files to make the seagulls sound like car horns?<br /></li><li>Download a picture of kittens from the Internet and see if you can wrap it around the boulder model. Kittens rock! You can pull the kittens into your project using the <strong class='bbc'>Assets | Import New Asset</strong> option in the menu.<br /></li></ul><br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>A tuner's paradise</strong><br />
The Unity 3D interface is designed to be customized. Not only can you define your own custom window layouts, but you can even write custom scripts to make certain buttons and panels appear inside Unity to speed up your workflow. That kind of thing is well beyond the scope of this article, but if you're the kind of person who really likes to get under the hood, you'll be happy to know that you can tweak Unity 3D to your heart's content—maybe add a few racing stripes and install an enormous pair of subwoofers in the back?</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
This article was all about getting a feel for what Unity can do and for what the program interface had to offer. Here's what we found out:<ul class='bbc'><br /><li>Massive 80 person teams, all the way down to tiny one- or two-person teams are using Unity to create fun games.<br /></li><li>By thinking small, we'll have more success in learning Unity and producing fully functional games instead of huge but half-baked abandoned projects.<br /></li><li>Different flavors of Unity help us deploy our games to different platforms. By using the free indie version, we can deploy to the Web, and the Mac and PC platforms.<br /></li><li>The Unity interface has controls and panels that let us visually compose our game assets, and test games on the fly right inside the program!<br /></li></ul><br />
I hope you've taken some time to thoroughly vandalize the Island Demo. Save the file by clicking on <strong class='bbc'>File | Save Project</strong> in case you want to come back and wreak more havoc a little later.]]></description>
		<pubDate>Tue, 21 Feb 2012 17:47:26 +0000</pubDate>
		<guid isPermaLink="false">064d5929fb1f298f64353d6f3e25ffac</guid>
	</item>
	<item>
		<title>How to Do Gesture Recognition With Kinect Using...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/game-programming/how-to-do-gesture-recognition-with-kinect-using-r2874</link>
		<description></description>
		<pubDate>Tue, 21 Feb 2012 11:57:12 +0000</pubDate>
		<guid isPermaLink="false">77684c8fdb7c184134e96d5535715990</guid>
	</item>
	<item>
		<title>GLSL 4.0: Discarding Fragments to Create a Perf...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/opengl/glsl-40-discarding-fragments-to-create-a-perf-r2873</link>
		<description><![CDATA[Fragment shaders can make use of the <em class='bbc'>discard</em> keyword to "throw away" fragments. Use of this keyword causes the fragment shader to stop execution, without writing anything (including depth) to the output buffer. This provides a way to create holes in polygons without using blending. In fact, since fragments are completely discarded, there is no dependence on the order in which objects are drawn, saving us the trouble of doing any depth sorting that might have been necessary if blending was used. In this recipe by <strong class='bbc'>David Wolff</strong>, author of <a href='http://www.packtpub.com/opengl-4-0-shading-language-cookbook/book/rk/opengl4-abr6/0811?utm_source=rk_opengl4_abr6_0811&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>OpenGL 4.0 Shading Language Cookbook</a>, we'll draw a teapot, and use the discard keyword to remove fragments selectively based on texture coordinates.<br />
<br />
The result will look like the following image:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_18.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
The vertex position, normal, and texture coordinates must be provided to the vertex shader from the OpenGL application. The position should be provided at location 0, the normal at location 1, and the texture coordinates at location 2. As in <a href='http://www.packtpub.com/article/opengl-glsl-4-shaders-basics' class='bbc_url' title='External link' rel='nofollow external'>previous examples</a>, the lighting parameters must be set from the OpenGL application via the appropriate uniform variables.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To create a shader program that discards fragments based on a square lattice (as in the preceding image), use the following code:<br />
<br />
Use the following code for the vertex shader:<br />
<pre class='prettyprint'>#version 400<br /><br />layout (location = 0) in vec3 VertexPosition;<br />layout (location = 1) in vec3 VertexNormal;<br />layout (location = 2) in vec2 VertexTexCoord;<br /><br />out vec3 FrontColor;<br />out vec3 BackColor;<br />out vec2 TexCoord;<br /><br />struct LightInfo {<br />  vec4 Position; // Light position in eye coords.<br />  vec3 La; // Ambient light intensity<br />  vec3 Ld; // Diffuse light intensity<br />  vec3 Ls; // Specular light intensity<br />};<br />uniform LightInfo Light;<br /><br />struct MaterialInfo {<br />  vec3 Ka; // Ambient reflectivity<br />  vec3 Kd; // Diffuse reflectivity<br />  vec3 Ks; // Specular reflectivity<br />  float Shininess; // Specular shininess factor<br />};<br />uniform MaterialInfo Material;<br /><br />uniform mat4 ModelViewMatrix;<br />uniform mat3 NormalMatrix;<br />uniform mat4 ProjectionMatrix;<br />uniform mat4 MVP;<br /><br />void getEyeSpace( out vec3 norm, out vec4 position )<br />{<br />  norm = normalize( NormalMatrix * VertexNormal);<br />  position = ModelViewMatrix * vec4(VertexPosition,1.0);<br />}<br /><br />vec3 phongModel( vec4 position, vec3 norm )<br />{<br />  // The ADS shading calculations go here (see: "Using<br />  // functions in shaders," and "Implementing<br />  // per-vertex ambient, diffuse and specular (ADS) shading")<br />  ...<br />}<br /><br />void main()<br />{<br />  vec3 eyeNorm;<br />  vec4 eyePosition;<br /><br />  TexCoord = VertexTexCoord;<br /><br />  // Get the position and normal in eye space<br />  getEyeSpace(eyeNorm, eyePosition);<br /><br />  FrontColor = phongModel( eyePosition, eyeNorm );<br />  BackColor = phongModel( eyePosition, -eyeNorm );<br /><br />  gl_Position = MVP * vec4(VertexPosition,1.0);<br />}</pre><br />
<br />
Use the following code for the fragment shader:<br />
<pre class='prettyprint'>#version 400<br /><br />in vec3 FrontColor;<br />in vec3 BackColor;<br />in vec2 TexCoord;<br /><br />layout( location = 0 ) out vec4 FragColor;<br /><br />void main() {<br />  const float scale = 15.0;<br />  bvec2 toDiscard = greaterThan( fract(TexCoord * scale),<br />								 vec2(0.2,0.2) );<br /><br />if( all(toDiscard) )<br />	discard;<br /><br />if( gl_FrontFacing )<br />	FragColor = vec4(FrontColor, 1.0);<br />else<br />	FragColor = vec4(BackColor, 1.0);<br />}</pre><br />
<br />
Compile and link both shaders within the OpenGL application, and install the shader program prior to rendering.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
Since we will be discarding some parts of the teapot, we will be able to see through the teapot to the other side. This will cause the back sides of some polygons to become visible. Therefore, we need to compute the lighting equation appropriately for both sides of each face. We'll use the same technique presented earlier in the two-sided shading recipe.<br />
<br />
The vertex shader is essentially the same as in the two-sided shading recipe, with the main difference being the addition of the texture coordinate. The differences are highlighted in the above listing. To manage the texture coordinate, we have an additional input variable, <em class='bbc'>VertexTexCoord</em>, that corresponds to attribute location 2. The value of this input variable is passed directly on to the fragment shader unchanged via the output variable <em class='bbc'>TexCoord</em>. The ADS shading model is calculated twice, once using the given normal vector, storing the result in <em class='bbc'>FrontColor</em>, and again using the reversed normal, storing that result in <em class='bbc'>BackColor</em>.<br />
<br />
In the fragment shader, we calculate whether or not the fragment should be discarded based on a simple technique designed to produce the lattice-like pattern shown in the preceding image. We first scale the texture coordinate by the arbitrary scaling factor <em class='bbc'>scale</em>. This corresponds to the number of lattice rectangles per unit (scaled) texture coordinate. We then compute the fractional part of each component of the scaled texture coordinate using the built-in function <em class='bbc'>fract</em>. Each component is compared to 0.2 using the built-in function <em class='bbc'>greaterThan</em>, and the result is stored in the <em class='bbc'>bool</em> vector <em class='bbc'>toDiscard</em>. The <em class='bbc'>greaterThan</em> function compares the two vectors component-wise, and stores the Boolean results in the corresponding components of the return value.<br />
<br />
If both components of the vector <em class='bbc'>toDiscard</em> are true, then the fragment lies within the inside of each lattice frame, and therefore we wish to discard this fragment. We can use the built-in function <em class='bbc'>all</em> to help with this check. The function <em class='bbc'>all</em> will return true if all of the components of the parameter vector are true. If the function returns true, we execute the <em class='bbc'>discard</em> statement to reject the fragment.<br />
<br />
In the else branch, we color the fragment based on the orientation of the polygon, as in the two-sided shading recipe presented earlier.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
This recipe showed us how to use the <em class='bbc'>discard</em> keyword to "throw away" fragments and create a perforated look.]]></description>
		<pubDate>Tue, 07 Feb 2012 02:41:41 +0000</pubDate>
		<guid isPermaLink="false">08b90c2ebcce5d7f46176eb7c05af0ea</guid>
	</item>
	<item>
		<title>GLSL 4.0: Using Subroutines to Select Shader Fu...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/opengl/glsl-40-using-subroutines-to-select-shader-fu-r2872</link>
		<description><![CDATA[In GLSL, a subroutine is a mechanism for binding a function call to one of a set of possible function definitions based on the value of a variable. Subroutines therefore provide a way to select alternate implementations at runtime without swapping shader programs and/or recompiling, or using <em class='bbc'>if</em> statements along with a uniform variable.<br />
<br />
In this article by <strong class='bbc'>David Wolff</strong>, author of <a href='http://www.packtpub.com/opengl-4-0-shading-language-cookbook/book/rk/opengl4-abr5/0811?utm_source=rk_opengl4_abr5_0811&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>OpenGL 4.0 Shading Language Cookbook</a>, we'll demonstrate the use of subroutines by rendering a teapot twice. The first teapot will be rendered with the <a href='http://www.packtpub.com/article/opengl-glsl-4-shaders-basics' class='bbc_url' title='External link' rel='nofollow external'>full ADS shading model</a> described earlier. The second teapot will be rendered with diffuse shading only. A subroutine uniform will be used to choose between the two shading techniques.<br />
<br />
In many ways it is similar to function pointers in C. A uniform variable serves as the pointer and is used to invoke the function. The value of this variable can be set from the OpenGL side, thereby binding it to one of a few possible definitions. The subroutine's function definitions need not have the same name, but must have the same number and type of parameters and the same return type.<br />
<br />
A single shader could be written to provide several shading algorithms intended for use on different objects within the scene. When rendering the scene, rather than swapping shader programs (or using a conditional statement), we can simply change the subroutine's uniform variable to choose the appropriate shading algorithm as each object is rendered.<br />
 <br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>Since performance is crucial in shader programs, avoiding a conditional statement or a shader swap can be very valuable. With subroutines, we can implement the functionality of a conditional statement or shader swap without the computational overhead.</em></p><br />
In the following image, we see an example of a rendering that was created using subroutines. The teapot on the left is rendered with the full ADS shading model, and the teapot on the right is rendered with diffuse shading only. A subroutine is used to switch between shader functionality.<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_17.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
As with <a href='http://www.packtpub.com/article/opengl-glsl-4-shaders-basics' class='bbc_url' title='External link' rel='nofollow external'>previous recipes</a>, provide the vertex position at attribute location 0 and the vertex normal at attribute location 1. Uniform variables for all of the ADS coefficients should be set from the OpenGL side, as well as the light position and the standard matrices.<br />
<br />
We'll assume that, in the OpenGL application, the variable <em class='bbc'>programHandle</em> contains the handle to the shader program object.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To create a shader program that uses a subroutine to switch between pure-diffuse and ADS shading, use the following code:<br />
<br />
Use the following code for the vertex shader:<br />
<pre class='prettyprint'>#version 400<br /><br />subroutine vec3 shadeModelType( vec4 position, vec3 normal);<br /><br />subroutine uniform shadeModelType shadeModel;<br /><br />layout (location = 0) in vec3 VertexPosition;<br />layout (location = 1) in vec3 VertexNormal;<br /><br />out vec3 LightIntensity;<br /><br />struct LightInfo {<br />  vec4 Position; // Light position in eye coords.<br />  vec3 La; // Ambient light intensity<br />  vec3 Ld; // Diffuse light intensity<br />  vec3 Ls; // Specular light intensity<br />};<br />uniform LightInfo Light;<br /><br />struct MaterialInfo {<br />  vec3 Ka; // Ambient reflectivity<br />  vec3 Kd; // Diffuse reflectivity<br />  vec3 Ks; // Specular reflectivity<br />  float Shininess; // Specular shininess factor<br />};<br />uniform MaterialInfo Material;<br /><br />uniform mat4 ModelViewMatrix;<br />uniform mat3 NormalMatrix;<br />uniform mat4 ProjectionMatrix;<br />uniform mat4 MVP;<br /><br />void getEyeSpace( out vec3 norm, out vec4 position )<br />{<br />  norm = normalize( NormalMatrix * VertexNormal);<br />  position = ModelViewMatrix * vec4(VertexPosition,1.0);<br />}<br /><br />subroutine( shadeModelType )<br /><br />vec3 phongModel( vec4 position, vec3 norm )<br />{<br />  // The ADS shading calculations go here (see: "Using<br />  // functions in shaders," and "Implementing<br />  // per-vertex ambient, diffuse and specular (ADS) shading")<br />  ...<br />}<br /><br />subroutine( shadeModelType )<br /><br />vec3 diffuseOnly( vec4 position, vec3 norm )<br />{<br />  vec3 s = normalize( vec3(Light.Position - position) );<br />  return<br />	  Light.Ld * Material.Kd * max( dot(s, norm), 0.0 );<br />}<br /><br />void main()<br />{<br />  vec3 eyeNorm;<br />  vec4 eyePosition;<br /><br />  // Get the position and normal in eye space<br /><br />  getEyeSpace(eyeNorm, eyePosition);<br /><br />  // Evaluate the shading equation. This will call one of<br />  // the functions: diffuseOnly or phongModel.<br />  LightIntensity = shadeModel( eyePosition, eyeNorm );<br /><br />  gl_Position = MVP * vec4(VertexPosition,1.0);<br />}</pre><br />
<br />
Use the following code for the fragment shader:<br />
<pre class='prettyprint'>#version 400<br /><br />in vec3 LightIntensity;<br /><br />layout( location = 0 ) out vec4 FragColor;<br /><br />void main() {<br />FragColor = vec4(LightIntensity, 1.0);<br />}</pre><br />
<br />
In the OpenGL application, compile and link the above shaders into a shader program, and install the program into the OpenGL pipeline.<br />
<br />
Within the render function of the OpenGL application, use the following code:<br />
<pre class='prettyprint'>GLuint adsIndex =<br />glGetSubroutineIndex( programHandle,<br />					 GL_VERTEX_SHADER,"phongModel" );<br />GLuint diffuseIndex =<br />  glGetSubroutineIndex(programHandle,<br />					   GL_VERTEX_SHADER, "diffuseOnly");<br /><br />glUniformSubroutinesuiv( GL_VERTEX_SHADER, 1, &adsIndex);<br />... // Render the left teapot<br /><br />glUniformSubroutinesuiv( GL_VERTEX_SHADER, 1, &diffuseIndex);<br />... // Render the right teapot</pre><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
In this example, the subroutine is defined within the vertex shader. The first step involves declaring the subroutine type.<br />
<br />
<pre class='prettyprint'>subroutine vec3 shadeModelType( vec4 position,<br />					 vec3 normal);</pre><br />
<br />
This defines a new subroutine type with the name <em class='bbc'>shadeModelType</em>. The syntax is very similar to a function prototype, in that it defines a name, a parameter list, and a return type. As with function prototypes, the parameter names are optional.<br />
<br />
After creating the new subroutine type, we declare a uniform variable of that type named <em class='bbc'>shadeModel</em>.<br />
<br />
<pre class='prettyprint'>subroutine uniform shadeModelType shadeModel;</pre><br />
<br />
This variable serves as our function pointer and will be assigned to one of the two possible functions in the OpenGL application.<br />
<br />
We declare two functions to be part of the subroutine by prefixing their definition with the subroutine qualifier:<br />
<br />
<pre class='prettyprint'>subroutine ( shadeModelType )</pre><br />
<br />
This indicates that the function matches the subroutine type, and therefore its header must match the one in the subroutine type definition. We use this prefix for the definition of the functions <em class='bbc'>phongModel</em> and <em class='bbc'>diffuseOnly</em>. The <em class='bbc'>diffuseOnly</em> function computes the diffuse shading equation, and the <em class='bbc'>phongModel</em> function computes the complete ADS shading equation.<br />
<br />
We call one of the two subroutine functions by utilizing the subroutine uniform <em class='bbc'>shadeModel</em> within the main function.<br />
<br />
<pre class='prettyprint'>LightIntensity = shadeModel( eyePosition, eyeNorm );</pre><br />
<br />
Again, this call will be bound to one of the two functions depending on the value of the subroutine uniform <em class='bbc'>shadeModel</em>, which we will set within the OpenGL application.<br />
<br />
Within the render function of the OpenGL application, we assign a value to the subroutine uniform with the following steps. First, we query for the index of each subroutine function using <em class='bbc'>glGetSubroutineIndex</em>. The first argument is the program handle. The second is the shader stage. In this case, the subroutine is defined within the vertex shader, so we use <em class='bbc'>GL_VERTEX_SHADER</em> here. The third argument is the name of the subroutine. We query for each function individually and store the indexes in the variables <em class='bbc'>adsIndex</em> and <em class='bbc'>diffuseIndex</em>.<br />
<br />
To select the appropriate subroutine function, we need to set the value of the subroutine uniform <em class='bbc'>shadeModel</em>. To do so, we call <em class='bbc'>glUniformSubroutinesuiv</em>. This function is designed for setting multiple subroutine uniforms at once. In our case, of course, we are setting only a single uniform. The first argument is the shader stage (<em class='bbc'>GL_VERTEX_SHADER</em>), the second is the number of uniforms being set, and the third is a pointer to an array of subroutine function indexes. Since we are setting a single uniform, we simply provide the address of the <em class='bbc'>GLuint</em> variable containing the index, rather than a true array of values. Of course, we would use an array if multiple uniforms were being set. In general, the array of values provided as the third argument is assigned to subroutine uniform variables in the following way. The ith element of the array is assigned to the subroutine uniform variable with index <em class='bbc'>i</em>. Since we have provided only a single value, we are setting the subroutine uniform at index zero.<br />
<br />
You may be wondering, "How do we know that our subroutine uniform is located at index zero? We didn't query for the index before calling <em class='bbc'>glUniformSubroutinesuiv</em>!" The reason that this code works is that we are relying on the fact that OpenGL will always number the indexes of the subroutines consecutively starting at zero. If we had multiple subroutine uniforms, we could (and should) query for their indexes using <em class='bbc'>glGetSubroutineUniformLocation</em>, and then order our array appropriately.<br />
<br />
Finally, we select the <em class='bbc'>phongModel</em> function by setting the uniform to <em class='bbc'>adsIndex</em> and then render the left teapot. We then select the <em class='bbc'>diffuseOnly</em> function by setting the uniform to <em class='bbc'>diffuseIndex</em> and render the right teapot.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
A subroutine function defined in a shader can match multiple subroutine types. In that case, the subroutine qualifier can contain a comma-separated list of subroutine types. For example, if a subroutine matched the types <em class='bbc'>type1</em> and <em class='bbc'>type2</em>, we could use the following qualifier:<br />
<br />
<pre class='prettyprint'>subroutine( type1, type2 )</pre><br />
<br />
This would allow us to use subroutine uniforms of differing types to refer to the same subroutine function.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
With subroutines we can implement the functionality of a conditional statement or shader swap without the computational overhead.]]></description>
		<pubDate>Fri, 03 Feb 2012 02:41:38 +0000</pubDate>
		<guid isPermaLink="false">83b7e1c6a22424f5b4c47bb30798b770</guid>
	</item>
	<item>
		<title>Building a Complete Board-based Puzzle Game wit...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/directx-and-xna/building-a-complete-board-based-puzzle-game-wit-r2871</link>
		<description><![CDATA[This article by <strong class='bbc'>Kurt Jaegers</strong>, author of <a href='http://www.packtpub.com/xna-4-0-game-development-by-example-beginners-guide/book/rk/xna4_abr1/0910?utm_source=rk_xna4_abr1_0910&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>XNA 4.0 Game Development by Example: Beginner's Guide</a>, introduces a board-based puzzle game called Flood Control. We introduce the XNA Content Pipeline, and build a recursive function to determine the state of the game board while playing.<br />
<br />
This article focuses on the following concepts:<br />
<ul class='bbc'><br /><li>Using the Content Pipeline to load textures from disk<br /></li><li>Creating classes to divide code into logical units<br /></li><li>Recursively evaluating the status of the game board to check for scoring chains<br /></li><li>Drawing textures using the <em class='bbc'>SpriteBatch.Draw()</em> method<br /></li><li>Managing simple game states<br /></li></ul><br />
<br />
<br />
<br />
<br />
<br />
<br />
<em class='bbc'>It was just another day at the bottom of the ocean until an explosion in one of</em> <em class='bbc'>the storage bays cracked the protective dome around Deep Sea Research Lab</em> <em class='bbc'>Alpha. Now the entire place is flooding, and the emergency pump system is a chaotic jumble of loose parts.</em><br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_01.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Designing a puzzle game</strong></span><br />
The Puzzler has always been a popular game genre. From old standbys like Tetris to modern crazes like Bejeweled, puzzle games are attractive to players because they do not require a long-term time investment or a steep learning curve.<br />
<br />
The game mechanic is the heart of any good puzzle game. This mechanic is usually very simple, with perhaps a few twists to keep the players on their toes.<br />
<br />
In Flood Control, the player will be faced with a board containing 80 pieces of pipe. Some will be straight pipes and some will be curved. The objective of the game is to rotate the pipes to form a continuous line to pump water from the left side of the board to the right side of the board.<br />
<br />
Completing a section of pipe drains water out of the base and scores points for the player, but destroys the pipes used. New pipes will fall into place for the player to begin another row.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - set up the Flood Control project</strong></span><span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
You have now set up a workspace for building Flood Control, and created a couple of folders for organizing game content. You have also imported the sample graphics for the Flood Control game into the project.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Introducing the Content Pipeline</strong></span><br />
The <strong class='bbc'>Flood ControlContent (Content)</strong> project inside <strong class='bbc'>Solution Explorer</strong> is a special kind of project called a Content Project. Items in your game's content project are converted into .XNB resource files by Content Importers and Content Processors.<br />
<br />
If you right-click on one of the image files you just added to the Flood Control project and select <strong class='bbc'>Properties</strong>, you will see that for both the Importer and Processor, the Content Pipeline will use <strong class='bbc'>Texture - XNA Framework</strong>. This means that the Importer will take the file in its native format (.PNG in this case) and convert it to a format that the Processor recognizes as an image. The Processor then converts the image into an <em class='bbc'>.XNB</em> file which is a compressed binary format that XNA's content manager can read directly into a Texture2D object.<br />
<br />
There are Content Importer/Processor pairs for several different types of content—images, audio, video, fonts, 3D models, and shader language effects files. All of these content types get converted to .XNB files which can be used at runtime.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_02.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
In order to see how to use the Content Pipeline at runtime, let's go ahead and write the code to read these textures into memory when the game starts:<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - reading textures into memory</strong></span><ul class='bbcol decimal'><br /><li>Double-click on <em class='bbc'>Game1.cs</em> in <strong class='bbc'>Solution Explorer</strong> to open it or bring it to the front if it is already open.<br /></li><li>In the Class Declarations area of Game1 (right below SpriteBatch spriteBatch;), add:<br />	<pre class='prettyprint'>	<br />Texture2D playingPieces;<br />	Texture2D backgroundScreen;<br />	Texture2D titleScreen;	<br />	</pre><br /></li><li>Add code to load each of the Texture2D objects at the end of <em class='bbc'>LoadContent()</em>:<br />	<pre class='prettyprint'>	<br />playingPieces = Content.Load(@"Textures&#092;Tile_Sheet");<br />	backgroundScreen = <br />		Content.Load(@"Textures&#092;Background");<br />	titleScreen = Content.Load(@"Textures&#092;TitleScreen");	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
In order to load the textures from disk, you need an in-memory object to hold them. These are declared as instances of the <em class='bbc'>Texture2D</em> class.<br />
<br />
A default XNA project sets up the Content instance of the ContentManager class for you automatically. The Content object's <em class='bbc'>Load()</em> method is used to read .XNB files from disk and into the Texture2D instances declared earlier.<br />
<br />
One thing to note here is that the <em class='bbc'>Load()</em> method requires a type identifier, specified in angled brackets (), before the parameter list. Known in C# as a "Generic", many classes and methods support this kind of type specification to allow code to operate on a variety of data types. We will make more extensive use of Generics later when we need to store lists of objects in memory. The <em class='bbc'>Load()</em> method is used not only for textures, but also for all other kinds of content (sounds, 3D models, fonts, etc.) as well. It is important to let the <em class='bbc'>Load()</em> method know what kind of data you are reading so that it knows what kind of object to return.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Sprites and sprite sheets</strong></span><br />
As far as XNA and the SpriteBatch class are concerned, a sprite is a 2D bitmapped image that can be drawn either with or without transparency information to the screen.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Sprites vs. Textures</strong><br />
XNA defines a "sprite" as a 2D bitmap that is drawn directly to the screen. While these bitmaps are stored in Texture2D objects, the term "texture" is used when a 2D image is mapped onto a 3D object, providing a visual representation of the surface of the object. In practice, all XNA graphics are actually performed in 3D, with 2D sprites being rendered via special configurations of the XNA rendering engine.</em></p><br />
<br />
The simple form of the <em class='bbc'>SpriteBatch.Draw()</em> call when drawing squares only needs three parameters: a <em class='bbc'>Texture2D</em> to draw, a <em class='bbc'>Rectangle</em> indicating where to draw it, and a <em class='bbc'>Color</em> to specify the tint to overlay onto the sprite.<br />
<br />
Other overloads of the <em class='bbc'>Draw()</em> method, however, also allow you to specify a <em class='bbc'>Rectangle</em> representing the source area within the <em class='bbc'>Texture2D</em> to copy from. If no source <em class='bbc'>Rectangle</em> is specified, the entire <em class='bbc'>Texture2D</em> is copied and resized to fit the destination <em class='bbc'>Rectangle</em>.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Overloads</strong><br />
When multiple versions of the same method are declared with either different parameters lists or different return values, each different declaration is called an "overload" of the method. Overloads allow methods to work with different types of data (for example, when setting a position you could accept two separate X and Y coordinates or a Vector2 value), or leave out parameters that can then be assigned default values.</em></p><br />
<br />
By specifying a source <em class='bbc'>Rectangle</em>, however, individual pieces can be pulled from a large image. A bitmap with multiple sprites on it that will be drawn this way is called a "sprite sheet".<br />
<br />
The <em class='bbc'>Tile_Sheet.png</em> file for the Flood Control project is a sprite sheet containing 13 different sprites that will be used to represent the pieces of pipe used in the game. Each image is 40 pixels wide and 40 pixels high, with a one pixel border between each sprite and also around the entire image. When we call <em class='bbc'>SpriteBatch.Draw()</em> we can limit what gets drawn from our texture to one of these 40 by 40 squares, allowing a single texture to hold all of the playing piece images that we need for the game:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_03.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The <em class='bbc'>Tile_Sheet.png</em> file was created with alpha-based transparency. When it is drawn to the screen, the alpha level of each pixel will be used to merge that pixel with any color that already occupies that location on the screen.<br />
<br />
Using this fact, you can create sprites that don't look like they are rectangular. Internally, you will still be drawing rectangles, but visually the image can be of any shape.<br />
<br />
What we really need now to be able to work with the playing pieces is a way to reference an individual piece, knowing not only what to draw to the screen, but what ends of the pipe connect to adjacent squares on the game board.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Alpha blending</strong><br />
Each pixel in a sprite can be fully opaque, fully transparent, or partially transparent. Fully opaque pixels are drawn directly, while fully transparent pixels are not drawn at all, leaving whatever has already been drawn to that pixel on the screen unchanged. In 32-bit color mode, each channel of a color (Red, Green, Blue, and Alpha) are represented by 8 bits, meaning that there are 256 different degrees of transparency between fully opaque (255) and fully transparent (0). Partially transparent pixels are combined with the current pixel color at that location to create a mixed color as if the pixels below were being seen through the new color.</em></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Classes used in Flood Control</strong></span><br />
While it would certainly be possible to simply pile all of the game code into the Game1 class, the result would be difficult to read and manage later on. Instead, we need to consider how to logically divide the game into classes that can manage themselves and help to organize our code.<br />
<br />
A good rule of thumb is that a class should represent a single thing or type of thing. If you can say "This object is made up of these other objects" or "This object contains these objects", consider creating classes to represent those relationships.<br />
<br />
The Flood Control game contains a game board made up of 80 pipes. We can abstract these pipes as a class called GamePiece, and provide it with the code it needs to handle rotation and provide the code that will display the piece with a Rectangle that can be used to pull the sprite off the sprite sheet.<br />
<br />
The game board itself can be represented by a <em class='bbc'>GameBoard</em> class, which will handle managing individual GamePiece objects and be responsible for determining which pieces should be filled with water and which ones should be empty.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>The GamePiece class</strong></span><br />
The GamePiece class represents an individual pipe on the game board. One GamePiece has no knowledge of any other game pieces (that is the responsibility of the GameBoard class), but it will need to be able to provide information about the pipe to objects that use the GamePiece class. Our class has the following requirements:<br />
<ul class='bbc'><br /><li>Identify the sides of each piece that contain pipe connectors<br /></li><li>Differentiate between game pieces that are filled with water and that are empty<br /></li><li>Allow game pieces to be updated<br /></li><li>Automatically handle rotation by changing the piece type to the appropriate new piece type<br /></li><li>Given one side of a piece, provide the other sides of the piece in order to facilitate determining where water can flow through the game board<br /></li><li>Provide a Rectangle that will be used when the piece is drawn, to locate the graphic for the piece on the sprite sheet<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>Identifying a GamePiece</strong></span><br />
While the sprite sheet contains thirteen different images, only twelve of them are actual game pieces (the last one is an empty square). Of the twelve remaining pieces, only six of them are unique pieces. The other six are the water-filled versions of the first six images.<br />
<br />
Each of the game pieces can be identified by which sides of the square contain a connecting pipe. This results in two straight pieces and four pieces with 90 degree bends in them.<br />
<br />
A second value can be tracked to determine if the piece is filled with water or not instead of treating filled pieces as separate types of pieces.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - build a GamePiece class - declarations</strong></span><ul class='bbcol decimal'><br /><li>Switch back to your Visual C# window if you have your image editor open.<br /></li><li>Right-click on <strong class='bbc'>Flood Control</strong> in <strong class='bbc'>Solution Explorer</strong> and select <strong class='bbc'>Add | Class...</strong><br /></li><li>Name the class <strong class='bbc'>GamePiece.cs</strong> and click on <strong class='bbc'>Add</strong>.<br /></li><li>At the top of the GamePiece.cs file, add the following to the using directives already in the class:<br />	<pre class='prettyprint'>	<br />using Microsoft.Xna.Framework.Graphics;<br />	using Microsoft.Xna.Framework;	<br />	</pre><br /></li><li>In the class declarations section, add the following:<br />	<pre class='prettyprint'>	<br />public static string&#91;&#93; PieceTypes = <br />	{ <br />	  "Left,Right", <br />	  "Top,Bottom", <br />	  "Left,Top", <br />	  "Top,Right",<br />	  "Right,Bottom", <br />	  "Bottom,Left",<br />	  "Empty"<br />	};<br />	<br />	public const int PieceHeight = 40;<br />	public const int PieceWidth = 40;<br />	<br />	public const int MaxPlayablePieceIndex = 5;<br />	public const int EmptyPieceIndex = 6;<br />	<br />	private const int textureOffsetX = 1;<br />	private const int textureOffsetY = 1;<br />	private const int texturePaddingX = 1;<br />	private const int texturePaddingY = 1;<br />	<br />	private string pieceType = "";<br />	private string pieceSuffix = "";	<br />	</pre><br /></li><li>Add two properties to retrieve information about the piece:<br />	<pre class='prettyprint'>	<br />public string PieceType<br />	{<br />		get { return pieceType; }<br />	}<br />	<br />	public string Suffix<br />	{<br />		get { return pieceSuffix; }<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
You have created a new code file called <em class='bbc'>GamePiece.cs</em> and included the using statements necessary to access the pieces of the XNA Framework that the class will use.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Using Directives</strong><br />
Adding the XNA Framework using directives at the top of the class file allows you to access classes like Rectangle and Vector2 without specifying their full assembly names. Without these statements, you would need Microsoft.Xna.Framework.Rectangle in your code every time you reference the type, instead of simply typing Rectangle.</em></p><br />
<br />
In the declarations area, you have added an array called <em class='bbc'>PieceTypes</em> that gives a name to each of the different types of game pieces that will be added to the game board. There are two straight pieces, four angled pieces, and an empty tile with a background image on it, but no pipe. The array is declared as <em class='bbc'>static</em> because all instances of the GamePiece class will share the same array. A <em class='bbc'>static</em> member can be updated at execution time, but all members of the class will see the same changes.<br />
<br />
Then, you have declared two integer constants that specify the height and width of an individual playing piece in pixels, along with two variables that specify the array index of the last piece that can be placed on the board (<em class='bbc'>MaxPlayablePieceIndex</em>) and of the fake "Empty" piece.<br />
<br />
Next are four integers that describe the layout of the texture file you are using. There is a one pixel offset from the left and top edge of the texture (the one pixel border) and a single pixel of padding between each sprite on the sprite sheet.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Constants vs. Numeric literals</strong><br />
Why create constants for things like PieceWidth and PieceHeight and have to type them out when you could simply use the number 40 in their place? If you need to go back and resize your pieces later, you only need to change the size in one place instead of hoping that you find each place in the code where you entered 40 and change them all to something else. Even if you do not change the number in the game you are working on, you may reuse the code for something else later and having easily changeable parameters will make the job much easier.</em></p><br />
<br />
There are only two pieces of information that each instance of GamePiece will track about itself—the type of the piece and any suffix associated with the piece. The instance members <em class='bbc'>pieceType</em> and <em class='bbc'>pieceSuffix</em> store these values. We will use the suffix to determine if the pipe that the piece represents is empty or filled with water.<br />
<br />
However, these members are declared as <em class='bbc'>private</em> in order to prevent code outside the class from directly altering the values. To allow them to be read but not written to, we create a pair of properties (<em class='bbc'>pieceType</em> and <em class='bbc'>pieceSuffix</em>) that contain get blocks but no set blocks. This makes these values accessible in a read-only mode to code outside the GamePiece class.<br />
<br />
<br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Creating a GamePiece</strong></span><br />
The only information we need to create an instance of GamePiece is the piece type and, potentially, the suffix.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - building a GamePiece class: constructors</strong></span><ul class='bbcol decimal'><br /><li>Add two constructors to your GamePiece.cs file after the declarations:<br />	<pre class='prettyprint'>	<br />public GamePiece(string type, string suffix)<br />	{<br />		pieceType=type;<br />		pieceSuffix=suffix;<br />	}<br />	<br />	public GamePiece(string type)<br />	{<br />		pieceType=type;<br />		pieceSuffix="";<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
A constructor is run when an instance of the GamePiece class is created. By specifying two constructors, we will allow future code to create a GamePiece by specifying a piece type with or without a suffix. If no suffix is specified, an empty suffix is assumed.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Updating a GamePiece</strong></span><br />
When a GamePiece is updated, you can change the piece type, the suffix, or both.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - GamePiece class methods - part 1 - updating</strong></span><ul class='bbcol decimal'><br /><li>Add the following methods to the GamePiece class:<br />	<pre class='prettyprint'>	<br />public void SetPiece(string type, string suffix)<br />	{<br />		pieceType = type;<br />		pieceSuffix = suffix;<br />	}<br />	<br />	public void SetPiece(string type)<br />	{<br />		  SetPiece(type,"");<br />	}<br />	<br />	public void AddSuffix(string suffix)<br />	{<br />		if (!pieceSuffix.Contains(suffix))<br />			pieceSuffix += suffix;<br />	}<br />	<br />	public void RemoveSuffix(string suffix)<br />	{<br />		pieceSuffix = pieceSuffix.Replace(suffix, "");<br />	}	<br />	</pre><br /></li></ul><br />
The first two methods are overloads with the same name, but different parameter lists. In a manner similar to the GamePiece constructors, code that wishes to update a GamePiece can pass it a piece type, and optionally a suffix.<br />
<br />
Additional methods have been added to modify suffixes without changing the <em class='bbc'>pieceType</em> associated with the piece. The <em class='bbc'>AddSuffix()</em> method first checks to see if the piece already contains the suffix. If it does, nothing happens. If it does not, the suffix value passed to the method is added to the <em class='bbc'>pieceSuffix</em> member variable.<br />
<br />
The <em class='bbc'>RemoveSuffix()</em> method uses the <em class='bbc'>Replace()</em> method of the string class to remove the passed suffix from the <em class='bbc'>pieceSuffix</em> variable.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Rotating pieces</strong></span><br />
The heart of the Flood Control play mechanic is the ability of the player to rotate pieces on the game board to form continuous pipes. In order to accomplish this, we can build a table that, given an existing piece type and a rotation direction, supplies the name of the piece type after rotation. We can then implement this code as a switch statement:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_04.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - GamePiece class methods - part 2 - rotation</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>RotatePiece()</em> method to the GamePiece class:<br />	<pre class='prettyprint'>	<br />public void RotatePiece(bool Clockwise)<br />	{<br />		 switch (pieceType)<br />		{<br />			case "Left,Right":<br />				pieceType = "Top,Bottom";<br />				break;<br />			case "Top,Bottom":<br />				pieceType = "Left,Right";<br />				break;<br />			case "Left,Top":<br />				if (Clockwise)<br />					pieceType = "Top,Right";<br />				else<br />					pieceType = "Bottom,Left";<br />				break;<br />			case "Top,Right":<br />				if (Clockwise)<br />					pieceType = "Right,Bottom";<br />				else<br />					pieceType = "Left,Top";<br />				break;<br />			case "Right,Bottom":<br />				if (Clockwise)<br />					pieceType = "Bottom,Left";<br />				else<br />					pieceType = "Top,Right";<br />				break;<br />			case "Bottom,Left":<br />				if (Clockwise)<br />					pieceType = "Left,Top";<br />				else<br />					pieceType = "Right,Bottom";<br />				break;<br />			case "Empty":<br />				break;<br />		}<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The only information the <em class='bbc'>RotatePiece()</em> method needs is a rotation direction. For straight pieces, rotation direction doesn't matter (a left/right piece will always become a top/bottom piece and vice versa).<br />
<br />
For angled pieces, the piece type is updated based on the rotation direction and the diagram above.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Why all the strings?</strong><br />
It would certainly be reasonable to create constants that represent the various piece positions instead of fully spelling out things like Bottom,Left as strings. However, because the Flood Control game is not taxing on the system, the additional processing time required for string manipulation will not impact the game negatively and helps clarify how the logic works.</em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Pipe connectors</strong></span><br />
Our GamePiece class will need to be able to provide information about the connectors it contains (<em class='bbc'>Top, Bottom, Left,</em> and <em class='bbc'>Right</em>) to the rest of the game. Since we have represented the piece types as simple strings, a string comparison will determine what connectors the piece contains.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - GamePiece class methods - part 3 -connection methods</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>GetOtherEnds()</em> method to the GamePiece class:<br />	<pre class='prettyprint'>	<br />public string&#91;&#93; GetOtherEnds(string startingEnd)<br />	{<br />		List opposites = new List();<br />	<br />		foreach (string end in pieceType.Split(','))<br />		{<br />			if (end != startingEnd)<br />				opposites.Add(end);<br />		}<br />		 return opposites.ToArray();<br />	}	<br />	</pre><br /></li><li>Add the <em class='bbc'>HasConnector()</em> method to the <em class='bbc'>GamePiece</em> class:<br />	<pre class='prettyprint'>	<br />public bool HasConnector(string direction)<br />	{<br />		return pieceType.Contains(direction);<br />	}	<br />	</pre><br /></li></ul><br />
The <em class='bbc'>GetOtherEnds()</em> method creates an empty List object for holding the ends we want to return to the calling code. It then uses the Split() method of the string class to get each end listed in the pieceType. For example, the Top,Bottom piece will return an array with two elements. The first element will contain Top and the second will contain Bottom. The comma delimiter will not be returned with either string.<br />
<br />
If the end in question is not the same as the startingEnd parameter that was passed to the method, it is added to the list. After all of the items in the string have been examined, the list is converted to an array and returned to the calling code.<br />
<br />
In the previous example, requesting GetOtherEnds("Top") from a GamePiece with a pieceType value of Top,Bottom will return a string array with a single element containing Bottom.<br />
<br />
We will need this information in a few moments when we have to figure out which pipes are filled with water and which are empty.<br />
<br />
The second function, <em class='bbc'>HasConnector()</em> simply returns "true" if the pieceType string contains the string value passed in as the direction parameter. This will allow code outside the GamePiece class to determine if the piece has a connector facing in any particular direction.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Sprite sheet coordinates</strong></span><br />
Because we set up the <em class='bbc'>PieceTypes</em> array listing the pieces in the same order that they exist on the sprite sheet texture, we can calculate the position of the rectangle to draw from based on the <em class='bbc'>pieceType</em>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - GamePiece class methods - part 4 - GetSourceRect</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>GetSourceRect(</em>) method to the GamePiece class:<br />	<pre class='prettyprint'>	<br />public Rectangle GetSourceRect()<br />	{<br />		int x = textureOffsetX;<br />		int y = textureOffsetY;<br />	<br />		if (pieceSuffix.Contains("W"))<br />			x += PieceWidth + texturePaddingX;<br />	<br />		y += (Array.IndexOf(PieceTypes, pieceType) * <br />			 (PieceHeight + texturePaddingY));<br />	<br />	<br />		return new Rectangle(x, y, PieceWidth, PieceHeight);<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
Initially, the x and y variables are set to the <em class='bbc'>textureOffsets</em> that are listed in the GamePiece class declaration. This means they will both start with a value of one.<br />
<br />
Because the sprite sheet is organized with a single type of pipe on each row, the x coordinate of the <em class='bbc'>Rectangle</em> is the easiest to determine. If the <em class='bbc'>pieceSuffix</em> variable does not contain a W (signifying that the piece is filled with water), the x coordinate will simply remain 1.<br />
<br />
If the <em class='bbc'>pieceSuffix</em> does contain the letter W (indicating the pipe is filled), the width of a piece (40 pixels), along with the padding between the pieces (1 pixel), are added to the x coordinate of the source <em class='bbc'>Rectangle</em>. This shifts the x coordinate from 1 to a value of <strong class='bbc'>1</strong> + <strong class='bbc'>40</strong> + <strong class='bbc'>1</strong>, or <strong class='bbc'>42</strong> which corresponds to the second column of images on the sprite sheet.<br />
<br />
To determine the y coordinate for the source rectangle, <em class='bbc'>Array.IndexOf(PieceTypes, pieceType)</em> is used to locate the <em class='bbc'>pieceType</em> within the <em class='bbc'>PieceTypes</em> array. The index that is returned represents the position of the tile on the sprite sheet (because the array is organized in the same order as the pieces on the image). For example, <em class='bbc'>Left</em>,<em class='bbc'>Right</em> returns zero, while <em class='bbc'>Top</em>,<em class='bbc'>Bottom</em> returns one and <em class='bbc'>Empty</em> returns six.<br />
<br />
The value of this index is multiplied by the height of a game piece plus the padding between pieces. For our sprite sheet, an index of 2 (the <em class='bbc'>Left</em>,<em class='bbc'>Top</em> piece) would be multiplied by <strong class='bbc'>41</strong> (<em class='bbc'>PieceHeight</em> of <strong class='bbc'>40</strong> plus <em class='bbc'>texturePaddingY</em> of <strong class='bbc'>1</strong>) resulting in a value of <strong class='bbc'>82</strong> being added to the y variable.<br />
<br />
Finally, the new <em class='bbc'>Rectangle</em> is returned, comprised of the calculated x and y coordinates and the predefined width and height of a piece:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_05.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>The GameBoard class</strong></span><br />
Now that we have a way to represent pieces in memory, the next logical step is to create a way to represent an entire board of playing pieces.<br />
<br />
The game board is a two-dimensional array of GamePiece objects, and we can build in some additional functionality to allow our code to interact with pieces on the game board by their X and Y coordinates.<br />
<br />
The GameBoard class needs to:<br />
<ul class='bbc'><br /><li>Store a GamePiece object for each square on the game board<br /></li><li>Provide methods for code using the GameBoard to update individual pieces by passing calls through to the underlying GamePiece instances<br /></li><li>Randomly assign a piece type to a GamePiece<br /></li><li>Set and clear the "Filled with water" flags on individual GamePieces<br /></li><li>Determine which pipes should be filled with water based on their position and orientation and mark them as filled<br /></li><li>Return lists of potentially scoring water chains to code using the GameBoard<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - create the GameBoard.cs class</strong></span><ul class='bbcol decimal'><br /><li>As you did to create the GamePiece class, right-click on <strong class='bbc'>Flood Control</strong> in <strong class='bbc'>Solution Explorer</strong> and select <strong class='bbc'>Add | Class...</strong> Name the new class file <strong class='bbc'>GameBoard.cs</strong>.<br /></li><li>Add the using directive for the XNA framework at the top of the file:<br />	<pre class='prettyprint'>	<br />using Microsoft.Xna.Framework;	<br />	</pre><br /></li><li>Add the following declarations to the GameBoard class:<br />	<pre class='prettyprint'>	<br />Random rand = new Random();<br />	<br />	public const int GameBoardWidth = 8;<br />	public const int GameBoardHeight = 10;<br />	<br />	private GamePiece&#91;,&#93; boardSquares = <br />	  new GamePiece&#91;GameBoardWidth, GameBoardHeight&#93;;<br />	<br />	private List WaterTracker = new List();	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
We used the Random class in SquareChase to generate random numbers. Since we will need to randomly generate pieces to add to the game board, we need an instance of Random in the GameBoard class.<br />
<br />
The two constants and the boardSquares array provide the storage mechanism for the GamePiece objects that make up the 8 by 10 piece board.<br />
<br />
Finally, a List of Vector2 objects is declared that we will use to identify scoring pipe combinations. The List class is one of C#'s Generic Collection classes—classes that use the Generic templates (angle brackets) we first saw when loading a texture for SquareChase. Each of the Collection classes can be used to store multiple items of the same type, with different methods to access the entries in the collection. We will use several of the Collection classes in our projects. The List class is much like an array, except that we can add any number of values at runtime, and remove values in the List if necessary.<br />
<br />
A <em class='bbc'>Vector2</em> is a structure defined by the XNA Framework that holds two floating point values, X and Y. Together the two values represent a vector pointing in any direction from an imaginary origin (0, 0) point. We will use <em class='bbc'>Vector2</em> structures to represent the locations on our game board in Flood Control, placing the origin in the upper left corner of the board.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Creating the game board</strong></span><br />
If we were to try to use any of the elements in the <em class='bbc'>boardSquares</em> array, at this point, we would get a Null Reference exception because none of the GamePiece objects in the array have actually been created yet.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - initialize the game board</strong></span><ul class='bbcol decimal'><br /><li>Add a constructor to the GameBoard class:<br />	<pre class='prettyprint'>	<br />public GameBoard()<br />	{<br />	  ClearBoard();<br />	}	<br />	</pre><br /></li><li>Add the <em class='bbc'>ClearBoard()</em> helper method to the GameBoard class:<br />	<pre class='prettyprint'>	<br />public void ClearBoard()<br />	{<br />		for (int x = 0; x		 for (int y = 0; y			 boardSquares&#91;x, y&#93; = new GamePiece("Empty");<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
When a new instance of the <em class='bbc'>GameBoard</em> class is created, the constructor calls the <em class='bbc'>ClearBoard()</em> helper method, which simply creates 80 empty game pieces and assigns them to each element in the array.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'><strong class='bbc'>Helper methods</strong><br />
Why not simply put the two for loops that clear the board into the GameBoard constructor? Splitting the work into methods that accomplish a single purpose greatly helps to keep your code both readable and maintainable. Additionally, by splitting ClearBoard() out as its own method we can call it separately from the constructor. When we add increasing difficulty levels, we  make use of this call when a new level starts.</em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Updating GamePieces</strong></span><br />
The <em class='bbc'>boardSquares</em> array in the GameBoard class is declared as a private member, meaning that the code that uses the GameBoard will not have direct access to the pieces contained on the board.<br />
<br />
In order for code in our Game1 class to interact with a GamePiece, we will need to create public methods in the GameBoard class that expose the pieces in boardSquares.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - manipulating the game board</strong></span><ul class='bbcol decimal'><br /><li>Add public methods to the GameBoard class to interact with GamePiece:<br />	<pre class='prettyprint'>	<br />public void RotatePiece(int x, int y, bool clockwise)<br />	{<br />		boardSquares&#91;x, y&#93;.RotatePiece(clockwise);<br />	}<br />	<br />	public Rectangle GetSourceRect(int x, int y)<br />	{<br />		return boardSquares&#91;x, y&#93;.GetSourceRect();<br />	}<br />	<br />	public string GetSquare(int x, int y)<br />	{<br />		return boardSquares&#91;x, y&#93;.PieceType;<br />	}<br />	<br />	public void SetSquare(int x, int y, string pieceName)<br />	{<br />		boardSquares&#91;x, y&#93;.SetPiece(pieceName);<br />	}<br />	<br />	public bool HasConnector(int x, int y, string direction)<br />	{<br />		return boardSquares&#91;x, y&#93;.HasConnector(direction); <br />	}<br />	<br />	public void RandomPiece(int x, int y)<br />	{<br />	  boardSquares&#91;x, y&#93;.SetPiece(GamePiece.PieceTypes&#91;rand.Next(0, <br />		   GamePiece.MaxPlayablePieceIndex+1)&#93;);<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
<em class='bbc'>RotatePiece()</em>, <em class='bbc'>GetSourceRect()</em>, <em class='bbc'>GetSquare()</em>, <em class='bbc'>SetSquare()</em>, and <em class='bbc'>HasConnector()</em> methods simply locate the appropriate <em class='bbc'>GamePiece</em> within the <em class='bbc'>boardSquares</em> array and pass on the function request to the piece.<br />
<br />
The <em class='bbc'>RandomPiece()</em> method uses the rand object to get a random value from the <em class='bbc'>PieceTypes</em> array and assign it to a <em class='bbc'>GamePiece</em>. It is important to remember that with the Random.Next() method overload used here, the second parameter is non-inclusive. In order to generate a random number from 0 through 5, the second parameter needs to be 6.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Filling in the gaps</strong></span><br />
Whenever the player completes a scoring chain, the pieces in that chain are removed from the board. Any pieces above them fall down into the vacated spots and new pieces are generated.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - filling in the gaps</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>FillFromAbove()</em> method to the GameBoard class.<br />	<pre class='prettyprint'>	<br />public void FillFromAbove(int x, int y)<br />	{<br />		int rowLookup = y - 1;<br />	<br />		while (rowLookup &gt;= 0)<br />		{<br />			if (GetSquare(x, rowLookup) != "Empty")<br />			{<br />				SetSquare(x, y,<br />				  GetSquare(x, rowLookup));<br />				SetSquare(x, rowLookup, "Empty");<br />				rowLookup = -1;<br />			}<br />			rowLookup--;<br />		}<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
Given a square to fill, <em class='bbc'>FillFromAbove()</em> looks at the piece directly above to see if it is marked as Empty. If it is, the method will subtract one from rowLookup and start over until it reaches the top of the board. If no non-empty pieces are found when the top of the board is reached, the method does nothing and exits.<br />
<br />
When a non-empty piece is found, it is copied to the destination square, and the copied piece is changed to an empty piece. The <em class='bbc'>rowLookup</em> variable is set to -1 to ensure that the loop does not continue to run.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Generating new pieces</strong></span><br />
We can create a single method that will fill any empty spaces on the game board, and use it when the game begins and when pieces are removed from the board after scoring.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - generating new pieces</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>GenerateNewPieces()</em> method to the GameBoard class:<br />	<pre class='prettyprint'>	<br />public void GenerateNewPieces(bool dropSquares)<br />	{<br />	<br />		if (dropSquares)<br />		{<br />			for (int x = 0; x		 {<br />				for (int y = GameBoard.GameBoardHeight - 1; y &gt;= 0; y--)<br />				{<br />					if (GetSquare(x, y) == "Empty")<br />					{<br />						FillFromAbove(x, y);<br />					}<br />				}<br />			}<br />		}<br />	<br />		for (int y = 0; y		 for (int x = 0; x		 {<br />				if (GetSquare(x, y) == "Empty")<br />				{<br />					RandomPiece(x, y);<br />				}<br />			}<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
When <em class='bbc'>GenerateNewPieces()</em> is called with "true" passed as dropSquares, the looping logic processes one column at a time from the bottom up. When it finds an empty square it calls <em class='bbc'>FillFromAbove()</em> to pull a filled square from above into that location.<br />
<br />
The reason the processing order is important here is that, by filling a lower square from a higher position, that higher position will become empty. It, in turn, will need to be filled from above.<br />
<br />
After the holes are filled (or if <em class='bbc'>dropSquares</em> is set to false) <em class='bbc'>GenerateNewPieces()</em> examines each square in <em class='bbc'>boardSquares</em> and asks it to generate random pieces for each square that contains an empty piece.<br />
<br />
<br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Water filled pipes</strong></span><br />
Whether or not a pipe is filled with water is managed separately from its orientation. Rotating a single pipe could change the water-filled status of any number of other pipes without changing their rotation.<br />
<br />
Instead of filling and emptying individual pipes, however, it is easier to empty all of the pipes and then refill the pipes that need to be marked as having water in them.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - water in the pipes</strong></span><ul class='bbcol decimal'><br /><li>Add a method to the GameBoard class to clear the water marker from all pieces:<br />	<pre class='prettyprint'>	<br />public void ResetWater()<br />	{<br />		for (int y = 0; y		 for (int x = 0; x			 boardSquares&#91;x,y&#93;.RemoveSuffix("W");<br />	}	<br />	</pre><br /></li><li>Add a method to the GameBoard class to fill an individual piece with water:<br />	<pre class='prettyprint'>	<br />public void FillPiece(int X, int Y)<br />	{<br />		boardSquares&#91;X,Y&#93;.AddSuffix("W");<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The <em class='bbc'>ResetWater()</em> method simply loops through each item in the <em class='bbc'>boardSquares</em> array and removes the W suffix from the GamePiece. Similarly, to fill a piece with water, the <em class='bbc'>FillPiece()</em> method adds the W suffix to the GamePiece. Recall that by having a W suffix, the <em class='bbc'>GetSourceRect()</em> method of GamePiece shifts the source rectangle one tile to the right on the sprite sheet, returning the image for a pipe filled with water instead of an empty pipe.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Propagating water</strong></span><br />
Now that we can fill individual pipes with water, we can write the logic to determine which pipes should be filled depending on their orientation.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - making the connection</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>PropagateWater()</em> method to the GameBoard class:<br />	<pre class='prettyprint'>	<br />public void PropagateWater(int x, int y, string fromDirection)<br />	{<br />		if ((y &gt;= 0) && (y		 (x &gt;= 0) && (x	 {<br />			if (boardSquares&#91;x,y&#93;.HasConnector(fromDirection) &&<br />				!boardSquares&#91;x,y&#93;.Suffix.Contains("W"))<br />			{<br />				FillPiece(x, y);<br />				WaterTracker.Add(new Vector2(x, y));<br />				foreach (string end in<br />						 boardSquares&#91;x,y&#93;.GetOtherEnds(fromDirection))<br />					switch (end)<br />						  {<br />						case "Left": PropagateWater(x - 1, y, "Right");<br />							break;<br />						case "Right": PropagateWater(x + 1, y, "Left");<br />							break;<br />						case "Top": PropagateWater(x, y - 1, "Bottom");<br />							break;<br />						case "Bottom": PropagateWater(x, y + 1, "Top");<br />							break;<br />					}<br />			}<br />		}<br />	}	<br />	</pre><br /></li><li>Add the <em class='bbc'>GetWaterChain()</em> method to the GameBoard class:<br />	<pre class='prettyprint'>	<br />public List GetWaterChain(int y)<br />	{<br />		WaterTracker.Clear();<br />		PropagateWater(0, y, "Left");<br />		return WaterTracker;<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
Together, <em class='bbc'>GetWaterChain()</em> and <em class='bbc'>PropagateWater()</em> are the keys to the entire Flood Control game, so understanding how they work is vital. When the game code wants to know if the player has completed a scoring row, it will call the <em class='bbc'>GetWaterChain()</em> method once for each row on the game board:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_06.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The WaterTracker list is cleared and <em class='bbc'>GetWaterChain()</em> calls <em class='bbc'>PropagateWater()</em> for the first square in the row, indicating that the water is coming from the <strong class='bbc'>Left</strong> direction.<br />
<br />
The <em class='bbc'>PropagateWater()</em> method checks to make sure that the <strong class='bbc'>x</strong> and <strong class='bbc'>y</strong> coordinates passed to it exist within the board and, if they do, checks to see if the piece at that location has a connector matching the fromDirection parameter and that the piece is not already filled with water. If all of these conditions are met, that piece gets filled with water and added to the WaterTracker list.<br />
<br />
Finally, <em class='bbc'>PropagateWater()</em> gets a list of all other directions that the piece contains (in other words, all directions the piece contains that do not match fromDirection). For each of these directions <em class='bbc'>PropagateWater()</em> recursively calls itself, passing in the new <strong class='bbc'>x</strong> and <strong class='bbc'>y</strong> location as well as the direction the water is coming from.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Building the game</strong></span><br />
We now have the component classes we need to build the Flood Control game, so it is time to bring the pieces together in the Game1 class.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Declarations</strong></span><br />
We only need a handful of game-wide declarations to manage things like the game board, the player's score, and the game state.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - Game1 declarations</strong></span><ul class='bbcol decimal'><br /><li>Double click on the Game1.cs file in <strong class='bbc'>Solution Explorer</strong> to reactivate the <strong class='bbc'>Game1.cs</strong> code file wind&#111;w.<br /></li><li>Add the following declarations to the Game1 class member declaration area:<br />	<pre class='prettyprint'>	<br />GameBoard gameBoard;<br />	<br />	Vector2 gameBoardDisplayOrigin = new Vector2(70, 89);<br />	<br />	int playerScore = 0;<br />	<br />	enum GameStates { TitleScreen, Playing };<br />	GameStates gameState = GameStates.TitleScreen;<br />	<br />	Rectangle EmptyPiece = new Rectangle(1, 247, 40, 40);<br />	<br />	const float MinTimeSinceLastInput = 0.25f;<br />	float timeSinceLastInput = 0.0f;	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The <em class='bbc'>gameBoard</em> instance of GameBoard will hold all of the playing pieces, while the <em class='bbc'>gameBoardDisplayOrigin</em> vector points to where on the screen the board will be drawn. Using a vector like this makes it easy to move the board in the event that you wish to change the layout of your game screen.<br />
<br />
As we did in SquareChase, we store the player's score and will display it in the window title bar.<br />
<br />
In order to implement a simple game state mechanism, we define two game states. When in the <em class='bbc'>TitleScreen</em> state, the game's title image will be displayed and the game will wait until the user presses the <em class='bbc'>Space bar</em> to start the game. The state will then switch to <em class='bbc'>Playing</em>, which will display the game board and allow the user to play.<br />
<br />
If you look at the sprite sheet for the game, the pipe images themselves do not cover the entire 40x40 pixel area of a game square. In order to provide a background, an empty tile image will be drawn in each square first. The <em class='bbc'>EmptyPiece Rectangle</em> is a convenient pointer to where the empty background is located on the sprite sheet.<br />
<br />
Just as we used an accumulating timer in SquareChase to determine how long to leave a square in place before moving it to a new location, we will use the same timing mechanism to make sure that a single click by the user does not send a game piece spinning unpredictably. Remember that the <em class='bbc'>Update()</em> method will be executing up to 60 times each second, so slowing the pace of user input is necessary to make the game respond in a way that feels natural.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Initialization</strong></span><br />
Before we can use the gameBoard instance, it needs to be initialized. We will also need to enable the mouse cursor.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - updating the Initialize() method</strong></span><ul class='bbcol decimal'><br /><li>Update the <em class='bbc'>Initialize()</em> method to include the following:<br />	<pre class='prettyprint'>	<br />this.IsMouseVisible = true;<br />	graphics.PreferredBackBufferWidth = 800;<br />	graphics.PreferredBackBufferHeight = 600;<br />	graphics.ApplyChanges();<br />	gameBoard = new GameBoard();	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
After making the mouse cursor visible, we set the size of the <em class='bbc'>BackBuffer</em> to <em class='bbc'>800</em> by <em class='bbc'>600</em> pixels. On Windows, this will size the game window to <em class='bbc'>800</em> by <em class='bbc'>600</em> pixels as well.<br />
<br />
The constructor for the GameBoard class calls the <em class='bbc'>ClearBoard()</em> member, so each of the pieces on the <em class='bbc'>gameBoard</em> instance will be set to <em class='bbc'>Empty</em>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Draw() method - the title screen</strong></span><br />
In the declarations section, we established two possible game states. The first (and default) state is <em class='bbc'>GameStates.TitleScreen</em>, indicating that the game should not be processing actual game play, but should instead be displaying the game's logo and waiting for the user to begin the game.<br />
<br />
Time for action - drawing the screen - the title screen<br />
<ul class='bbcol decimal'><br /><li>Modify the <em class='bbc'>Draw()</em> method of Game1 to include the code necessary to draw the game's title screen after <em class='bbc'>GraphicsDevice.Clear(Color.CornflowerBlue)</em>;<br />	<pre class='prettyprint'>	<br />if (gameState == GameStates.TitleScreen)<br />	{<br />		spriteBatch.Begin();<br />		spriteBatch.Draw(titleScreen,<br />			new Rectangle(0, 0,<br />				this.wind&#111;w.ClientBounds.Width,<br />				this.wind&#111;w.ClientBounds.Height),<br />			Color.White);<br />		spriteBatch.End();<br />	}	<br />	</pre><br /></li><li>Run the game and verify that the title screen is displayed. You will not be able to start the game however, as we haven't written the <em class='bbc'>Update()</em> method yet.<br /></li><li>Stop the game by pressing <em class='bbc'>Alt</em> + <em class='bbc'>F4</em>.<br /></li></ul><br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/0669_02_07.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The title screen is drawn with a single call to the <em class='bbc'>Draw()</em> method of the <em class='bbc'>spriteBatch</em> object. Since the title screen will cover the entire display, a rectangle is created that is equal to the width and height of the game wind&#111;w.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>The Draw() method - the play screen</strong></span><br />
Finally, we are ready to display the playing pieces on the screen. We will accomplish this by using a simple loop to display all of the playing pieces in the <em class='bbc'>gameBoard</em> object.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - drawing the screen - the play screen</strong></span><ul class='bbcol decimal'><br /><li>Update the <em class='bbc'>Draw()</em> method of the Game1 class to add the code to draw the game board after the code that draws the title screen:<br />	<pre class='prettyprint'>	<br />if (gameState == GameStates.Playing)<br />	{<br />		spriteBatch.Begin();<br />	<br />		spriteBatch.Draw(backgroundScreen,<br />			new Rectangle(0, 0,<br />				this.wind&#111;w.ClientBounds.Width,<br />				this.wind&#111;w.ClientBounds.Height),<br />			Color.White);<br />	<br />		for (int x = 0; x		 for (int y = 0; y		 {<br />				int pixelX = (int)gameBoardDisplayOrigin.X + <br />					(x * GamePiece.PieceWidth);<br />				int pixelY = (int)gameBoardDisplayOrigin.Y + <br />					(y * GamePiece.PieceHeight);<br />	<br />				spriteBatch.Draw(<br />					playingPieces,<br />					new Rectangle(<br />					  pixelX, <br />					  pixelY, <br />					  GamePiece.PieceWidth, <br />					  GamePiece.PieceHeight),<br />					EmptyPiece,<br />					Color.White);<br />	<br />				spriteBatch.Draw(<br />					playingPieces, new Rectangle(<br />						pixelX, <br />						pixelY, <br />						GamePiece.PieceWidth, <br />						GamePiece.PieceHeight),<br />					gameBoard.GetSourceRect(x, y),<br />					Color.White);<br />			}<br />	<br />		this.wind&#111;w.Title = playerScore.ToString();<br />	<br />		spriteBatch.End();<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
As you can see, the code to draw the game board begins exactly like the code to draw the title screen. Since we are using a background image that takes up the full screen, we draw it exactly the same way as the title screen.<br />
<br />
Next, we simply loop through gameBoard to draw the squares. The <em class='bbc'>pixelX</em> and <em class='bbc'>pixelY</em> variables are calculated to determine where on the screen each of the game pieces will be drawn. Since both x and y begin at 0, the <em class='bbc'>(x * GamePiece.PieceWidth)</em> and <em class='bbc'>(y * GamePiece.PieceHeight)</em> will also be equal to zero, resulting in the first square being drawn at the location specified by the <em class='bbc'>gameBoardDisplayOrigin</em> vector.<br />
<br />
As x increments, each new piece is drawn 40 pixels further to the right than the previous piece. After a row has been completed, the y value increments, and a new row is started 40 pixels below the previous row.<br />
<br />
The first <em class='bbc'>spriteBatch.Draw()</em> call uses Rectangle(<em class='bbc'>pixelX</em>, <em class='bbc'>pixelY</em>, <em class='bbc'>GamePiece.PieceWidth</em>, <em class='bbc'>GamePiece.PieceHeight</em>) as the destination rectangle and <em class='bbc'>EmptyPiece</em> as the source rectangle. Recall that we added this <em class='bbc'>Rectangle</em> to our declarations area as a shortcut to the location of the empty piece on the sprite sheet.<br />
<br />
The second <em class='bbc'>spriteBatch.Draw()</em> call uses the same destination rectangle, overlaying the playing piece image onto the empty piece that was just drawn. It asks the <em class='bbc'>gameBoard</em> to provide the source rectangle for the piece it needs to draw.<br />
<br />
The player's score is displayed in the window title bar, and <em class='bbc'>spriteBatch.End()</em> is called to finish up the <em class='bbc'>Draw()</em> method.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Keeping score</strong></span><br />
Longer chains of filled water pipes score the player more points. However, if we were to simply assign a single point to each piece in the pipe chain, there would be no scoring advantage to making longer chains versus quickly making shorter chains.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - scores and scoring chains</strong></span><ul class='bbcol decimal'><br /><li>Add a method to the Game1 class to calculate a score based on the number of pipes used:<br />	<pre class='prettyprint'>	<br />private int DetermineScore(int SquareCount)<br />	{<br />		return (int)((Math.Pow((SquareCount/5), 2) + SquareCount)*10);<br />	}	<br />	</pre><br /></li><li>Add a method to evaluate a chain to determine if it scores and process it:<br />	<pre class='prettyprint'>	<br />private void CheckScoringChain(List WaterChain)<br />	{<br />	<br />		if (WaterChain.Count &gt; 0)<br />		{<br />			Vector2 LastPipe = WaterChain&#91;WaterChain.Count - 1&#93;;<br />	<br />			if (LastPipe.X == GameBoard.GameBoardWidth - 1)<br />			{<br />				if (gameBoard.HasConnector(<br />					(int)LastPipe.X, (int)LastPipe.Y, "Right"))<br />				{<br />					playerScore += DetermineScore(WaterChain.Count);<br />	<br />					foreach (Vector2 ScoringSquare in WaterChain)<br />					{<br />						gameBoard.SetSquare((int)ScoringSquare.X,<br />							(int)ScoringSquare.Y, "Empty");<br />					}<br />				}<br />			}<br />		}<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
<em class='bbc'>DetermineScore()</em> accepts the number of squares in a scoring chain and returns a score value for that chain. The number of squares in the chain is divided by 5, and that number is squared. The initial number of squares is added to the result, and the final amount is multiplied by 10.<br />
<br />
<pre class='prettyprint'><br />Score = (((Squares / 5) ^ 2) + Squares) * 10<br /><br /></pre><br />
For example, a minimum scoring chain would be 8 squares (forming a straight line across the board). This would result in 1 squared plus 8 times 10, or 90 points. If a chain had 18 squares the result would be 3 squared plus 18 times 10, or 270 points. This makes longer scoring chains (especially increments of five squares) award much higher scores than a series of shorter chains.<br />
<br />
The <em class='bbc'>CheckScoringRow()</em> method makes sure that there are entries in the <em class='bbc'>WaterChain</em> list, and then examines the last piece in the chain and checks to see if it has an X value of 7 (the right-most column on the board). If it does, the <em class='bbc'>HasConnector()</em> method is checked to see if the last pipe has a connector to the right, indicating that it completes a chain across the board.<br />
<br />
After updating <em class='bbc'>playerScore</em> for the scoring row, <em class='bbc'>CheckScoringRow()</em> sets all of the pieces in the scoring row to Empty. They will be refilled by a subsequent call to the <em class='bbc'>GenerateNewPieces()</em> method.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Input handling</strong></span><br />
The player interacts with Flood Control using the mouse. For readability reasons, we will create a helper method that deals with mouse input and call it when appropriate from the <em class='bbc'>Update()</em> method.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - handling mouse input</strong></span><ul class='bbcol decimal'><br /><li>Add the <em class='bbc'>HandleMouseInput()</em> helper method to the Game1 class:<br />	<pre class='prettyprint'>	<br />private void HandleMouseInput(MouseState mouseState)<br />	{<br />	<br />		int x = ((mouseState.X -<br />			(int)gameBoardDisplayOrigin.X) / GamePiece.PieceWidth);<br />	<br />		int y = ((mouseState.Y -<br />			(int)gameBoardDisplayOrigin.Y) / GamePiece.PieceHeight);<br />	<br />		if ((x &gt;= 0) && (x	   (y &gt;= 0) && (y	 {<br />			if (mouseState.LeftButton == ButtonState.Pressed)<br />			{<br />				gameBoard.RotatePiece(x, y, false);<br />				timeSinceLastInput = 0.0f;<br />			}<br />	<br />			if (mouseState.RightButton == ButtonState.Pressed)<br />			{<br />				gameBoard.RotatePiece(x, y, true);<br />				timeSinceLastInput = 0.0f;<br />			}<br />		}<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The MouseState class reports the X and Y position of the mouse relative to the upper left corner of the wind&#111;w. What we really need to know is what square on the game board the mouse was over.<br />
<br />
We calculate this by taking the mouse position and subtracting the <em class='bbc'>gameBoardDisplayOrigin</em> from it and then dividing the remaining number by the size of a game board square.<br />
<br />
If the resulting X and Y locations fall within the game board, the left and right mouse buttons are checked. If the left button is pressed, the piece is rotated counterclockwise. The right button rotates the piece clockwise. In either case, the input delay timer is reset to <em class='bbc'>0.0f</em> since input was just processed.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Letting the player play!</strong></span><br />
Only one more section to go and you can begin playing Flood Control. We need to code the <em class='bbc'>Update()</em> method to tie together all of the game logic we have created so far.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Time for action - letting the player play</strong></span><ul class='bbcol decimal'><br /><li>Modify the <em class='bbc'>Update()</em> method of <em class='bbc'>Game1.cs</em> by adding the following before the call to <em class='bbc'>base.Update(gameTime)</em>:<br />	<pre class='prettyprint'>	<br />switch (gameState)<br />	{<br />		case GameStates.TitleScreen:<br />			if (Keyboard.GetState().IsKeyDown(Keys.Space))<br />			{<br />				gameBoard.ClearBoard();<br />				gameBoard.GenerateNewPieces(false);<br />				playerScore = 0;<br />				gameState = GameStates.Playing;<br />			}<br />			break;<br />	<br />		case GameStates.Playing:<br />			timeSinceLastInput +=<br />			  (float)gameTime.ElapsedGameTime.TotalSeconds;<br />	<br />			if (timeSinceLastInput &gt;= MinTimeSinceLastInput)<br />			{<br />				HandleMouseInput(Mouse.GetState());<br />			}<br />	<br />			gameBoard.ResetWater();<br />	<br />			for (int y = 0; y		 {<br />				CheckScoringChain(gameBoard.GetWaterChain(y));		<br />			}<br />	<br />			gameBoard.GenerateNewPieces(true);<br />	<br />			break;<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
The <em class='bbc'>Update()</em> method performs two different functions, depending on the current gameState value. If the game is in <em class='bbc'>TitleScreen</em> state, <em class='bbc'>Update()</em> examines the keyboard, waiting for the <em class='bbc'>Space bar</em> to be pressed. When it is, <em class='bbc'>Update()</em> clears the <em class='bbc'>gameBoard</em>, generates a new set of pieces, resets the player's score, and changes <em class='bbc'>gameState</em> to <em class='bbc'>Playing</em>.<br />
<br />
While in the <em class='bbc'>Playing</em> state, <em class='bbc'>Update()</em> accumulates time in <em class='bbc'>timeSinceLastInput</em> in order to pace the game play properly. If enough time has passed, the <em class='bbc'>HandleMouseInput()</em> method is called to allow the player to rotate game pieces.<br />
<br />
<em class='bbc'>Update()</em> then calls <em class='bbc'>ResetWater()</em> to clear the water flags for all pieces on the game board. This is followed by a loop that processes each row, starting at the top and working downward, using <em class='bbc'>CheckScoringChain()</em> and <em class='bbc'>GetWaterChain()</em> to "fill" any pieces that should have water in them and check the results of each row for completed chains.<br />
<br />
Finally, <em class='bbc'>GenerateNewPieces()</em> is called with the "true" parameter for <em class='bbc'>dropSquares</em>, which will cause <em class='bbc'>GenerateNewPieces()</em> to fill the empty holes from the squares above, and then generate new pipes to replace the empty squares.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Play the game</strong></span><br />
You now have all of the components assembled, and can run Flood Control and play!<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
You now have a working Flood Control game. In this article we have looked at:<br />
<ul class='bbc'><br /><li>Adding content objects to your project and loading them into textures at runtime using an instance of the ContentManager class<br /></li><li>Dividing the code into classes that represent objects in the game<br /></li><li>Building a recursive method<br /></li><li>Use the <em class='bbc'>SpriteBatch.Draw()</em> method to display images<br /></li><li>Divide the <em class='bbc'>Update()</em> and <em class='bbc'>Draw()</em> code into different units based on the current game state<br /></li></ul><br />
In the next article, we will spruce up the Flood Control game, adding animation by modifying the parameters of the <em class='bbc'>SpriteBatch.Draw()</em> method and creating text effects in order to make the game visually more appealing.]]></description>
		<pubDate>Wed, 01 Feb 2012 17:51:05 +0000</pubDate>
		<guid isPermaLink="false">f1b9528d5fb5c272d2f05a5b82611b3c</guid>
	</item>
	<item>
		<title>JIRA: Programming Workflows</title>
		<link>http://www.gamedev.net/page/resources/_/technical/general-programming/jira-programming-workflows-r2870</link>
		<description><![CDATA[In this article by <strong class='bbc'>Jobin Kuruvilla</strong> author of <a href='http://www.packtpub.com/jira-to-develop-customize-plugins-program-workflows-cookbook/book/sk/jira-abr1/1211?utm_source=sk_jira_abr1_1211&utm_medium=content&utm_campaign=sakina' class='bbc_url' title='External link' rel='nofollow external'>JIRA Development Cookbook</a>, we will cover:<ul class='bbc'><br /><li>Writing a workflow condition<br /></li><li>Writing a workflow validator<br /></li><li>Writing a workflow post function<br /></li><li>Editing an active workflow<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Introduction</strong></span><br />
Workflows are one standout feature which help users to transform JIRA into a user-friendly system. It helps users to define a lifecycle for the issues, depending on the issue type, the purpose for which they are using JIRA, and so on. As the Atlassian documentation says at <a href='http://confluence.atlassian.com/display/JIRA/Configuring+Workflow' class='bbc_url' title='External link' rel='nofollow external'>http://confluence.at...guring+Workflow</a>:<br />
<br />
<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>A JIRA workflow is the set of steps and transitions an issue goes through during its lifecycle. Workflows typically represent business processes. </em></p><br />
<br />
JIRA uses Opensymphony's OSWorkflow which is highly configurable, and more importantly pluggable, to cater for the various requirements. JIRA uses three different plugin modules to add extra functionalities into its workflow, which we will see in detail through this chapter.<br />
To make things easier, JIRA ships with a default workflow. We can't modify the default workflow, but can copy it into a new workflow and amend it to suit our needs. Before we go into the development aspect of a workflow, it makes sense to understand the various components of a workflow.<br />
The two most important components of a JIRA workflow are <strong class='bbc'>Step</strong> and <strong class='bbc'>Transition</strong>. At any point of time, an <strong class='bbc'>Issue</strong> will be in a step. Each step in the workflow is linked to a workflow Status (<a href='http://confluence.atlassian.com/display/JIRA/Defining+%27Status%27+Field+Values' class='bbc_url' title='External link' rel='nofollow external'>http://confluence.at...+%27Status%27+F</a> ield+Values) and it is this status that you will see on the issue at every stage. A transition, on the other hand, is a link between two steps. It allows the user to move an issue from one step to another (which essentially moves the issue from one status to another).<br />
Few key points to remember or understand about a workflow:<ul class='bbc'><br /><li>An issue can exist in only one step at any point in time<br /></li><li>A status can be mapped to only one step in the workflow<br /></li><li>A transition is always one-way. So if you need to go back to the previous step, you need a different transition<br /></li><li>A transition can optionally specify a screen to be presented to the user with the right fields on it<br /></li></ul><br />
OSWorkflow, and hence JIRA, provides us with the option of adding various elements into a workflow transition which can be summarized as follows:<ul class='bbc'><br /><li><strong class='bbc'>Conditions</strong>: A set of conditions that need to be satisfied before the user can actually see the workflow action (transition) on the issue<br /></li><li><strong class='bbc'>Validators</strong>: A set of validators which can be used to validate the user input before moving to the destination step<br /></li><li><strong class='bbc'>Post Functions</strong>: A set of actions which will be performed after the issue is successfully moved to the destination step<br /></li></ul><br />
These three elements give us the flexibility of handling the various use cases when an issue is moved from one status to another. JIRA ships with a few built-in conditions, validators, and post functions. There are plugins out there which also provide a wide variety of useful workflow elements. And if you still don't find the one you are looking for, JIRA lets us write them as plugins. We will see how to do it in the various recipes in this chapter. Hopefully, that gives you a fair idea about the various workflow elements. A lot more on JIRA workflows can be found in the JIRA documentation at <a href='http://confluence.atlassian.com/display/JIRA/Configuring+Workflow' class='bbc_url' title='External link' rel='nofollow external'>http://confluence.at...guring+Workflow</a>.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Writing a workflow condition</strong></span><br />
What are workflow conditions? They determine whether a workflow action is available or not. Considering the importance of a workflow in installations and how there is a need to restrict the actions either to a set of people, roles, and so on, or based on some criteria (for example, the field is not empty!), writing workflow conditions is inevitable.<br />
Workflow conditions are created with the help of the <em class='bbc'>workflow-condition</em> module. The following are the key attributes and elements supported. See <a href='http://confluence.atlassian.com/display/JIRADEV/Workflow+Plugin+Modules#WorkflowPluginModules-Conditions' class='bbc_url' title='External link' rel='nofollow external'>http://confluence.at...ules-Conditions</a> for more details.<br />
<br />
<strong class='bbc'>Attributes:</strong><br />
<br />
<br />
										<br />
Class to provide contexts for rendered velocity templates. Must implement the com.atlassian.jira.plugin.workflow.WorkflowPluginConditionFactory interface.						<br />
<strong class='bbc'>Elements:</strong><br />
<br />
<br />
										<br />
Class to determine whether the user can see the workflow transition. Must implement com.opensymphony.workflow.Condition. Recommended to extend the com.atlassian.jira.workflow.condition.AbstractJiraCondition class.						<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
As usual, create a skeleton plugin. Create an eclipse project using the skeleton plugin and we are good to go!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
In this recipe, let's assume we are going to develop a workflow condition that limits a transition only to the users belonging to a specific project role. The following are the steps to write our condition:<ul class='bbcol decimal'><br /><li>Define the inputs needed to configure the workflow condition.<br />			We need to implement the <em class='bbc'>WorkflowPluginFactory</em> interface, which mainly exists to provide velocity parameters to the templates. It will be used to extract the input parameters that are used in defining the condition. To make it clear, the inputs here are not the inputs while performing the workflow action, but the inputs in defining the condition.<br />			The condition factory class, <em class='bbc'>RoleConditionFactory</em> in this case, extends the <em class='bbc'>AbstractWorkflowPluginFactory</em>, which implements the <em class='bbc'>WorkflowPluginFactory </em>interface. There are three abstract methods that we should implement, that is, <em class='bbc'>getVelocityParamsForInput</em>, <em class='bbc'>getVelocityParamsForEdit</em>, and <em class='bbc'>getVelocityParamsForView</em>. All of them, as the name suggests, are used for populating the velocity parameters for the different scenarios.<br />			In our example, we need to limit the workflow action to a certain project role, and so we need to select the project role while defining the condition. The three methods will be implemented as follows:<br />			<pre class='prettyprint'>	<br />		private static final String ROLE_NAME = "role";<br />			private static final String ROLES = "roles";<br />			.......<br />			@Override<br />			  protected void getVelocityParamsForEdit(Map<br />			velocityParams, AbstractDescriptor descriptor) {<br />				velocityParams.put(ROLE, getRole(descriptor));<br />				velocityParams.put(ROLES, getProjectRoles());<br />			  }  @Override<br />			  protected void getVelocityParamsForInput(Map<br />			velocityParams) {<br />				velocityParams.put(ROLES, getProjectRoles());<br />			  }  @Override<br />			  protected void getVelocityParamsForView(Map<br />			velocityParams, AbstractDescriptor descriptor) {<br />				velocityParams.put(ROLE, getRole(descriptor));<br />			  }	<br />			</pre><br />			<br />		Let's look at the methods in detail:<br /><ul class='bbc'><br /><li><em class='bbc'>getVelocityParamsForInput</em>: This method defines the velocity parameters for input scenario, that is, when the user initially configures the workflow. In our example, we need to display all the project roles so that the user can select one to define the condition. The method getProjectRoles merely returns all the project roles and the collection of roles is then put into the velocity parameters with the key <em class='bbc'>ROLES</em>.<br /></li><li><em class='bbc'>getVelocityParamsForView</em>: This method defines the velocity parameters for the view scenario, that is, how the user sees the condition after it is configured. In our example, we have defined a role and so we should display it to the user after retrieving it back from the workflow descriptor. If you have noticed, the descriptor, which is an instance of <em class='bbc'>AbstractDescriptor</em>, is available as an argument in the method. All we need is to extract the role from the descriptor, which can be done as follows:<br />			<pre class='prettyprint'>	<br />		private ProjectRole getRole(AbstractDescriptor descriptor){<br />				if (!(descriptor instanceof ConditionDescriptor)) {<br />				  throw new IllegalArgumentException("Descriptor must be a<br />			ConditionDescriptor.");<br />				}<br />				<br />			  ConditionDescriptor functionDescriptor = (ConditionDescriptor)<br />			descriptor;<br />				<br />			 String role = (String) functionDescriptor.getArgs().get(ROLE);<br />				if (role!=null && role.trim().length()&gt;0)<br />				  return getProjectRole(role);<br />				else<br />				  return null;<br />			  }	<br />			</pre><br />			<br />		Just check if the descriptor is a condition descriptor or not, and then extract the role as shown in the preceding snippet.<br /></li><li><em class='bbc'>getVelocityParamsForEdit</em>: This method defines the velocity parameters for the edit scenario, that is, when the user modifies the existing condition. Here we need both the options and the selected value. Hence, we put both the project roles collection and the selected role on to the velocity parameters.<br /></li></ul>	<br /></li></ul><br />
	<ul class='bbc'><br /><li>The second step is to define the velocity templates for each of the three aforementioned scenarios: input, view, and edit. We can use the same template here for input and edit with a simple check to keep the old role selected for the edit scenario. Let us look at the templates:<br /><ul class='bbc'><br /><li><em class='bbc'>edit-roleCondition.vm</em>: Displays all project roles and highlights the already-selected one in the edit mode. In the input mode, the same template is reused, but the selected role will be null and hence a null check is done:<br />	<pre class='prettyprint'>	<br />	<br />	<br />		<br />		<br />			<br />			#foreach ($field in $roles)<br />						  #if ($role && (${field.id}==${role.id}))<br />					SELECTED<br />				#end<br />				&gt;$field.name<br />			#end<br />			<br />			<br />	Select the role in which the user<br />	should be present!<br />		<br />	<br />	<br />	</pre><br /></li><li><em class='bbc'>view-roleCondition.vm</em>: Displays the selected role:<br /></li></ul>	<pre class='prettyprint'>	<br />#if ($role)<br />	  User should have ${role.name} Role!<br />	#else<br />	  Role Not Defined<br />	#end	<br />	</pre><br />	<br />	</li><li>The third step is to write the actual condition. The condition class should extend the <em class='bbc'>AbstractJiraCondition</em> class. Here we need to implement the <em class='bbc'>passesCondition</em> method. In our case, we retrieve the project from the issue, check if the user has the appropriate project role, and return true if the user does:<br />	<pre class='prettyprint'>	<br />public boolean passesCondition(Map transientVars, Map args,<br />	PropertySet ps) throws WorkflowException {<br />		Issue issue = getIssue(transientVars);<br />		User user = getCaller(transientVars, args);	project project = issue.getProjectObject();<br />		String role = (String)args.get(ROLE);<br />		Long roleId = new Long(role);	return projectRoleManager.isUserInProjectRole(user,<br />	projectRoleManager.getProjectRole(roleId), project);<br />	}	<br />	</pre><br />	<br />The issue on which the condition is checked can be retrieved using the <em class='bbc'>getIssue</em> method implemented in the <em class='bbc'>AbstractJiraCondition</em> class. Similarly, the user can be retrieved using the <em class='bbc'>getCaller</em> method. In the preceding method, <em class='bbc'>projectRoleManager</em> is injected in the constructor, as we have seen before.<br /></li><li>We can see that the <em class='bbc'>ROLE</em> key is used to retrieve the project role ID from the args parameter in the <em class='bbc'>passesCondition</em> method. In order for the <em class='bbc'>ROLE</em> key to be available in the args map, we need to override the <em class='bbc'>getDescriptorParams</em> method in the condition factory class, <em class='bbc'>RoleConditionFactory </em>in this case. The <em class='bbc'>getDescriptorParams</em> method returns a map of sanitized parameters, which will be passed into workflow plugin instances from the values in an array form submitted by velocity, given a set of <em class='bbc'>name:value </em>parameters from the plugin configuration page (that is, the 'input-parameters' velocity template). In our case, the method is overridden as follows:<br />	<pre class='prettyprint'>	<br />public Map getDescriptorParams(Map<br />	conditionParams) {<br />		if (conditionParams != null &&<br />	conditionParams.containsKey(ROLE))<br />			{<br />				return EasyMap.build(ROLE,<br />	extractSingleParam(conditionParams, ROLE));<br />			}<br />			// Create a 'hard coded' parameter<br />			return EasyMap.build();<br />	  }	<br />	</pre><br />	<br />The method here builds a map of the <em class='bbc'>key:value</em> pair, where key is <em class='bbc'>ROLE</em> and the value is the role value entered in the input configuration page. The <em class='bbc'>extractSingleParam</em> method is implemented in the <em class='bbc'>AbstractWorkflowPluginFactory</em> class. The <em class='bbc'>extractMultipleParams</em> method can be used if there is more than one parameter to be extracted!<br /></li><li>All that is left now is to populate the <em class='bbc'>atlassian-plugin.xml</em> file with the aforementioned components. We use the <em class='bbc'>workflow-condition</em> module and it looks like the following block of code:<br />	<pre class='prettyprint'>	<br />	<br />	</pre><br /></li><li>Package the plugin and deploy it!<br />How it works...<br />After the plugin is deployed, we need to modify the workflow to include the condition. The following screenshot is how the condition looks when it is added initially. This, as you now know, is rendered using the input template:<br /></li></ul><br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-01.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
After the condition is added (that is, after selecting the <strong class='bbc'>Developers</strong> role), the view is rendered using the view template and looks as shown in the following screenshot:<br />
 <br />
<p class='bbc_center'>/sites/default/files/Article-Images/1803-04-02.png</p><br />
<br />
<p class='bbc_center'><em class='bbc'>(Move the mouse over the image to enlarge.)</em></p><br />
<br />
If you try to edit it, the screen will be rendered using the edit template, as shown in the following screenshot:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-03.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
Note that the <strong class='bbc'>Developers </strong>role is already selected.<br />
After the workflow is configured, when the user goes to an issue, he/she will be presented with the transition only if he/she is a member of the project role where the issue belongs. It is while viewing the issue that the <em class='bbc'>passesCondition</em> method in the <em class='bbc'>condition</em> class is executed.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Writing a workflow validator</strong></span><br />
Workflow validators are specific validators that check whether some pre-defined constraints are satisfied or not while progressing on a workflow. The constraints are configured in the workflow and the user will get an error if some of them are not satisfied. A typical example would be to check if a particular field is present or not before the issue is moved to a different status.<br />
Workflow validators are created with the help of the <em class='bbc'>workflow- validator</em> module. The following are the key attributes and elements supported.<br />
<br />
<strong class='bbc'>Attributes:</strong><br />
<br />
<br />
										<br />
Class to provide contexts for rendered velocity templates. Must implement the com.atlassian.jira.plugin.workflow.WorkflowPluginValidatorFactory interface.						<br />
<strong class='bbc'>Elements:</strong><br />
<br />
<br />
										<br />
Class which does the validation. Must implement com.opensymphony.workflow.Validator.						<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>See <a href='http://confluence.atlassian.com/display/JIRADEV/Workflow+Plugin+Modules#WorkflowPluginModules-Validators' class='bbc_url' title='External link' rel='nofollow external'>http://confluence.at...ules-Validators</a> for more details. </em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
As usual, create a skeleton plugin. Create an eclipse project using the skeleton plugin and we are good to go!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
Let us consider writing a validator that checks whether a particular field has a value entered on the issue or not! We can do this using the following steps:<br />
<ul class='bbcol decimal'><br /><li>Define the inputs needed to configure the workflow validator:<br />			We need to implement the <em class='bbc'>WorkflowPluginValidatorFactory</em> interface, which mainly exists to provide velocity parameters to the templates. It will be used to extract the input parameters that are used in defining the validator. To make it clear, the inputs here are not the input while performing the workflow action, but the inputs in defining the validator.<br />			The validator factory class, <em class='bbc'>FieldValidatorFactory</em> in this case, extends the <em class='bbc'>AbstractWorkflowPluginFactory</em> interface and implements the <em class='bbc'>WorkflowPluginValidatorFactory</em> interface. Just like conditions, there are three abstract methods that we should implement. They are <em class='bbc'>getVelocityParamsForInput</em>, <em class='bbc'>getVelocityParamsForEdit</em>, and <em class='bbc'>getVelocityParamsForView</em>. All of them, as the names suggest, are used for populating the velocity parameters in different scenarios.<br />			In our example, we have a single input field, which is the name of a custom field. The three methods will be implemented as follows:<br />			<pre class='prettyprint'>	<br />		@Override<br />			protected void getVelocityParamsForEdit(Map velocityParams,<br />			AbstractDescriptor descriptor) {<br />				velocityParams.put(FIELD_NAME, getFieldName(descriptor));<br />			  velocityParams.put(FIELDS, getCFFields());<br />			}@Override<br />			protected void getVelocityParamsForInput(Map velocityParams) {<br />				velocityParams.put(FIELDS, getCFFields());<br />			}@Override<br />			protected void getVelocityParamsForView(Map velocityParams,<br />			AbstractDescriptor descriptor) {<br />				velocityParams.put(FIELD_NAME, getFieldName(descriptor));<br />			}	<br />			</pre><br />			<br />		You may have noticed that the methods look quite similar to the ones in a workflow condition, except for the business logic! Let us look at the methods in detail:<br /><ul class='bbc'><br /><li><em class='bbc'>getVelocityParamsForInput</em>: This method defines the velocity parameters for input scenario, that is, when the user initially configures the workflow. In our example, we need to display all the custom fields, so that the user can select one to use in the validator. The method <em class='bbc'>getCFFields</em> returns all the custom fields and the collection of fields is then put into the velocity parameters with the key fields.<br /></li><li><em class='bbc'>getVelocityParamsForView</em>: This method defines the velocity parameters for the view scenario, that is, how the user sees the validator after it is configured. In our example, we have defined a field and so we should display it to the user after retrieving it back from the workflow descriptor. You may have noticed that the descriptor, which is an instance of <em class='bbc'>AbstractDescriptor</em>, is available as an argument in the method. All we need is to extract the field name from the descriptor, which can be done as follows:<br />			<pre class='prettyprint'>	<br />		private String getFieldName(AbstractDescriptor descriptor){<br />			  if (!(descriptor instanceof ValidatorDescriptor)) {<br />				throw new IllegalArgumentException('Descriptor must be a<br />			ValidatorDescriptor.');<br />			  }<br />			  <br />			  ValidatorDescriptor validatorDescriptor = (ValidatorDescriptor)<br />			descriptor;  String field = (String)<br />			validatorDescriptor.getArgs().get(FIELD_NAME);<br />			  if (field != null && field.trim().length() &gt; 0)<br />				return field;<br />			  else<br />				return NOT_DEFINED;<br />			}	<br />			</pre><br />			<br />		Just check if the descriptor is a validator descriptor or not and then extract the field as shown in the preceding snippet.<br /></li><li><em class='bbc'>getVelocityParamsForEdit</em>: This method defines the velocity parameters for the edit scenario, that is, when the user modifies the existing validator. Here we need both the options and the selected value. Hence we put both the custom fields' collection and the field name onto the velocity parameters.<br /></li></ul>	<br /></li></ul><br />
	<ul class='bbc'><br /><li>The second step is to define the velocity templates for each of the three aforementioned scenarios, namely, input, view, and edit. We can use the same template here for input and edit with a simple checking to keep the old field selected for the edit scenario. Let us look at the template:<br /><ul class='bbc'><br /><li><em class='bbc'>edit-fieldValidator.vm</em>: Displays all custom fields and highlights the already selected one in edit mode. In input mode, the field variable will be null, and so nothing is pre-selected:<br />	<pre class='prettyprint'>	<br />	<br />	<br />	  <br />	  <br />		<br />		#foreach ($cf in $fields)<br />				  #if ($cf.name.equals($field)) SELECTED #end<br />		  &gt;$cf.name<br />		#end<br />		<br />		<br />	Select the Custom Field to be validated<br />	for NULL<br />	  <br />	<br />	<br />	</pre><br /></li><li>view-fieldValidator.vm: Displays the selected field:<br />	<pre class='prettyprint'>	<br />#if ($field)<br />	  Field '$field' is Required!<br />	#end	<br />	</pre><br /></li></ul>	</li><li>The third step is to write the actual validator. The <em class='bbc'>validator</em> class should implement the <em class='bbc'>Validator</em> interface. All we need here is to implement the <em class='bbc'>validate</em> method. In our example, we retrieve the custom field value from the issue and throw an <em class='bbc'>InvalidInputException</em> if the value is null (empty):<br />	<pre class='prettyprint'>	<br />public void validate(Map transientVars, Map args, PropertySet ps)<br />	throws InvalidInputException, WorkflowException {<br />		Issue issue = (Issue) transientVars.get("issue");<br />		String field = (String) args.get(FIELD_NAME);	  CustomField customField =<br />	customFieldManager.getCustomFieldObjectByName(field);	if (customField!=null){<br />		  //Check if the custom field value is NULL<br />		  if (issue.getCustomFieldValue(customField) == null){<br />			throw new InvalidInputException("The field:"+field+" is<br />				 required!"); }<br />		}<br />	  }	<br />	</pre><br />	<br />The issue on which the validation is done can be retrieved from the <em class='bbc'>transientVars</em> map. <em class='bbc'>customFieldManager</em> is injected in the constructor as usual.<br /></li><li>All that is left now is to populate the <em class='bbc'>atlassian-plugin.xml</em> file with these components. We use the <em class='bbc'>workflow-validator</em> module, and it looks like the following block of code:<br />	<pre class='prettyprint'>	<br />class="com.jtricks.FieldValidatorFactory"&gt;<br />		Field Not Empty Workflow Validator	com.jtricks.FieldValidator	location="templates/com/jtricks/view-fieldValidator.vm"/&gt;<br />		location="templates/com/jtricks/edit-fieldValidator.vm"/&gt;<br />		location="templates/com/jtricks/edit-fieldValidator.vm"/&gt;	<br />	</pre><br /></li><li>Package the plugin and deploy it!<br />Note that we have stored the role name instead of the ID in the workflow, unlike what we did in the workflow condition. However, it is safe to use the ID because administrators can rename the roles, which would then need changes in the workflows.<br /><br />How it works...<br />After the plugin is deployed, we need to modify the workflow to include the validator. The following screenshot is how the validator looks when it is added initially. This, as you now know, is rendered using the input template:<br /></li></ul><br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-04.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
After the validator is added (after selecting the <strong class='bbc'>Test Number</strong> field), it is rendered using the view template and looks as follows:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-05.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
If you try to edit it, the screen will be rendered using the edit template, as shown in the following screenshot:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-06.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
Note that the <strong class='bbc'>Test Number</strong> field is already selected.<br />
After the workflow is configured, when the user goes to an issue and tries to progress it, the validator will check if the <strong class='bbc'>Test Number</strong> field has a value or not. It is at this point that the validate method in the <em class='bbc'>FieldValidator</em> class is executed.<br />
If the value is missing, you will see an error, as shown in the following screenshot:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-07.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Writing a workflow post function</strong></span><br />
Let us now look at workflow post functions. Workflow post functions are very effective and heavily used. They allow you to do a lot of things when you progress on the workflow on an issue. A lot of customizations and workarounds take this route!<br />
Workflow post functions are created with the help of the <em class='bbc'>workflow-function</em> module. The following are the key attributes and elements supported.<br />
<br />
<strong class='bbc'>Attributes:</strong><br />
<br />
<br />
										<br />
Class to provide contexts for rendered velocity templates. Must implement the com.atlassian.jira.plugin.workflow.WorkflowNoInputPluginFactory interface if the function doesn't need input, or com.atlassian.jira.plugin.workflow.WorkflowPluginFunctionFactory if it needs input.						<br />
<strong class='bbc'>Elements:</strong><br />
<br />
<br />
										<br />
Class which does the validation. Must implement com.opensymphony.workflow.FunctionProvider. Recommended to extend com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider, as it already implements many useful methods.						<br />
There are three other elements that can be used with a post function. They are explained as follows:<br />
<ul class='bbc'><br /><li><em class='bbc'>orderable </em>– (true/false) Specifies if this function can be re-ordered within the list of functions associated with a transition. The position within the list determines when the function actually executes.<br /></li><li><em class='bbc'>unique </em>– (true/false) Specifies if this function is unique, that is, if it is possible to add multiple instances of this post function on a single transition.<br /></li><li><em class='bbc'>deletable</em> – (true/false) Specifies if this function can be removed from a transition.<br /></li></ul><br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>See <a href='http://confluence.atlassian.com/display/JIRADEV/Workflow+Plugin+Modules#WorkflowPluginModules-Functions' class='bbc_url' title='External link' rel='nofollow external'>http://confluence.at...dules-Functions</a> for more details. </em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
As usual, create a skeleton plugin. Create an eclipse project using the skeleton plugin and we are good to go!<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
Assume we have a user custom field and we want to set the current user or a specified user name on to the custom field when a particular transition happens. A typical use case for this will be to store the name of the user who last resolved an issue. The following are the steps to write a generic post function that sets the current username or a username provided by the user on a user custom field:<br />
<ul class='bbcol decimal'><br /><li>Define the inputs needed to configure the workflow post function:<br />			As opposed to workflow conditions and validators, there are two interfaces available for a workflow post function factory class. If there are no inputs needed to configure the function, the factory class must implement <em class='bbc'>WorkflowNoInputPluginFactory</em>.<br />			An example will be to set the current user's name as the custom field value instead of the user configured name. If inputs are needed to configure the post function, the factory class must implement <em class='bbc'>WorkflowPluginFunctionFactory</em>. In our example, we take the username as the input.<br />			Both the interfaces mainly exist to provide velocity parameters to the templates. They will be used to extract the input parameters that are used in defining the functions. To make it clear, the inputs here are not the input while performing the workflow action, but the inputs in defining the post function.<br />			The function factory class, <em class='bbc'>SetUserCFFunctionFactory</em> in this case, extends the <em class='bbc'>AbstractWorkflowPluginFactory</em> and implements the <em class='bbc'>WorkflowPluginFunctionFactory</em> interface. Just like conditions, there are three abstract methods that we should implement, namely, <em class='bbc'>getVelocityParamsForInput</em>, <em class='bbc'>getVelocityParamsForEdit</em>, and <em class='bbc'>getVelocityParamsForView</em>. All of them, as the names suggest, are used for populating the velocity parameters for the different scenarios:<br />			<pre class='prettyprint'>	<br />		@Override<br />			protected void getVelocityParamsForEdit(Map velocityParams,<br />			AbstractDescriptor descriptor) {<br />				velocityParams.put(USER_NAME, getUserName(descriptor));<br />			}@Override<br />			protected void getVelocityParamsForInput(Map velocityParams) {<br />				velocityParams.put(USER_NAME, CURRENT_USER); }@Override<br />			protected void getVelocityParamsForView(Map velocityParams,<br />			AbstractDescriptor descriptor) {<br />				velocityParams.put(USER_NAME, getUserName(descriptor));<br />			}	<br />			</pre><br />			<br />		You may have noticed that the methods look very similar to the ones in workflow conditions or validators, except for the business logic! Let us look at the methods in detail:<br /><ul class='bbc'><br /><li><em class='bbc'>getVelocityParamsForInput</em> : This method defines the velocity parameters for input scenario, that is, when the user initially configures the workflow. In our example, we need to use a text field that captures the username to be added on the issue.<br /></li><li><em class='bbc'>getVelocityParamsForView</em>: This method defines the velocity parameters for the view scenario, that is, how the user sees the post function after it is configured. In our example, we have defined a field, and so we should display it to the user after retrieving it from the workflow descriptor. You may have noticed that the descriptor, which is an instance of <em class='bbc'>AbstractDescriptor</em>, is available as an argument in the method. All we need is to extract the username from the descriptor, which can be done as follows:<br />			<pre class='prettyprint'>	<br />		private String getUserName(AbstractDescriptor descriptor){<br />				if (!(descriptor instanceof FunctionDescriptor)) {<br />				  throw new IllegalArgumentException("Descriptor must be a<br />			 FunctionDescriptor.");<br />				}	FunctionDescriptor functionDescriptor =<br />			(FunctionDescriptor) descriptor;<br />			 String user = (String)<br />			functionDescriptor.getArgs().get(USER_NAME);<br />				if (user!=null && user.trim().length()&gt;0)<br />				  return user;<br />				else<br />				  return CURRENT_USER;<br />			  }	<br />			</pre><br />			<br />		Just check if the descriptor is a validator descriptor or not, and then extract the field as shown in the preceding snippet.<br /></li><li><em class='bbc'>getVelocityParamsForEdit</em>: This method defines the velocity parameters for the edit scenario, that is, when the user modifies the existing validator. Here we need both the options and the selected value. Hence, we put both the custom fields' collection and the field name on to the velocity parameters.<br /></li></ul>	<br /></li></ul><br />
	<ul class='bbc'><br /><li>The second step is to define the velocity templates for each of the three scenarios: input, view, and edit. We can use the same template here for input and edit with a simple checking to keep the old field selected for the edit scenario. Let us look at the templates:<br /><ul class='bbc'><br /><li><em class='bbc'>edit-userCFFunction.vm</em>: Displays all custom fields and highlights the already selected one in the edit mode:<br />	<pre class='prettyprint'>	<br />	<br />	</pre><br /></li><li><em class='bbc'>view-userCFFunction.vm</em> .displays the selected field:<br />	<pre class='prettyprint'>	<br />#if ($user)<br />	  The 'Test User' CF will be set with value : $user!<br />	#end	<br />	</pre><br /></li></ul>	</li><li>The third step is to write the actual function. The function class must extend the <em class='bbc'>AbstractJiraFunctionProvider</em> interface. All we need here is to implement the <em class='bbc'>execute</em> method. In our example, we retrieve the username from the issue and set it on the <em class='bbc'>Test User</em> custom field:<br />	<pre class='prettyprint'>	<br />public void execute(Map transientVars, Map args, PropertySet ps)<br />	throws WorkflowException {<br />		MutableIssue issue = getIssue(transientVars);<br />		User user = null;	if (args.get("user") != null) {<br />		  String userName = (String) args.get("user");<br />		  if (userName.equals("Current User")){<br />			// Set the current user here!<br />			user = authContext.getUser();<br />		  } else {<br />			user = userUtil.getUser(userName);<br />		  }<br />		} else {<br />		  // Set the current user here!<br />		  user = authContext.getUser();<br />		}<br />		// Now set the user value to the custom field<br />		CustomField userField =<br />	customFieldManager.getCustomFieldObjectByName("Test User");<br />		if (userField != null) {<br />		  try {<br />			setUserValue(issue, user, userField);<br />		  } catch (FieldLayoutStorageException e) {<br />			System.out.println("Error while setting the user Field");<br />		  }<br />		}<br />	 }	<br />	</pre><br />	<br />Like a validator, the issue on which the post function is executed can be retrieved using the <em class='bbc'>transientVars</em> map. The user can be retrieved from the <em class='bbc'>args</em> map.<br />	Here the <em class='bbc'>setUserValue </em>method simply sets the username on the passed custom field, as shown in the following block of code:	<br />	<pre class='prettyprint'>	<br />private void setUserValue(MutableIssue issue, User user,<br />	CustomField userField) throws FieldLayoutStorageException {<br />		issue.setCustomFieldValue(userField, user);<br />		Map modifiedFields = issue.getModifiedFields();<br />		FieldLayoutItem fieldLayoutItem =<br />	ComponentManager.getInstance().getFieldLayoutManager().getFieldLay<br />	out(issue).getFieldLayoutItem(userField);<br />		DefaultIssueChangeHolder issueChangeHolder = new<br />	DefaultIssueChangeHolder();<br />		final ModifiedValue modifiedValue = (ModifiedValue)<br />	modifiedFields.get(userField.getId());	<br />	userField.updateValue(fieldLayoutItem, issue, modifiedValue,<br />	issueChangeHolder);<br />	  }	<br />	</pre><br /></li><li>All that is left now is to populate the <em class='bbc'>atlassian-plugin.xml</em> file with these components. We use the <em class='bbc'>workflow-condition</em> module and it looks like the following block of code:<br />	<pre class='prettyprint'>	<br />	<br />	</pre><br /></li><li>Package the plugin and deploy it!<br />How it works...<br />After the plugin is deployed, we need to modify the workflow to include the function. The following is where the function appears along with the built-in ones:<br /></li></ul><br />
<p class='bbc_center'>/sites/default/files/Article-Images/1803-04-08.png</p><br />
<br />
Clicking on our post function takes us to the configuration page, shown next. This, as you now know, is rendered using the input template:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-09.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
After the function is added (after entering in the <strong class='bbc'>UserName</strong> field), it looks as follows:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-10.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
If you try to edit, the screen will be rendered using the edit template, as shown in the following screenshot:<br />
 <br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/1803-04-11.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
Note that the <strong class='bbc'>UserName</strong> field is already populated.<br />
After the workflow is configured, when the user executes the workflow action, the <strong class='bbc'>Test User</strong> custom field is set with the value <strong class='bbc'>jobinkk</strong>.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Editing an active workflow</strong></span><br />
We have seen how the workflow plays an important role in configuring our JIRA and how we can write plugins to add more workflow conditions, validators, and post functions. Once these plugins are added, we need to modify the workflow to include the newly created components at the appropriate transitions.<br />
Modifying an inactive workflow or creating a new workflow is pretty easy. You can add the conditions/validators/post functions when you create the transition or just click on the transition to modify them. But to edit an active workflow, there are a few more steps involved which we will see in this recipe.<br />
A workflow is active when it is being used in an active workflow scheme that is tied to a project. You can check whether a workflow is active by navigating to <strong class='bbc'>Administration Global Settings | Workflows|</strong>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
The following are the steps to edit an active workflow:<ul class='bbcol decimal'><br /><li>Login as a JIRA Administrator.<br /></li><li>Navigate to <strong class='bbc'>Administration Global Settings | Workflows|</strong>.<br /></li><li>Click on the <strong class='bbc'>Create a draft workflow</strong> link on the workflow you want to edit. The link can be found under the <strong class='bbc'>Operations</strong> column.<br /></li><li>Click on the step or transition that you want to modify.<br /></li><li>Make the changes. The changes won't be effective until the workflow is published.<br /></li><li>After all the changes are made, click on the <strong class='bbc'>publish this draft</strong> link at the top of the page if you are still viewing the modified workflow. You can also click on <strong class='bbc'>Publish </strong>under the <strong class='bbc'>Operations</strong> column while viewing all the workflows.<br /></li><li>Make a copy of the old workflow, when prompted, if you need a backup, and click on <strong class='bbc'>Publish</strong>.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
After making changes on the draft and clicking on <strong class='bbc'>Publish</strong>, the new workflow will be active. However, there are some limitations to this procedure, which are detailed as follows:<br />
<ul class='bbc'><br /><li>You can't delete an existing workflow step<br /></li><li>You can't edit the status associated with an existing step<br /></li><li>If an existing step has no outgoing transitions, you can't add any new outgoing transitions<br /></li><li>You can't change the step IDs for any existing steps<br /></li></ul><br />
If you want to overcome these limitations, you need to copy the workflow, modify the copy, and make it active by migrating the projects on to the new workflow.<br />
After the new workflow is active, any transitions on the issue will be based on the new workflow.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
If you want to modify an active workflow, thus overcoming some of the limitations aforementioned but don't want to go through the pain of migrating all the projects involved, you might want to look at modifying it directly in the JIRA database.<br />
Note that we should be careful about the workflow changes when we do this. For example, if there are issues in a status that is removed in the modified workflow, those issues will be stuck at the removed status. The same can happen for the removed steps.<br />
<br />
<strong class='bbc'>	Modifying workflows in JIRA database</strong><br />
<br />
The following are the steps to modify the workflows in the database:<ul class='bbcol decimal'><br /><li>export the workflow that needs to be modified into XML. You can do it using the XML link under the <strong class='bbc'>Operations</strong> column of a workflow.<br /></li><li>Modify the XML to include your changes (or alternatively, make changes in a copy of the JIRA workflow and export that as XML).<br /></li><li>Stop the JIRA instance.<br /></li><li>Connect to your JIRA database.<br /></li><li>Take a backup of the existing database. We can revert to this backup if anything goes wrong.<br /></li><li>Update the <em class='bbc'>JIRAWORKFLOWS </em>table to modify the <em class='bbc'>descriptor</em> column with the new XML file for the appropriate workflow. When the workflow XML is huge, it might be useful to rely on database-specific methods to update the table. For example, we can use Oracle XML database utilities (<a href='http://download.oracle.com/docs/cd/B12037_01/appdev.101/b10790/xdb01int.htm' class='bbc_url' title='External link' rel='nofollow external'>http://download.orac...90/xdb01int.htm</a>), if JIRA is connected to the Oracle database.<br /></li><li>Commit the changes and disconnect from the database.<br /></li><li>Start the JIRA instance.<br /></li><li>Re-index JIRA.<br /></li></ul>]]></description>
		<pubDate>Wed, 01 Feb 2012 03:30:23 +0000</pubDate>
		<guid isPermaLink="false">8c23abf230b77ce18d89e5c51ee4f509</guid>
	</item>
	<item>
		<title>.NET Generics 4.0: Container Patterns and Best...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/general-programming/net-generics-40-container-patterns-and-best-r2869</link>
		<description><![CDATA[There are several generic containers and generic algorithms available in the .NET Framework and a couple of other majorly accepted APIs such as Power Collections and C5.<br />
In this article by <strong class='bbc'>Sudipta Mukherjee</strong>, author of <a href='http://www.packtpub.com/net-generics-4-0-beginners-guide/book/vf/netgenerics-abr1/0112?utm_source=vf_netgenerics_abr1_0112&utm_medium=content&utm_campaign=veronica' class='bbc_url' title='External link' rel='nofollow external'>.NET Generics 4.0 Beginner’s Guide</a>, we will take a look at:<br />
<ul class='bbc'><br /><li>Generic container patterns: There are several patterns that are used more than the others in code bases that use Generics. Here, we shall walk through some of these very popular generic structures.<br /></li><li>Best practices: Here we shall walk through a list of best practices with succinct causes to back them.<br /></li></ul><br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Generic container patterns</strong></span><br />
There are several generic containers such as <em class='bbc'>List</em>, <em class='bbc'>Dictionary</em>, and so on. Now, let's take a look at some of the patterns involving these generic containers that show up more often in code.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How these are organized</strong></span><br />
Each pattern discussed in this article has a few sections. First is the title. This is written against the pattern sequence number. For example, the title for <em class='bbc'>Pattern 1</em> is <em class='bbc'>One-to-one mapping</em>. The <em class='bbc'>Pattern interface</em> section denotes the interface implementation of the pattern. So anything that conforms to that interface is a concrete implementation of that pattern. For example, <em class='bbc'>Dictionary</em> is a concrete implementation of <em class='bbc'>IDictionary</em>. The Example usages section shows some implementations where <em class='bbc'>TKey</em> and <em class='bbc'>TValue</em> are replaced with real data types such as <em class='bbc'>string</em> or <em class='bbc'>int</em>. The last section, as the name suggests, showcases some ideas where this pattern can be used.<br />
<br />
<strong class='bbc'>	Pattern 1: One-to-one mapping</strong><br />
<br />
One-to-one mapping maps one element to another.<br />
<br />
<strong class='bbc'>	Pattern interface</strong><br />
<br />
The following is an interface implementation of this pattern:<br />
<em class='bbc'>IDictionary</em><br />
<br />
<strong class='bbc'>	Some concrete implementations</strong><br />
<br />
Some concrete implementations of this pattern are as follows:<br />
<br />
<strong class='bbc'>	Example usages</strong><br />
<br />
The following are examples where <em class='bbc'>TKey</em> and <em class='bbc'>TValue</em> are replaced with real data types such as <em class='bbc'>string</em> or <em class='bbc'>int</em>:<br />
<ul class='bbc'><br /><li><em class='bbc'>Dictionary</em><br /></li><li><em class='bbc'>SortedDictionary</em><br /></li><li><em class='bbc'>SortedList</em><br /></li><li><em class='bbc'>Dictionary</em><br /></li></ul><br />
<strong class='bbc'>	Some situations where this pattern can be used</strong><br />
<br />
One-to-one mapping can be used in the following situations:<br />
<ul class='bbc'><br /><li>Mapping some class objects with a string ID<br /></li><li>Converting an <em class='bbc'>enum</em> to a string<br /></li><li>General conversion between types<br /></li><li>Find and replace algorithms where the <em class='bbc'>find</em> and <em class='bbc'>replace</em> strings become key and value pairs<br /></li><li>Implementing a state machine where each state has a description, which becomes the key, and the concrete implementation of the <em class='bbc'>IState</em> interface becomes the value of a structure such as <em class='bbc'>Dictionary</em><br /></li></ul><br />
<strong class='bbc'>	Pattern 2: One-to-many unique value mapping</strong><br />
<br />
One-to-many unique value mapping maps one element to a set of unique values.<br />
<br />
<strong class='bbc'>	Pattern interface</strong><br />
<br />
The following is an interface implementation of this pattern:<br />
<em class='bbc'>IDictionary></em><br />
<br />
<strong class='bbc'>	Some concrete implementations</strong><br />
<br />
Some concrete implementations of this pattern are as follows:<br />
<ul class='bbc'><br /><li><em class='bbc'>Dictionary></em><br /></li><li><em class='bbc'>SortedDictionary></em><br /></li><li><em class='bbc'>SortedList></em><br /></li><li><em class='bbc'>Dictionary></em><br /></li></ul><br />
<strong class='bbc'>	Example usages</strong><br />
<br />
The following are examples where <em class='bbc'>TKey</em> and <em class='bbc'>TValue</em> are replaced with real data types such as <em class='bbc'>string</em> or <em class='bbc'>int</em>:<br />
<br />
<strong class='bbc'>	Some situations where this pattern can be used</strong><br />
<br />
One-to-many unique value mapping can be used in the following situations:<br />
<ul class='bbc'><br /><li>Mapping all the anagrams of a given word<br /></li><li>Creating spell check where all spelling mistakes can be pre-calculated and stored as unique values<br /></li></ul><br />
<strong class='bbc'>	Pattern 3: One-to-many value mapping</strong><br />
<br />
One-to-many value mapping maps an element to a list of values. This might contain duplicates.<br />
<br />
<strong class='bbc'>	Pattern interface</strong><br />
<br />
The following are the interface implementations of this pattern:<br />
<br />
<strong class='bbc'>	Some concrete implementations</strong><br />
<br />
Some concrete implementations of this pattern are as follows:<br />
<ul class='bbc'><br /><li><em class='bbc'>Dictionary></em><br /></li><li><em class='bbc'>SortedDictionary></em><br /></li><li><em class='bbc'>SortedList></em><br /></li><li><em class='bbc'>Dictionary></em><br /></li></ul><br />
<strong class='bbc'>	Example usages</strong><br />
<br />
The following are examples where <em class='bbc'>TKey</em> and <em class='bbc'>TValue</em> are replaced with real data types such as <em class='bbc'>string</em> or <em class='bbc'>int</em>:<br />
<ul class='bbc'><br /><li><em class='bbc'>Dictionary></em><br /></li><li><em class='bbc'>SortedDictionary></em><br /></li><li><em class='bbc'>SortedList></em><br /></li><li><em class='bbc'>Dictionary></em><br /></li></ul><br />
<strong class='bbc'>	Some situations where this pattern can be used</strong><br />
<br />
One-to-many value mapping can be used in the following situations:<br />
<ul class='bbc'><br /><li>Mapping all the grades obtained by a student. The ID of the student can be the key and the grades obtained in each subject (which may be duplicate) can be stored as the values in a list.<br /></li><li>Tracking all the followers of a Twitter account. The user ID for the account will be the key and all follower IDs can be stored as values in a list.<br /></li><li>Scheduling all the appointments for a patient whose user ID will serve as the key.<br /></li></ul><br />
<strong class='bbc'>	Pattern 4: Many-to-many mapping</strong><br />
<br />
Many-to-many mapping maps many elements of a group to many elements in other groups. Both can have duplicate entries.<br />
<br />
<strong class='bbc'>	Pattern interface</strong><br />
<br />
The following are the interface implementations of this pattern:<br />
<br />
<strong class='bbc'>	Some concrete implementations</strong><br />
<br />
A concrete implementation of this pattern is as follows:<br />
<em class='bbc'>IList>></em><br />
<br />
<strong class='bbc'>	Example usages</strong><br />
<br />
The following are examples where <em class='bbc'>TKey</em> and <em class='bbc'>TValue</em> are replaced with real data types such as <em class='bbc'>string</em> or <em class='bbc'>int</em>:<br />
<br />
<strong class='bbc'>	Some situations where this pattern can be used</strong><br />
<br />
Many-to-many mapping can be used in the following situations:<br />
<ul class='bbc'><br /><li>If many independent values can be mapped to a set of values, then these patterns should be used. <em class='bbc'>ISet</em> implementations don't allow duplicates while <em class='bbc'>ICollection</em> implementations, such as <em class='bbc'>IList</em>, do.<br /></li><li>Imagine a company wants to give a pay hike to its employees based on certain conditions. In this situation, the parameters for conditions can be the independent variable of the Tuples, and IDs of employees eligible for the hike can be stored in an <em class='bbc'>ISet</em> implementation.<br /></li></ul><br />
For concurrency support, replace non-concurrent implementations with their concurrent cousins. For example, replace <em class='bbc'>Dictionary</em> with <em class='bbc'>ConcurrentDictionary</em>.<br />
<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>A special Tuple pattern</strong></span><br />
Since Tuple is a new inclusion in the .NET 4.0 Framework and can prove to be handy in a lot of situations, I thought it would be a great place to showcase an unusual use of this beautiful data representation technique.<br />
<br />
Let's say we have situations involving four integers. This is generally represented using nested if-else blocks, as shown in the following code. However, we can use a Tuple to refactor this code, as we shall see in a while:<br />
<ul class='bbcol decimal'><br /><li>Create a console app and add these four variables:<br />	<pre class='prettyprint'>	<br />static int x = 11;<br />	static int y = 9;<br />	static int z = 20;<br />	static int w = 30;	<br />	</pre><br /></li><li>Now, add these nested if-else blocks in the <em class='bbc'>Main()</em> method:<br />	<pre class='prettyprint'>	<br />if (x &gt; 9)<br />	{<br />	  if (y &gt; x)<br />	  {<br />		if (z &gt; y)<br />		{<br />		  if (w &gt; 10)<br />		  {<br />			Console.WriteLine(" y &gt; x and z &gt; y and w &gt; 10 ");<br />		  }<br />		  else<br />		  {<br />			Console.WriteLine(" y &gt; x and z &gt; y and w	   }<br />		}<br />		else<br />		{<br />		  if (w &gt; 10)<br />		  {<br />			Console.WriteLine(" y &gt; x and z  10 ");<br />		  }<br />		  else<br />		  {<br />			Console.WriteLine(" y &gt; x and z	   }<br />		}<br />	  }<br />	  else<br />	  {<br />		if (z &gt; y)<br />		{<br />		  if (w &gt; 10)<br />		  {<br />			Console.WriteLine(" y  y and w &gt; 10 ");<br />		  }<br />		  else<br />		  {<br />			Console.WriteLine(" y  y and w	   }<br />		}<br />		else<br />		{<br />		  if (w &gt; 10)<br />		  {<br />			Console.WriteLine(" y  10 ");<br />		  }<br />		  else<br />		  {<br />			Console.WriteLine(" y	   }<br />		}<br />	  }<br />	}	<br />	</pre><br /></li><li>If you run this, you shall see the following output:<br />	<pre class='prettyprint'>	<br />y  y and w &gt; 10	<br />	</pre><br /></li><li>Although this code performs the job, it has the following problems:<br /><ul class='bbc'><br /><li>It is very long. Most programmers will lose track of what they were reading.<br /></li><li>It is impossible to re-use any part of the code that is available under a specific branching.<br /></li></ul>	<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Time for action – refactoring deeply nested if-else blocks</strong></span><br />
Follow the given steps:<br />
<ul class='bbcol decimal'><br /><li>We must acknowledge that by using a maximum of four variables there can be 16 different branchings. Of these only eight are shown here. This type of code can be remodeled using the following structure. Now, delete everything in the <em class='bbc'>Main()</em> method and copy the following code:<br />	<pre class='prettyprint'>	<br />//Creating rules list<br />	List&gt;&gt;<br />	rules =<br />	new Liststring&gt;&gt;&gt;();<br />	<br />	//adding rules.The benefit is that entire nested if-else is<br />	//flatend.<br />	rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y &gt; x, z &gt; y, w &gt; 10, DoThis));<br />	rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y &gt; x, z &gt; y, w rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y &gt; x, z  10, DoThis));<br />	rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y &gt; x, z rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y  y, w &gt; 10, DoThis));<br />	rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y  y, w rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y  10, DoThis));<br />	rules.Add(new Tupleint, string&gt;&gt;<br />	(x &gt; 9, y <br />	Console.WriteLine ("Printing using tuple");<br />	//Finding the first rule that matches these conditions.<br />	Tuple&gt;<br />	matchingRule<br />				= rules.First<br />				   (<br />					 rule =&gt;<br />						rule.Item1 == GetExp&lt;b&gt;&lt;/b&gt;ressi&#111;n(x, 9)<br />						//represents x &gt; 9<br />						&& rule.Item2 == GetExp&lt;b&gt;&lt;/b&gt;ressi&#111;n(y, x)<br />						//represents y &gt; x<br />						&& rule.Item3 == GetExp&lt;b&gt;&lt;/b&gt;ressi&#111;n(z, y)<br />						//represents z &gt; y<br />						&& rule.Item4 == GetExp&lt;b&gt;&lt;/b&gt;ressi&#111;n(w, 10)<br />						//represents w &gt; 10<br />					  );<br />	//Find the Matching function.<br />	Func function = matchingRule.Item5;<br />	//Invoke the function.<br />	Console.WriteLine(function.Invoke(x,y,z,w));	<br />	</pre><br /></li><li>This will not compile yet because the <em class='bbc'>DoThis()</em> and <em class='bbc'>GetExp<b></b>ressi&#111;n()</em> methods are not defined. So add these methods as follows:<br />	<pre class='prettyprint'>	<br />private static string DoThis(int x, int y, int z, int w)<br />	{<br />	  string partOne = y &gt; x ? " y &gt; x " : " y   string partTwo = z &gt; y ? " z &gt; y " : " z   string partThree = w &gt; 10 ? " w &gt; 10 " : " w   return partOne + "and" + partTwo + "and" + partThree;<br />	}<br />	<br />	private static bool GetExp&lt;b&gt;&lt;/b&gt;ressi&#111;n(int x, int y)<br />	{<br />	  return x &gt; y;<br />	}	<br />	</pre><br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>What just happened?</strong></span><br />
Now if you run the program, you shall see the same output as before:<br />
<br />
<pre class='prettyprint'><br />y  y and w &gt; 10<br /><br /></pre><br />
So you saw how the if-else blocks were removed while the rules are still intact. Moreover, the code is more readable now.<br />
<br />
Let's see how this worked. Notice carefully that the last parameter of the Tuples used in the rules is <em class='bbc'>Func</em>. This means, we can place any function that takes four integer parameters and returns a string. The <em class='bbc'>DoThis()</em> method matches this requirement and so we place it in the list:<br />
<br />
<pre class='prettyprint'><br />Tuple&gt;<br /><br /></pre><br />
The previous list represents a relationship between four Boolean exp<b></b>ressi&#111;ns and a function. These Boolean exp<b></b>ressi&#111;ns are independent and the associated function is found using the following concern:<br />
<br />
<pre class='prettyprint'><br />Func function = matchingRule.Item5;<br /><br /></pre><br />
<em class='bbc'>Invoke()</em> is a method to call the function.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Best practices when using Generics</strong></span><br />
The following are the best practices to be followed while using Generics:<br />
<ul class='bbcol decimal'><br /><li>Don't use Generics when you know the situation won't always be generic.<br /></li><li>Use <em class='bbc'>Stack</em> for a Last In First Out (LIFO) list implementation.<br /></li><li>Use <em class='bbc'>Queue</em> for a First In First Out (FIFO) implementation.<br /></li><li>Use <em class='bbc'>List</em> for random access lists with zero-based indexing.<br /></li><li>Use <em class='bbc'>LinkedList</em> to implement a deque because it offers faster insertion and deletion at both ends as opposed to other collections.<br /></li><li>If you have to frequently insert random locations in the list, prefer <em class='bbc'>LinkedList</em> over <em class='bbc'>List</em> because <em class='bbc'>LinkedList</em> is a constant time operation to insert one item in between two elements in a linked list.<br /></li><li>If the random list does not have a duplicate, use <em class='bbc'>HashSet</em> instead. It is the fastest.<br /></li><li>Don't use a for loop over a <em class='bbc'>IDictionary</em> implementation. It can give incorrect results. Use a foreach loop over the keys collection instead.<br /></li><li>Avoid using <em class='bbc'>ElementAt()</em> or, its cousin, the <em class='bbc'>ElementAtOrDefault()</em> method on generic collections that natively don't support zero-based integer indexing, (for example, <em class='bbc'>Stack</em> or <em class='bbc'>Dictionary</em>); since dictionary elements are not guaranteed to be available on an index where they were added.<br /></li><li>Don't use a Tuple with more than seven parameters. Create a class with those parameters and then create a list of that class' objects. Using a Tuple with more than four parameters makes the code look messy and it's not efficient.<br /></li><li>Use <em class='bbc'>SortedDictionary</em> just to get the entries sorted. Don't use it to store simple associative "one-to-one" and "one-to-many" relationships as keeping the keys sorted isn't absolutely necessary. It is very slow compared to a normal dictionary.<br /></li><li>Use <em class='bbc'>HashSet</em> to create a generic set. It's the fastest set implementation available in the .NET Framework.<br /></li><li>Use <em class='bbc'>SortedSet</em> only to create a sorted generic set. Don't use it when you don't want the set to be sorted because it is slower than <em class='bbc'>HashSet</em>.<br /></li><li>Don't expect indexing to work on an array or a list as it would on sets or dictionaries, because sets and dictionaries use hashing or tree-based internal data structures to place elements in the collection.<br /></li><li>Use the available bare minimum implementation for your customized need or resort to creating your own custom collection class from the interfaces. This is a design guideline. Try to make sure your code is as lightweight as possible. If you want a queue, use a <em class='bbc'>Queue</em> instead of a <em class='bbc'>List</em>.<br /></li><li>Use <em class='bbc'>LinkedList</em> when you need to insert elements at arbitrary positions but you don't need to access them randomly via integer indexing.<br /></li><li>Use <em class='bbc'>KeyValuePair</em> to store a key value pair. Avoid using <em class='bbc'>Tuple></em> for this purpose because <em class='bbc'>KeyValuePair</em> is more efficient.<br /></li><li>Prefer <em class='bbc'>Dictionary></em> over <em class='bbc'>List></em> whenever possible for representing a one-to- many relationship between two entities. Lookup speed will be much faster and client code will be less clumsy.<br /></li><li>Prefer <em class='bbc'>List></em> to represent a many-to-one relationship between two entities over <em class='bbc'>Dictionary,TValue></em> if there is a duplicate.<br /></li><li>If no more entries need to be added to a collection, call TrimExcess() to free up the extra memory.<br /></li><li>Prefer LINQ Standard Query Operator <em class='bbc'>Where()</em> over <em class='bbc'>Contains()</em>, <em class='bbc'>Exists()</em>, or <em class='bbc'>Find()</em> methods to check whether a value is present in a <em class='bbc'>List</em> instance.<br /></li><li>If you implement <em class='bbc'>IEnumerable</em> in your custom collection, don't forget to implement IEnumerable also. This is to ensure backward compatibility and the Liskov substitution principle.<br /></li><li>Use <em class='bbc'>SortedList</em> if you want a concrete implementation of <em class='bbc'>IDictionary</em> that supports native indexing. However, it is slower than <em class='bbc'>Dictionary</em>. Avoid <em class='bbc'>SortedList</em> when you don't want indexing.<br /></li><li>Don't use the <em class='bbc'>ElementAt()</em> or the <em class='bbc'>ElementAtOrDefault()</em> method on <em class='bbc'>IDictionary</em> implementations except <em class='bbc'>SortedList</em>, because dictionary elements are not guaranteed to be in the index where they are added.<br /></li><li>Avoid conversions between data structure formats (for example, array to list, or vice versa using LINQ operators) as far as possible. Use other language constructs. For example, consider using a foreach loop than converting an <em class='bbc'>IEnumerable</em> instance to a list using the <em class='bbc'>ToList()</em> method before performing some operations on each item in the list.<br /></li><li>Use the <em class='bbc'>OrderBy()</em> or the <em class='bbc'>OrderByDescending()</em> method to sort any <em class='bbc'>IEnumerable</em>.<br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>Selecting a generic collection</strong></span><br />
Not all generic containers are geared to do each job well, as we already know it. Here is a table that will let you pick a generic container that supports some features listed in the lefthand column.<br />
<br />
<br />
<br />
<br />
<br />
You can download the <strong class='bbc'>GenGuru</strong> app from the <a href='http://www.packtpub.com/support' class='bbc_url' title='External link' rel='nofollow external'>support website</a>. It's a kind of wizard that will recommend the generic containers available in .NET Generics that you should use. It will ask you few questions and recommend a collection. You can see it in action at <a href='http://sudipta.posterous.com/private/niixaeFlmk' class='bbc_url' title='External link' rel='nofollow external'>http:// sudipta.posterous.com/private/niixaeFlmk</a>.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Best practices when creating custom generic collections</strong></span><br />
The following are the best practices while creating custom generic collections:<br />
<ul class='bbcol decimal'><br /><li>Try to use built-in generic classes for maintaining internal data structures.<br /></li><li>Try to use interfaces as return type and method arguments for publicly exposed methods for your collection. For example, consider using <em class='bbc'>IEnumerable</em> over <em class='bbc'>List</em>.<br /></li><li>Try to keep the names aligned as much as possible towards the names available in frameworks. For example, if you are creating a concrete implementation of <em class='bbc'>IDictionary</em> then try to use the suffix Dictionary in the name of the class, such as <em class='bbc'>MultiDictionary</em>.<br /></li><li>Try to provide overloaded constructors to offer flexibility such that the class can be created from many diverse data sources.<br /></li><li>Use Generics constraints judiciously. Remember that these constraints are like boomerangs. You should know what exactly you can allow as an input parameter for a constrained generic type. Otherwise, these can backfire and hurt you and the users of your collection.<br /></li><li>Make sure to always implement the <em class='bbc'>IEnumerable</em>, <em class='bbc'>IEnumerable</em>, <em class='bbc'>ICollection</em>, <em class='bbc'>IDisposable</em>, and <em class='bbc'>IClonable</em> interfaces.<br /></li><li>Make sure that your collection confirms to the Liskov substitution principle. Divide into subclasses only when it makes sense, otherwise use composition.<br /></li><li>Offer a constructor overload to create a thread-safe instance of your collection.<br /></li><li>Make sure it supports LINQ, which will be obvious if you implement <em class='bbc'>IEnumearble</em> properly. LINQ is changing the way we see and solve problems. So if you miss LINQ, your collection will probably fail to impress a large section of the target audience.<br /></li><li>Thrive for performance. Make sure that performance is as best as it could be.<br /></li><li>Make sure your collection is as lightweight as possible. If a <em class='bbc'>Queue</em> can do what you want done internally in your collection, use it. Don't consider using a more versatile list implementation such as <em class='bbc'>List</em>.<br /></li><li>Don't write raw events by yourself to monitor the collection; rather expose <em class='bbc'>ObservableCollection</em> to offer this functionality.<br /></li><li>Don't provide functionalities that can be achieved by a simple combination of exposed functions. For example, take a look at the Date Time API from the .NET Framework. There is a method called <em class='bbc'>AddDays()</em> that can take a positive or negative integer such that you can go to a past or a future date. However, the framework doesn't provide a method or a public property to compute <em class='bbc'>Tomorrow()</em> or <em class='bbc'>Yesterday()</em> as they can be easily calculated using the <em class='bbc'>AddDays()</em> method. While exposing public functions for your generic collection, remember to expose only those methods that can be used as building blocks for several reasons.<br /></li><li>However, you have to strike a balance. The framework also has the <em class='bbc'>AddYears()</em> method because it will be cumbersome, although technically achievable, to duplicate <em class='bbc'>AddYears()</em> using the <em class='bbc'>AddDays()</em> method.<br /></li></ul><br />
Remember these points while coming up with your own generic collection.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
In this article, we took a look at generic container patterns and best practices for Generics.]]></description>
		<pubDate>Wed, 01 Feb 2012 03:28:05 +0000</pubDate>
		<guid isPermaLink="false">5ed17b7aeb1316a3f8daf637f4a7a6b4</guid>
	</item>
	<item>
		<title>Sedge: An Automated Error Reporting Tool</title>
		<link>http://www.gamedev.net/page/resources/_/technical/general-programming/sedge-an-automated-error-reporting-tool-r2867</link>
		<description><![CDATA[<ul class='bbc'><br /><li><a href='http://uploads.gamedev.net/cp/1327954995-sedge.bin.1.0.zip' class='bbc_url' title='External link' rel='nofollow external'>Download demo - 248 KB</a><br /></li><li><a href='http://uploads.gamedev.net/cp/1327954995-sedge.src.1.0.zip' class='bbc_url' title='External link' rel='nofollow external'>Download source - 1.26 MB</a><br /></li></ul><br />
<br />
License: <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'><span class='bbc_underline'><strong class='bbc'>Ms-PL</strong></span></a><br />
 <br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954995-Screen1.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Introduction</strong></span><br />
<br />
Every developer knows how important a good bug report is, and every developer wants as much details about the issue as the user can provide. There are different solutions that aim to facilitate the error reporting process, from tiny third-party components to such powerful technologies like Microsoft Windows Error Reporting, but most of them are designed to report fatal error only.<br />
<br />
Missed text, incorrect functionality, wrong output - your users may want to report these issues too. And, even if it looks like a minor problem for the user, you may want to see log files, configurations, system information, etc. Moreover, the user may use multiple applications developed by your company, and to locate the problem, you may be interested to add to the report a few common logs or configurations.<br />
<br />
All these thoughts were taken into account during the designing of <a href='http://sedge.codeplex.com/' class='bbc_url' title='External link' rel='nofollow external'>Sedge</a> - an Open Source, free utility that helps to automate error reporting by collecting all the necessary information, files, descriptions, and presenting it in a nice HTML view. The target platform is Microsoft .NET 2.0.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How it works</strong></span><br />
<br />
Sedge is a wizard style application, and proposes the user to take an issue screenshot, enter description and contact information, and add the user's files. The last step of the wizard is a report generation. Sedge copies all the files you want to see in the report, collects system information, creates report HTML pages, and zips the report. The user can review the report and email it to you.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954995-Screen2.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The configuration file (default extension is <em class='bbc'>.sedge</em>) is the key to all the features of the tool. The configuration describes all the aspects of the process - the wizard's steps, files, and information to collect, report representation, etc. If the path to the configuration file is not provided as a command line parameter, Sedge will try to read it from <em class='bbc'>Sedge.exe.config</em> and tries to search for it in the current folder and subfolders.<br />
<br />
Command line example:<br />
<pre class='prettyprint'><br /><br />Sedge.exe /suite="C:&#092;Apps&#092;QuickStart.sedge"<br /></pre><br />
<br />
<br />
<br />
Configuration example:<br />
<pre class='prettyprint'><br /><br />?&gt;<br />xml version="1.0" encoding="UTF-8" &gt;<br />&lt;Sedge&gt;<br />  &lt;Suite name="LunarFrog.TaggedFrog" <br />	   caption="TaggedFrog Error Reporting" partial="no"&gt;<br />	&lt;Schedule&gt;<br />	  &lt;Step name="Screenshot" /&gt;<br />	  &lt;Step name="ErrorDetails" /&gt;<br />	  &lt;Step name="Contacts" /&gt;<br />	  &lt;Step name="Collect" /&gt;<br />	&lt;/Schedule&gt;<br /><br />	&lt;Transport name="Email"&gt;<br />	  &lt;Option name="to" value="error_mail@company.com" /&gt;<br />	  &lt;Option name="subject" value="Error report" /&gt;<br />	&lt;/Transport&gt;<br /><br />	&lt;Report&gt;<br />	  &lt;Group name="UserGroup" caption="User Information"&gt;<br />		&lt;Page name="ImagePage" caption="Screenshot"&gt;<br />		  &lt;Temp name="screenshot" caption="Screen" /&gt;<br />		&lt;/Page&gt;<br />		&lt;Page name="InfoPage" caption="Information"&gt;<br />		  &lt;Temp name="ReportDetails" caption="Details"/&gt;<br />		  &lt;Temp name="Contacts" caption="Contact Information" /&gt;<br />		  &lt;Temp name="UserFiles" /&gt;<br />		&lt;/Page&gt;<br />	  &lt;/Group&gt;<br />	  &lt;Group name="EnvGroup" caption="Enviroment"&gt;<br />		&lt;Page name="ProcessesPage" caption="Processes"&gt;<br />		  &lt;Data name="Processes" /&gt;<br />		&lt;/Page&gt;<br />		&lt;Page name="SystemPage" caption="System"&gt;<br />		  &lt;Data name="System" /&gt;<br />		&lt;/Page&gt;<br />	  &lt;/Group&gt;<br />	&lt;/Report&gt;<br /><br />	&lt;Application name="TaggedFrog" caption="TaggedFrog"&gt;<br />	  &lt;Report&gt;<br />		&lt;Group name="ApplicationGroup" caption="Application"&gt;<br />		&lt;/Group&gt;<br />	  &lt;/Report&gt;<br />	&lt;/Application&gt;<br /><br />  &lt;/Suite&gt;<br />&lt;/Sedge&gt;<br /></pre><br />
<br />
<br />
<br />
The main unit of the configuration is a suite. The suite represents a collection of the related applications, and could be described in one file or split into multiple parts. This means that you can have one main configuration file describing the wizard UI and the common properties, and add/remove the suite part when you install/uninstall applications. The error report will include information requested in the main configuration plus information specific for the reported application (see Sample 4 in the attached archive).<br />
<br />
The schedule section describes the steps that will be displayed to the user. Every step tag represents a class implementing the IStepController interface, and you can easily create your own steps to add or replace the existing ones (Sample 5). Because the GUI code is separated from the logic, you can even completely replace the user interface, for example, if you like to use WPF instead of WinForms.<br />
<br />
Eventually, you are able to customize almost every aspect of the process. For example, if you don't like e-mail as a method of reports delivering, you can add your own transport protocol.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Report</strong></span><br />
<br />
The next aspect of the report generations is... the report itself. The configuration defines the structure of the report while the style is controlled by the template. The template consists of the HTML, CSS files, and the images, so you can modify it to match your corporate style.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954995-HtmlReport.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
Every page may include one or more sources of information to report. There are four types of sources:<br />
<ul class='bbc'><br /><li>displays information provided by the user (screenshots, error details, etc.)<br /></li><li>displays information about the files - path, size, and version<br /></li><li>instructs the application to copy files to the report and print links to these files on the page<br /></li><li>is actually a meta-source; the name attribute is used to select a class implementing the IDataSource interface and returning the required information<br /></li></ul><br />
Out of the box, there are three classes:<br />
<ul class='bbc'><br /><li>Processes to display the running processes information<br /></li><li>System to display information about the OS and the hardware<br /></li><li>Table to print the provided information in the table form; it can be used to display the information contained in the properties<br /></li></ul><br />
And as usual, you can create your own source:<br />
<pre class='prettyprint'><br /><br />&lt;&lt;/span&gt;Data name="CurrentDate" assembly="${custom.dll}" caption="Now" /&gt;<br /></pre><br />
<br />
<br />
<br />
A property is a container that can store text information, and can be set directly in the configuration to get a value from the Registry. If you'd like to setup a property in a different way, for example from <em class='bbc'>.ini</em> files, you are able to create a custom property handler.<br />
<pre class='prettyprint'><br /><br />public class EchoProperty : ICustomProperty<br />{<br />	public string GetValue(Options options)<br />	{<br />		return String.Concat("Echo: ", <br />		  options.GetGeneralOption("Param", "param"));<br />	}<br />}<br /></pre><br />
<br />
<br />
<pre class='prettyprint'><br /><br />&lt;Properties&gt;<br />	&lt;Property name="custom.dll" <br />	  value="${sedge.this.folder}&#092;DLL&#092;Demo.Customization.dll" /&gt;<br />	&lt;CustomProperty name="echo.message" <br />	  assembly="${custom.dll}" value="Echo"&gt;<br />		&lt;Option name="Param" value="Hello World!" /&gt;<br />	&lt;/CustomProperty&gt;<br />&lt;/Properties&gt;<br /></pre><br />
<br />
<br />
<br />
Two predefined properties are available in every configuration: <em class='bbc'>${sedge.this.folder}</em> - the path to the configuration file, and <em class='bbc'>${sedge.this.file}</em> - the configuration file name.<br />
<br />
To be usable in the real world, Sedge supports localization and rebranding. All strings are located in a separate file; you can modify the current translation or add a new one, and change the application name.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Conclusion</strong></span><br />
<br />
Sedge aims to help your customers create better bug reports, and gives you a way to control what information should be added to the report. With Sedge, users can report not only fatal crashes but also usability issues, incorrect functionality, etc. One of the main tasks of the application is to provide an error report in the context of the application suites, and it could be achieved using partial configurations. Sedge can be used as a ready-to-go tool, or customized to satisfy your specific goals.<br />
<br />
Project site: <a href='http://sedge.codeplex.com/' class='bbc_url' title='External link' rel='nofollow external'>sedge.codeplex.com</a>.<br />
<br />
First version of the article.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>About the Author</strong></span><br />
<br />
	I am a software developer from Toronto with 15 years of experience in software design and development. My major professional area is the development of highly customized software solutions, including desktop and web applications. Industrial process automation and hardware-related software development are among my favorite projects and I enjoyed developing several applications for semiconductor manufacturing companies.<br />
 <br />
My blog: <a href='http://LunarFrog.com/blog' class='bbc_url' title='External link' rel='nofollow external'>http://LunarFrog.com/blog</a>	<br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>License</strong></span><br />
<br />
This article was authored by Andrei Marukovich and reproduced for the benefit of our viewers under the terms of the <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'>Ms-PL</a> license.]]></description>
		<pubDate>Mon, 30 Jan 2012 20:26:03 +0000</pubDate>
		<guid isPermaLink="false">ae306dc92ae6dfe9049d4b2177bb932d</guid>
	</item>
	<item>
		<title>Wrapper Pattern for Silverlight and WPF</title>
		<link>http://www.gamedev.net/page/resources/_/technical/apis-and-tools/wrapper-pattern-for-silverlight-and-wpf-r2866</link>
		<description><![CDATA[<ul class='bbc'><br /><li><a href='http://uploads.gamedev.net/cp/1327954866-WrapperPatternExample.zip' class='bbc_url' title='External link' rel='nofollow external'>Download sample (Silverlight and WPF) - 368 KB</a><br /></li></ul><br />
<br />
License: <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'><span class='bbc_underline'><strong class='bbc'>Ms-PL</strong></span></a><br />
 <br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Table of contents</strong></span><br />
<br />
<strong class='bbc'>	Introduction</strong><br />
<br />
<br />
It has been a long time since my last article. This one is short and a bit less creative than the previous ones, but I hope you'll like it! <img src='http://public.gamedev.net//public/style_emoticons/default/smile.png' class='bbc_emoticon' alt=':)' /><br />
<br />
I hope none of you have never particularly talked about that before, but probably you have already used what I will talk about, without naming it: the wrapper pattern in WPF and Silverlight.<br />
<br />
<strong class='bbc'>	Pattern sheet</strong><br />
<br />
<br />
<strong class='bbc'>Pattern type</strong>: Presentation pattern.<br />
<br />
<strong class='bbc'>Problem</strong>: You want to create an animation or to bind on a property which does not exist on your object -the target- or doesn't support the use of Storyboard or Binding.<br />
<br />
<strong class='bbc'>Solution</strong>: Create an object -a wrapper- which will expose this property, and will modify the target object accordingly.<br />
<br />
<strong class='bbc'>Alternatives</strong>:<br />
<ul class='bbc'><br /><li>Use attached properties; however, it will fail in Silverlight 3.0 (it does not support animation on attached properties in XAML).<br /></li><li>Use a decorator, but it doesn't exist on Silverlight, and sometimes makes your XAML harder to read.<br /></li></ul><br />
<strong class='bbc'>Actor</strong>:<br />
<ul class='bbc'><br /><li>The object we want to animate is called the "target".<br /></li><li>The object we will create to expose new properties to animate is called the "wrapper".<br /></li></ul><br />
<strong class='bbc'>	Concrete examples</strong><br />
<br />
<ul class='bbc'><br /><li>The first is a common problem in Silverlight: binding to the ActualWidth/Height property.<br /></li><li>The second is an element hider; it allows you to show or "push" an element at the border of the screen (like dockable views in Visual Studio).<br /></li></ul><br />
For these two examples, the wrapper pattern provides a really nice solution.<br />
<br />
<strong class='bbc'>	Example 1 - Binding to ActualWidth and ActualHeight</strong><br />
<br />
Here is the example:<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954866-SizeWrapper.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The sliders are bound to the Height and Width of a grid which wraps the green rectangle. The red rectangle's width and height are bound to ActualWidth and ActualHeight of the green rectangle. The Height and Width properties of the green rectangle are not set.<br />
<br />
Here is the code:<br />
<pre class='prettyprint'><br /><br />&lt;&lt;/span&gt;StackPanel&gt;<br />	&lt;&lt;/span&gt;Canvas Background="Yellow" Height="500" Width="500" &gt;<br />		&lt;&lt;/span&gt;Grid x:Name="grid" Canvas.Top="0" Height="100" Width="100"&gt;<br />			&lt;&lt;/span&gt;Rectangle x:Name="greenRect" Fill="Green"&gt;&lt;&lt;/span&gt;/Rectangle&gt;<br />		&lt;&lt;/span&gt;/Grid&gt;<br />		&lt;&lt;/span&gt;Rectangle Canvas.Top="300" Fill="Red" <br />		  Height="{Binding ActualHeight, ElementName=greenRect}" <br />		  Width="{Binding ActualWidth, ElementName=greenRect}"&gt;&lt;&lt;/span&gt;/Rectangle&gt;<br />	&lt;&lt;/span&gt;/Canvas&gt;<br />	<br />	&lt;&lt;/span&gt;Slider Maximum="500" Minimum="0" <br />	  Value="{Binding Height, ElementName=grid, Mode=TwoWay}"&gt;&lt;&lt;/span&gt;/Slider&gt;<br />	&lt;&lt;/span&gt;Slider Maximum="500" Minimum="0" <br />	  Value="{Binding Width, ElementName=grid, Mode=TwoWay}"&gt;&lt;&lt;/span&gt;/Slider&gt;<br />&lt;&lt;/span&gt;/StackPanel&gt;<br /></pre><br />
<br />
<br />
<br />
I want the green and red rectangle to have the same size, and everything goes well in the world of WPF... but Silverlight can't bind to ActualHeight and ActualWidth. So, what is the solution? It's simple, we will create a wrapper, SizeWrapper, with three properties: RealWidth, RealHeight, and Element, the target element.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954866-SizeWrapperClass.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
It will listen to the SizeChanged event of the target element and update its two properties. Here is the code:<br />
<pre class='prettyprint'><br /><br />public class SizeWrapper : FrameworkElement<br />{<br />	public FrameworkElement Element<br />	{<br />		get<br />		{<br />			return (FrameworkElement)GetValue(ElementProperty);<br />		}<br />		set<br />		{<br />			SetValue(ElementProperty, value);<br />		}<br />	}<br /><br />	public double RealHeight<br />	{<br />		get<br />		{<br />			return (double)GetValue(RealHeightProperty);<br />		}<br />		set<br />		{<br />			SetValue(RealHeightProperty, value);<br />		}<br />	}<br /><br />	// Using a DependencyProperty as the backing store for RealHeight.<br />	// This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty RealHeightProperty =<br />		DependencyProperty.Register("RealHeight", <br />		typeof(double), typeof(SizeWrapper), Helper.CreateMetadata(.));<br /><br />	public double RealWidth<br />	{<br />		get<br />		{<br />			return (double)GetValue(RealWidthProperty);<br />		}<br />		set<br />		{<br />			SetValue(RealWidthProperty, value);<br />		}<br />	}<br /><br />	// Using a DependencyProperty as the backing store for RealWidth.<br />	// This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty RealWidthProperty =<br />		DependencyProperty.Register("RealWidth", <br />		typeof(double), typeof(SizeWrapper), Helper.CreateMetadata(.));<br /><br />	// Using a DependencyProperty as the backing store<br />	// for Element. This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty ElementProperty =<br />		DependencyProperty.Register("Element", typeof(FrameworkElement), <br />		typeof(SizeWrapper), Helper.CreateMetadata(null, OnElementChanged));<br /><br />	private static void OnElementChanged(DependencyObject sender, <br />			DependencyPropertyChangedEventArgs args)<br />	{<br />		var wrapper = (SizeWrapper)sender;<br />		var oldElement = args.OldValue as FrameworkElement;<br />		var newElement = args.NewValue as FrameworkElement;<br />		if(oldElement != null)<br />			oldElement.SizeChanged -= wrapper.SizeChanged;<br />		if(newElement != null)<br />		{<br />			newElement.SizeChanged += wrapper.SizeChanged;<br />			wrapper.UpdateSize(new Size(newElement.ActualWidth, <br />										newElement.ActualHeight));<br />		}<br />	}<br /><br />	void SizeChanged(object sender, SizeChangedEventArgs e)<br />	{<br />		UpdateSize(e.NewSize);<br />	}<br /><br />	private void UpdateSize(Size size)<br />	{<br />		RealHeight = size.Height;<br />		RealWidth = size.Width;<br />	}<br />}<br /></pre><br />
<br />
<br />
<br />
Now, here is the slightly modified version. The only modification is that the red rectangle binds to the wrapper's properties instead of the green rectangle directly. As you will expect, it works well. The wrapper is inside the canvas.<br />
<pre class='prettyprint'><br /><br />&lt;&lt;/span&gt;StackPanel&gt;<br />	&lt;&lt;/span&gt;Canvas Height="500" Width="500" &gt;<br />		&lt;&lt;/span&gt;wrappers:SizeWrapper x:Name="sizeWrapper" <br />				   Element="{Binding ElementName=greenRect}"&gt;&lt;&lt;/span&gt;/wrappers:SizeWrapper&gt;<br />		&lt;&lt;/span&gt;Grid x:Name="grid" Canvas.Top="0" <br />				   Height="100" Width="100"&gt;<br />			&lt;&lt;/span&gt;Rectangle x:Name="greenRect" Fill="Green"&gt;&lt;&lt;/span&gt;/Rectangle&gt;<br />		&lt;&lt;/span&gt;/Grid&gt;<br />		&lt;&lt;/span&gt;Rectangle Canvas.Top="300" Fill="Red" <br />		  Height="{Binding RealHeight, ElementName=sizeWrapper}" <br />		  Width="{Binding RealWidth, ElementName=sizeWrapper}"&gt;&lt;&lt;/span&gt;/Rectangle&gt;<br />	&lt;&lt;/span&gt;/Canvas&gt;<br /><br />	&lt;&lt;/span&gt;Slider Maximum="500" Minimum="0" <br />	  Value="{Binding Height, ElementName=grid, Mode=TwoWay}"&gt;&lt;&lt;/span&gt;/Slider&gt;<br />	&lt;&lt;/span&gt;Slider Maximum="500" Minimum="0" <br />	 Value="{Binding Width, ElementName=grid, Mode=TwoWay}"&gt;&lt;&lt;/span&gt;/Slider&gt;<br />&lt;&lt;/span&gt;/StackPanel&gt;<br /></pre><br />
<br />
<br />
<br />
<strong class='bbc'>	Example 2 - Element hider</strong><br />
<br />
Some of you might say: well, it's just useful for a specific workaround; wait a second, read this second example, and you'll appreciate the simplicity!<br />
<br />
This example should deserve its own article because I suspect lots people would want it.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954866-ElementHidderWrapper1.jpg' alt='Posted Image' class='bbc_img' /></span><span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954866-ElementHidderWrapper2.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
This time we will use a wrapper called 'ElementHidderWrapper' to "push" an element on the border of the screen (as you can do with the dockable views in Visual Studio).<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954866-ElementHidderWrapperClass.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
If Show is 0, then the target is completely collapsed; if it is 1.0, it's completely visible. MinMargin is the minimum margin to show when Show equals 0. HideSide is the side where the element will hide. Here is how to use it:<br />
<pre class='prettyprint'><br /><br />&lt;&lt;/span&gt;Grid&gt;<br />	&lt;&lt;/span&gt;wrappers:ElementHidderWrapper<br />		x:Name="hidder"<br />		Element="{Binding ElementName=border}"<br />		MinMargin="20"<br />		HideSide="Left"<br />		Show="1.0"<br />		&gt;&lt;&lt;/span&gt;/wrappers:ElementHidderWrapper&gt;<br /><br />	&lt;&lt;/span&gt;Border x:Name="border" HorizontalAlignment="Left" <br />			VerticalAlignment="Top" BorderThickness="1.0" <br />			Width="100" Height="300" <br />			BorderBrush="Black" <br />			CornerRadius="0,10,10,0" Background="Green"&gt;<br />		&lt;&lt;/span&gt;Grid&gt;<br />			&lt;&lt;/span&gt;TextBlock Text="blabla" <br />			   HorizontalAlignment="Center" <br />			   VerticalAlignment="Top"&gt;&lt;&lt;/span&gt;/TextBlock&gt;<br />			&lt;&lt;/span&gt;CheckBox IsChecked="True" <br />			   HorizontalAlignment="Right" <br />			   VerticalAlignment="Bottom" <br />			   Click="CheckBox_Click"&gt;<br />			&lt;&lt;/span&gt;/CheckBox&gt;<br />		&lt;&lt;/span&gt;/Grid&gt;<br />	&lt;&lt;/span&gt;/Border&gt;<br />&lt;&lt;/span&gt;/Grid&gt;<br /></pre><br />
<br />
<br />
<br />
The target element is the border. Initially, everything is shown. MinMargin is set to 20 px; this way, we can always click on the checkbox. When you click on the checkbox, it will hide/show the border to the left. It's easy to do, I just need to fire an animation on the Show property of my wrapper.<br />
<pre class='prettyprint'><br /><br />private void CheckBox_Click(object sender, RoutedEventArgs e)<br />{<br />	CheckBox checkBox = (CheckBox)sender;<br />	Storyboard storyBoard = new Storyboard();<br />	DoubleAnimation showAnimation = new DoubleAnimation();<br />	Storyboard.SetTarget(showAnimation, hidder);<br />	Storyboard.SetTargetProperty(showAnimation, new PropertyPath("Show"));<br />	showAnimation.Duration = new Duration(new TimeSpan(, , , , 400));<br />	showAnimation.To = checkBox.IsChecked.Value ? 1. : .;<br />	storyBoard.Children.Add(showAnimation);<br />	storyBoard.Begin();<br />}<br /></pre><br />
<br />
<br />
<br />
The code of the wrapper is not the point, but I will quickly explain: every time a property of the wrapper changes, I recalculate the margins of the target, and it's done.<br />
<pre class='prettyprint'><br /><br />public enum HideSide<br />{<br />	Top,<br />	Bottom,<br />	Left,<br />	Right<br />}<br /><br />public class ElementHidderWrapper : FrameworkElement<br />{<br />	public double MinMargin<br />	{<br />		get<br />		{<br />			return (double)GetValue(MinMarginProperty);<br />		}<br />		set<br />		{<br />			SetValue(MinMarginProperty, value);<br />		}<br />	}<br /><br />	// Using a DependencyProperty as the backing store for MaxShow.<br />	// This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty MinMarginProperty =<br />		DependencyProperty.Register("MinMargin", typeof(double), <br />		typeof(ElementHidderWrapper), <br />		Helper.CreateMetadata(., MinMarginChanged));<br /><br />	private static void MinMarginChanged(DependencyObject sender, <br />						DependencyPropertyChangedEventArgs args)<br />	{<br />		ElementHidderWrapper hidder = (ElementHidderWrapper)sender;<br />		hidder.UpdateElement();<br />	}<br /><br />	public HideSide HideSide<br />	{<br />		get<br />		{<br />			return (HideSide)GetValue(HideSideProperty);<br />		}<br />		set<br />		{<br />			SetValue(HideSideProperty, value);<br />		}<br />	}<br /><br />	// Using a DependencyProperty as the backing store<br />	// for HideSide. This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty HideSideProperty =<br />		DependencyProperty.Register("HideSide", typeof(HideSide), <br />		typeof(ElementHidderWrapper), Helper.CreateMetadata(HideSide.Bottom));<br /><br />	public double Show<br />	{<br />		get<br />		{<br />			return (double)GetValue(ShowProperty);<br />		}<br />		set<br />		{<br />			SetValue(ShowProperty, value);<br />		}<br />	}<br /><br />	// Using a DependencyProperty as the backing store for Show.<br />	// This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty ShowProperty =<br />		DependencyProperty.Register("Show", typeof(double), <br />		typeof(ElementHidderWrapper), Helper.CreateMetadata(1., ShowChanged));<br /><br />	public FrameworkElement Element<br />	{<br />		get<br />		{<br />			return (FrameworkElement)GetValue(ElementProperty);<br />		}<br />		set<br />		{<br />			SetValue(ElementProperty, value);<br />		}<br />	}<br /><br />	// Using a DependencyProperty as the backing store for Element.<br />	// This enables animation, styling, binding, etc...<br />	public static readonly DependencyProperty ElementProperty =<br />		DependencyProperty.Register("Element", <br />		typeof(FrameworkElement), typeof(ElementHidderWrapper), <br />		Helper.CreateMetadata(null, ElementChanged));<br /><br />	private static void ElementChanged(DependencyObject sender, <br />						DependencyPropertyChangedEventArgs args)<br />	{<br />		ElementHidderWrapper hidder = (ElementHidderWrapper)sender;<br />		FrameworkElement oldValue = args.OldValue as FrameworkElement;<br />		FrameworkElement newValue = args.NewValue as FrameworkElement;<br />		if(oldValue != null)<br />			oldValue.SizeChanged -= hidder.SizeChanged;<br />		if(newValue != null)<br />			newValue.SizeChanged += hidder.SizeChanged;<br />		hidder.UpdateElement();<br />	}<br /><br />	private void SizeChanged(object sender, SizeChangedEventArgs e)<br />	{<br />		UpdateElement();<br />	}<br /><br />	private static void ShowChanged(DependencyObject sender, <br />			DependencyPropertyChangedEventArgs args)<br />	{<br />		ElementHidderWrapper hidder = (ElementHidderWrapper)sender;<br />		hidder.UpdateElement();<br />	}<br /><br />	private void UpdateElement()<br />	{<br />		if(Element == null)<br />			return;<br />		var maxValue = GetMaxShowValue(Element);<br />		var minValue = MinMargin;<br />		var calculatedShowValue = minValue + (maxValue - minValue) * Show;<br />		var marginValue = maxValue - calculatedShowValue;<br />		SetMarginValue(Element, marginValue);<br /><br />	}<br /><br />	private void SetMarginValue(FrameworkElement element, double marginValue)<br />	{<br />		if(HideSide == HideSide.Left)<br />		{<br />			element.Margin = new Thickness(-marginValue, <br />			  element.Margin.Top, element.Margin.Right, element.Margin.Bottom);<br />		}<br />		else if(HideSide == HideSide.Top)<br />		{<br />			element.Margin = new Thickness(element.Margin.Left, <br />			  -marginValue, element.Margin.Right, element.Margin.Bottom);<br />		}<br />		else if(HideSide == HideSide.Right)<br />		{<br />			element.Margin = new Thickness(element.Margin.Left, <br />			  element.Margin.Top, -marginValue, element.Margin.Bottom);<br />		}<br />		else if(HideSide == HideSide.Bottom)<br />		{<br />			element.Margin = new Thickness(element.Margin.Left, <br />			  element.Margin.Top, element.Margin.Right, -marginValue);<br />		}<br />	}<br /><br />	private double GetMaxShowValue(FrameworkElement element)<br />	{<br />		if(HideSide == HideSide.Bottom &#124;&#124; HideSide == HideSide.Top)<br />			return element.ActualHeight;<br />		else<br />			return element.ActualWidth;<br />	}<br />}<br /></pre><br />
<br />
<br />
<br />
<strong class='bbc'>	Conclusion</strong><br />
<br />
<br />
This pattern is not great news; however, putting a name on something will help people to use and remember where it fits well. This pattern should definitively be in the toolbox of the WPF/SL developer.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>About the Author</strong></span><br />
<br />
	My goal as a developer, a community member, and enterpreneur is the same : making the minimal product that will help then getting myself out the way. My work is yours.<br />
 <br />
If you are interested for working with me, this way	  <br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>License</strong></span><br />
<br />
This article was authored by Nicolas Dorier and reproduced for the benefit of our viewers under the terms of the <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'>Ms-PL</a> license.]]></description>
		<pubDate>Mon, 30 Jan 2012 20:22:05 +0000</pubDate>
		<guid isPermaLink="false">5444df470d67382653f5c5600221ddb7</guid>
	</item>
	<item>
		<title>Inter-Process Communication (IPC) Introduction...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/general-programming/inter-process-communication-ipc-introduction-r2865</link>
		<description><![CDATA[<ul class='bbc'><br /><li><a href='http://uploads.gamedev.net/cp/1327954670-IPC_src.zip' class='bbc_url' title='External link' rel='nofollow external'>Download IPC source code - 229.21 KB</a><br /></li></ul><br />
<br />
License: <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'><span class='bbc_underline'><strong class='bbc'>Ms-PL</strong></span></a><br />
 <br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Introduction</strong></span><br />
<br />
Inter-Process Communication (IPC) is a set of techniques for the exchange of data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC techniques include Named Pipes, File Mapping, Mailslot, Remote Procedure Calls (RPC), etc.<br />
<br />
In All-In-One Code Framework, we have already implemented samples (C++ and C#) for Named Pipes, File Mapping, Mail Slot, and Remoting. We are going to add more techniques like: Clickbord, Winsock, etc. You can download the latest code from <a href='http://cfx.codeplex.com/' class='bbc_url' title='External link' rel='nofollow external'>http://cfx.codeplex.com/</a>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Background</strong></span><br />
<br />
<a href='http://cfx.codeplex.com/' class='bbc_url' title='External link' rel='nofollow external'>All-In-One Code Framework</a> (short as AIO) delineates the framework and skeleton of most Microsoft development techniques (e.g., COM, Data Access, IPC) using typical sample codes in different programming languages (e.g., Visual C#, VB.NET, Visual C++).<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Using the Code</strong></span><br />
<br />
Find samples by following the steps below:<br />
<ul class='bbcol decimal'><br /><li>Download the zip file and unzip it.<br /></li><li>Open the folder <em class='bbc'>[Visual Studio 2008]</em>.<br /></li><li>Open the solution file <em class='bbc'>IPC.sln</em>. You must pre-install Visual Studio 2008 on the machine.<br /></li><li>In the Solution Explorer, open the <em class='bbc'>[Process] &#092; [IPC and RPC]</em> folder.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>Samples Structure and Relationship</strong></span><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954670-Structure_of_CodeFx_2008.jpg' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Named Pipe</strong></span><br />
<br />
Named pipes is a mechanism for one-way or bi-directional inter-process communication between a pipe server and one or more pipe clients in the local machine or across computers in an intranet:<br />
<pre class='prettyprint'><br /><br />&#91;b&#93;PIPE_ACCESS_INBOUND:&#91;/b&#93;<br /><br />Client (GENERIC_WRITE) ---&gt; Server (GENERIC_READ)<br /><br /><br />&#91;b&#93;PIPE_ACCESS_OUTBOUND:&#91;/b&#93;<br /><br />Client (GENERIC_READ) &lt;--- Server (GENERIC_WRITE)<br /><br /><br />&#91;b&#93;PIPE_ACCESS_DUPLEX:&#91;/b&#93;<br /><br />Client (GENERIC_READ or GENERIC_WRITE, or both) <br />				&lt;--&gt; Server (GENERIC_READ and GENERIC_WRITE)<br /></pre><br />
<br />
<br />
<br />
This sample demonstrates a named pipe server, <em class='bbc'>&#092;&#092;.&#092;pipe&#092;HelloWorld</em>, that supports PIPE_ACCESS_DUPLEX. It first creates such a named pipe, then it listens to the client's connection. When a client is connected, the server attempts to read the client's requests from the pipe and writes a response.<br />
<br />
A named pipe client attempts to connect to the pipe server, <em class='bbc'>&#092;&#092;.&#092;pipe&#092;HelloWorld</em>, with the GENERIC_READ and GENERIC_WRITE permissions. The client writes a message to the pipe server and receives its response.<br />
<br />
<strong class='bbc'>	Code Logic</strong><br />
<br />
Server-side logic:<br />
<ul class='bbcol decimal'><br /><li>Create a named pipe. (CreateNamedPipe)<br /></li><li>Wait for the client to connect. (ConnectNamedPipe)<br /></li><li>Read client requests from the pipe and write the response. (ReadFile, WriteFile)<br /></li><li>Disconnect the pipe, and close the handle. (DisconnectNamedPipe, CloseHandle)<br /></li></ul><br />
Client-side logic:<br />
<ul class='bbcol decimal'><br /><li>Try to open a named pipe. (CreateFile)<br /></li><li>Set the read mode and the blocking mode of the specified named pipe. (SetNamedPipeHandleState)<br /></li><li>Send a message to the pipe server and receive its response. (WriteFile, ReadFile)<br /></li><li>Close the pipe. (CloseHandle)<br /></li></ul><br />
<strong class='bbc'>	Code - CreateNamedPipe (C++)</strong><br />
<pre class='prettyprint'><br /><br />// Create the named pipe.<br />HANDLE hPipe = CreateNamedPipe(<br /><br />strPipeName,					  // The unique pipe name. This string must<br />								  // have the form of &#092;&#092;.&#092;pipe&#092;pipename<br />PIPE_ACCESS_DUPLEX,			   // The pipe is bi-directional; both <br />								  // server and client processes can read<br />								  // from and write to the pipe<br />PIPE_TYPE_MESSAGE &#124;			   // Message type pipe<br />PIPE_READMODE_MESSAGE &#124;		   // Message-read mode<br />PIPE_WAIT,						// Blocking mode is enabled<br />PIPE_UNLIMITED_INSTANCES,		 // Max. instances<br /><br />// These two buffer sizes have nothing to do with the buffers that<br />// are used to read from or write to the messages. The input and<br />// output buffer sizes are advisory. The actual buffer size reserved<br />// for each end of the named pipe is either the system default, the<br />// system minimum or maximum, or the specified size rounded up to the<br />// next allocation boundary. The buffer size specified should be<br />// small enough that your process will not run out of nonpaged pool,<br />// but large enough to accommodate typical requests.<br /><br />BUFFER_SIZE,					  // Output buffer size in bytes<br />BUFFER_SIZE,					  // Input buffer size in bytes<br />NMPWAIT_USE_DEFAULT_WAIT,		 // Time-out interval<br />&sa							   // Security attributes<br />)<br /></pre><br />
<br />
<br />
<br />
For more code samples, please download AIO source code.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Security Attribute for Named Pipes</strong></span><br />
<br />
If lpSecurityAttributes of CreateNamedPipe is NULL, the named pipe gets a default security descriptor and the handle cannot be inherited. The ACLs in the default security descriptor for a named pipe grants full control to the LocalSystem account, administrators, and the creator owner. They also grant read access to members of the Everyone group and the anonymous account. In other words, with NULL as the security attribute, the named pipe cannot be connected with WRITE permission across the network, or from a local client running as a lower integrity level. Here, we fill the security attributes to grant EVERYONE all access (not just the connect access) to the server. This solves the cross-network and cross-IL issues, but it creates a security hole right there: the clients have WRITE_OWNER access and then the server just loses the control of the pipe object.<br />
<br />
<strong class='bbc'>	Code - Security Attributes (C++)</strong><br />
<pre class='prettyprint'><br /><br />SECURITY_ATTRIBUTES sa;<br />sa.lpSecurityDescriptor = (PSECURITY_DESCRIPTOR)malloc(SECURITY_DESCRIPTOR_MIN_LENGTH);<br />InitializeSecurityDescriptor(sa.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);<br />// ACL is set as NULL in order to allow all access to the object.<br />SetSecurityDescriptorDacl(sa.lpSecurityDescriptor, TRUE, NULL, FALSE);<br />sa.nLength = sizeof(sa);<br />sa.bInheritHandle = TRUE;<br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>.NET Named Pipe</strong></span><br />
<br />
.NET supports named pipes in two ways:<br />
<ul class='bbcol decimal'><br /><li>P/Invoke the native APIs.	<br />By P/Invoke-ing the native APIs from .NET, we can mimic the code logic in CppNamedPipeServer to create the named pipe server, <em class='bbc'>&#092;&#092;.&#092;pipe&#092;HelloWorld</em>, that supports PIPE_ACCESS_DUPLEX.	<br />	<br />PInvokeNativePipeServer first creates such a named pipe, then it listens to the client's connection. When a client is connected, the server attempts to read the client's requests from the pipe and write a response.<br /></li><li>System.IO.Pipes namespace	<br />In .NET Framework 3.5, the namespace System.IO.Pipes and a set of classes (e.g., PipeStream, NamedPipeServerStream) are added to the .NET BCL. These classes make the programming of named pipes in .NET much easier and safer than P/Invoke-ing the native APIs directly.	<br />	<br />BCLSystemIOPipeServer first creates such a named pipe, then it listens to the client's connection. When a client is connected, the server attempts to read the client's requests from the pipe and write a response.<br /></li></ul><br />
<strong class='bbc'>	Code - Create Named Pipe (C#)</strong><br />
<pre class='prettyprint'><br /><br />// Prepare the security attributes <br />// Granting everyone the full control of the pipe is just for <br />// demo purpose, though it creates a security hole. <br />PipeSecurity pipeSa = new PipeSecurity(); <br />pipeSa.SetAccessRule(new PipeAccessRule("Everyone", <br />	   PipeAccessRights.ReadWrite, AccessControlType.Allow)); <br /><br />// Create the named pipe <br />pipeServer = new NamedPipeServerStream( <br />	strPipeName,					// The unique pipe name. <br />	PipeDirection.InOut,			// The pipe is bi-directional <br />	NamedPipeServerStream.MaxAllowedServerInstances, <br />	PipeTransmissionMode.Message,   // Message type pipe <br />	PipeOptions.None,			   // No additional parameters <br />	BUFFER_SIZE,					// Input buffer size <br />	BUFFER_SIZE,					// Output buffer size <br />	pipeSa,						 // Pipe security attributes <br />	HandleInheritability.None	   // Not inheritable <br />);<br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>File Mapping</strong></span><br />
<br />
File mapping is a mechanism for one-way or bi-directional inter-process communication among two or more processes in the local machine. To share a file or memory, all of the processes must use the name or the handle of the same file mapping object.<br />
<br />
To share a file, the first process creates or opens a file by using the CreateFile function. Next, it creates a file mapping object by using the CreateFileMapping function, specifying the file handle and a name for the file mapping object. The names of events, semaphores, mutexes, waitable timers, jobs, and file mapping objects share the same namespace. Therefore, the CreateFileMapping and OpenFileMapping functions fail if they specify a name that is in use by an object of another type.<br />
<br />
To share memory that is not associated with a file, a process must use the CreateFileMapping function and specify INVALID_HANDLE_VALUE as the hFile parameter instead of an existing file handle. The corresponding file mapping object accesses memory backed by the system paging file. You must specify a size greater than zero when you specify an hFile of INVALID_HANDLE_VALUE in a call to CreateFileMapping.<br />
<br />
Processes that share files or memory must create file views by using the MapViewOfFile or MapViewOfFileEx functions. They must coordinate their access using semaphores, mutexes, events, or some other mutual exclusion techniques.<br />
<br />
This example demonstrates a named shared memory server, <em class='bbc'>Local&#092;HelloWorld</em>, that creates the file mapping object with INVALID_HANDLE_VALUE. By using the PAGE_READWRITE flag, the process has read/write permission to the memory through any file view that is created.<br />
<br />
The named shared memory client, <em class='bbc'>Local&#092;HelloWorld</em>, can access the string written to the shared memory by the first process. The console displays the message "Message from the first process" that is read from the file mapping created by the first process.<br />
<br />
<strong class='bbc'>	Code Logic</strong><br />
<br />
Service-side logic:<br />
<ul class='bbcol decimal'><br /><li>Create a file mapping. (CreateFileMapping)<br /></li><li>Map the view of the file mapping into the address space of the current process. (MapViewOfFile)<br /></li><li>Write message to the file view. (CopyMemory)<br /></li><li>Unmap the file view and close the file mapping objects. (UnmapViewOfFile, CloseHandle)<br /></li></ul><br />
Client-side logic:<br />
<ul class='bbcol decimal'><br /><li>Try to open a named file mapping. (OpenFileMapping)<br /></li><li>Maps the view of the file mapping into the address space of the current process. (MapViewOfFile)<br /></li><li>Read message from the view of the shared memory.<br /></li><li>Unmap the file view and close the file mapping objects. (UnmapViewOfFile, CloseHandle)<br /></li></ul><br />
<strong class='bbc'>	Code - CreateFileMapping (C++)</strong><br />
<pre class='prettyprint'><br /><br />// In terminal services: The name can have a "Global&#092;" or "Local&#092;" prefix<br />// to explicitly create the object in the global or session namespace.<br />// The remainder of the name can contain any character except the  <br />// backslash character (&#092;). For details, please refer to: <br />// http&#58;//msdn.microsoft.com/en-us/library/aa366537.aspx <br />TCHAR szMapFileName&#91;&#93; = _T("Local&#092;&#092;HelloWorld"); <br /><br />// Create the file mapping object <br />HANDLE hMapFile = CreateFileMapping( <br />	   INVALID_HANDLE_VALUE,	  // Use paging file instead of existing file. <br />								  // Pass file handle to share in a file. <br /><br />	   NULL,					  // Default security <br />	   PAGE_READWRITE,			// Read/write access <br />	   ,						 // Max. object size <br />	   BUFFER_SIZE,			   // Buffer size  <br />	   szMapFileName			  // Name of mapping object <br />);<br /></pre><br />
<br />
<br />
<br />
.NET only supports P/Invoke native APIs currently. By P/Invoke, .NET can simulate similar behaviors as native code.<br />
<br />
<strong class='bbc'>	Sample Code 4 (C# - P/Invoke)</strong><br />
<pre class='prettyprint'><br /><br />/// &lt;&lt;/span&gt;summary&gt; <br />/// Creates or opens a named or unnamed file mapping object for <br />/// a specified file. <br />/// &lt;&lt;/span&gt;/summary&gt; <br />/// &lt;&lt;/span&gt;param name="hFile"&gt;A handle to the file from which to create <br />/// a file mapping object.&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="lpAttributes"&gt;A pointer to a SECURITY_ATTRIBUTES <br />/// structure that determines whether a returned handle can be <br />/// inherited by child processes.&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="flProtect"&gt;Specifies the page protection of the <br />/// file mapping object. All mapped views of the object must be <br />/// compatible with this protection.&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="dwMaximumSizeHigh"&gt;The high-order DWORD of the <br />/// maximum size of the file mapping object.&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="dwMaximumSizeLow"&gt;The low-order DWORD of the <br />/// maximum size of the file mapping object.&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="lpName"&gt;The name of the file mapping object. <br />/// &lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;returns&gt;If the function succeeds, the return value is a <br />/// handle to the newly created file mapping object.&lt;&lt;/span&gt;/returns&gt; <br />&#91;DllImport("Kernel32.dll", SetLastError = true)&#93; <br />public static extern IntPtr CreateFileMapping( <br />	IntPtr hFile,				   // Handle to the file <br />	IntPtr lpAttributes,			// Security Attributes <br />	FileProtection flProtect,	   // File protection <br />	uint dwMaximumSizeHigh,		 // High-order DWORD of size <br />	uint dwMaximumSizeLow,		  // Low-order DWORD of size <br />	string lpName				   // File mapping object name <br />);<br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Mailslot</strong></span><br />
<br />
Mailslot is a mechanism for one-way inter-process communication in the local machine or across computers in the intranet. Any client can store messages in a mailslot. The creator of the slot, i.e., the server, retrieves the messages that are stored there:<br />
<pre class='prettyprint'><br /><br />Client (GENERIC_WRITE) ---&gt; Server (GENERIC_READ)<br /></pre><br />
<br />
<br />
<br />
This sample demonstrates a mailslot server, <em class='bbc'>&#092;&#092;.&#092;mailslot&#092;HelloWorld</em>. It first creates such a mailslot, then it reads the new messages in the slot every five seconds. Then, a mailslot client connects and writes to the mailslot <em class='bbc'>&#092;&#092;.&#092;mailslot&#092;HelloWorld</em>.<br />
<br />
<strong class='bbc'>	Code Logic</strong><br />
<br />
Server-side logic:<br />
<ul class='bbcol decimal'><br /><li>Create a mailslot. (CreateMailslot)<br /></li><li>Check messages in the mailslot. (ReadMailslot)<br /><ul class='bbcol decimal'><br /><li>Check for the number of messages in the mailslot. (GetMailslotInfo)<br /></li><li>Retrieve the messages one by one from the mailslot. While reading, update the number of messages that are left in the mailslot. (ReadFile, GetMailslotInfo)<br /></li></ul>	</li><li>Close the handle of the mailslot instance. (CloseHandle)<br /></li></ul><br />
Client-side logic:<br />
<ul class='bbcol decimal'><br /><li>Open the mailslot. (CreateFile)<br /></li><li>Write messages to the mailslot. (WriteMailslot, WriteFile)<br /></li><li>Close the slot. (CloseHandle)<br /></li></ul><br />
<strong class='bbc'>	Code - GetMailslotInfo (C++)</strong><br />
<pre class='prettyprint'><br /><br />///////////////////////////////////////////////////////////////////////// <br />// Check for the number of messages in the mailslot. <br />//bResult = GetMailslotInfo( <br />		hMailslot,					// Handle of the mailslot <br />		NULL,						 // No maximum message size <br />		&cbMessageBytes,			  // Size of next message <br />		&cMessages,				   // Number of messages <br />		NULL);						// No read time-out<br /></pre><br />
<br />
<br />
<br />
<strong class='bbc'>	Code - CreateMailslot (C# - P/Invoke)</strong><br />
<pre class='prettyprint'><br /><br />/// &lt;&lt;/span&gt;summary&gt; <br />/// Creates an instance of a mailslot and returns a handle for subsequent <br />/// operations. <br />/// &lt;&lt;/span&gt;/summary&gt; <br />/// &lt;&lt;/span&gt;param name="lpName"&gt;mailslot name&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="nMaxMessageSize"&gt;The maximum size of a single message <br />/// &lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="lReadTimeout"&gt;The time a read operation can wait for a <br />/// message&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;param name="lpSecurityAttributes"&gt;Security attributes&lt;&lt;/span&gt;/param&gt; <br />/// &lt;&lt;/span&gt;returns&gt;If the function succeeds, the return value is a handle to <br />/// the server end of a mailslot instance.&lt;&lt;/span&gt;/returns&gt; <br />&#91;DllImport("kernel32.dll", SetLastError = true)&#93; <br />public static extern IntPtr CreateMailslot( <br />	string lpName,			  // Mailslot name <br />	uint nMaxMessageSize,	   // Max size of a single message in bytes <br />	int lReadTimeout,		   // Timeout of a read operation <br />	IntPtr lpSecurityAttributes // Security attributes <br />);<br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Remoting</strong></span><br />
<br />
.NET Remoting is a mechanism for one-way inter-process communication and RPC between .NET applications in the local machine or across computers in the intranet and internet.<br />
<br />
.NET Remoting allows an application to make a remotable object available across remoting boundaries, which includes different appdomains, processes, or even different computers connected by a network. .NET Remoting makes a reference of a remotable object available to a client application, which then instantiates and uses a remotable object as if it were a local object. However, the actual code execution happens at the server-side. All requests to the remotable object are proxied by the .NET Remoting runtime over Channel objects that encapsulate the actual transport mode, including TCP streams, HTTP streams, and named pipes. As a result, by instantiating proper Channel objects, a .NET Remoting application can be made to support different communication protocols without recompiling the application. The runtime itself manages the act of serialization and marshalling of objects across the client and server appdomains.<br />
<br />
<strong class='bbc'>	Code - Create and Register a Channel (C#)</strong><br />
<pre class='prettyprint'><br /><br />///////////////////////////////////////////////////////////////////// <br />// Create and register a channel (TCP channel in this example) that <br />// is used to transport messages across the remoting boundary. <br />//// Properties of the channel <br />IDictionary props = new Hashtable(); <br />props&#91;"port"&#93; = 6100;   // Port of the TCP channel <br />props&#91;"typeFilterLevel"&#93; = TypeFilterLevel.Full; <br />// Formatters of the messages for delivery <br />BinaryClientFormatterSinkProvider clientProvider = null; <br />BinaryServerFormatterSinkProvider serverProvider = <br />			  new BinaryServerFormatterSinkProvider(); <br />serverProvider.TypeFilterLevel = TypeFilterLevel.Full; <br /><br />// Create a TCP channel <br />TcpChannel tcpChannel = new TcpChannel(props, clientProvider, serverProvider); <br /><br />// Register the TCP channel <br />ChannelServices.RegisterChannel(tcpChannel, true); <br /></pre><br />
<br />
<br />
<br />
<strong class='bbc'>	Code - Register Remotable Types (VB.NET)</strong><br />
<pre class='prettyprint'><br /><br />'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''<br />' Register the remotable types on the service end as<br />' server-activated types (aka well-known types) or client-activated<br />' types.<br />' Register RemotingShared.SingleCallObject as a SingleCall server-<br />' activated type.<br />RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingShared.SingleCallObject), _<br />					  "SingleCallService", WellKnownObjectMode.SingleCall)<br />' Register RemotingShared.SingletonObject as a Singleton server-<br />' activated type.<br />RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingShared.SingletonObject), _<br />					  "SingletonService", WellKnownObjectMode.Singleton)<br />' Register RemotingShared.ClientActivatedObject as a client-<br />' activated type.<br />RemotingConfiguration.ApplicationName = "RemotingService"<br />RemotingConfiguration.RegisterActivatedServiceType(_<br />		GetType(Global.RemotingShared.ClientActivatedObject)) <br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Points of Interest</strong></span><br />
<br />
In the pilot phase of the AIO project, we focus on five techniques: COM, Library, IPC, Office, and Data Access. There has been 42 code examples in the project. The collection currently grows at a rate of seven examples per week.<br />
<br />
This article was created on 3/12/2009.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>About the Author</strong></span><br />
<br />
	Microsoft All-In-One Code Framework delineates the framework and skeleton of Microsoft development techniques through typical sample codes in three popular programming languages (Visual C#, VB.NET, Visual C++). Each sample is elaborately selected, composed, and documented to demonstrate one frequently-asked, tested or used coding scenario based on our support experience in MSDN newsgroups and forums. If you are a software developer, you can fill the skeleton with blood, muscle and soul. If you are a software tester or a support engineer like us, you may extend the sample codes a little to fit your specific test scenario or refer your customer to this project if the customer's question coincides with what we collected.<br />
<a href='http://cfx.codeplex.com/' class='bbc_url' title='External link' rel='nofollow external'>http://cfx.codeplex.com/</a>	<br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>License</strong></span><br />
<br />
This article was authored by All-In-One Code Framework and reproduced for the benefit of our viewers under the terms of the <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'>Ms-PL</a> license.]]></description>
		<pubDate>Mon, 30 Jan 2012 20:18:28 +0000</pubDate>
		<guid isPermaLink="false">576258b4a6dbcfc5b4839354868731d3</guid>
	</item>
	<item>
		<title>Parallel programming in .NET - Internals</title>
		<link>http://www.gamedev.net/page/resources/_/technical/general-programming/parallel-programming-in-net-internals-r2864</link>
		<description><![CDATA[<ul class='bbc'><br /><li><a href='http://uploads.gamedev.net/cp/1327954523-InParallel.zip' class='bbc_url' title='External link' rel='nofollow external'>Download demo - 2.67 KB</a><br /></li></ul><br />
<br />
License: <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'><span class='bbc_underline'><strong class='bbc'>Ms-PL</strong></span></a><br />
 <br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Introduction</strong></span><br />
<br />
.NET 4 brings a powerful Task library to support a piece of code to run in parallel processors. It just simply spawns threads into multiple processes using the newly written Task libraries (System.Threading.Tasks) in Mscorlib 4.0. Task libraries contain methods like For, ForEach, and Invoke to support parallelism in .NET languages, which I will discuss in detail later on.<br />
<br />
Let's see what's got changed in .NET 4.0 to bring up parallel extensions.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>CLR Thread Pool 4.0</strong></span><br />
<br />
The old thread pool of .NET 2.0 used to support only 1-4 processors, where the "single queue", "single lock" schema was sufficient. The improved thread pool in .NET 4.0 can hold up to 16-256 processors.<br />
<ul class='bbc'><br /><li>The new ThreadPool significantly reduces the synchronization overhead associated with pushing/pulling work items to/from the pool. While in previous versions, the ThreadPool queue was implemented as a linked list protected by a big lock, the new version of the queue is based on the new array-style, lock-free, GC-friendly <a href='http://msdn.microsoft.com/en-us/library/dd267265.aspx' class='bbc_url' title='External link' rel='nofollow external'>ConcurrentQueue</a> class.<br /></li><li>The CLR 4.0 thread pool also supports a local queue per task, and implements a work stealing algorithm that load balances the work amongst the queues.<br /></li><li>In the 4.0 version of the CLR thread pool, the 'thread injection and retirement algorithm' has changed. In cases where there are more running threads than CPUs, instead of creating new threads at the rate of 1 thread per 0.5 second, the new thread pool takes the liberty to 'hold back' threads (i.e., reduce the concurrency level) for a while.<br /></li></ul><span style='font-size: 14px;'><strong class='bbc'>MSCORLIB 4.0</strong></span><br />
<br />
<strong class='bbc'>	System.Collections.Concurrent Namespace</strong><br />
<br />
The System.Collections.Concurrent namespace provides several thread-safe collection classes that should be used in place of the corresponding types in the <a href='http://msdn.microsoft.com/en-us/library/system.collections.aspx' class='bbc_url' title='External link' rel='nofollow external'>System.Collections</a> and <a href='http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx' class='bbc_url' title='External link' rel='nofollow external'>System.Collections.Generic</a> namespaces whenever multiple threads are accessing the collection concurrently.<br />
<br />
<strong class='bbc'>	System.Threading.Tasks Namespace</strong><br />
<br />
The System.Threading.Tasks namespace provides types that simplify the work of writing concurrent and asynchronous code. The main types are <a href='http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx' class='bbc_url' title='External link' rel='nofollow external'>System.Threading.Tasks.Task</a>, which represents an asynchronous operation that can be waited on and cancelled, and <a href='http://msdn.microsoft.com/en-us/library/dd321424.aspx' class='bbc_url' title='External link' rel='nofollow external'>System.Threading.Tasks.Task(Of TResult)</a>, which is a task that can return a value. The Factory class provides static methods for creating and starting tasks, and the <a href='http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.aspx' class='bbc_url' title='External link' rel='nofollow external'>System.Threading.Tasks.TaskScheduler</a> class provides the default thread scheduling infrastructure.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>.NET 4 Cancellation Framework</strong></span><br />
<br />
A very interesting addition to .NET 4 is a set of new types that specifically assist with building cancellation-aware applications and libraries. The new types enable rich scenarios for convenient and safe cancellation, and help simplify situations that used to be be difficult and error-prone and non-composable.<br />
<br />
Two new types form the basis of the framework: a CancellationToken is a struct that represents a 'potential request for cancellation'. This struct is passed into method calls as a parameter, and the method can poll on it or register a callback to be fired when cancellation is requested. A CancellationTokenSource is a class that provides the mechanism for initiating a cancellation request, and it has a Token property for obtaining an associated token. It would have been natural to combine these two classes into one, but this design allows the two key operations (initiating a cancellation request vs. observing and responding to cancellation) to be cleanly separated. In particular, methods that take only a CancellationToken can observe a cancellation request but cannot initiate one.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How it Works</strong></span><br />
<br />
Now you have got enough familiarization of the changes in .NET to bring up code parallelization. Let's start with a simple entity of parallelization called Task in our case. The new System.Threading.Tasks.Task class takes care of thread allocation and synchronization; yeah, it's internally using threads, but in a very efficient way.<br />
<br />
The Task class implements the <a href='http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:4.0.0.0:b77a5c561934e089/System.Threading.IThreadPoolWorkItem' class='bbc_url' title='External link' rel='nofollow external'>IThreadPoolWorkItem</a> interface, which is responsible for executing work items from the thread pool queue. The full flow of task parallelization is shown in the diagram below:<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-parallelarch_small.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The ThreadPoolTaskScheduler class pushes Tasks (IThreadPoolWorkItem) to a global queue using the ThreadPool API. Worker threads picks up the tasks from Global Queue (QueueSegment). Once the processing is done, it informs the task by calling the manual reset event of System.Threading. If a task is created within a task, then it will not be pushed to the Global Queue, but instead maintained in a local queue (work stealing queue). Any task item in the work stealing queue can be shared by any other worker thread. How does work stealing work? The worker thread looks first into the local queue; if there is no work item to pick, then it searches the global queue. Still, if there is no work for the thread, it will look for any pending work item in other queues. So during the task processing, none of the threads are sitting idle, which actually gives 100% utilization of all cores of machines.<br />
<br />
I think we have a lot of benefits of Local Queues and Work Stealing Queues, which were missing in the legacy thread pool, like less contention in the Global Queue, thread workers are effectively used, and many more. One thing to notice is that the huge performance improvement is also caused by changing the linked list based queues to array style queues; all the local and global queues are array based, which means there is no Big Lock for concurrency.<br />
<br />
Let's hit Visual Studio now..<br />
<br />
I ran the below sample of code in my dual core machine, better to try in a quad core.<br />
<pre class='prettyprint'><br /><br />//In Static void Main<br />DoSomeBigStuff(1, 10000);<br />DoSomeBigStuff(2, 10000);<br /><br />//In some class<br />public void DoSomeBigStuff(int inp,int limit)<br />{<br />	ProcessItem();<br /><br />	if (inp &gt; limit)<br />	{<br />		return;<br />	}<br />	DoSomeBigStuff(++inp, limit);<br />}<br /><br />public void ProcessItem()<br />{<br />	Thread.SpinWait(100000);<br />}<br /></pre><br />
<br />
<br />
<br />
Running this on my dual core system gets the result in 8431ms, but if you check out the CPU performance, only 50% of the CPU is getting used.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-cpu1.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
Let's make some changes to the above code, and put DoSomeBigStuff in a task:<br />
<pre class='prettyprint'><br /><br />Task t1 = new Task(() =&gt;<br />{<br />	DoSomeBigStuff(1, 10000);<br />});<br />Task t2 = new Task(() =&gt;<br />{<br />	DoSomeBigStuff(2, 10000);<br />});<br /></pre><br />
<br />
<br />
<br />
The CPU picture totally changes and now starts using both the cores. The code finishes in 4589 ms, which is a drastic improvement. Now I don't have to think about scaling up my code; just run the same code on an 8 proc machine and it will take lesser than 1000ms. The Task class encapsulates the logic of handling the number of threads based on processors and work item allocation.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-cpu2.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
There is some overhead associated with threading, so the individual tasks may take a little longer - in this case, they went from about 82 milliseconds for the single-threaded example to a wide range, some as high as 300 milliseconds, in the parallel.<br />
<br />
This overhead should be part of your decision about when and what to parallelize in your application. What's more important for your application: that it finishes faster, or uses less total CPU time? Another consideration is ordering of the work.<br />
<br />
Let's look at the threads. Check the thread debug window; you can see two new threads spawned with the Main thread.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-thread1_small.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The Parallel Library has started two threads to do the work equal to the number of cores. One more thread got created, which handles the callbacks from the queue to the main thread.<br />
<br />
Check out the call stack of a single thread; it does the same stuff as we discussed above in the diagram.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-callstack.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
You can figure out what the Execute method is doing; it just pushes the item into the global queue. The interesting method that I want to discuss here is ThreadPoolWorkQueue.Dispatch(). Let's go step by step in this method.<br />
<pre class='prettyprint'><br /><br />ThreadPoolGlobals.workQueue.MarkThreadRequestSatisfied();<br /></pre><br />
<br />
<br />
<br />
This decrements the outstanding thread request, which means it gets the thread out of the pool.<br />
<pre class='prettyprint'><br /><br />ThreadPoolWorkQueueThreadLocals tl = <br />   ThreadPoolGlobals.workQueue.EnsureCurrentThreadHasQueue();<br /></pre><br />
<br />
<br />
<br />
This creates a Local Queue if not already created for the current thread worker.<br />
<pre class='prettyprint'><br /><br />ThreadPoolGlobals.workQueue.Dequeue(tl, out callback, out missedSteal);<br /></pre><br />
<br />
<br />
<br />
This dequeues the task from the work queue. The Dequeue method is intelligent enough to pick the task if not present in the global or local queue; then it tries to steal the task from other queues.<br />
<pre class='prettyprint'><br /><br />callback.ExecuteWorkItem();<br />ThreadPool.NotifyWorkItemComplete();<br />ThreadPoolGlobals.workQueue.EnsureThreadRequested();<br /></pre><br />
<br />
<br />
<br />
Execute the work item and notify the thread pool that the work is completed. If successful, it returns the thread back to the pool.<br />
<br />
All this looks simple to me, but efficient logic to work out with threads. The picture below will give quite a good idea about the thread handling part done by the Task libraries.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-threadsdetailed_small.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<strong class='bbc'>	What's Extra</strong><br />
<br />
The Task Parallel library provides one more class to play with, called Parallel. The APIs present in the Parallel class are used for iterations like For, ForEach, and Invoke. All these extension methods use the same Task libraries discussed above.<br />
<br />
We will see one more example before proceeding ahead.<br />
										<pre class='prettyprint'>				<br /><br />				for (int i=0; i &lt; 1000; i++){<br />					Calculate(i);<br />				}<br />				public void Calculate(int pos){<br />					double result = new Random().NextDouble();<br />					for (int i = ; i &lt; 20000; i++){<br />						result += Math.Acos(new <br />						Random().NextDouble());<br />					}<br />				}				<br />				</pre><br />
				<br />
				 							<pre class='prettyprint'>				<br /><br />				Parallel.For(, 1000, delegate(int i)<br />				{<br />					Calculate(i);<br />				}<br />				);				<br />				</pre><br />
				<br />
				<br />
				<br />
Completed in half of the time compared to the legacy For loop.						<br />
Parallel.For directly jumps into the ForWorker method with the following params in the Parallel class:<br />
<pre class='prettyprint'><br /><br />ForWorker&lt;&lt;span class="code-keyword"&gt;object&gt;(fromInclusive, toExclusive, <br />		  s_defaultParallelOptions, body, null, null, null, null);<br /></pre><br />
<br />
<br />
<br />
Internally, the ForWorker method creates an instance of ParallelForReplicatingTask which inherits from Task, with the default set to InternalTaskOptions.SelfReplicating. ForWorker creates an empty root task, and iteration tasks are created as child tasks of the root task.<br />
<pre class='prettyprint'><br /><br />rootTask.RunSynchronously(parallelOptions.EffectiveTaskScheduler);<br /></pre><br />
<br />
<br />
<br />
This method starts the self-replication process of child tasks, and starts queuing them in the local queue. The Parallel class decides the number of thread workers which is equal to the number of processors.<br />
<br />
In all methods of the Parallel class, it's been taken care that if any cancel task request comes, the threads will not be aborted, but cancelled softly.<br />
<br />
While self replicating, .NET has to make sure the following points:<br />
<ul class='bbc'><br /><li>Self-replicating should have an inter-replica communication mechanism for communicating the completion of the overall activity.<br /></li><li>Only use when the cost of this communication and the management of partitions is considerably less than the potential benefit gained from parallelism.<br /></li><li>Do not assume that the task is always replicated. It is only replicated if there are available resources. For the same reason, do not assume that there will be a specific number of replicas.<br /></li><li>In some instances, the number of replicas could far exceed the number of cores in the machine.<br /></li><li>You may choose to use optimistic concurrency when it is possible to correctly deal with multiple executions of the same step.<br /></li></ul><br />
And I think they have done a good job in handling the number of thread workers, using concurrency queues and the effective cancellation framework.<br />
<br />
Here is the demo source code:<br />
<br />
Below are the results after running the source on a dual core and quad core:<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-cpu2core.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954523-cpu4core.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>A Bonus Item</strong></span><br />
<br />
Visual Stuido Team Launched Concurrency Analyzer: If you have VS 2010, you can see the option under Analyze->Launch Performance Wizard->Concurrency.<br />
<br />
It generates a full analysis report with graphs about the thread and cores usage. If building a thread intensive app, then you should go through this analysis. Also see the <a href='http://channel9.msdn.com/shows/Going+Deep/Visualizing-Concurrency-Inside-the-Concurrency-Visualizer-Profiling-Tool/' class='bbc_url' title='External link' rel='nofollow external'>Concurrency Analyzer Video</a>.<br />
<br />
Good job done .NET Parallel Extension team!!<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>License</strong></span><br />
<br />
This article was authored by Manabendra Roy (Manab) and reproduced for the benefit of our viewers under the terms of the <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'>Ms-PL</a> license.]]></description>
		<pubDate>Mon, 30 Jan 2012 20:16:20 +0000</pubDate>
		<guid isPermaLink="false">240497d1c93f3ea543976e5f331f3f9d</guid>
	</item>
	<item>
		<title>Kinect Reception</title>
		<link>http://www.gamedev.net/page/resources/_/technical/game-programming/kinect-reception-r2862</link>
		<description><![CDATA[<ul class='bbc'><br /><li><a href='http://uploads.gamedev.net/cp/1327954025-KinectReception.zip' class='bbc_url' title='External link' rel='nofollow external'>Download source - 1.01 MB</a><br /></li></ul><br />
<br />
License: <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'><span class='bbc_underline'><strong class='bbc'>Ms-PL</strong></span></a><br />
 <br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-1.png' alt='Posted Image' class='bbc_img' /></span><br />
<span style='font-size: 14px;'><strong class='bbc'>Introduction</strong></span><br />
<br />
<strong class='bbc'>The Idea:</strong> TV Screen in the Reception, When nothing happens (no one is in the reception) we can display videos on the screen but when someone enters the frame, show him the Kinect Image, and if the user is doing something funny, capture his image and save it.<br />
<br />
The question is how can I know if the person is doing something funny?<br />
<br />
For that, I've created Image AuthenticManager that contains a set of rules defining what positions or combinations are funny.<br />
<br />
<strong class='bbc'>For example:</strong> If right hand position is higher than head position, then add 2 points, if the left foot position is crossing the right foot, then add an additional 2 points, etc.<br />
When the user reaches the goal, we decide then to take his picture.<br />
<br />
Before jumping to coding, let's talk about the application flow:<br />
The main window is controlled by two Timers and the AuthenticManager:<br />
<br />
<strong class='bbc'>SeriousTimer</strong> set to 10 secs and it starts Ticking as the Kinect Skeleton Event is first fired (this event will only work when the Kinect identifies a full person skeleton).<br />
Inside the SkeletonFrameReady, we also have integer called _fpsCount that increases itself by 1 each time the SkeletonFrameReady is called after starting the SeriousTimer, this will help us to make sure the user is standing in front of the Kinect and not just walk by him.<br />
<br />
Now how can the _fbsCount tell me that? ll we need to do is multiply the SeriousTimer seconds interval by the Minimum Fps (for example 10) and the _fpsCount should be bigger if the user stands in front of the Kinect.<br />
<br />
In this case, the Timer will stop the Video feed and will display the Kinect Image.<br />
<br />
<strong class='bbc'>IdleTimer</strong> by default is set to 30 seconds and each time the SkeletonFrameReady method is fired, we restart the IdleTimer.<br />
<br />
So if there are no events for SkeletonFrameReady, the IdleTimer will return the Video feed.<br />
<br />
JointID - AuthenticManager works with RuleObject that contains JointID Source and JointID Target (More about Joints - <a href='http://blogs.microsoft.co.il/blogs/shair/archive/2011/06/17/kinect-getting-started-become-the-incredible-hulk.aspx' class='bbc_url' title='External link' rel='nofollow external'>Kinect - Getting Started - Become The Incredible Hulk</a>).<br />
<strong class='bbc'>AuthenticManager</strong> is the heart of Kinect Reception application, this class will check if the user position is funny by your own rules.<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-11.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
What is Joint?<br />
[indent]<br />
The data is provided from the Kinect application code as a set of points, called skeleton positions, that compose a skeleton structure.[/indent]<pre class='prettyprint'><br /><br />public enum JointID<br />  {<br />	HipCenter = ,<br />	Spine = 1,<br />	ShoulderCenter = 2,<br />	Head = 3,<br />	ShoulderLeft = 4,<br />	ElbowLeft = 5,<br />	WristLeft = 6,<br />	HandLeft = 7,<br />	ShoulderRight = 8,<br />	ElbowRight = 9,<br />	WristRight = 10,<br />	HandRight = 11,<br />	HipLeft = 12,<br />	KneeLeft = 13,<br />	AnkleLeft = 14,<br />	FootLeft = 15,<br />	HipRight = 16,<br />	KneeRight = 17,<br />	AnkleRight = 18,<br />	FootRight = 19,<br />	Count = 20,<br />  } <br /></pre><br />
<br />
<br />
<ul class='bbc'><br /><li>Vector - For Source and Target Joints, you also have to define the Vector to check X or Y against one another.<br /></li><li>Operator - Do you expect the Source Vector to be Bigger or Smaller than the Target Vector?<br /></li><li>Score - If the rule is true, what is the score for the rule.<br /></li></ul><br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-3.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Background</strong></span><br />
<br />
Since Microsoft has released the Kinect.NET SDK, I wrote many articles on that subject:<br />
<br />
I think Kinect is very cool and I'm searching for more projects and good ideas for Kinect. A couple of days ago, I talked with my friend <a href='http://blogs.microsoft.co.il/blogs/bursteg/' class='bbc_url' title='External link' rel='nofollow external'>Guy Burstein</a> and he came up with an idea for Kinect application, he said what if people will enter the Microsoft Israel reception and instead of video screen showing commercials, let's add something interesting with Kinect.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Using the Code</strong></span><br />
<br />
Using Kinect events, I can see when user enters the frame, using two timers I can check if the user is just passing by or is standing in front of the camera.<br />
<br />
The below image describes the application flow, at the beginning the application will show random videos, when the Kinect Skeleton Event will raise then the Serious Timer will begin ticking, each tick based on the FPS rate will be aggregated to variable called NumTicks, when the Serious Timer completes we check if NumTicks is big enough based on the FPS, if so then we'll start the Idle Timer and switch to Kinect Image.<br />
<br />
Idle Timer - Each time the Kinect Skeleton Event is raised, the Idle Timer will be restart, so if there is no one in front of the Kinect camera, the Idle Timer will switch back to Videos.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-4.png' alt='Posted Image' class='bbc_img' /></span><br />
As you can see from the images below (or <a href='http://www.youtube.com/watch?v=aw6_bqMeBgo' class='bbc_url' title='External link' rel='nofollow external'>Full Video</a>), when I moved my hands or legs, the Score Bar has changed based on the rules you defined:<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-5.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-6.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-7.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
<strong class='bbc'>You reached the Goal!!!</strong><br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-8.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The entire application works with 4 managers:<br />
<ul class='bbcol decimal'><br /><li>Kinect Manager<br /></li><li>Configuration Manager<br /></li><li>Video Manager<br /></li><li>Authentic Manager<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>Kinect Manager</strong></span><br />
<br />
I've shown how to get started with Kinect many times in my previous posts, but for this application, I've created a singleton class to handle everything related to the Kinect settings, from restarting the Kinect RunTime object to changing the camera angle.<br />
<pre class='prettyprint'><br /><br />public KinectManager()<br />{<br />	try<br />	{<br /><br />	KinectNui = new Runtime();<br /><br />	KinectNui.Initialize(RuntimeOptions.UseColor &#124; RuntimeOptions.UseSkeletalTracking &#124;<br />							RuntimeOptions.UseColor);<br /><br />	KinectNui.VideoStream.Open(ImageStreamType.Video, 2, <br />	ImageResolution.Resolution640x480, <br />			ImageType.ColorYuv);<br /><br />	KinectNui.SkeletonEngine.TransformSmooth = true;<br />	var parameters = new TransformSmoothParameters<br />							{<br />							Smoothing = 1.0f,<br />							Correction = .1f,<br />							Prediction = .1f,<br />							JitterRadius = .05f,<br />							MaxDeviationRadius = .05f<br />							};<br />	KinectNui.SkeletonEngine.SmoothParameters = parameters;<br /><br />	_lastTime = DateTime.Now;<br />	Camera = KinectNui.NuiCamera;<br /><br />	IsInitialize = true;<br />	StatusMessage = Properties.Resources.KinectReady;<br />	}<br />	catch (InvalidOperationException ex)<br />	{<br />	IsInitialize = false;<br />	StatusMessage = ex.Message;<br />	}<br />} <br /></pre><br />
<br />
<br />
<br />
Another important method the KinectManager has is the CameraAngle control.<br />
<pre class='prettyprint'><br /><br />public void ChangeCameraAngle(ChangeDirection dir)<br />{<br />	if (!IsInitialize) return;<br /><br />	try<br />	{<br />	if (dir == ChangeDirection.Up)<br />		Camera.ElevationAngle = Camera.ElevationAngle +<br />		Properties.Settings.Default.ElevationAngleInterval;<br />	else<br />		Camera.ElevationAngle = Camera.ElevationAngle -<br />		Properties.Settings.Default.ElevationAngleInterval;<br /><br />	StatusMessage = Properties.Resources.KinectReady;<br />	}<br />	catch (InvalidOperationException ex)<br />	{<br />	StatusMessage = ex.Message;<br />	}<br />	catch (ArgumentOutOfRangeException outOfRangeException)<br />	{<br />	StatusMessage = outOfRangeException.Message;<br />	}<br />}  <br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Video Manager</strong></span><br />
<br />
The Video Manager has two specific types of Videos to play and the main Videos folders to pick random video each time.<br />
<br />
<strong class='bbc'>Specific</strong>? When the user enters the Kinect Range, you can choose to play a specific video just before the Kinect Image will appear, and when the user leaves Kinect Range, you can choose to play the Out Video.<br />
<br />
Define the type of video you want to play. If you ask for out video and there isn't one, return null - Stop Video and start showing Kinect Image. If you ask for in video and there isn't one, then return random video.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-9.png' alt='Posted Image' class='bbc_img' /></span><br />
<pre class='prettyprint'><br /><br />public static Uri GetVideo(VideoType type)<br />{<br />  if (string.IsNullOrEmpty(Properties.Settings.Default.VideosLibraryFolder) &#124;&#124;<br />	  !Directory.Exists(Properties.Settings.Default.VideosLibraryFolder))<br />	  return null;<br />  else<br />  {<br />	  string value = null;<br />	  switch (type)<br />	  {<br />		  case VideoType.In:<br />			  value = Properties.Settings.Default.VideosLibraryInFile;<br />			  return string.IsNullOrEmpty(value) &#124;&#124; !File.Exists(value) ?<br />				  CollectRandomMovie() : new Uri(value);<br />		  case VideoType.Out:<br />			  value = Properties.Settings.Default.VideosLibraryOutFile;<br />			  return string.IsNullOrEmpty(value) &#124;&#124; !File.Exists(value) ?<br />				  null : new Uri(value);<br />		  default:<br />			  return CollectRandomMovie();<br />	  }<br />  }<br />} <br /> private static Uri CollectRandomMovie()<br />{<br />	var movies = new ArrayList();<br /><br />	foreach (var filter in Properties.Settings.Default.VideoFilter)<br />		movies.AddRange(Directory.GetFiles(Properties.Settings.Default.VideosLibraryFolder,<br />			filter));<br /><br />	if (movies.Count == ) return null;<br /><br />	var rnd = new Random();<br />	return new Uri(movies&#91;rnd.Next(movies.Count)&#93;.ToString());<br />} <br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Configuration Manager</strong></span><br />
Kinect Reception allows you to set a range or rules to define what is considered <strong class='bbc'>Funny</strong>, the rule are based on Joint to Joint and each rule defines the Score if the rule applies.<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-10.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
The RuleObject contains the Source Joint and Target Joint, Vector to check for both, the operator (Bigger or Smaller) and the Score.<br />
<br />
<span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-2.png' alt='Posted Image' class='bbc_img' /></span><br />
<br />
So what does the configuration manager do? It saves the rules. (Using MemoryStream to translate the Rule to string and then save it into the application resources.)<br />
<pre class='prettyprint'><br /><br />public static ObservableCollection Load()<br />{<br />	var deserializer = new XmlSerializer(typeof(ObservableCollection));<br />	try<br />	{<br />		var xs = new XmlSerializer(typeof(ObservableCollection));<br />		var memoryStream = <br />	new MemoryStream(Encoding.UTF8.GetBytes(Properties.Settings.Default.Rules));<br />		var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);<br />		return (ObservableCollection)xs.Deserialize(memoryStream);<br />	}<br />	catch (Exception)<br />	{<br />		return new ObservableCollection();<br />	}<br />} <br />public static void Save(ObservableCollection items)<br />{<br />	try<br />	{<br />		var memoryStream = new MemoryStream();<br />		var xs = new XmlSerializer(typeof(ObservableCollection));<br /><br />		var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);<br />		xs.Serialize(xmlTextWriter, items);<br /><br />		memoryStream = (MemoryStream)xmlTextWriter.BaseStream;<br />		var xmlizedString = Encoding.UTF8.GetString(memoryStream.ToArray());<br /><br />		Properties.Settings.Default.Rules = xmlizedString;<br />	}<br />	catch (Exception ex)<br />	{<br />		throw new ArgumentException(ex.Message);<br />	}<br />} <br /></pre><br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Authentic Manager</strong></span><br />
<br />
The Authentic Manager is the core of Kinect Reception, he will take all rules defined by you and check them against the Skeleton Joints.<br />
<br />
The method below will extract the UnTracked joints and will make sure the joints quality are enough for calculation (We don't want the user moving out of the picture to be considered as funny <span rel='lightbox'><img src='http://uploads.gamedev.net/cp/1327954025-wlEmoticon-sadsmile_3B5BBA5A.png' alt='Posted Image' class='bbc_img' /></span>).<br />
<br />
If the Skeleton Joints reach the Goal Score you define then an event will raise telling the main window to save the current Image and display for the user.<br />
<pre class='prettyprint'><br /><br />public void ChecksForAuthentic(JointsCollection joints)<br />{<br />  if (_rules.Count == ) return;<br /><br />  var fixJoints =<br />	  joints.Cast().Where(<br />		  joint =&gt; joint.Position.W &gt;= .6f &&<br />			  joint.TrackingState == JointTrackingState.Tracked).ToList();<br /><br />  var sb = new StringBuilder();<br />  for (var index = ; index &lt; _rules.Count; index++)<br />  {<br />	var rule = _rules&#91;index&#93;;<br />	var s = (from j in fixJoints.Where(joint =&gt; joint.ID == rule.Source) select j).<br />		DefaultIfEmpty(new Joint() { TrackingState = JointTrackingState.NotTracked }).<br />		Single();<br /><br />	var t = (from j in fixJoints.Where(joint =&gt; joint.ID == rule.Target) select j).<br />		DefaultIfEmpty(new Joint() { TrackingState = JointTrackingState.NotTracked }).<br />		Single();<br /><br />	if (s.TrackingState == JointTrackingState.NotTracked &#124;&#124;<br />		t.TrackingState == JointTrackingState.NotTracked) break;<br /><br />	var sv = s.ToFloat(rule.SourceVector);<br />	var tv = t.ToFloat(rule.TargetVector);<br /><br />	if (rule.Operator == Operators.Bigger && sv &gt; tv)<br />	{<br />	  Score = Score + rule.Score;<br />	  sb.AppendLine(string.Format("Bigger -&gt; Source: {0}, Target:{1} , Vector:{2}",<br />		  rule.Source, rule.Target, rule.SourceVector));<br />	}<br />	else if (rule.Operator == Operators.Smaller && sv &lt; tv)<br />	{<br />	  Score = Score + rule.Score;<br />	  sb.AppendLine(string.Format("Smaller -&gt; Source: {0}, Target:{1} , Vector:{2}",<br />		  rule.Source, rule.Target, rule.SourceVector));<br />	}<br />  }<br /><br />  if (Score &gt;= _goal)<br />	IsAuthentic(Score, sb.ToString());<br />} <br /></pre><br />
<br />
 <br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>About the Author</strong></span><br />
<br />
	Shai Raiten is VS ALM MVP, currently working for Sela Group as a ALM senior consultant and trainer specializes in Microsoft technologies especially Team System and .NET technology. He is currently consulting in various enterprises in Israel, planning and analysis Load and performance problems using Team System, building Team System customizations and adjusts ALM processes for enterprises. Shai is known as one of the top Team System experts in Israel. He conducts lectures and workshops for developers&#092;QA and enterprises who want to specialize in Team System.<br />
 <br />
My Blog: <a href='http://blogs.microsoft.co.il/blogs/shair/' class='bbc_url' title='External link' rel='nofollow external'>http://blogs.microso...il/blogs/shair/</a>	<br />
<br />
<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>License</strong></span><br />
<br />
This article was authored by Shai Raiten and reproduced for the benefit of our viewers under the terms of the <a href='http://www.opensource.org/licenses/ms-pl.html' class='bbc_url' title='External link' rel='nofollow external'>Ms-PL</a> license.]]></description>
		<pubDate>Mon, 30 Jan 2012 20:07:42 +0000</pubDate>
		<guid isPermaLink="false">e056e52c8dcd019a63e6a3f169892cc9</guid>
	</item>
	<item>
		<title>The Basics of GLSL 4.0 Shaders</title>
		<link>http://www.gamedev.net/page/resources/_/technical/opengl/the-basics-of-glsl-40-shaders-r2861</link>
		<description><![CDATA[Shaders give us the power to implement alternative rendering algorithms and a greater degree of flexibility in the implementation of those techniques. With shaders, we can run custom code directly on the GPU, providing us with the opportunity to leverage the high degree of parallelism available with modern GPUs.<br />
<br />
This article by <strong class='bbc'>David Wolff</strong>, author of <a href='http://www.packtpub.com/opengl-4-0-shading-language-cookbook/book/rk/opengl4-abr4/0811?utm_source=rk_opengl4_abr4_0811&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>OpenGL 4.0 Shading Language Cookbook</a>, provides examples of basic shading techniques such as diffuse shading, two-sided shading, and flat shading. Specifically, we will cover:<br />
<ul class='bbc'><br /><li>Implementing diffuse, per-vertex shading with a single point light source<br /></li><li>Implementing per-vertex ambient, diffuse, and, specular (ADS) shading<br /></li><li>Using functions in shaders<br /></li><li>Implementing two sided shading<br /></li><li>Implementing flat shading<br /></li></ul><br />
<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Introduction</strong></span><br />
Shaders were first introduced into OpenGL in version 2.0, introducing programmability into the formerly fixed-function OpenGL pipeline. Shaders are implemented using the OpenGL Shading Language (GLSL). The GLSL is syntactically similar to C, which should make it easier for experienced OpenGL programmers to learn. Due to the nature of this text, I won't present a thorough introduction to GLSL here. Instead, if you're new to GLSL, reading through these recipes should help you to learn the language by example. If you are already comfortable with GLSL, but don't have experience with version 4.0, you'll see how to implement these techniques utilizing the newer API. However, before we jump into GLSL programming, let's take a quick look at how vertex and fragment shaders fit within the OpenGL pipeline.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Vertex and fragment shaders</strong></span><br />
In OpenGL version 4.0, there are five shader stages: vertex, geometry, tessellation control, tessellation evaluation, and fragment. In this article we'll focus only on the vertex and fragment stages.<br />
<br />
Shaders replace parts of the OpenGL pipeline. More specifically, they make those parts of the pipeline programmable. The following block diagram shows a simplified view of the OpenGL pipeline with only the vertex and fragment shaders installed.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_01.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
Vertex data is sent down the pipeline and arrives at the vertex shader via shader input variables. The vertex shader's input variables correspond to vertex attributes (see <a href='http://www.packtpub.com/article/tips-tricks-getting-started-with-opengl-glsl-4' class='bbc_url' title='External link' rel='nofollow external'>Sending data to a shader using per-vertex attributes and vertex buffer objects</a>). In general, a shader receives its input via programmer-defined input variables, and the data for those variables comes either from the main OpenGL application or previous pipeline stages (other shaders). For example, a fragment shader's input variables might be fed from the output variables of the vertex shader. Data can also be provided to any shader stage using uniform variables (see <a href='http://www.packtpub.com/article/opengl-glsl-4-using-uniform-blocks-buffer-objects' class='bbc_url' title='External link' rel='nofollow external'>Sending data to a shader using uniform variables</a>). These are used for information that changes less often than vertex attributes (for example, matrices, light position, and other settings). The following figure shows a simplified view of the relationships between input and output variables when there are two shaders active (vertex and fragment).<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_02.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The vertex shader is executed once for each vertex, possibly in parallel. The data corresponding to vertex position must be transformed into clip coordinates and assigned to the output variable <em class='bbc'>gl_Position</em> before the vertex shader finishes execution. The vertex shader can send other information down the pipeline using shader output variables. For example, the vertex shader might also compute the color associated with the vertex. That color would be passed to later stages via an appropriate output variable.<br />
<br />
Between the vertex and fragment shader, the vertices are assembled into primitives, clipping takes place, and the viewport transformation is applied (among other operations). The rasterization process then takes place and the polygon is filled (if necessary). The fragment shader is executed once for each fragment (pixel) of the polygon being rendered (typically in parallel). Data provided from the vertex shader is (by default) interpolated in a perspective correct manner, and provided to the fragment shader via shader input variables. The fragment shader determines the appropriate color for the pixel and sends it to the frame buffer using output variables. The depth information is handled automatically.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Replicating the old fixed functionality</strong></span><br />
Programmable shaders give us tremendous power and flexibility. However, in some cases we might just want to re-implement the basic shading techniques that were used in the default fixed-function pipeline, or perhaps use them as a basis for other shading techniques. Studying the basic shading algorithm of the old fixed-function pipeline can also be a good way to get started when learning about shader programming.<br />
<br />
In this article, we'll look at the basic techniques for implementing shading similar to that of the old fixed-function pipeline. We'll cover the standard ambient, diffuse, and specular (ADS) shading algorithm, the implementation of two-sided rendering, and flat shading. in the next article, we'll also see some examples of other GLSL features such as <a href='http://www.packtpub.com/article/opengl-glsl-4-using-subroutines-select-shader-functionality' class='bbc_url' title='External link' rel='nofollow external'>functions, subroutines</a>, and the <a href='http://www.packtpub.com/article/opengl-glsl-4-discarding-fragments-create-perforated-look' class='bbc_url' title='External link' rel='nofollow external'>discard</a> keyword.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Implementing diffuse, per-vertex shading with a single point light source</strong></span><br />
One of the simplest shading techniques is to assume that the surface exhibits purely diffuse reflection. That is to say that the surface is one that appears to scatter light in all directions equally, regardless of direction. Incoming light strikes the surface and penetrates slightly before being re-radiated in all directions. Of course, the incoming light interacts with the surface before it is scattered, causing some wavelengths to be fully or partially absorbed and others to be scattered. A typical example of a diffuse surface is a surface that has been painted with a matte paint. The surface has a dull look with no shine at all.<br />
<br />
The following image shows a torus rendered with diffuse shading.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_03.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The mathematical model for diffuse reflection involves two vectors: the direction from the surface point to the light source (<strong class='bbc'>s</strong>), and the normal vector at the surface point (<strong class='bbc'>n</strong>). The vectors are represented in the following diagram.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_04.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The amount of incoming light (or radiance) that reaches the surface is partially dependent on the orientation of the surface with respect to the light source. The physics of the situation tells us that the amount of radiation that reaches a point on a surface is maximal when the light arrives along the direction of the normal vector, and zero when the light is perpendicular to the normal. In between, it is proportional to the cosine of the angle between the direction towards the light source and the normal vector. So, since the dot product is proportional to the cosine of the angle between two vectors, we can express the amount of radiation striking the surface as the product of the light intensity and the dot product of <strong class='bbc'>s</strong> and <strong class='bbc'>n</strong>.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_05.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
Where L<sub class='bbc'>d</sub> is the intensity of the light source, and the vectors <strong class='bbc'>s</strong> and <strong class='bbc'>n</strong> are assumed to be normalized. You may recall that the dot product of two unit vectors is equal to the cosine of the angle between them.<br />
<br />
As stated previously, some of the incoming light is absorbed before it is re-emitted. We can model this interaction by using a reflection coefficient (K<sub class='bbc'>d</sub>), which represents the fraction of the incoming light that is scattered. This is sometimes referred to as the <strong class='bbc'>diffuse reflectivity</strong>, or the diffuse reflection coefficient. The diffuse reflectivity becomes a scaling factor for the incoming radiation, so the intensity of the outgoing light can be expressed as follows:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_06.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
Because this model depends only on the direction towards the light source and the normal to the surface, not on the direction towards the viewer, we have a model that represents uniform (omnidirectional) scattering.<br />
<br />
In this recipe, we'll evaluate this equation at each vertex in the vertex shader and interpolate the resulting color across the face.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>In this and the following recipes, light intensities and material reflectivity coefficients are represented by 3-component (RGB) vectors. Therefore, the equations should be treated as component-wise operations, applied to each of the three components separately. Luckily, the GLSL will make this nearly transparent because the needed operators will operate component-wise on vector variables.</em></p><br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
Start with an OpenGL application that provides the vertex position in attribute location 0, and the vertex normal in attribute location 1 (see <a href='http://www.packtpub.com/article/tips-tricks-getting-started-with-opengl-glsl-4' class='bbc_url' title='External link' rel='nofollow external'>Sending data to a shader using per-vertex attributes and vertex buffer objects</a>). The OpenGL application also should provide the standard transformation matrices (projection, modelview, and normal) via uniform variables.<br />
<br />
The light position (in eye coordinates), <em class='bbc'>Kd</em>, and <em class='bbc'>Ld</em> should also be provided by the OpenGL application via uniform variables. Note that <em class='bbc'>Kd</em> and <em class='bbc'>Ld</em> are type vec3. We can use a <em class='bbc'>vec3</em> to store an RGB color as well as a vector or point.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To create a shader pair that implements diffuse shading, use the following code:<br />
<ul class='bbcol decimal'><br /><li>Use the following code for the vertex shader.<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	layout (location = 0) in vec3 VertexPosition;<br />	layout (location = 1) in vec3 VertexNormal;<br />	<br />	out vec3 LightIntensity;<br />	<br />	uniform vec4 LightPosition; // Light position in eye coords.<br />	uniform vec3 Kd; // Diffuse reflectivity<br />	uniform vec3 Ld; // Light source intensity<br />	<br />	uniform mat4 ModelViewMatrix;<br />	uniform mat3 NormalMatrix;<br />	uniform mat4 ProjectionMatrix;<br />	uniform mat4 MVP; // Projection * ModelView<br />	<br />	void main()<br />	{<br />	  // Convert normal and position to eye coords<br />	  vec3 tnorm = normalize( NormalMatrix * VertexNormal);<br />	  vec4 eyeCoords = ModelViewMatrix *<br />					   vec4(VertexPosition,1.0));<br />	  vec3 s = normalize(vec3(LightPosition - eyeCoords));<br />	<br />	  // The diffuse shading equation<br />	  LightIntensity = Ld * Kd * max( dot( s, tnorm ), 0.0 );<br />	<br />	  // Convert position to clip coordinates and pass along<br />	  gl_Position = MVP * vec4(VertexPosition,1.0);<br />	}	<br />	</pre><br /></li><li>Use the following code for the fragment shader.<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	in vec3 LightIntensity;<br />	<br />	layout( location = 0 ) out vec4 FragColor;<br />	<br />	void main() {<br />		FragColor = vec4(LightIntensity, 1.0);<br />	}	<br />	</pre><br /></li><li>Compile and link both shaders within the OpenGL application, and install the shader program prior to rendering. See <a href='http://www.packtpub.com/article/tips-tricks-getting-started-with-opengl-glsl-4' class='bbc_url' title='External link' rel='nofollow external'>Tips and Tricks for Getting Started with OpenGL and GLSL 4.0</a> for details about compiling, linking, and installing shaders.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
The vertex shader does all of the work in this example. The diffuse reflection is computed in eye coordinates by first transforming the normal vector using the normal matrix, normalizing, and storing the result in <em class='bbc'>tnorm</em>. Note that the normalization here may not be necessary if your normal vectors are already normalized and the normal matrix does not do any scaling.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>The normal matrix is typically the inverse transpose of the upper-left 3x3 portion of the model-view matrix. We use the inverse transpose because normal vectors transform differently than the vertex position. For a more thorough discussion of the normal matrix, and the reasons why, see any introductory computer graphics textbook. (A good choice would be Computer Graphics with OpenGL by Hearn and Baker.) If your model-view matrix does not include any non-uniform scalings, then one can use the upper-left 3x3 of the model-view matrix in place of the normal matrix to transform your normal vectors. However, if your model-view matrix does include (uniform) scalings, you'll still need to (re)normalize your normal vectors after transforming them.</em></p><br />
<br />
The next step converts the vertex position to eye (camera) coordinates by transforming it via the model-view matrix. Then we compute the direction towards the light source by subtracting the vertex position from the light position and storing the result in s.<br />
<br />
Next, we compute the scattered light intensity using the equation described above and store the result in the output variable <em class='bbc'>LightIntensity</em>. Note the use of the <em class='bbc'>max</em> function here. If the dot product is less than zero, then the angle between the normal vector and the light direction is greater than 90 degrees. This means that the incoming light is coming from inside the surface. Since such a situation is not physically possible (for a closed mesh), we use a value of 0.0. However, you may decide that you want to properly light both sides of your surface, in which case the normal vector needs to be reversed for those situations where the light is striking the back side of the surface (see <em class='bbc'>Implementing two-sided shading</em>).<br />
<br />
Finally, we convert the vertex position to clip coordinates by multiplying with the model-view projection matrix, (which is: <em class='bbc'>projection * view * model</em>) and store the result in the built-in output variable <em class='bbc'>gl_Position</em>.<br />
<br />
<pre class='prettyprint'><br />gl_Position = MVP * vec4(VertexPosition,1.0);<br /><br /></pre><br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>The subsequent stage of the OpenGL pipeline expects that the vertex position will be provided in clip coordinates in the output variable gl_Position. This variable does not directly correspond to any input variable in the fragment shader, but is used by the OpenGL pipeline in the primitive assembly, clipping, and rasterization stages that follow the vertex shader. It is important that we always provide a valid value for this variable.</em></p><br />
<br />
Since <em class='bbc'>LightIntensity</em> is an output variable from the vertex shader, its value is interpolated across the face and passed into the fragment shader. The fragment shader then simply assigns the value to the output fragment.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
Diffuse shading is a technique that models only a very limited range of surfaces. It is best used for surfaces that have a "matte" appearance. Additionally, with the technique used above, the dark areas may look a bit too dark. In fact, those areas that are not directly illuminated are completely black. In real scenes, there is typically some light that has been reflected about the room that brightens these surfaces. In the following recipes, we'll look at ways to model more surface types, as well as provide some light for those dark parts of the surface.<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Implementing per-vertex ambient, diffuse, and specular (ADS) shading</strong></span><br />
The OpenGL fixed function pipeline implemented a default shading technique which is very similar to the one presented here. It models the light-surface interaction as a combination of three components: ambient, diffuse, and specular. The <strong class='bbc'>ambient</strong> component is intended to model light that has been reflected so many times that it appears to be emanating uniformly from all directions. The <strong class='bbc'>diffuse</strong> component was discussed in the previous recipe, and represents omnidirectional reflection. The <strong class='bbc'>specular</strong> component models the shininess of the surface and represents reflection around a preferred direction. Combining these three components together can model a nice (but limited) variety of surface types. This shading model is also sometimes called the <strong class='bbc'>Phong reflection model</strong> (or <strong class='bbc'>Phong shading model</strong>), after Bui Tuong Phong.<br />
<br />
An example of a torus rendered with the ADS shading model is shown in the following screenshot:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_07.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The ADS model is implemented as the sum of the three components: ambient, diffuse, and specular. The ambient component represents light that illuminates all surfaces equally and reflects equally in all directions. It is often used to help brighten some of the darker areas within a scene. Since it does not depend on the incoming or outgoing directions of the light, it can be modeled simply by multiplying the light source intensity (L<sub class='bbc'>a</sub>) by the surface reflectivity (K<sub class='bbc'>a</sub>).<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_08.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The diffuse component models a rough surface that scatters light in all directions (see <em class='bbc'>Implementing diffuse per-vertex shading with a single point light source</em> above). The intensity of the outgoing light depends on the angle between the surface normal and the vector towards the light source.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_09.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
The specular component is used for modeling the shininess of a surface. When a surface has a glossy shine to it, the light is reflected off of the surface in a mirror-like fashion. The reflected light is strongest in the direction of perfect (mirror-like) reflection. The physics of the situation tells us that for perfect reflection, the angle of incidence is the same as the angle of reflection and that the vectors are coplanar with the surface normal, as shown in the following diagram:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_10.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
In the preceding diagram, r represents the vector of pure-reflection corresponding to the incoming light vector (<strong class='bbc'>-s</strong>), and n is the surface normal. We can compute <strong class='bbc'>r</strong> by using the following equation:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_11.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
To model specular reflection, we need to compute the following (normalized) vectors: the direction towards the light source (<strong class='bbc'>s</strong>), the vector of perfect reflection (<strong class='bbc'>r</strong>), the vector towards the viewer (<strong class='bbc'>v</strong>), and the surface normal (<strong class='bbc'>n</strong>). These vectors are represented in the following image:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_12.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
We would like the reflection to be maximal when the viewer is aligned with the vector <strong class='bbc'>r</strong>, and to fall off quickly as the viewer moves further away from alignment with <strong class='bbc'>r</strong>. This can be modeled using the cosine of the angle between <strong class='bbc'>v</strong> and <strong class='bbc'>r</strong> raised to some power (f).<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_13.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
(Recall that the dot product is proportional to the cosine of the angle between the vectors involved.) The larger the power, the faster the value drops towards zero as the angle between <strong class='bbc'>v</strong> and <strong class='bbc'>r</strong> increases. Again, similar to the other components, we also introduce a specular light intensity term (L<sub class='bbc'>s</sub>) and reflectivity term (K<sub class='bbc'>s</sub>).<br />
<br />
The specular component creates <strong class='bbc'>specular highlights</strong> (bright spots) that are typical of glossy surfaces. The larger the power of f in the equation, the smaller the specular highlight and the shinier the surface appears. The value for f is typically chosen to be somewhere between 1 and 200.<br />
<br />
Putting all of this together, we have the following shading equation:<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_14.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
In the following code, we'll evaluate this equation in the vertex shader, and interpolate the color across the polygon.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
In the OpenGL application, provide the vertex position in location 0 and the vertex normal in location 1. The light position and the other configurable terms for our lighting equation are uniform variables in the vertex shader and their values must be set from the OpenGL application.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To create a shader pair that implements ADS shading, use the following code:<br />
<ul class='bbcol decimal'><br /><li>Use the following code for the vertex shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	layout (location = 0) in vec3 VertexPosition;<br />	layout (location = 1) in vec3 VertexNormal;<br />	<br />	out vec3 LightIntensity;<br />	<br />	struct LightInfo {<br />	  vec4 Position; // Light position in eye coords.<br />	  vec3 La; // Ambient light intensity<br />	  vec3 Ld; // Diffuse light intensity<br />	  vec3 Ls; // Specular light intensity<br />	};<br />	uniform LightInfo Light;<br />	<br />	struct MaterialInfo {<br />	  vec3 Ka; // Ambient reflectivity<br />	  vec3 Kd; // Diffuse reflectivity<br />	  vec3 Ks; // Specular reflectivity<br />	  float Shininess; // Specular shininess factor<br />	};<br />	uniform MaterialInfo Material;<br />	<br />	uniform mat4 ModelViewMatrix;<br />	uniform mat3 NormalMatrix;<br />	uniform mat4 ProjectionMatrix;<br />	uniform mat4 MVP;<br />	<br />	void main()<br />	{<br />	  vec3 tnorm = normalize( NormalMatrix * VertexNormal);<br />	  vec4 eyeCoords = ModelViewMatrix *<br />					   vec4(VertexPosition,1.0);<br />	  vec3 s = normalize(vec3(Light.Position - eyeCoords));<br />	  vec3 v = normalize(-eyeCoords.xyz);<br />	  vec3 r = reflect( -s, tnorm );<br />	  vec3 ambient = Light.La * Material.Ka;<br />	  float sDotN = max( dot(s,tnorm), 0.0 );<br />	  vec3 diffuse = Light.Ld * Material.Kd * sDotN;<br />	  vec3 spec = vec3(0.0);<br />	  if( sDotN &gt; 0.0 )<br />		spec = Light.Ls * Material.Ks *<br />			   pow( max( dot(r,v), 0.0 ), Material.Shininess );<br />	<br />	  LightIntensity = ambient + diffuse + spec;<br />	  gl_Position = MVP * vec4(VertexPosition,1.0);<br />	}	<br />	</pre><br /></li><li>Use the following code for the fragment shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	in vec3 LightIntensity;<br />	<br />	layout( location = 0 ) out vec4 FragColor;<br />	<br />	void main() {<br />		FragColor = vec4(LightIntensity, 1.0);<br />	}	<br />	</pre><br /></li><li>Compile and link both shaders within the OpenGL application, and install the shader program prior to rendering.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
The vertex shader computes the shading equation in eye coordinates. It begins by transforming the vertex normal into eye coordinates and normalizing, then storing the result in <em class='bbc'>tnorm</em>. The vertex position is then transformed into eye coordinates and stored in <em class='bbc'>eyeCoords</em>.<br />
<br />
Next, we compute the normalized direction towards the light source (s). This is done by subtracting the vertex position in eye coordinates from the light position and normalizing the result.<br />
<br />
The direction towards the viewer (<em class='bbc'>v</em>) is the negation of the position (normalized) because in eye coordinates the viewer is at the origin.<br />
<br />
We compute the direction of pure reflection by calling the GLSL built-in function <em class='bbc'>reflect</em>, which reflects the first argument about the second. We don't need to normalize the result because the two vectors involved are already normalized.<br />
<br />
The ambient component is computed and stored in the variable <em class='bbc'>ambient</em>. The dot product of <em class='bbc'>s</em> and <em class='bbc'>n</em> is computed next. As in the preceding recipe, we use the built-in function max to limit the range of values to between one and zero. The result is stored in the variable named <em class='bbc'>sDotN</em>, and is used to compute the diffuse component. The resulting value for the diffuse component is stored in the variable <em class='bbc'>diffuse</em>. Before computing the specular component, we check the value of <em class='bbc'>sDotN</em>. If <em class='bbc'>sDotN</em> is zero, then there is no light reaching the surface, so there is no point in computing the specular component, as its value must be zero. Otherwise, if <em class='bbc'>sDotN</em> is greater than zero, we compute the specular component using the equation presented earlier. Again, we use the built-in function <em class='bbc'>max</em> to limit the range of values of the dot product to between one and zero, and the function <em class='bbc'>pow</em> raises the dot product to the power of the <em class='bbc'>Shininess</em> exponent (corresponding to f in our lighting equation).<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>If we did not check sDotN before computing the specular component, it is possible that some specular highlights could appear on faces that are facing away from the light source. This is clearly a non-realistic and undesirable result. Some people solve this problem by multiplying the specular component by the diffuse component, which would decrease the specular component substantially and alter its color. The solution presented here avoids this, at the cost of a branch statement (the if statement).</em></p><br />
<br />
The sum of the three components is then stored in the output variable <em class='bbc'>LightIntensity</em>. This value will be associated with the vertex and passed down the pipeline. Before reaching the fragment shader, its value will be interpolated in a perspective correct manner across the face of the polygon.<br />
<br />
Finally, the vertex shader transforms the position into clip coordinates, and assigns the result to the built-in output variable <em class='bbc'>gl_Position</em> (see <em class='bbc'>Implementing diffuse, per-vertex shading with a single point light source</em>).<br />
<br />
The fragment shader simply applies the interpolated value of <em class='bbc'>LightIntensity</em> to the output fragment by storing it in the shader output variable <em class='bbc'>FragColor</em>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
This version of the ADS (Ambient, Diffuse, and Specular) reflection model is by no means optimal. There are several improvements that could be made. For example, the computation of the vector of pure reflection can be avoided via the use of the so-called "halfway vector".<br />
<br />
<strong class='bbc'>	Using a non-local viewer</strong><br />
<br />
We can avoid the extra normalization needed to compute the vector towards the viewer (v), by using a so-called <strong class='bbc'>non-local viewer</strong>. Instead of computing the direction towards the origin, we simply use the constant vector (0, 0, 1) for all vertices. This is similar to assuming that the viewer is located infinitely far away in the z direction. Of course, it is not accurate, but in practice the visual results are very similar, often visually indistinguishable, saving us normalization.<br />
<br />
In the old fixed-function pipeline, the non-local viewer was the default, and could be adjusted (turned on or off) using the function <em class='bbc'>glLightModel</em>.<br />
<br />
<strong class='bbc'>	Per-vertex vs. Per-fragment</strong><br />
<br />
Since the shading equation is computed within the vertex shader, we refer to this as <strong class='bbc'>per-vertex lighting</strong>. One of the disadvantages of per-vertex lighting is that specular highlights can be warped or lost, due to the fact that the shading equation is not evaluated at each point across the face. For example, a specular highlight that should appear in the middle of a polygon might not appear at all when per-vertex lighting is used, because of the fact that the shading equation is only computed at the vertices where the specular component is near zero.<br />
<br />
<strong class='bbc'>	Directional lights</strong><br />
<br />
We can also avoid the need to compute a light direction (s), for each vertex if we assume a directional light. A <strong class='bbc'>directional light source</strong> is one that can be thought of as located infinitely far away in a given direction. Instead of computing the direction towards the source for each vertex, a constant vector is used, which represents the direction towards the remote light source.<br />
<br />
<strong class='bbc'>	Light attenuation with distance</strong><br />
<br />
You might think that this shading model is missing one important component. It doesn't take into account the effect of the distance to the light source. In fact, it is known that the intensity of radiation from a source falls off in proportion to the inverse square of the distance from the source. So why not include this in our model?<br />
<br />
It would be fairly simple to do so, however, the visual results are often less than appealing. It tends to exaggerate the distance effects and create unrealistic looking images. Remember, our equation is just an approximation of the physics involved and is not a truly realistic model, so it is not surprising that adding a term based on a strict physical law produces unrealistic results.<br />
<br />
In the OpenGL fixed-function pipeline, it was possible to turn on distance attenuation using the <em class='bbc'>glLight</em> function. If desired, it would be straightforward to add a few uniform variables to our shader to produce the same effect.<br />
<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Using functions in shaders</strong></span><br />
The GLSL supports functions that are syntactically similar to C functions. However, the calling conventions are somewhat different. In this example, we'll revisit the ADS shader using functions to help provide abstractions for the major steps.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
As with previous recipes, provide the vertex position at attribute location 0 and the vertex normal at attribute location 1. Uniform variables for all of the ADS coefficients should be set from the OpenGL side, as well as the light position and the standard matrices.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To implement ADS shading using functions, use the following code:<br />
<ul class='bbcol decimal'><br /><li>Use the following vertex shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	layout (location = 0) in vec3 VertexPosition;<br />	layout (location = 1) in vec3 VertexNormal;<br />	<br />	out vec3 LightIntensity;<br />	<br />	struct LightInfo {<br />	  vec4 Position; // Light position in eye coords.<br />	  vec3 La; // Ambient light intensity<br />	  vec3 Ld; // Diffuse light intensity<br />	  vec3 Ls; // Specular light intensity<br />	};<br />	uniform LightInfo Light;<br />	<br />	struct MaterialInfo {<br />	  vec3 Ka; // Ambient reflectivity<br />	  vec3 Kd; // Diffuse reflectivity<br />	  vec3 Ks; // Specular reflectivity<br />	  float Shininess; // Specular shininess factor<br />	};<br />	uniform MaterialInfo Material;<br />	<br />	uniform mat4 ModelViewMatrix;<br />	uniform mat3 NormalMatrix;<br />	uniform mat4 ProjectionMatrix;<br />	uniform mat4 MVP;<br />	<br />	void getEyeSpace( out vec3 norm, out vec4 position )<br />	{<br />	  norm = normalize( NormalMatrix * VertexNormal);<br />	  position = ModelViewMatrix * vec4(VertexPosition,1.0);<br />	}<br />	<br />	vec3 phongModel( vec4 position, vec3 norm )<br />	{<br />	  vec3 s = normalize(vec3(Light.Position - position));<br />	  vec3 v = normalize(-position.xyz);<br />	  vec3 r = reflect( -s, norm );<br />	  vec3 ambient = Light.La * Material.Ka;<br />	  float sDotN = max( dot(s,norm), 0.0 );<br />	  vec3 diffuse = Light.Ld * Material.Kd * sDotN;<br />	  vec3 spec = vec3(0.0);<br />	  if( sDotN &gt; 0.0 )<br />		  spec = Light.Ls * Material.Ks *<br />				 pow( max( dot(r,v), 0.0 ), Material.Shininess );<br />	  return ambient + diffuse + spec;<br />	}<br />	<br />	void main()<br />	{<br />	  vec3 eyeNorm;<br />	  vec4 eyePosition;<br />	  // Get the position and normal in eye space<br />	  getEyeSpace(eyeNorm, eyePosition);<br />	  // Evaluate the lighting equation.<br />	  LightIntensity = phongModel( eyePosition, eyeNorm );<br />	  gl_Position = MVP * vec4(VertexPosition,1.0);<br />	}	<br />	</pre><br /></li><li>Use the following fragment shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	in vec3 LightIntensity;<br />	layout( location = 0 ) out vec4 FragColor;<br />	void main() {<br />		FragColor = vec4(LightIntensity, 1.0);<br />	}	<br />	</pre><br /></li><li>Compile and link both shaders within the OpenGL application, and install the shader program prior to rendering.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
In GLSL functions, the evaluation strategy is "call by value-return" (also called "call by copyrestore" or "call by value-result"). Parameter variables can be qualified with <em class='bbc'>in</em>, <em class='bbc'>out</em>, or <em class='bbc'>inout</em>. Arguments corresponding to input parameters (those qualified with in or inout) are copied into the parameter variable at call time, and output parameters (those qualified with <em class='bbc'>out</em> or <em class='bbc'>inout</em>) are copied back to the corresponding argument before the function returns. If a parameter variable does not have any of the three qualifiers, the default qualifier is <em class='bbc'>in</em>.<br />
<br />
We've created two functions in the vertex shader. The first, named <em class='bbc'>getEyeSpace</em>, transforms the vertex position and vertex normal into eye space, and returns them via output parameters. In the <em class='bbc'>main</em> function, we create two uninitialized variables (<em class='bbc'>eyeNorm</em> and <em class='bbc'>eyePosition</em>) to store the results, and then call the function with the variables as the function's arguments. The function stores the results into the parameter variables (<em class='bbc'>norm</em> and <em class='bbc'>position</em>) which are copied into the arguments before the function returns.<br />
<br />
The second function, <em class='bbc'>phongModel</em>, uses only input parameters. The function receives the eye-space position and normal, and computes the result of the ADS shading equation. The result is returned by the function and stored in the shader output variable <em class='bbc'>LightIntensity</em>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
Since it makes no sense to read from an output parameter variable, output parameters should only be written to within the function. Their value is undefined.<br />
<br />
Within a function, writing to an input only parameter (qualified with <em class='bbc'>in</em>) is allowed. The function's copy of the argument is modified, and changes are not reflected in the argument.<br />
<br />
<strong class='bbc'>	The const qualifier</strong><br />
<br />
The additional qualifier <em class='bbc'>const</em> can be used with input-only parameters (not with <em class='bbc'>out</em> or <em class='bbc'>inout</em>). This qualifier makes the input parameter read-only, so it cannot be written to within the function.<br />
<br />
<strong class='bbc'>	Function overloading</strong><br />
<br />
Functions can be overloaded by creating multiple functions with the same name, but with different number and/or type of parameters. As with many languages, two overloaded functions may not differ in return type only.<br />
<br />
<strong class='bbc'>	Passing arrays or structures to a function</strong><br />
<br />
It should be noted that when passing arrays or structures to functions, they are passed by value. If a large array or structure is passed, it can incur a large copy operation which may not be desired. It would be a better choice to declare these variables in the global scope.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Implementing two-sided shading</strong></span><br />
When rendering a mesh that is completely closed, the back faces of polygons are hidden. However, if a mesh contains holes, it might be the case that the back faces would become visible. In this case, the polygons may be shaded incorrectly due to the fact that the normal vector is pointing in the wrong direction. To properly shade those back faces, one needs to invert the normal vector and compute the lighting equations based on the inverted normal.<br />
<br />
The following image shows a teapot with the lid removed. On the left, the ADS lighting model is used. On the right, the ADS model is augmented with the two-sided rendering technique discussed in this recipe.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_15.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
In this recipe, we'll look at an example that uses the ADS model discussed in the previous recipes, augmented with the ability to correctly shade back faces.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Getting ready</strong></span><br />
The vertex position should be provided in attribute location 0 and the vertex normal in attribute location 1. As in previous examples, the lighting parameters must be provided to the shader via uniform variables.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To implement a shader pair that uses the ADS shading model with two-sided lighting, use the following code:<br />
<ul class='bbcol decimal'><br /><li>Use the following code for the vertex shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	layout (location = 0) in vec3 VertexPosition;<br />	layout (location = 1) in vec3 VertexNormal;<br />	<br />	out vec3 FrontColor;<br />	out vec3 BackColor;<br />	<br />	struct LightInfo {<br />	  vec4 Position; // Light position in eye coords.<br />	  vec3 La; // Ambient light intensity<br />	  vec3 Ld; // Diffuse light intensity<br />	  vec3 Ls; // Specular light intensity<br />	};<br />	uniform LightInfo Light;<br />	<br />	struct MaterialInfo {<br />	  vec3 Ka; // Ambient reflectivity<br />	  vec3 Kd; // Diffuse reflectivity<br />	  vec3 Ks; // Specular reflectivity<br />	  float Shininess; // Specular shininess factor<br />	};<br />	uniform MaterialInfo Material;<br />	<br />	uniform mat4 ModelViewMatrix;<br />	uniform mat3 NormalMatrix;<br />	uniform mat4 ProjectionMatrix;<br />	uniform mat4 MVP;<br />	<br />	vec3 phongModel( vec4 position, vec3 normal ) {<br />	  // The ADS shading calculations go here (see: "Using<br />	  // functions in shaders," and "Implementing<br />	  // per-vertex ambient, diffuse and specular (ADS) shading")<br />	  ...<br />	}<br />	<br />	void main()<br />	{<br />	  vec3 tnorm = normalize( NormalMatrix * VertexNormal);<br />	  vec4 eyeCoords = ModelViewMatrix *<br />					   vec4(VertexPosition,1.0);<br />	<br />	  FrontColor = phongModel( eyeCoords, tnorm );<br />	<br />	  BackColor = phongModel( eyeCoords, -tnorm );<br />	<br />	  gl_Position = MVP * vec4(VertexPosition,1.0);<br />	}	<br />	</pre><br /></li><li>Use the following for the fragment shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	in vec3 FrontColor;<br />	in vec3 BackColor;<br />	<br />	layout( location = 0 ) out vec4 FragColor;<br />	<br />	void main() {<br />	<br />	  if( gl_FrontFacing ) {<br />		  FragColor = vec4(FrontColor, 1.0);<br />	  } else {<br />		  FragColor = vec4(BackColor, 1.0);<br />	  }<br />	}	<br />	</pre><br /></li><li>Compile and link both shaders within the OpenGL application, and install the shader program prior to rendering.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
In the vertex shader, we compute the lighting equation using both the vertex normal and the inverted version, and pass each resultant color to the fragment shader. The fragment shader chooses and applies the appropriate color depending on the orientation of the face.<br />
<br />
The vertex shader is a slightly modified version of the vertex shader presented in the recipe <em class='bbc'>Implementing per-vertex ambient, diffuse, and specular (ADS) shading</em>. The evaluation of the shading model is placed within a function named <em class='bbc'>phongModel</em>. The function is called twice, first using the normal vector (transformed into eye coordinates), and second using the inverted normal vector. The combined results are stored in <em class='bbc'>FrontColor</em> and <em class='bbc'>BackColor</em>, respectively.<br />
<br />
<p class='bbc_indent' style='margin-left: 40px;'><em class='bbc'>Note that there are a few aspects of the shading model that are independent of the orientation of the normal vector (such as the ambient component). One could optimize this code by rewriting it so that the redundant calculations are only done once. However, in this recipe we compute the entire shading model twice in the interest of making things clear and readable.</em></p><br />
<br />
In the fragment shader, we determine which color to apply based on the value of the built-in variable <em class='bbc'>gl_FrontFacing</em>. This is a Boolean value that indicates whether the fragment is part of a front or back facing polygon. Note that this determination is based on the <strong class='bbc'>winding</strong> of the polygon, and not the normal vector. (A polygon is said to have counter-clockwise winding if the vertices are specified in counter-clockwise order as viewed from the front side of the polygon.) By default when rendering, if the order of the vertices appear on the screen in a counter-clockwise order, it indicates a front facing polygon, however, we can change this by calling <em class='bbc'>glFrontFace</em> from the OpenGL program.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>There's more...</strong></span><br />
In the vertex shader we determine the front side of the polygon by the direction of the normal vector, and in the fragment shader, the determination is based on the polygon's winding. For this to work properly, the normal vector must be defined appropriately for the face determined by the setting of <em class='bbc'>glFrontFace</em>.<br />
<br />
<strong class='bbc'>	Using two-sided rendering for debugging</strong><br />
<br />
It can sometimes be useful to visually determine which faces are front facing and which are back facing. For example, when working with arbitrary meshes, polygons may not be specified using the appropriate winding. As another example, when developing a mesh procedurally, it can sometimes be helpful to determine which faces are oriented in the proper direction in order to help with debugging. We can easily tweak our fragment shader to help us solve these kinds of problems by mixing a solid color with all back (or front) faces. For example, we could change the <em class='bbc'>else</em> clause within our fragment shader to the following:<br />
<br />
<pre class='prettyprint'><br />FragColor = mix( vec4(BackColor,1.0),<br />				vec4(1.0,0.0,0.0,1.0), 0.7 );<br /><br /></pre><br />
This would mix a solid red color with all back faces, helping them to stand out, as shown in the following image. In the image, back faces are mixed with 70% red as shown in the preceding code.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Implementing flat shading</strong></span><br />
Per-vertex shading involves computation of the shading model at each vertex and associating the result (a color) with that vertex. The colors are then interpolated across the face of the polygon to produce a smooth shading effect. This is also referred to as <strong class='bbc'>Gouraud shading</strong>. In earlier versions of OpenGL, this per-vertex shading with color interpolation was the default shading technique.<br />
<br />
It is sometimes desirable to use a single color for each polygon so that there is no variation of color across the face of the polygon, causing each polygon to have a flat appearance. This can be useful in situations where the shape of the object warrants such a technique, perhaps because the faces really are intended to look flat, or to help visualize the locations of the polygons in a complex mesh. Using a single color for each polygon is commonly called <strong class='bbc'>flat shading</strong>.<br />
<br />
The images below show a mesh rendered with the ADS shading model. On the left, Gouraud shading is used. On the right, flat shading is used.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_02_16.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
In earlier versions of OpenGL, flat shading was enabled by calling the function <em class='bbc'>glShadeModel</em> with the argument <em class='bbc'>GL_FLAT</em>. In which case, the computed color of the last vertex of each polygon was used across the entire face.<br />
<br />
In OpenGL 4.0, flat shading is facilitated by the interpolation qualifiers available for shader input/output variables.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>How to do it...</strong></span><br />
To modify the ADS shading model to implement flat shading, use the following steps:<br />
<ul class='bbcol decimal'><br /><li>Use the same vertex shader as in the ADS example provided earlier. Change the output variable <em class='bbc'>LightIntensity</em> as follows:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	layout (location = 0) in vec3 VertexPosition;<br />	layout (location = 1) in vec3 VertexNormal;<br />	<br />	flat out vec3 LightIntensity;<br />	<br />	// the rest is identical to the ADS shader...	<br />	</pre><br /></li><li>Use the following code for the fragment shader:<br />	<pre class='prettyprint'>	<br />#version 400<br />	<br />	flat in vec3 LightIntensity;<br />	<br />	layout( location = 0 ) out vec4 FragColor;<br />	<br />	void main() {<br />		FragColor = vec4(LightIntensity, 1.0);<br />	}	<br />	</pre><br /></li><li>Compile and link both shaders within the OpenGL application, and install the shader program prior to rendering.<br /></li></ul><br />
<span style='font-size: 14px;'><strong class='bbc'>How it works...</strong></span><br />
Flat shading is enabled by qualifying the vertex output variable (and its corresponding fragment input variable) with the <em class='bbc'>flat</em> qualifier. This qualifier indicates that no interpolation of the value is to be done before it reaches the fragment shader. The value presented to the fragment shader will be the one corresponding to the result of the invocation of the vertex shader for either the first or last vertex of the polygon. This vertex is called the <strong class='bbc'>provoking vertex</strong>, and can be configured using the OpenGL function <em class='bbc'>glProvokingVertex</em>. For example, the call:<br />
<br />
<pre class='prettyprint'><br />glProvokingVertex(GL_FIRST_VERTEX_CONVENTION);<br /><br /></pre><br />
This indicates that the first vertex should be used as the value for the flat shaded variable. The argument <em class='bbc'>GL_LAST_VERTEX_CONVENTION</em> indicates that the last vertex should be used.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
This article provided examples of basic shading techniques such as diffuse shading, two-sided shading, and flat shading.]]></description>
		<pubDate>Fri, 27 Jan 2012 04:46:14 +0000</pubDate>
		<guid isPermaLink="false">75a84b531abe6e9fe5de743f134186ab</guid>
	</item>
	<item>
		<title>OpenGL 4.0: Using Uniform Blocks and Uniform Bu...</title>
		<link>http://www.gamedev.net/page/resources/_/technical/opengl/opengl-40-using-uniform-blocks-and-uniform-bu-r2860</link>
		<description><![CDATA[If your OpenGL/GLSL program involves multiple shader programs that use the same uniform variables, one has to manage the variables separately for each program. Uniform blocks were designed to ease the sharing of uniform data between programs. In this article by <strong class='bbc'>David Wolff</strong>, author of <a href='http://www.packtpub.com/opengl-4-0-shading-language-cookbook/book/rk/opengl4-abr2/0811?utm_source=rk_opengl4_abr2_0811&utm_medium=content&utm_campaign=ramsai' class='bbc_url' title='External link' rel='nofollow external'>OpenGL 4.0 Shading Language Cookbook</a>, we will create a buffer object for storing the values of all the uniform variables, and bind the buffer to the uniform block. Then when changing programs, the same buffer object need only be re-bound to the corresponding block in the new program.<br />
<br />
Uniform locations are generated when a program is linked, so the locations of the uniforms may change from one program to the next. The data for those uniforms may have to be re-generated and applied to the new locations.<br />
<br />
A uniform block is simply a group of uniform variables defined within a syntactical structure known as a uniform block. For example, in this recipe, we'll use the following uniform block:<br />
<br />
<pre class='prettyprint'><br />uniform BlobSettings {<br />  vec4 InnerColor;<br />  vec4 OuterColor;<br />  float RadiusInner;<br />  float RadiusOuter;<br />};<br /><br /></pre><br />
This defines a block with the name <em class='bbc'>BlobSettings</em> that contains four uniform variables. With this type of block definition, the variables within the block are still part of the global scope and do not need to be qualified with the block name.<br />
<br />
The buffer object used to store the data for the uniforms is often referred to as a <strong class='bbc'>uniform buffer object</strong>. We'll see that a uniform buffer object is simply just a buffer object that is bound to a certain location.<br />
<br />
For this recipe, we'll use a simple example to demonstrate the use of uniform buffer objects and uniform blocks. We'll draw a quad (two triangles) with texture coordinates, and use our fragment shader to fill the quad with a fuzzy circle. The circle is a solid color in the center, but at its edge, it gradually fades to the background color, as shown in the following image.<br />
<br />
<p class='bbc_center'><span rel='lightbox'><img src='http://uploads.gamedev.net/packtpub/4767OS_01_06.png' alt='Posted Image' class='bbc_img' /></span></p><br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>Getting ready</strong></span><br />
Start with an OpenGL program that draws two triangles to form a quad. Provide the position at vertex attribute location 0, and the texture coordinate (0 to 1 in each direction) at vertex attribute location 1 (see: <a href='http://www.packtpub.com/article/tips-tricks-getting-started-with-opengl-glsl-4' class='bbc_url' title='External link' rel='nofollow external'>Sending data to a shader using per-vertex attributes and vertex buffer objects</a>).<br />
<br />
We'll use the following vertex shader:<br />
<br />
<pre class='prettyprint'><br />#version 400<br /><br />layout (location = 0) in vec3 VertexPosition;<br />layout (location = 1) in vec3 VertexTexCoord;<br /><br />out vec3 TexCoord;<br /><br />void main()<br />{<br />	TexCoord = VertexTexCoord;<br />	gl_Position = vec4(VertexPosition,1.0);<br />}<br /><br /></pre><br />
The fragment shader contains the uniform block, and is responsible for drawing our fuzzy circle:<br />
<br />
<pre class='prettyprint'><br />#version 400<br />in vec3 TexCoord;<br />layout (location = 0) out vec4 FragColor;<br /><br />uniform BlobSettings {<br />  vec4 InnerColor;<br />  vec4 OuterColor;<br />  float RadiusInner;<br />  float RadiusOuter;<br />};<br /><br />void main() {<br />	float dx = TexCoord.x - 0.5;<br />	float dy = TexCoord.y - 0.5;<br />	float dist = sqrt(dx * dx + dy * dy);<br />	FragColor =<br />	   mix( InnerColor, OuterColor,<br />			 smoothstep( RadiusInner, RadiusOuter, dist )<br />	   );<br />}<br /><br /></pre><br />
The uniform block is named <em class='bbc'>BlobSettings</em>. The variables within this block define the parameters of our fuzzy circle. The variable <em class='bbc'>OuterColor</em> defines the color outside of the circle. <em class='bbc'>InnerColor</em> is the color inside of the circle. <em class='bbc'>RadiusInner</em> is the radius defining the part of the circle that is a solid color (inside the fuzzy edge), and the distance from the center of the circle to the inner edge of the fuzzy boundary. <em class='bbc'>RadiusOuter</em> is the outer edge of the fuzzy boundary of the circle (when the color is equal to <em class='bbc'>OuterColor</em>).<br />
<br />
The code within the main function computes the distance of the texture coordinate to the center of the quad located at (0.5, 0.5). It then uses that distance to compute the color by using the <em class='bbc'>smoothstep</em> function. This function provides a value that smoothly varies between 0.0 and 1.0 when the value of the third argument is between the values of the first two arguments. Otherwise it returns 0.0 or 1.0 depending on whether it is less than the first or greater than the second, respectively. The <em class='bbc'>mix</em> function is then used to linearly interpolate between <em class='bbc'>InnerColor</em> and <em class='bbc'>OuterColor</em> based on the value returned by the <em class='bbc'>smoothstep</em> function.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>How to do it...</strong></span><br />
In the OpenGL program, after linking the shader program, use the following steps to send data to the uniform block in the fragment shader:<br />
<ul class='bbcol decimal'><br /><li>Get the index of the uniform block using <em class='bbc'>glGetUniformBlockIndex</em>.<br />	<pre class='prettyprint'>	<br />GLuint blockIndex = glGetUniformBlockIndex(programHandle,<br />											  "BlobSettings");	<br />	</pre><br /></li><li>Allocate space for the buffer to contain the data for the uniform block. We get the size of the block using <em class='bbc'>glGetActiveUniformBlockiv</em>.<br />	<pre class='prettyprint'>	<br />GLint blockSize;<br />	<br />	glGetActiveUniformBlockiv(programHandle, blockIndex,<br />						  GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);<br />	<br />	GLubyte * blockBuffer= (GLubyte *) malloc(blockSize);	<br />	</pre><br /></li><li>Query for the offset of each variable within the block. To do so, we first find the index of each variable within the block.<br />	<pre class='prettyprint'>	<br />// Query for the offsets of each block variable<br />	const GLchar *names&#91;&#93; = { "InnerColor", "OuterColor",<br />							  "RadiusInner", "RadiusOuter" };<br />	<br />	GLuint indices&#91;4&#93;;<br />	glGetUniformIndices(programHandle, 4, names, indices);<br />	<br />	GLint offset&#91;4&#93;;<br />	glGetActiveUniformsiv(programHandle, 4, indices,<br />						  GL_UNIFORM_OFFSET, offset);	<br />	</pre><br /></li><li>Place the data into the buffer at the appropriate offsets.<br />	<pre class='prettyprint'>	<br />GLfloat outerColor&#91;&#93; = {0.0f, 0.0f, 0.0f, 0.0f};<br />	GLfloat innerColor&#91;&#93; = {1.0f, 1.0f, 0.75f, 1.0f};<br />	GLfloat innerRadius = 0.25f, outerRadius = 0.45f;<br />	<br />	memcpy(blockBuffer + offset&#91;0&#93;, innerColor,<br />									4 * sizeof(GLfloat));<br />	memcpy(blockBuffer + offset&#91;1&#93;, outerColor,<br />									4 * sizeof(GLfloat));<br />	memcpy(blockBuffer + offset&#91;2&#93;, &innerRadius,<br />									sizeof(GLfloat));<br />	memcpy(blockBuffer + offset&#91;3&#93;, &outerRadius,<br />									sizeof(GLfloat));	<br />	</pre><br /></li><li>Create the OpenGL buffer object and copy the data into it.<br />	<pre class='prettyprint'>	<br />GLuint uboHandle;<br />	glGenBuffers( 1, &uboHandle );<br />	glBindBuffer( GL_UNIFORM_BUFFER, uboHandle );<br />	glBufferData( GL_UNIFORM_BUFFER, blockSize, blockBuffer,<br />				  GL_DYNAMIC_DRAW );	<br />	</pre><br /></li><li>Bind the buffer object to the uniform block.<br />	<pre class='prettyprint'>	<br />glBindBufferBase( GL_UNIFORM_BUFFER, blockIndex, uboHandle );	<br />	</pre><br /></li></ul><br />
<span style='font-size: 18px;'><strong class='bbc'>How it works...</strong></span><br />
Phew! This seems like a lot of work! However, the real advantage comes when using multiple programs where the same buffer object can be used for each program. Let's take a look at each step individually.<br />
<br />
First, we get the index of the uniform block by calling <em class='bbc'>glGetUniformBlockIndex</em>, then we query for the size of the block by calling <em class='bbc'>glGetActiveUniformBlockiv</em>. After getting the size, we allocate a temporary buffer named <em class='bbc'>blockBuffer</em> to hold the data for our block.<br />
<br />
The layout of data within a uniform block is implementation dependent, and implementations may use different padding and/or byte alignment. So, in order to accurately layout our data, we need to query for the offset of each variable within the block. This is done in two steps. First, we query for the index of each variable within the block by calling <em class='bbc'>glGetUniformIndices</em>. This accepts an array of variable names (third argument) and returns the indices of the variables in the array <em class='bbc'>indices</em> (fourth argument). Then we use the indices to query for the offsets by calling <em class='bbc'>glGetActiveUniformsiv</em>. When the fourth argument is <em class='bbc'>GL_UNIFORM_OFFSET</em>, this returns the offset of each variable in the array pointed to by the fifth argument. This function can also be used to query for the size and type; however, in this case we choose not to do so, to keep the code simple (albeit less general).<br />
<br />
The next step involves filling our temporary buffer <em class='bbc'>blockBuffer</em> with the data for the uniforms at the appropriate offsets. Here we use the standard library function <em class='bbc'>memcpy</em> to accomplish this.<br />
<br />
Now that the temporary buffer is populated with the data with the appropriate layout, we can create our buffer object and copy the data into the buffer object. We call <em class='bbc'>glGenBuffers</em> to generate a buffer handle, and then bind that buffer to the <em class='bbc'>GL_UNIFORM_BUFFER</em> binding point by calling <em class='bbc'>glBindBuffer</em>. The space is allocated within the buffer object and the data is copied when <em class='bbc'>glBufferData</em> is called. We use <em class='bbc'>GL_DYNAMIC_DRAW</em> as the usage hint here, because uniform data may be changed somewhat often during rendering. Of course, this is entirely dependent on the situation.<br />
<br />
Finally, we associate the buffer object with the uniform block by calling <em class='bbc'>glBindBufferBase</em>. This function binds to an index within a buffer binding point. Certain binding points are also so-called "indexed buffer targets". This means that the target is actually an array of targets, and <em class='bbc'>glBindBufferBase</em> allows us to bind to one index within the array.<br />
<br />
<span style='font-size: 18px;'><strong class='bbc'>There's more...</strong></span><br />
If the data for a uniform block needs to be changed at some later time, one can call <em class='bbc'>glBufferSubData</em> to replace all or part of the data within the buffer. If you do so, don't forget to first bind the buffer to the generic binding point <em class='bbc'>GL_UNIFORM_BUFFER</em>.<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Using an instance name with a uniform block</strong></span><br />
A uniform block can have an optional instance name. For example, with our <em class='bbc'>BlobSettings</em> block, we could have used the instance name <em class='bbc'>Blob</em>, as shown here:<br />
<br />
<pre class='prettyprint'><br />uniform BlobSettings {<br />  vec4 InnerColor;<br />  vec4 OuterColor;<br />  float RadiusInner;<br />  float RadiusOuter;<br />} Blob;<br /><br /></pre><br />
In this case, the variables within the block are placed within a namespace qualified by the instance name. Therefore our shader code needs to refer to them prefixed with the instance name. For example:<br />
<br />
<pre class='prettyprint'><br />FragColor =<br />   mix( Blob.InnerColor, Blob.OuterColor,<br />	   smoothstep( Blob.RadiusInner, Blob.RadiusOuter, dist )<br />   );<br /><br /></pre><br />
Additionally, we need to qualify the variable names within the OpenGL code when querying for variable indices. The OpenGL specification says that they must be qualified with the block name (<em class='bbc'>BlobSettings</em>). However, my tests using the ATI Catalyst (10.8) drivers required me to use the instance name (<em class='bbc'>Blob</em>).<br />
<br />
<span style='font-size: 14px;'><strong class='bbc'>Using layout qualifiers with uniform blocks</strong></span><br />
Since the layout of the data within a uniform buffer object is implementation dependent, it required us to query for the variable offsets. However, one can avoid this by asking OpenGL to use the standard layout <em class='bbc'>std140</em>. This is accomplished by using a layout qualifier when declaring the uniform block. For example:<br />
<br />
<pre class='prettyprint'><br />layout( std140 ) uniform BlobSettings {<br />   ...<br />};<br /><br /></pre><br />
The <em class='bbc'>std140</em> layout is described in detail within the OpenGL specification document (available at <a href='http://www.opengl.org/' class='bbc_url' title='External link' rel='nofollow external'>http://www.opengl.org</a>).<br />
<br />
Other options for the layout qualifier that apply to uniform block layouts include <em class='bbc'>packed</em> and <em class='bbc'>shared</em>. The <em class='bbc'>packed</em> qualifier simply states that the implementation is free to optimize memory in whatever way it finds necessary (based on variable usage or other criteria). With the <em class='bbc'>packed</em> qualifier, we still need to query for the offsets of each variable. The <em class='bbc'>shared</em> qualifier guarantees that the layout will be consistent between multiple programs and program stages provided that the uniform block declaration does not change. If you are planning to use the same buffer object between multiple programs and/or program stages, it is a good idea to use the <em class='bbc'>shared</em> option.<br />
<br />
There are two other layout qualifiers that are worth mentioning: <em class='bbc'>row_major</em> and <em class='bbc'>column_major</em>. These define the ordering of data within the matrix type variables within the uniform block.<br />
<br />
One can use multiple qualifiers for a block. For example, to define a block with both the <em class='bbc'>row_major</em> and <em class='bbc'>shared</em> qualifiers, we would use the following syntax:<br />
<br />
<pre class='prettyprint'><br />layout( row_major, shared ) uniform BlobSettings {<br />   ...<br />};<br /><br /></pre><br />
<span style='font-size: 18px;'><strong class='bbc'>Summary</strong></span><br />
This article covered the topic of <em class='bbc'>Using Uniform Blocks and Uniform Buffer Objects</em>.]]></description>
		<pubDate>Fri, 27 Jan 2012 04:42:12 +0000</pubDate>
		<guid isPermaLink="false">314954362f31609663dc4765ab4c7030</guid>
	</item>
</channel>
</rss>
