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

<channel>
	<title>Higher-Order Fun &#187; programming</title>
	<atom:link href="http://higherorderfun.com/blog/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://higherorderfun.com/blog</link>
	<description>Game Design &#38; Game Programming</description>
	<lastBuildDate>Sun, 31 Aug 2014 00:02:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.39</generator>
	<item>
		<title>Math for Game Programmers 05 &#8211; Vector Cheat Sheet</title>
		<link>http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/</link>
		<comments>http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/#comments</comments>
		<pubDate>Sun, 03 Jun 2012 17:23:53 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[articles]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://higherorderfun.com/blog/?p=123</guid>
		<description><![CDATA[This is the long due fifth article in this series. If you aren&#8217;t comfortable with vectors, you might want to take a look at the first four articles in this series before: Introduction, Vectors 101, Geometrical Representation of Vectors, Operations on Vectors. This cheat sheet will list several common geometrical problems found in games, and [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This is the long due fifth article in this series. If you aren&#8217;t comfortable with vectors, you might want to take a look at the first four articles in this series before: <a href="http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-01-introduction/">Introduction</a>, <a href="http://higherorderfun.com/blog/2009/06/07/math-for-game-programmers-02-vectors-101/">Vectors 101</a>, <a href="http://higherorderfun.com/blog/2009/06/13/math-for-game-programmers-03-geometrical-representation-of-vectors/">Geometrical Representation of Vectors</a>, <a href="http://higherorderfun.com/blog/2010/02/23/math-for-game-programmers-04-operations-on-vectors/">Operations on Vectors</a>.</p>
<p>This cheat sheet will list several common geometrical problems found in games, and how to solve them with vector math.</p>
<p><span id="more-123"></span></p>
<h2>Complete list of basic vector operations</h2>
<p>But first, a little review.</p>
<p>For this, I assume that you have a vector class readily available. This is mostly 2D-focused, but everything works the same for 3D, except for differences concerning vector product, which I will assume to return just a scalar in the 2D case, representing the &#8220;z&#8221; axis. Any case that only applies to 2D or 3D will be pointed out.</p>
<p>Strictly speaking, a point is not a vector &#8211; but a vector can be used to represent the distance from the origin (0, 0) to the point, and so, it is perfectly reasonable to just use vectors to represent positions as if they were points.</p>
<p>I expect the class to give you access to each of the components, and to the following operations (using C++ style notation, including operator overloading &#8211; but it should be easy to translate to any other language of your choice). If a given operation is not available, you can still do it manually, either by extending the class or creating a &#8220;VectorUtils&#8221; class. The examples below are usually for 2D vectors &#8211; but 3D is usually simply a matter of adding the z coordinate following the pattern of x and y.</p>
<ul>
<li><strong><em>Vector2f operator+(Vector2f vec): </em></strong>Returns the sum of the two vectors. (In a language without operator overloading, this will probably be called add(). Similarly for the next few ones.)<br />
<em>a + b = Vector2f(a.x + b.x, a.y + b.y);</em></li>
<li><em><strong><em>Vector2f operator-(Vector2f vec):Â </em></strong></em>Returns the difference between the two vectors.<em><br />
<em>a &#8211; b = Vector2f(a.x &#8211; b.x, a.y &#8211; b.y);</em></em></li>
<li><em><em><strong><em>Vector2f operator*(Vector2f vec):Â </em></strong></em></em>Returns the component-wise multiplication of the vectors.<em><em><br />
<em>a * b = Vector2f(a.x * b.x, a.y * b.y);</em></em></em></li>
<li><em><em><em><strong><em>Vector2f operator/(Vector2f vec):Â </em></strong></em></em>Returns the component-wise division of the vectors.<em><em><em><em><br />
<em>a / b = Vector2f(a.x / b.x, a.y / b.y);</em></em></em></em></em></em></li>
<li><strong><em>Vector2f operator*(float scalar)</em></strong>: Returns the vector with all components multiplied by the scalar parameter.<br />
<em>a * s = Vector2f(a.x * s, a.y * s);<br />
s * a = <em>Vector2f(a.x * s, a.y * s);</em></em></li>
<li><em><strong><em>Vector2f operator/(float scalar)</em></strong>: </em>Returns the vector with all components divided by the scalar parameter.<em><br />
<em>a / s = Vector2f(a.x / s, a.y / s);</em></em></li>
<li><strong><em>float dot(Vector2f vec)</em></strong>: Returns the dot product between the two vectors.<br />
<em>a.dot(b) = a.x * b.x + a.y * b.y;</em></li>
<li><strong><em>float cross(Vector2f vec)</em></strong>: (2D case) Returns the z component of the cross product of the two vectors augmented to 3D.<br />
<em>a.cross(b) = a.x * b.y &#8211; a.y * b.x;</em></li>
<li><strong><em>Vector3f cross(Vector3f vec)</em></strong>: (3D case) Returns the cross product of the two vectors.<br />
<em>a.cross(b) = Vector3f(a.y * b.z &#8211; a.z * b.y, a.z*b.x &#8211; a.x*b.z, a.x*b.y &#8211; a.y*b.x);</em></li>
<li><strong><em>float length()</em></strong>: Returns the length of the vector.<br />
<em>a.length() = sqrt(a.x * a.x + a.y * a.y);</em></li>
<li><em><strong>float squaredLength()</strong>: </em>Returns the square of the length of the vector. Useful when you just want to compare two vectors to see which is longest, as this avoids computing square roots<br />
<em>a.squaredLength() = a.x * a.x + a.y * a.y;</em></li>
<li><strong><em>float unit()</em></strong>: Returns a vector pointing on the same direction, but with a length of 1.<br />
<em>a.unit() = a / a.length();</em></li>
<li><em><strong>Vector2f turnLeft()</strong>: </em>Returns the vector rotated 90 degrees left. Useful for computing normals. (Assumes that y axis points up, otherwise this is turnRight)<br />
<em>a.turnLeft = Vector2f(-a.y, a.x);Â </em></li>
<li><em><em><strong>Vector2f turnRight()</strong>:Â </em></em>Returns the vector rotated 90 degrees right. Useful for computing normals. (Assumes that y axis points up, otherwise this is turnLeft)<em><br />
<em>a.turnRight = Vector2f(a.y, -a.x);</em></em></li>
<li><strong>Vector2f rotate(float angle)</strong>: Rotates the vector by the specified angle. This is an extremely useful operation, though it is rarely found in Vector classes. Equivalent to multiplying by the 2&#215;2 rotation matrix.<br />
<em>a.rotate(angle) = Â Vector2f(a.x * cos(angle) &#8211; a.y * sin(angle), a.x * sin(angle) + a.y * cos(angle));</em></li>
<li><strong><em>float angle():Â </em></strong>ReturnsÂ the angle that the vector points to.<br />
<em>a.angle() = atan2(a.y, a.x);</em></li>
</ul>
<h2>Simple cases &#8211; warming up</h2>
<h3>Case #01 &#8211; Distance between two points</h3>
<p>You probably know that this is done with the Pythagorean theorem, but the vectorial way is simpler. Given two vectors <em>a</em> and <em>b</em>:</p>
<pre class="brush: cpp; title: ; notranslate">float distance = (a-b).length();</pre>
<h3>Case #02 &#8211; Alignment</h3>
<p>Sometimes, you want to align an image by its center. Sometimes, by its top-left corner. Or sometimes, by its top-center point. More generally, you can do alignment using a vector whose two components go from 0 to 1 (or even beyond, if you&#8217;d like), giving you full control of alignment.</p>
<pre class="brush: cpp; title: ; notranslate">// imgPos, imgSize and align are all Vector2f
Vector2f drawPosition = imgPos + imgSize * align</pre>
<h3>Case #03 &#8211; Parametric Line Equation</h3>
<p>Two points define a line, but it can be tricky to do much with this definition. A better way to work with a line is its parametric equation: one point (&#8220;<em>P0&#8243;</em>) and a direction vector (&#8220;<em>dir&#8221;</em>).</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p0 = point1;
Vector2f dir = (point2 - point1).unit();</pre>
<p>With this, you can, for example, get a point 10 units away by simply doing:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p1 = p0 + dir * 10;</pre>
<h3>Case #04 &#8211; Midpoint and interpolation between points</h3>
<p>Say you have vectors <em>p0</em> and <em>p1</em>. The midpoint between them is simply <em>(p0+p1)/2</em>. More generally, the line segment defined by <em>p0</em> and <em>p1</em>Â can be generated by varying <em>t</em> between 0 and 1 in the following linear interpolation:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p = (1-t) * p0 + t * p1;</pre>
<p>At <em>t = 0</em>, you get <em>p0; </em>at <em>t = 1</em>, you get <em>p1</em>; at <em>t = 0.5</em>, you get the midpoint, etc.</p>
<h3>Case #05 &#8211; Finding the normal of a line segment</h3>
<p>You already know how to find the direction vector of a line segment (case #03). The normal vector is a 90 degree rotation of that, so just call <em>turnLeft()</em> or <em>turnRight()</em> on it!</p>
<h2>Projections using the Dot Product</h2>
<p>The dot product has the incredibly useful property of being able to compute the length of a vector&#8217;s projection along the axis of another. To do this, you need the vector that you&#8217;ll project (&#8220;<em>a</em>&#8220;) and a unit vector (so make sure that you call <em>unit()</em> on it first!) representing the direction (&#8220;<em>dir</em>&#8220;). The length is then simply <em>a.dot(dir)</em>. For example, if you have <em>a = (3, 4)</em> and <em>dir = (1, 0)</em>, thenÂ <em>a.dot(dir) = 3</em>, and you can tell that this is correct, because (1, 0) is the direction vector of the x axis. In fact, <em>a.x</em> is always equivalent to <em>a.dot(Vector2f(1, 0))</em>, and <em>a.y</em> is equivalent to <em>a.dot(Vector2f(0, 1))</em>.</p>
<p>Because the dot product between <em>a</em>Â and <em>b</em>Â is also defined as <em>|a||b|cos(alpha)</em> (where alpha is the angle between the two), the result will be 0 if the two vectors are perpendicular, positive if the angle between them is less than 90, and negative if greater. This can be used to tell if two vectors point in the same general direction.</p>
<p>If you multiply the result of that dot product by the direction vector itself, you get the vector projected along that axis &#8211; let&#8217;s call that &#8220;<em>at</em>&#8221; (t for tangent). If you now do <em>a &#8211; at</em>, you get the part of the vector that is perpendicular to the <em>dir</em> vector &#8211; let&#8217;s call that &#8220;<em>an</em>&#8221; (n for normal). <em>at + an = a</em>.</p>
<h3>Case #06 &#8211; Determining direction closest to dir</h3>
<p>Say that you have a list of directions represented as unit vectors, and you want to find which of them is the closest to <em>dir</em>. Simply find the largest dot product between <em>dir</em> and a vector in the list. Likewise, the smallest dot product will be the direction farthest away.</p>
<h3>Case #07 &#8211; Determining if the angle between two vectors is less than alpha</h3>
<p>Using the equation above, we know that the angle between two vectors <em>a </em>and<em> b </em>will be less than alpha if the dot product between their unit vectors is less than cosine of alpha.</p>
<pre class="brush: cpp; title: ; notranslate">bool isLessThanAlpha(Vector2f a, Vector2f b, float alpha) {
    return a.unit().dot(b.unit()) &lt; cos(alpha);
}</pre>
<h3>Case #08 &#8211; Determining which side of a half-plane a point is on</h3>
<p>Say that you have an arbitrary point in space, <em>p0</em>, and a direction (unit) vector, <em>dir</em>. Imagine that an infinite line goes by <em>p0</em>, perpendicular to <em>dir</em>, dividing the plane in two, the half-plane that <em>dir</em>Â points to, and the half-plane that it does not point to. How do I tell whether a point <em>p</em> is in the side pointed to by <em>dir</em>? Remember that dot product is positive when the angle between vectors is less than 90 degrees, so just project and check against that:</p>
<pre class="brush: cpp; title: ; notranslate">bool isInsideHalfPlane(Vector2f p, Vector2f p0, Vector dir) {
    return (p - p0).dot(dir) &gt;= 0;
}</pre>
<h3>Case #09 &#8211; Forcing a point to be inside a half-plane</h3>
<p>Similar to the case above, but instead of just checking, we&#8217;ll grab the projection and, if less than 0, use it to move the object -projection along dir, so it&#8217;s on the edge of the half-plane.</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f makeInsideHalfPlane(Vector2f p, Vector2f p0, Vector dir) {
    float proj = (p - p0).dot(dir);
    if (proj &gt;= 0)Â return p;
    else return p - proj * dir;
}</pre>
<h3><span style="color: #000000;">Case #10 &#8211; Checking<del>/forcing</del> a point inside a convex polygon</span></h3>
<p><span style="color: #000000;">A convex polygon can be defined to be the intersection of several half-planes, one for each edge of the polygon. Their <em>p0</em> is either vertex of the edge, and their <em>dir</em> is the edge&#8217;s inner-facing normal vector (e.g., if you wind clockwise, that&#8217;d be the <em>turnRight()</em> normal). A point is inside the polygon if and only if it&#8217;s inside all the half-planes. <del>Likewise, you can force it to be inside the polygon (by moving to the closest edge) by applying the <em>makeInsideHalfPlane</em> algorithm with every half-plane.</del>Â [ops, this actually only works if all angles are &gt;= 90 degrees]</span></p>
<h3>Case #11 &#8211; Reflecting a vector with a given normal</h3>
<p>Pong-like game. Ball hits a sloped wall. You know the ball&#8217;s velocity vector and the wall&#8217;s normal vector (see case #05). How do you reflect it realistically? Simple! Just reflect the ball&#8217;s normal velocity, and preserve its tangential velocity.</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f vel = getVel();
Vector2f dir = getWallNormal(); // Make sure this is a unit vector
Vector2f velN = dir * vel.dot(dir); // Normal component
Vector2f velT = vel - velN; // Tangential component
Vector2f reflectedVel = velT - velN;</pre>
<p>For more realism, you can multiply velT and velN by constants representing friction and restitution, respectively.</p>
<h3>Case #12 &#8211; Cancelling movement along an axis</h3>
<p>Sometimes, you want to restrict movement in a given axis. The idea is the same as above: decompose in a normal and tangential speed, and just keep tangential speed. This can be useful, for example, if the character is following a rail.</p>
<h2>Rotations</h2>
<h3>Case #13 &#8211; Rotating a point around a pivot</h3>
<p>If used to represent a point in space, the <em>rotate()</em> method will rotate that point around the origin. That might be interesting, but is limiting. Rotating around an arbitrary <em>pivot</em> vector is simple and much more useful &#8211; simply subtract the <em>pivot</em> from it, as if translating so the origin IS the <em>pivot</em>, then rotate, then add the <em>pivot</em> back:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f rotateAroundPivot(Vector2f p, Vector2f pivot) {
    return (pos - pivot).rotate(angle) + pivot;
}</pre>
<h3>Case #14 &#8211; Determining which direction to turn towards</h3>
<p>Say that you have a character that wants to rotate to face an enemy. He knows his direction, and the direction that he should be facing to be looking straight at the enemy. But should he turn left or right? The <em>cross</em> product provides a simple answer: <em>curDir.cross(targetDir)</em> will return positive if you should turn left, and negative if you should turn right (and 0 if you&#8217;re either facing it already, or 180 degrees from it).</p>
<h2>Other Geometric Cases</h2>
<p>Here are a few other useful cases that aren&#8217;t that heavily vector-based, but useful:</p>
<h3>Case #15 &#8211; Isometric world to screen coordinates</h3>
<p>Isometric game. You know where the (0, 0) of world is on the screen (let&#8217;s call that point <em>origin</em> and represent it with a vector), but how do you know where a given world (x, y) is on the screen? First, you need two vectors determining the coordinate base, a new x and y axes. For a typical isometric game, they can be <em>bx = Vector2f(2, 1)</em>Â and <em>by = Vector2f(-2, 1)Â </em>&#8211; They don&#8217;t necessarily have to be unit vectors. From now, it&#8217;s straightforward:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f p = getWorldPoint();
Vector2f screenPos = bx * p.x + by * p.y + origin;</pre>
<p>Yes, it&#8217;s that simple.</p>
<h3>Case #16 &#8211; Isometric screen to world coordinates</h3>
<p>Same case, but now you want to know which tile the mouse is over. This is more complicated. Since we know that <em>(x&#8217;, y&#8217;) = (x * bx.x + y * by.x, x * bx.y + y * by.y) + origin</em>, we can first subtract origin, and then solve the linear equation. Using <a href="http://en.wikipedia.org/wiki/Cramer%27s_rule">Cramer&#8217;s Rule</a>,Â except that we&#8217;ll be a little clever and use our 2D cross-product (see definition at the beginning of the article) to simplify things:</p>
<pre class="brush: cpp; title: ; notranslate">Vector2f pos = getMousePos() - origin;
float demDet = bx.cross(by);
float xDet = pos.cross(by);
float yDet = bx.cross(pos);
Vector2f worldPos = Vector2f(xDet / demDet, yDet / demDet);</pre>
<p>And now you don&#8217;t need to do that ugly find-rectangle-then-lookup-on-bitmap trick that I&#8217;ve seen done several times before.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>335</slash:comments>
		</item>
		<item>
		<title>Best of Game Development Videos and Presentations</title>
		<link>http://higherorderfun.com/blog/2011/09/09/best-of-game-development-videos-and-presentations/</link>
		<comments>http://higherorderfun.com/blog/2011/09/09/best-of-game-development-videos-and-presentations/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 02:17:32 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[game design]]></category>
		<category><![CDATA[lecture]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[technical]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://higherorderfun.com/blog/?p=80</guid>
		<description><![CDATA[Here&#8217;s a list of my favourite videos and presentations on several subjects related to game development. I strongly recommend every single video listed below, at least those that match your area of expertise. If you can think of any good videos that I missed, please leave a link on the comments. I will update the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a list of my favourite videos and presentations on several subjects related to game development. I strongly recommend every single video listed below, at least those that match your area of expertise.</p>
<p>If you can think of any good videos that I missed, please leave a link on the comments. I will update the post with any videos that I enjoy.</p>
<h3>Game Design</h3>
<ul>
<li>Jesse Schell, &#8220;Games for Change&#8221;<br />
<a href="http://www.g4tv.com/videos/54256/games-for-change-jesse-schell-presentation-video">http://www.g4tv.com/videos/54256/games-for-change-jesse-schell-presentation-video</a></li>
<li>Jesse Schell, &#8220;Design Outside the Box&#8221;<br />
<a href="http://www.g4tv.com/videos/44277/dice-2010-design-outside-the-box-presentation">http://www.g4tv.com/videos/44277/dice-2010-design-outside-the-box-presentation</a></li>
<li>Jonathan Blow, &#8220;Braid Postmortem&#8221;<br />
<a href="http://www.youtube.com/watch?v=gwsi7TEQxKc">http://www.youtube.com/watch?v=gwsi7TEQxKc</a></li>
<li>Jonathan Blow, &#8220;Video Games and the Human Condition&#8221;<br />
<a href="http://www.youtube.com/watch?v=SqFu5O-oPmU">http://www.youtube.com/watch?v=SqFu5O-oPmU</a></li>
<li>Petri Purho, &#8220;Why Being Poor and Having no Budget is Good for Making Games&#8221;<br />
<a href="http://www.youtube.com/watch?v=iwXFOgNVMww">http://www.youtube.com/watch?v=iwXFOgNVMww</a></li>
</ul>
<h3>Programming &amp; Technical</h3>
<ul>
<li>John Carmack, &#8220;Quakecon 2011 Keynote&#8221;<br />
<a href="http://www.youtube.com/watch?v=4zgYG-_ha28">http://www.youtube.com/watch?v=4zgYG-_ha28</a></li>
<li>David Aldridge, &#8220;I Shot You First! Gameplay Networking in Halo: Reach&#8221;<br />
<a href="http://www.gdcvault.com/play/1014345/I-Shot-You-First-Networking">http://www.gdcvault.com/play/1014345/I-Shot-You-First-Networking</a></li>
<li>Jonathan Blow, &#8220;Programming Aesthetics Learned from Making Independent Games&#8221;<br />
<a href="http://www.myplick.com/view/7CRyJCWLM71">http://www.myplick.com/view/7CRyJCWLM71</a></li>
</ul>
<h3>C++</h3>
<p>(Most of the following are highly technical and specific, but I recommend the first presentation, &#8220;Why C++?&#8221;, to every programmer.)</p>
<ul>
<li>Herb Sutter, &#8220;Why C++?&#8221;<br />
<a href="http://channel9.msdn.com/posts/C-and-Beyond-2011-Herb-Sutter-Why-C">http://channel9.msdn.com/posts/C-and-Beyond-2011-Herb-Sutter-Why-C</a></li>
<li>Herb Sutter, &#8220;Writing Modern C++ Code: How C++ has evolved over the years&#8221;<br />
<a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-835T">http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-835T</a></li>
<li>Herb Sutter, &#8220;C++ Questions and Answers&#8221;<br />
<a href="http://channel9.msdn.com/Shows/Going+Deep/Herb-Sutter-C-Questions-and-Answers">http://channel9.msdn.com/Shows/Going+Deep/Herb-Sutter-C-Questions-and-Answers</a></li>
<li>Herb Sutter, &#8220;Perspectives on Modern C++&#8221;<br />
<a href="http://channel9.msdn.com/Shows/Going+Deep/Conversation-with-Herb-Sutter-Perspectives-on-Modern-C0x11">http://channel9.msdn.com/Shows/Going+Deep/Conversation-with-Herb-Sutter-Perspectives-on-Modern-C0x11</a></li>
<li>Scott Meyers, Andrei Alexandrescu &amp; Herb Sutter, &#8220;C++ and Beyond&#8221;<br />
<a href="http://channel9.msdn.com/posts/Scott-Meyers-Andrei-Alexandrescu-and-Herb-Sutter-C-and-Beyond">http://channel9.msdn.com/posts/Scott-Meyers-Andrei-Alexandrescu-and-Herb-Sutter-C-and-Beyond</a></li>
<li>Herb Sutter, &#8220;Heterogeneous Computing and C++ AMP&#8221;<br />
<a href="http://channel9.msdn.com/posts/AFDS-Keynote-Herb-Sutter-Heterogeneous-Computing-and-C-AMP">http://channel9.msdn.com/posts/AFDS-Keynote-Herb-Sutter-Heterogeneous-Computing-and-C-AMP</a></li>
<li>Bjarne Stroustrup, &#8220;C++0x: An overview&#8221;<br />
<a href="http://video.google.com/videoplay?docid=-3478907067117491758">http://video.google.com/videoplay?docid=-3478907067117491758</a></li>
<li>Herb Sutter, &#8220;C++0x Lambda Functions&#8221;<br />
<a href="http://vimeo.com/23975522">http://vimeo.com/23975522<br />
</a> (slides: <a href="http://www.nwcpp.org/images/stories/lambda.pdf">http://www.nwcpp.org/images/stories/lambda.pdf</a>)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2011/09/09/best-of-game-development-videos-and-presentations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Multi-thread OpenGL texture loading</title>
		<link>http://higherorderfun.com/blog/2011/05/26/multi-thread-opengl-texture-loading/</link>
		<comments>http://higherorderfun.com/blog/2011/05/26/multi-thread-opengl-texture-loading/#comments</comments>
		<pubDate>Thu, 26 May 2011 08:29:55 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[opengl]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://higherorderfun.com/blog/?p=74</guid>
		<description><![CDATA[Those who have used OpenGL are probably aware that you can only invoke OpenGL procedures for a given context on the thread that currently owns it &#8211; usually, the main thread. This leads many programmers to assume that OpenGL is strictly single-threaded, and that no loading can be done on the background, inside some loader [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Those who have used OpenGL are probably aware that you can only invoke OpenGL procedures for a given context on the thread that currently owns it &#8211; usually, the main thread. This leads many programmers to assume that OpenGL is strictly single-threaded, and that no loading can be done on the background, inside some loader thread. This is not the actual case, and it&#8217;s actually fairly simple to work around this.</p>
<p>The key to multi-threaded OpenGL is in creating multiple contexts that share data between them. On Windows, it is done with the wglShareLists() procedure. On X and Apple APIs, it can be done during context creation (glXCreateContext() and aglCreateContext(), respectively). It boils down to creating a second context for the loader thread, and setting it to share data with the main context. This way, all data loaded on the second context will be available on the main one &#8211; you can just create a texture normally on the loader thread, and then glBindTexture() it on the main thread, for example.</p>
<p>On Windows/C++0x, the code looks like this:</p>
<pre class="brush: cpp; title: ; notranslate">void startLoader(HWND hwnd)
{
	// Assuming that this is the main thread
	HDC hdc = GetDC(hwnd);
	HGLRC mainContext = wglGetCurrentContext();
	HGLRC loaderContext = wglCreateContext(hdc);
	wglShareLists(loaderContext, mainContext); // Order matters

	boost::thread([=] () {
		wglMakeCurrent(hdc, loaderContext);
		runLoader();	// Your method for loading textures
		wglMakeCurrent(nullptr, nullptr);
		wglDeleteContext(loaderContext);
	});
}</pre>
<p>Most APIs (such as Allegro, SDL, wxWidgets, etc) will provide you with a simple method of retrieving the window handle, which is all that you require to call the above procedure.</p>
<p>Note that you could create the context and share the lists inside the loader thread, but wglShareLists() must be called BEFORE anything is done on the main context, so the safest way is to do it on the main thread (otherwise, the new thread could take a while to run and be too late to do it).</p>
<p><strong>IMPORTANT</strong>! I have observed that, on some cases (Windows 7 64, NVIDIA 320M), attempting to use a texture after it has been created (via glGenTextures()) but before its data finished uploaded (in this case, via glTexSubImage2D()) resulted in the texture being corrupted, and remaining corrupted even after it was uploaded. This will happen even if you wait for glTexSubImage2D() to return before using it on the main thread, since OpenGL is asynchronous. To avoid this problem, make sure that you glFinish() the loader thread before you attempt to use any textures initialized there.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2011/05/26/multi-thread-opengl-texture-loading/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>If programming languages were religions&#8230;</title>
		<link>http://higherorderfun.com/blog/2011/02/16/if-programming-languages-were-religions/</link>
		<comments>http://higherorderfun.com/blog/2011/02/16/if-programming-languages-were-religions/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 04:38:34 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[articles]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[humor]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[religion]]></category>

		<guid isPermaLink="false">http://higherorderfun.com/blog/?p=72</guid>
		<description><![CDATA[I originally wrote this article in December 15, 2008, and posted it on the Aegisub blog. I&#8217;m re-posting it here for archival purposes. &#8212; &#8220;If programming languages were religions&#8221; (Inspired by &#8220;If programming languages were cars&#8220;) C would beÂ Judaism &#8211; it&#8217;s old and restrictive, but most of the world is familiar with its laws and [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I originally wrote this article in December 15, 2008, and posted it on the <a href="http://blog.aegisub.org/2008/12/if-programming-languages-were-religions.html">Aegisub blog</a>. I&#8217;m re-posting it here for archival purposes.</p>
<p>&#8212;</p>
<p>&#8220;If programming languages were religions&#8221;</p>
<p>(Inspired by &#8220;<a href="http://www.cs.caltech.edu/~mvanier/hacking/rants/cars.html">If programming languages were cars</a>&#8220;)</p>
<p><strong>C</strong> would beÂ <strong>Judaism </strong>&#8211; it&#8217;s old and restrictive, but most of the world is familiar with its laws and respects them. The catch is, you can&#8217;t convert into it &#8211; you&#8217;re either into it from the start, or you will think that it&#8217;s insanity. Also, when things go wrong, many people are willing to blame the problems of the world on it.</p>
<p><strong><span id="more-72"></span>Java </strong>would be<strong> Fundamentalist Christianity</strong> &#8211; it&#8217;s theoretically based on C, but it voids so many of the old laws that it doesn&#8217;t feel like the original at all. Instead, it adds its own set of rigid rules, which its followers believe to be far superior to the original. Not only are they certain that it&#8217;s the best language in the world, but they&#8217;re willing to burn those who disagree at the stake.</p>
<p><strong>PHP</strong> would beÂ <strong>Cafeteria Christianity</strong> &#8211; Fights with Java for the web market. It draws a few concepts from C and Java, but only those that it really likes. Maybe it&#8217;s not as coherent as other languages, but at least it leaves you with much more freedom and ostensibly keeps the core idea of the whole thing. Also, the whole concept of &#8220;goto hell&#8221; was abandoned.</p>
<p><strong>C++</strong> would beÂ <strong>Islam </strong>&#8211; It takes C and not only keeps all its laws, but adds a very complex new set of laws on top of it. It&#8217;s so versatile that it can be used to be the foundation of anything, from great atrocities to beautiful works of art. Its followers are convinced that it is the ultimate universal language, and may be angered by those who disagree. Also, if you insult it or its founder, you&#8217;ll probably be threatened with death by more radical followers.</p>
<p><strong>C#</strong> would beÂ <strong>Mormonism </strong>&#8211; At first glance, it&#8217;s the same as Java, but at a closer look you realize that it&#8217;s controlled by a single corporation (which many Java followers believe to be evil), and that many theological concepts are quite different. You suspect that it&#8217;d probably be nice, if only all the followers of Java wouldn&#8217;t discriminate so much against you for following it.</p>
<p><strong>Lisp </strong>would beÂ Z<strong>en Buddhism</strong> &#8211; There is no syntax, there is no centralization of dogma, there are no deities to worship. The entire universe is there at your reach &#8211; if only you are enlightened enough to grasp it. Some say that it&#8217;s not a language at all; others say that it&#8217;s the only language that makes sense.</p>
<p><strong>Haskell </strong>would beÂ <strong>Taoism </strong>&#8211; It is so different from other languages that many people don&#8217;t understand how can anyone use it to produce anything useful. Its followers believe that it&#8217;s the true path to wisdom, but that wisdom is beyond the grasp of most mortals.</p>
<p><strong>Erlang </strong>would beÂ <strong>Hinduism</strong> &#8211; It&#8217;s another strange language that doesn&#8217;t look like it could be used for anything, but unlike most other modern languages, it&#8217;s built around the concept of multiple simultaneous deities.</p>
<p><strong>Perl</strong> would beÂ <strong>Voodoo</strong> &#8211; An incomprehensible series of arcane incantations that involve the blood of goats and permanently corrupt your soul. Often used when your boss requires you to do an urgent task at 21:00 on friday night.</p>
<p><strong>Lua</strong> would beÂ <strong>Wicca</strong> &#8211; A pantheistic language that can easily be adapted for different cultures and locations. Its code is very liberal, and allows for the use of techniques that might be described as magical by those used to more traditional languages. It has a strong connection to the moon.</p>
<p><strong>Ruby </strong>would beÂ <strong>Neo-Paganism</strong> &#8211; A mixture of different languages and ideas that was beaten together into something that might be identified as a language. Its adherents are growing fast, and although most people look at them suspiciously, they are mostly well-meaning people with no intention of harming anyone.</p>
<p><strong>Python</strong> would beÂ <strong>Humanism</strong>: It&#8217;s simple, unrestrictive, and all you need to follow it is common sense. Many of the followers claim to feel relieved from all the burden imposed by other languages, and that they have rediscovered the joy of programming. There are some who say that it is a form of pseudo-code.</p>
<p><strong>COBOL</strong> would beÂ <strong>Ancient Paganism</strong> &#8211; There was once a time when it ruled over a vast region and was important, but nowadays it&#8217;s almost dead, for the good of us all. Although many were scarred by the rituals demanded by its deities, there are some who insist on keeping it alive even today.</p>
<p><strong>APL</strong> would beÂ <strong>Scientology</strong> &#8211; There are many people who claim to follow it, but you&#8217;ve always suspected that it&#8217;s a huge and elaborate prank that got out of control.</p>
<p><strong>LOLCODE</strong> would beÂ <strong>Pastafarianism</strong> &#8211; An esoteric, Internet-born belief that nobody really takes seriously, despite all the efforts to develop and spread it.</p>
<p><strong>Visual Basic</strong> would beÂ <strong>Satanism </strong>&#8211; Except that you don&#8217;t REALLY need to sell your soul to be a Satanist&#8230;</p>
<p>Thanks to jfs and other people on #aegisub for the suggestions. Keep in mind, this list is a joke, and is not meant to offend anyone. Also, if you&#8217;re a Muslim, please don&#8217;t kill me. <img src="http://s.w.org/images/core/emoji/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2011/02/16/if-programming-languages-were-religions/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Understanding the Game Main Loop</title>
		<link>http://higherorderfun.com/blog/2010/08/17/understanding-the-game-main-loop/</link>
		<comments>http://higherorderfun.com/blog/2010/08/17/understanding-the-game-main-loop/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 06:54:26 +0000</pubDate>
		<dc:creator><![CDATA[amz]]></dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[main loop]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://higherorderfun.com/blog/?p=46</guid>
		<description><![CDATA[Video games are simply ordinary software &#8211; there&#8217;s nothing intrinsically special about them. However, they SEEM to behave in a very different way from your ordinary everyday applications &#8211; so much that many experienced programmers are at a complete loss when faced with the task of developing a game from scratch. This difference is mostly [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Video games are simply ordinary software &#8211; there&#8217;s nothing intrinsically special about them. However, they SEEM to behave in a very different way from your ordinary everyday applications &#8211; so much that many experienced programmers are at a complete loss when faced with the task of developing a game from scratch. This difference is mostly caused by game&#8217;s close ties to their main loop. In this article, we&#8217;ll examine what is the main loop, how it works, and why it&#8217;s important.</p>
<p><strong>A simple model</strong></p>
<p>How simply could we model a computer game? Let&#8217;s start by separating the game in two parts: the data inside the computer, and everything outside the computer. This might seem like a strange thing to say, but remember that games are, first and foremost, interactive software. So, outside the computer, we have (at the very least) the <em>player</em>. Inside the computer we have all sorts of data, but the most important is what we call the <em>game state</em>: it contains all the dynamic information of the game: the position of the player, monsters and camera; the current time; the score &#8211; in essence, everything that changes with time.</p>
<p>A computer game can then be understood as a system in which those two entities &#8211; <em>player</em> and <em>game state</em> &#8211; interact with each other according to a specific pattern of rules. The player <em>inputs </em>data into the system, and the system uses the game state to generate <em>output </em>to display to the player. This is not very different from ordinary applications, in which e.g. a click (input) might cause a dialog to show up (output). The difference is how that behaves in respect with time.</p>
<p><strong>The Game Loop</strong></p>
<p>Most applications are developed in a reactive way &#8211; your program just sits around waiting for the user to click something, and then it does something in response. There is a main loop behind your application as well, but it&#8217;s not important &#8211; it&#8217;s abstracted away. With games, your code is constantly being invoked, even in the absence of user input.</p>
<p>The pseudo-code for a video game will often look like this:</p>
<pre class="brush: cpp; title: ; notranslate">
void GameClass::main() {
    init();
    runMainLoop();
    deInit();
}
</pre>
<p>The main loop looks something like this:</p>
<pre class="brush: cpp; title: ; notranslate">
while (running) {
    processInput();
    updateGameState();
    drawScreen();
}
</pre>
<p>First, it reads input from the user and stores it somewhere. Here, it will check the keyboard, gamepad, plastic guitar and network message queues &#8211; basically, it will collect all information from the outside world.</p>
<p>After that, it will use that information to update the game state &#8211; depending on what conditions we have, they will have different results. For example, on the menu screen, detecting that the &#8220;down&#8221; arrow got pressed might increment the &#8220;currently selected menu item&#8221; variable, but the same input while on the game might instead trigger the &#8220;set player as moving down&#8221; flag. Note that the world update is invoked even if the user didn&#8217;t perform any input. This is a very important property of most video games.</p>
<p>Lastly, it will collect the current game state data to generate the output &#8211; it will figure out where the player and camera and everything else are, and generate an image to display on the screen. A more complicated game will also have to deal with other forms of output &#8211; audio and network, for example.<strong><br />
</strong></p>
<p><strong>A More Sophisticated Main Loop</strong></p>
<p>The loop pseudo-code above suffers from a major flaw: it will run at unpredictable speeds &#8211; on fast machines it might run thousands of times per second (which would be a waste), and on slow machines it might run on unacceptably slow speeds &#8211; perhaps only five updates per second or so. Besides the obvious issues, this makes the game much harder to program &#8211; it&#8217;s much easier to write your game logic when you know that you&#8217;ll have a <em>fixed number of steps per second</em>.</p>
<p>Consider this: the player presses the right arrow, and you store a flag containing that information. Now, on every step, regardless of any player action, you&#8217;ll move the player to the right by 1 unit in the game state (which, let&#8217;s say, corresponds to 1 pixel on the screen). If the game runs at 5 Hz (that is, 5 updates per second), the player will move VERY slowly. If it runs at 5000 Hz, he&#8217;ll be out of the screen before you can even see it!</p>
<p>A possible solution to this is to calculate the real time elapsed between two steps and use this information during the step. In practice, however, this makes the game development much harder and error prone. It will also make networking a true nightmare, and will essentially make reliable behavior (e.g. replays) impossible.</p>
<p>A much better solution is to fix the rate at which your game performs its updates. Most modern games use an internal clock of 60 Hz or 30 Hz. Let&#8217;s assume 60 Hz for our example. This means that, 60 times per second, your game will check the input from the player, update the game state, and try to display something on the screen. But how do we control that?</p>
<p>First, let&#8217;s consider the case of a very fast computer. In this case, before each iteration of the main loop, we&#8217;ll check if it&#8217;s time for the update. If it isn&#8217;t, we&#8217;ll simply wait (preferably yielding the time slice back to the operating system), without doing any processing.</p>
<p>In the case of a slower computer, things are trickier &#8211; we can&#8217;t skip on updating the game state, or the game will run in slow motion, so we must sacrifice the output &#8211; the screen rendering. On most games, screen rendering is the slowest part of the pipeline, meaning that most games WILL be able to run at 60 Hz given enough sacrifice on graphics. If not, then the game will be way too slow, and we have no choice but ask the player to get a better computer.</p>
<p>In pseudo-code, our new algorithm now looks somewhat like this:</p>
<pre class="brush: cpp; title: ; notranslate">
while (running) {
    if (isTimeToUpdate()) {
        processInput();
        updateGameState();
        if (hasTimeToDraw()) drawScreen();
    } else {
        waitUntilItsTime();
    }
}
</pre>
<p>It&#8217;s simple, but it&#8217;s very similar to real game loops found in real games.</p>
<p><strong>The Foundation</strong></p>
<p>At this point, it should be clear that the vast majority of the game code will run inside the main loop &#8211; in a simple game, everything except for initialization and deinitialization. Also, that code is now separated in three functions: processing input, updating the game state, and rendering the screen. Since all three of them are controlled by the loop, it&#8217;s the foundation block of every game.</p>
<p>Having this foundation, your task of implementing a game has been reduced into three simpler and relatively independent tasks. The input you collect will be used on the state updating stage, and the state created by that step will be used to generate the output to the user, but they are each their own logically distinct operations, and how they interact with each other is now clear.</p>
<p>If you understand the topic discussed in this article, then all you have to figure out in order to make a (very) simple game is &#8220;how to read user input?&#8221;, &#8220;how to draw stuff on the screen?&#8221; and &#8220;how to keep track of my state and update it?&#8221;. None of those are, at a basic level, difficult, but they might be different from what programmers are used to coding.</p>
<p>On the next article, we&#8217;ll try to figure those things out and write an extremely simple real-time game using those concepts.</p>
]]></content:encoded>
			<wfw:commentRss>http://higherorderfun.com/blog/2010/08/17/understanding-the-game-main-loop/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
