<?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>Limegarden.net &#187; C++</title>
	<atom:link href="http://limegarden.net/tag/cpp/feed/" rel="self" type="application/rss+xml" />
	<link>http://limegarden.net</link>
	<description>Personal site of Wouter Lindenhof</description>
	<lastBuildDate>Mon, 06 Sep 2010 21:15:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Events in C++</title>
		<link>http://limegarden.net/2010/05/17/events-in-c/</link>
		<comments>http://limegarden.net/2010/05/17/events-in-c/#comments</comments>
		<pubDate>Mon, 17 May 2010 17:27:15 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[event]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=312</guid>
		<description><![CDATA[This week I have decided to do some little work on Nova as I would like to use it for a game. But I’m currently missing a GUI. Since writing a GUI is often a pain while a nice GUI is its weight worth in gold it was worth to invest some time in it. [...]]]></description>
			<content:encoded><![CDATA[<p>This week I have decided to do some little work on Nova as I would like to use it for a game. But I’m currently missing a GUI. Since writing a GUI is often a pain while a nice GUI is its weight worth in gold it was worth to invest some time in it.<br />
One of the very first things I have decided on is that I want a good and proper event management system. I like how it is done in C#</p>
<pre class="brush: c#; ">

myButton.Click += new EventHandler(this.myButton_Click);
</pre>
<p>However something equally nice doesn't exist in plain C++, so I have decided to write one.</p>
<pre class="brush: c++; ">

struct GuiEvent
{
	bool cancel;
	GuiEvent() : cancel(false) {}
};

class Button
{
public:
	Event&lt;GuiEvent&gt; OnDown;
	Event&lt;GuiEvent&gt; OnUp;

	void FireClickEvent()
	{
		size_t cycle = 0; GuiEvent e;
		while(OnDown.Fire(cycle, e)) {
			if(e.cancel == true) return;
		}
		e = GuiEvent(); cycle = 0;
		while(OnUp.Fire(cycle, e));
	}
};

class Application : public BaseEvent::Receiver&lt;Application&gt;
{
	Button m_StartButton;
public:
	Application()
	{
		RegisterEvent&lt;GuiEvent&gt;(m_StartButton.OnDown, &amp;Application::StartDown);
		RegisterEvent&lt;GuiEvent&gt;(m_StartButton.OnUp,	&amp;Application::StartUp);
		m_StartButton.FireClickEvent();
	}

	void StartUp(GuiEvent&amp; eventParam)
	{
		std::cout &lt;&lt; &quot;The start button was released&quot; &lt;&lt; &quot;\n&quot;;
	}
	void StartDown(GuiEvent&amp; eventParam)
	{
		// If you set event param to true the release will never be called
		//eventParam.cancel = true;
		std::cout &lt;&lt; &quot;The start button is pressed down&quot; &lt;&lt; &quot;\n&quot;;
	}
};

int main(int argc, const char* argv[])
{
	Application myApp;
	return 0;
}
</pre>
<p>The above is rather primitive as I have written it quickly, but it looks nice and is code that is easy to understand. For the full source <a href='http://limegarden.net/wp-content/uploads/2010/05/main.cpp'>click here (C++ example of events)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/05/17/events-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solved undesired template specification</title>
		<link>http://limegarden.net/2010/04/07/solved-undesired-template-specification/</link>
		<comments>http://limegarden.net/2010/04/07/solved-undesired-template-specification/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 06:30:36 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=304</guid>
		<description><![CDATA[A while ago (why do I always start with that) I wrote an blog entry about undesired template specification, what to encounter and how to work around it. Anyway here is a quick definition of two structures I will be using in the article: /** * I will be using the following structures throughout the [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago (why do I always start with that) I wrote an blog entry about <a href="http://limegarden.net/2010/01/10/undesired-template-specification/" target="_blank">undesired template specification</a>, what to encounter and how to work around it.</p>
<p>Anyway here is a quick definition of two structures I will be using in the article:</p>
<pre class="brush: c++; ">

/**
 * I will be using the following structures throughout the article
 */
template &lt;typename T&gt; struct Vector3&lt;T&gt; {
	union {
		struct { T x, y, z; }
		T array[3];
	};
	Vector3&lt;T&gt;() : x(0), y(0), z(0) {}
	Vector3&lt;T&gt;(T nx, T ny, T nz) : x(nx), y(ny), z(nz) {}
};

template &lt;typename T&gt; struct Vector4&lt;T&gt; {
	union {
		struct { T x, y, z, w; }
		T array[4];
	};
	Vector4&lt;T&gt;() : x(0), y(0), z(0), w(0) {}
	Vector3&lt;T&gt;(T nx, T ny, T nz, T nw) : x(nx), y(ny), z(nz), w(nw) {}
};
typedef Vector3&lt;unsigned int&gt; Vector3u;
typedef Vector3&lt;float&gt;        Vector3f;
typedef Vector4&lt;unsigned int&gt; Vector4u;
typedef Vector4&lt;float&gt;        Vector4f;

struct SVertex
{
	Vector4f pos;
	Vector3f normal;
	Vector2f texcoord;
};
</pre>
<p>Because of Brick (3D random dungeon generator that takes design into account) I have noticed that there is one thing I do failry often:</p>
<pre class="brush: c++; ">

Vector3f position;
SVertex vertex;

/* Need to draw it, so I store position in vertex */
vertex.pos = position; // ERROR! Trying to assign Vector3f to Vector4f!!
</pre>
<p>And finally I used defines to do the conversion for me:</p>
<pre class="brush: c++; ">

#define VEC3TOVEC4(v) Vector4f((v).x, (v).y, (v).z, 0)
#define VEC4TOVEC3(v) Vector3f((v).x, (v).y, (v).z)

/* New code becomes */
vertex.pos = VEC3TOVEC4(position); // Works
</pre>
<p>Of course the above code is not nice to look at and I find it even plain ugly, but it works. However I don't want to do that in future projects (it feels like a hack), I would need to define something like that for every type (float, double, unsigned int et cetera) and on top of that it generates warnings:</p>
<pre class="brush: c++; ">

Vector3&lt;double&gt; position;	// Notice it is unsigned!
SVertex vertex;

/* Need to draw it, so I store position in vertex */
vertex.pos = VEC3TOVEC4(position); // Works, but generates warning about losing information
</pre>
<p>But I wouldn't be writing this post unless I tackled that little issue, and for once I can add that the solution is quite nice as well.</p>
<pre class="brush: c++; ">

Vector3&lt;double&gt; position;	// Notice it is unsigned!
SVertex vertex;

/* Need to draw it, so I store position in vertex */
vertex.pos.Set(position.array, 3); 		// Works, no errors and no warnings
vertex.pos = Vector4f(position.array, 3);	// Works fine as well
</pre>
<p>So what did I change?</p>
<p>Well, I used mutliple template (one for the class and for the function/constructor). This looks something like this:</p>
<pre class="brush: c++; ">

template &lt;typename T&gt; struct Vector4
{
	/* ... */
	template &lt;typename R&gt;
	explicit inline Vector4&lt;T&gt;(const R* values, const unsigned int elements/*=4*/);
	template &lt;typename R&gt;
	inline Vector4&lt;T&gt;&amp; Set(const R* values, const unsigned int elements/*=4*/);
	/* ... */
};

// Implementation
template &lt;typename T&gt; template &lt;typename R&gt;
Vector4&lt;T&gt;::Vector4(const R* values, unsigned int elements)
	: x(elements &gt; 0 ? (T)values[0] : 0), y(elements &gt; 1 ? (T)values[1] : 0)
	, z(elements &gt; 2 ? (T)values[2] : 0), w(elements &gt; 3 ? (T)values[3] : 0)
{
}
template &lt;typename T&gt; template &lt;typename R&gt;
Vector4&lt;T&gt;&amp; Vector4&lt;T&gt;::Set(const R* values, const unsigned int elements)
{
	x = (elements &gt; 0 ? (T)values[0] : 0);
	y = (elements &gt; 1 ? (T)values[1] : 0);
	z = (elements &gt; 2 ? (T)values[2] : 0);
	w = (elements &gt; 3 ? (T)values[3] : 0);
	return *this;
}
</pre>
<p>If you take a look at the code I think it is quite clear except that you might have some questions.</p>
<ol>
<li>
<div><b>Q:</b> Why do you use <code class="codecolorer cpp geshi"><span class="cpp"><span style="color: #0000ff;">explicit</span></span></code> with the constructor?</div>
<div><b>A:</b> Because that prevents the implicit use of constructors. If I would allow it a <code class="codecolorer cpp geshi"><span class="cpp">Vector4u</span></code> could be implicit assigned to <code class="codecolorer cpp geshi"><span class="cpp">Vector3f</span></code>, although it would be missing an argument. However I think that when you are converting, you should be somewhat aware of it, especially when it can be expensive.</div>
</li>
<li>
<div><b>Q:</b> Why have you commented out the default value for <code class="codecolorer cpp geshi"><span class="cpp">elements</span></code>?</div>
<div><b>A:</b> Because you don't know how many elements there are in <code class="codecolorer cpp geshi"><span class="cpp">values</span></code> might be (there is a method to find out). </div>
</li>
<li>
<div><b>Q:</b> So why don't you find out automatically and what is with those conditionals in the constructor?</div>
<div><b>A:</b> Those two are related. By telling it explicitly there is a real good chance that the compiler removes the conditionals, so the <code class="codecolorer cpp geshi"><span class="cpp">&nbsp;<span style="color: #008000;">&#40;</span> check <span style="color: #008080;">?</span> true<span style="color: #000040;">-</span>value <span style="color: #008080;">:</span> false<span style="color: #000040;">-</span>value<span style="color: #008000;">&#41;</span></span></code> check will be removed. </div>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/04/07/solved-undesired-template-specification/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Combo hit!! in code</title>
		<link>http://limegarden.net/2010/04/06/combo-hit-in-code/</link>
		<comments>http://limegarden.net/2010/04/06/combo-hit-in-code/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 07:17:24 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=302</guid>
		<description><![CDATA[I have always wondered how hard it would be to write a combo system. Not that hard I guess. And after a bit of morning programming I already got it working. The only reason it took longer than anticipated was because of muscle memory. One of the features I wanted to test was the delay. [...]]]></description>
			<content:encoded><![CDATA[<p>I have always wondered how hard it would be to write a combo system. Not that hard I guess. And after a bit of morning programming I already got it working. </p>
<p>The only reason it took longer than anticipated was because of muscle memory. One of the features I wanted to test was the delay. For example you want to do the "asdf" combo, but you are for some reason not fast enough, than the combo should not start. Simulating this is easy, just begin the combo and stop somewhere for a second and then complete the combo. So "asd", pause and then "f".<br />
However when I tried that for some reason the combo was sometimes completed. Only after adding the debug messages I noticed that I often automatically did complete the combo. The problem was muscle memory.</p>
<p>Anyway below is the code and if anyone wants to extend it (wrong next key, combo breakers, roman cancel, and follow-up combos) feel free to do so and let me know.</p>
<pre class="brush: c++; ">

/*******************************************************************************
 * The MIT License
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2010 Wouter Lindenhof (http://limegarden.net)
 *
 * Demonstration of a simple ComboHit system
 *******************************************************************************/

#include &lt;Windows.h&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;
#pragma comment(lib, &quot;Winmm.lib&quot;)

#define DEBUGLOG 1 // Set to 0 to turn debug messages off

class KeyHit
{
public:
	UINT m_Key;
	UINT m_Delay;
	UINT m_Waiting;
public:
	KeyHit(UINT key, UINT delay) : m_Key(key), m_Delay(delay), m_Waiting(0) { }
};

class HitCombo
{
	UINT m_SequenceIndex;
	std::vector&lt;KeyHit&gt; m_Keys;
public:
	HitCombo() : m_SequenceIndex(0) { }

	void Cancel();
	void Update(DWORD ms);
	operator bool();
	HitCombo&amp; operator &lt;&lt; (const KeyHit&amp; hit);
};

int main(int argc, const char* argv[])
{
	std::cout &lt;&lt; &quot;-----------------------------------------------&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;This is a combo key tester: &quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;Press \&quot;ASDF\&quot; quickly to do a combo hit&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;Press \&quot;Wouter\&quot; quickly to write my name&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;Press SHIFT and then escape to quit&quot; &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;-----------------------------------------------&quot; &lt;&lt; std::endl;
	HitCombo QuitApplication, ComboHit, WouterCombo;
	QuitApplication &lt;&lt; KeyHit(VK_SHIFT, 250) &lt;&lt; KeyHit(VK_ESCAPE, 250);
	ComboHit		&lt;&lt; KeyHit(&#039;A&#039;, 250) &lt;&lt; KeyHit(&#039;S&#039;, 250) &lt;&lt; KeyHit(&#039;D&#039;, 250)
					&lt;&lt; KeyHit(&#039;F&#039;, 250);
	WouterCombo		&lt;&lt; KeyHit(&#039;W&#039;, 250) &lt;&lt; KeyHit(&#039;O&#039;, 250) &lt;&lt; KeyHit(&#039;U&#039;, 250)
					&lt;&lt; KeyHit(&#039;T&#039;, 250) &lt;&lt; KeyHit(&#039;E&#039;, 250) &lt;&lt; KeyHit(&#039;R&#039;, 250);

	DWORD lastTime = timeGetTime();
	DWORD curTime = lastTime;
	DWORD difference = 0;

	while(true)
	{
		curTime = timeGetTime();
		difference = curTime - lastTime;
		lastTime = curTime;
		if(ComboHit)
		{
			std::cout &lt;&lt; &quot;You did a combo hit!!&quot; &lt;&lt; std::endl;
			WouterCombo.Cancel();
			QuitApplication.Cancel();
		}
		if(WouterCombo)
		{
			std::cout &lt;&lt; &quot;You wrote &#039;Wouter&#039;, good for you!&quot; &lt;&lt; std::endl;
			ComboHit.Cancel();
			QuitApplication.Cancel();
		}
		if(QuitApplication)
		{
			std::cout &lt;&lt; &quot;You quit the application!&quot; &lt;&lt; std::endl;
			ComboHit.Cancel();
			WouterCombo.Cancel();
			break;
		}
		ComboHit.Update(difference);
		QuitApplication.Update(difference);
		WouterCombo.Update(difference);
	}

	return 0;
}

void HitCombo::Cancel() {
	m_SequenceIndex = 0;
}

// Implementation
HitCombo&amp; HitCombo::operator &lt;&lt;(const KeyHit &amp;hit) {
	m_Keys.push_back(hit);
	return *this;
}

HitCombo::operator bool() {
	return m_SequenceIndex == m_Keys.size();
}
void HitCombo::Update(DWORD ms)
{
	if(m_SequenceIndex &lt; m_Keys.size())
	{
		KeyHit&amp; hit = m_Keys[m_SequenceIndex];
		hit.m_Waiting += ms;
		if(GetAsyncKeyState(hit.m_Key) != 0)
		{
			if(hit.m_Waiting &lt; hit.m_Delay)
			{
				hit.m_Waiting = 0;
				m_SequenceIndex++;
#if DEBUGLOG = 1
				std::cout &lt;&lt; &quot;you pressed key &quot; &lt;&lt; (char)hit.m_Key &lt;&lt; std::endl;
#endif
			}else
			{
#if DEBUGLOG = 1
				std::cout &lt;&lt; &quot;Delay too long&quot; &lt;&lt; std::endl;
#endif
				hit.m_Waiting = 0;
				m_SequenceIndex = 0;
			}
			if(m_SequenceIndex == 0)
			{
				hit.m_Waiting = 0;
			}
		}else if(m_SequenceIndex==0)
		{
			hit.m_Waiting = 0;
		}else
		{
			if(hit.m_Waiting &gt; hit.m_Delay)
			{
				m_SequenceIndex = 0;
				hit.m_Waiting = 0;
#if DEBUGLOG
				std::cout &lt;&lt; &quot;Delay too long&quot; &lt;&lt; std::endl;
#endif
			}
		}
	}else
	{
		m_SequenceIndex = 0;
		KeyHit&amp; hit = m_Keys[m_SequenceIndex];
		hit.m_Waiting = 0;
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/04/06/combo-hit-in-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Brick4 in week 10</title>
		<link>http://limegarden.net/2010/03/29/brick4-in-week-10/</link>
		<comments>http://limegarden.net/2010/03/29/brick4-in-week-10/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 12:29:08 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[Brick4]]></category>
		<category><![CDATA[Project]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[graduation project]]></category>
		<category><![CDATA[Procedural]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://limegarden.net/?p=299</guid>
		<description><![CDATA[Well, the major glitches in the building creation system are finished. The graphics also look nice now. Anyway a picture says more than a thousand words in this case.]]></description>
			<content:encoded><![CDATA[<p>Well, the major glitches in the building creation system are finished. The graphics also look nice now. Anyway a picture says more than a thousand words in this case.<br />
<a href="http://limegarden.net/wp-content/uploads/2010/03/Week10.png"><img src="http://limegarden.net/wp-content/uploads/2010/03/Week10-300x233.png" alt="Brick after 10 weeks of development" title="Week10" width="300" height="233" class="aligncenter size-medium wp-image-300" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/03/29/brick4-in-week-10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wavefront Obj Mesh Loader</title>
		<link>http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/</link>
		<comments>http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 02:06:47 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[model loading]]></category>
		<category><![CDATA[Wavefront]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/</guid>
		<description><![CDATA[UPDATED 2010-03-02 11:07: There was a minor bug in the code which caused to tokens recognition to file. You won't encounter it in an obj file, but I fixed it for the good order. I can remember the first time I wrote my Obj Mesh loader. It took hours. Today I needed also an obj [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATED 2010-03-02 11:07:</strong> There was a minor bug in the code which caused to tokens recognition to file. You won't encounter it in an obj file, but I fixed it for the good order.</p>
<p>I can remember the first time I wrote my Obj Mesh loader. It took hours. Today I needed also an obj mesh loader and this time it took mere minutes (under 15 minutes at least), so I have decided to share it. Keep in mind you should most likely separate it in header and source files.</p>
<pre class="brush: cpp; ">

/**
 * The MIT License
 *
 * Copyright (c) 2010 Wouter Lindenhof (http://limegarden.net)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the &quot;Software&quot;), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;sstream&gt;
#include &lt;fstream&gt;

#define TOKEN_VERTEX_POS &quot;v&quot;
#define TOKEN_VERTEX_NOR &quot;vn&quot;
#define TOKEN_VERTEX_TEX &quot;vt&quot;
#define TOKEN_FACE &quot;f&quot;

struct Vector2f{
    float x, y;
};
struct Vector3f{
    float x, y, z;
};

struct ObjMeshVertex{
    Vector3f pos;
    Vector2f texcoord;
    Vector3f normal;
};

/* This is a triangle, that we can render */
struct ObjMeshFace{
    ObjMeshVertex vertices[3];
};

/* This contains a list of triangles */
struct ObjMesh{
    std::vector&lt;ObjMeshFace&gt; faces;
};

/* Internal structure */
struct _ObjMeshFaceIndex{
    int pos_index[3];
    int tex_index[3];
    int nor_index[3];
};

/* Call this function to load a model, only loads trianglized meshes */
ObjMesh LoadObjMesh(std::string filename){
    ObjMesh myMesh;

    std::vector&lt;Vector3f&gt;           positions;
    std::vector&lt;Vector2f&gt;           texcoords;
    std::vector&lt;Vector3f&gt;           normals;
    std::vector&lt;_ObjMeshFaceIndex&gt;  faces;
    /**
     * Load file, parse it
     * Lines beginning with:
     * &#039;#&#039;  are comments can be ignored
     * &#039;v&#039;  are vertices positions (3 floats that can be positive or negative)
     * &#039;vt&#039; are vertices texcoords (2 floats that can be positive or negative)
     * &#039;vn&#039; are vertices normals   (3 floats that can be positive or negative)
     * &#039;f&#039;  are faces, 3 values that contain 3 values which are separated by / and &lt;space&gt;
     */

    char char_buffer[256];
    std::ifstream filestream;
    filestream.open(filename.c_str());
    while(filestream.eof() == false &amp;&amp; filestream.bad() == false){
        memset(char_buffer, 0, 256);
        filestream.getline(char_buffer, 256);
        /* FIXED:
         * Where strlen stood was first 256, however this would cause a problem
         * when you only have a token
         */
        std::stringstream str_stream(std::string(char_buffer, strlen(char_buffer)));
        std::string type_str;
        str_stream &gt;&gt; type_str;
        if(type_str == TOKEN_VERTEX_POS){
            Vector3f pos;
            str_stream &gt;&gt; pos.x &gt;&gt; pos.y &gt;&gt; pos.z;
            positions.push_back(pos);
        }else if(type_str == TOKEN_VERTEX_TEX){
            Vector2f tex;
            str_stream &gt;&gt; tex.x &gt;&gt; tex.y;
            texcoords.push_back(tex);
        }else if(type_str == TOKEN_VERTEX_NOR){
            Vector3f nor;
            str_stream &gt;&gt; nor.x &gt;&gt; nor.y &gt;&gt; nor.z;
            normals.push_back(nor);
        }else if(type_str == TOKEN_FACE){
            _ObjMeshFaceIndex face_index;
            char interupt;
            for(int i = 0; i &lt; 3; ++i){
                str_stream &gt;&gt;  face_index.pos_index[i] &gt;&gt; interupt
                           &gt;&gt; face_index.tex_index[i]  &gt;&gt; interupt
                           &gt;&gt; face_index.nor_index[i];
            }
            faces.push_back(face_index);
        }
    }
    filestream.close();

    for(size_t i = 0; i &lt; faces.size(); ++i){
        ObjMeshFace face;
        for(size_t j = 0; j &lt; 3; ++j){
            face.vertices[j].pos        = positions[faces[i].pos_index[j] - 1];
            face.vertices[j].texcoord   = texcoords[faces[i].tex_index[j] - 1];
            face.vertices[j].normal     = normals[faces[i].nor_index[j] - 1];
        }
        myMesh.faces.push_back(face);
    }

    return myMesh;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/03/02/wavefront-obj-mesh-loader/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Undesired template specification</title>
		<link>http://limegarden.net/2010/01/10/undesired-template-specification/</link>
		<comments>http://limegarden.net/2010/01/10/undesired-template-specification/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 05:47:57 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/01/10/undesired-template-specification/</guid>
		<description><![CDATA[Updated 10 January 2010: The download was not working, this is now fixed Yesterday I decided to improve my math library and to make it more flexible. One of the things that I wanted to do was convert it to a template, so that I could easily make vectors of different types. However when it [...]]]></description>
			<content:encoded><![CDATA[<p><b>Updated 10 January 2010: </b>The download was not working, this is now fixed</p>
<p>Yesterday I decided to improve my math library and to make it more flexible. One of the things that I wanted to do was convert it to a template, so that I could easily make vectors of different types. However when it was finished and I started testing it I came across a lot of issues which my old math library didn't have. The reason that my old library didn't have them was because all of the structures used floats and when used with any other variable type would be automatically be casted, promoted or demoted to match the type float. However templates are more strict on that area since templates need to specialize. I know this is confusing so let me explain by example.<br />
I will show three examples of the above problem and I will explain how to solve any of them. I hope that throughout the progress you will also understand why the problems happen. <br />
But first let me define the class that I use. This piece of code won't change until I cover the solution of the third problem. <br />
The Vector2 class:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">class</span> tVector2 <br />
<span style="color: #008000;">&#123;</span><br />
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span> <br />
&nbsp; &nbsp; T X, Y<span style="color: #008080;">;</span> <br />
&nbsp; &nbsp; tVector2<span style="color: #008000;">&#40;</span>T x, T y<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> X<span style="color: #008000;">&#40;</span>x<span style="color: #008000;">&#41;</span>, Y<span style="color: #008000;">&#40;</span>y<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// Assigrnent operator </span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> operator <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> v<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> X <span style="color: #000080;">=</span> v.<span style="color: #007788;">X</span>, Y<span style="color: #000080;">=</span>v.<span style="color: #007788;">Y</span><span style="color: #008080;">;</span> <span style="color: #0000ff;">return</span> <span style="color: #000040;">*</span><span style="color: #0000dd;">this</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span> &nbsp;<br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<span style="color: #666666;">// Multiplication operator </span><br />
<span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span> tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> v, T r<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>v.<span style="color: #007788;">X</span><span style="color: #000040;">*</span>r, v.<span style="color: #007788;">Y</span><span style="color: #000040;">*</span>r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p><strong>FIRST PROBLEM: ONLY A SINGLE TEMPLATE ARGUMENT</strong></p>
<p>The first problem shows itself rather fast.</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> testMain1<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #666666;">// Think of this as a normal main</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> Vec2<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; Vec2 <span style="color: #000080;">=</span> Vec2 <span style="color: #000040;">*</span> <span style="color:#800080;">2.0f</span><span style="color: #008080;">;</span> <span style="color: #666666;">// Does compile</span><br />
&nbsp; &nbsp; Vec2 <span style="color: #000080;">=</span> Vec2 <span style="color: #000040;">*</span> <span style="color:#800080;">2.0</span><span style="color: #008080;">;</span>&nbsp; <span style="color: #666666;">// Does not compile</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>Visual Studio comes with two errors:</p>
<div class="codecolorer-container text geshi" style="border:1px solid #9F9F9F;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">error C2782: 'tVector2&lt;T&gt; operator *(tVector2&lt;T&gt;,T)' : template parameter 'T' is ambiguous<br />
error C2676: binary '*' : 'tVector2&lt;T&gt;' does not define this operator or a conversion to a type acceptable to the predefined operator</div></div>
<p>If we think about the reason for this problem is rather easy. If we would think as the compiler we would have the following two forms of multiplication:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> &nbsp;operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> &nbsp;v, <span style="color: #0000ff;">float</span> &nbsp;r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> v, <span style="color: #0000ff;">double</span> r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></div></td></tr></tbody></table></div>
<p>The first multiplication in the example does compile as it makes use of the first form, the second multiplication in the example however raises two errors. As you can see neither form can be applied on our multiplication, which has the form <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span></span></code> multiplied by a double. Since the compiler can't figure out whether template argument T is a float or a double, he throws the error that is ambiguous.  <br />
The second error comes forth because the compiler still tries to solve. However it cannot convert <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span></span></code> to a <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span></span></code> and he can't demote the second argument "2.0" to a float because their second form exists and denies him from demoting just like the following examples forbids only using the first form.</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">void</span> TestFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">float</span> &nbsp;v<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #0000ff;">void</span> TestFunction<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> v<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; TestFunction<span style="color: #008000;">&#40;</span><span style="color:#800080;">2.0f</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// Use first form</span><br />
&nbsp; &nbsp; TestFunction<span style="color: #008000;">&#40;</span><span style="color:#800080;">2.0</span> <span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #666666;">// Use second form</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p><b>FIRST SOLUTION: USE MULTIPLE TEMPLATE ARGUMENTS</b></p>
<p>The title of the first solution might feel contradicting as <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span></span></code> does not change, but it is rather easy. We simply add another operator which look as followed.</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T, <span style="color: #0000ff;">typename</span> R<span style="color: #000080;">&gt;</span><br />
tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> v, R r<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>v.<span style="color: #007788;">X</span><span style="color: #000040;">*</span>r, v.<span style="color: #007788;">Y</span><span style="color: #000040;">*</span>r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>The biggest change is that because of using two template arguments, which are used for the first and second argument, is that compiler no longer have to match the types. So the compiler can generate the following:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> &nbsp;operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> v, <span style="color: #0000ff;">int</span> &nbsp; &nbsp;r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> &nbsp;operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> v, <span style="color: #0000ff;">float</span> &nbsp;r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> &nbsp;operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> v, <span style="color: #0000ff;">double</span> r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></div></td></tr></tbody></table></div>
<p>And the everything works. You can even remove the old multiplication method if you want.</p>
<p><b>SECOND PROBLEM: MULTIPLYING DIFFERENT TYPES</b></p>
<p>This problem is exactly the same as the first one, but I cover it none the less as it took me a few seconds more to realize this than I wanted.</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> testMain2<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #666666;">// Think of it as a seperate program</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// Second problem: Multiplying different types</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> Vec2<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> Vec2d<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; Vec2d <span style="color: #000080;">=</span> Vec2d <span style="color: #000040;">*</span> Vec2<span style="color: #008080;">;</span> &nbsp; <span style="color: #666666;">// tVector2&lt;double&gt;=tVector2&lt;double&gt;*tVector2&lt;float&gt;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>When we compile this visual studio comes two times with two different errors (total is four):</p>
<div class="codecolorer-container text geshi" style="border:1px solid #9F9F9F;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">error C2784: 'tVector2&lt;T&gt; operator *(tVector2&lt;T&gt;,R)' : could not deduce template argument for 'tVector2&lt;T&gt;' from 'double'<br />
error C2677: binary '*' : no global operator found which takes type 'tVector2&lt;T&gt;' (or there is no acceptable conversion)</div></div>
<p>The errors all take place in the solution of the previous problem as it tries to solve that function in to the following form:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> v, tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> r<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>v.<span style="color: #007788;">X</span><span style="color: #000040;">*</span>r, v.<span style="color: #007788;">Y</span><span style="color: #000040;">*</span>r<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>I have added on purpose also the body of the form because that is what you should concentrate on. As you can see it tries to multiply <code class="codecolorer cpp geshi"><span class="cpp">v.<span style="color: #007788;">X</span></span></code> with <code class="codecolorer cpp geshi"><span class="cpp">r</span></code>. While <code class="codecolorer cpp geshi"><span class="cpp">v.<span style="color: #007788;">X</span></span></code>is a float, which is correct. <code class="codecolorer cpp geshi"><span class="cpp">r</span></code> is of the type <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span></span></code> and although there are times where this kind of multiplication is correct, the result would be a tVector2 which is wrong. In fact the above code could even be made working with a few simple steps. It would not give the result we are looking for, but it would work. The wrong steps would be, adding a new constructor which has as input two vectors and allowing numbers be multiplied by vectors (like in the first solution, but then the two function arguments switched around). However I will provide you with the correct solution.</p>
<p><b>SECOND SOLUTION: USE MULTIPLE TEMPLATE ARGUMENTS WITH TYPES</b></p>
<p>Similar to the first problem we add the following function:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T, <span style="color: #0000ff;">typename</span> R<span style="color: #000080;">&gt;</span> <br />
tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> operator <span style="color: #000040;">*</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> v, tVector2<span style="color: #000080;">&lt;</span>R<span style="color: #000080;">&gt;</span> r<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>v.<span style="color: #007788;">X</span><span style="color: #000040;">*</span>r.<span style="color: #007788;">X</span>, v.<span style="color: #007788;">Y</span><span style="color: #000040;">*</span>r.<span style="color: #007788;">Y</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>There is however one down side to this solution and that is that type returned is the same as the first template argument, even if the second template argument would be bigger. For example the first template argument is a float and the second is of the type double. In that case we would lose precision.</p>
<p><b>THIRD PROBLEM: CONVERTING FROM ONE TYPE TO ANOTHER TYPE</b></p>
<p>The test case is similar to that of the second problem, but with a little change.</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> testMain3<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #666666;">// Think of it as a seperate program</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// Third problem: Storing different types</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span> Vec2<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span> Vec2d<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">1</span>,<span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; Vec2d <span style="color: #000080;">=</span> Vec2 <span style="color: #000040;">*</span> Vec2d<span style="color: #008080;">;</span> &nbsp; <span style="color: #666666;">// tVector2&lt;double&gt; = tVector2&lt;float&gt; * tVector2&lt;double&gt;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>As you can see the result of the multiplication is now <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span></span></code> while it previously was a <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span></span></code>. This multiplication works, but the problem is the assignment operation. We try to store a <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">float</span><span style="color: #000080;">&gt;</span></span></code> in a <code class="codecolorer cpp geshi"><span class="cpp">tVector2<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">double</span><span style="color: #000080;">&gt;</span></span></code> and that is not allowed. If you look back at the original class you will see that the assignment operator requires that the function argument is of the same type as the class to which it belongs. And if there is one thing I have learned from the previous problem then it is that is not allowed. <br />
However unlike the solutions of the first two problems, this operator needs to be a member function. So we should store a tVector of a unknown type in a tVector of a specialized type (which is actually also unknown, but the compiler specializes this so it is known to him, but not to us).</p>
<p><b>THIRD SOLUTION: TEMPLATE FUNCTION INSIDE A TEMPLATE CLASS</b></p>
<p>To be honest, I didn't think this was at all possible but since I had solved the previous two problems I was intended to find a solution for this one as well. In retrospect the solution was just as simple as the previous one, but then again everything seems easy in retrospect. <br />
The new class looks as followed:</p>
<div class="codecolorer-container cpp geshi" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> T<span style="color: #000080;">&gt;</span> <span style="color: #0000ff;">class</span> tVector2<br />
<span style="color: #008000;">&#123;</span><br />
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; T X, Y<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; tVector2<span style="color: #008000;">&#40;</span>T x, T y<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> X<span style="color: #008000;">&#40;</span>x<span style="color: #008000;">&#41;</span>, Y<span style="color: #008000;">&#40;</span>y<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// Assigment operator (didn't solve the third problem)</span><br />
&nbsp; &nbsp; tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> operator <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> v<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> X <span style="color: #000080;">=</span> v.<span style="color: #007788;">X</span>, Y<span style="color: #000080;">=</span>v.<span style="color: #007788;">Y</span><span style="color: #008080;">;</span> <span style="color: #0000ff;">return</span> <span style="color: #000040;">*</span><span style="color: #0000dd;">this</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #666666;">// Assigment operator which allows other types (solved third problem)</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span><span style="color: #0000ff;">typename</span> R<span style="color: #000080;">&gt;</span> tVector2<span style="color: #000080;">&lt;</span>T<span style="color: #000080;">&gt;</span> operator <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>tVector2<span style="color: #000080;">&lt;</span>R<span style="color: #000080;">&gt;</span> v<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; X <span style="color: #000080;">=</span> v.<span style="color: #007788;">X</span>, Y<span style="color: #000080;">=</span>v.<span style="color: #007788;">Y</span><span style="color: #008080;">;</span> <span style="color: #0000ff;">return</span> <span style="color: #000040;">*</span><span style="color: #0000dd;">this</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></div></td></tr></tbody></table></div>
<p>As you can see a new function has been added, which is a template function. Quite a simple and elegant solution once you accept the fact that you are allowed to create template functions inside a class as well.</p>
<p><b>FINAL WORDS</b></p>
<p>Although the title of the article is "Undesired template specification" it was only how I felt when I encountered all these problems. Afterwards I think it was not undesired at all, because this is how the language should work. If it wouldn't work like this we would barely have control what some of the functions would and then it would really become undesired. <br />
I hope that the all of the above was easy enough to follow (assuming you are familiar with templates) and helped you understand in what went wrong and how to solve it. <br />
As usual I have added the full source code at the bottom of the article. All the functions are in it, however in a production environment I would recommend you remove the old versions of some of the functions since the new functions also cover the functionality of the old ones.</p>
<p>Source code: <a href='http://limegarden.net/2010/01/10/undesired-template-specification/templatetest_0/' rel='attachment wp-att-252'>templatetest_0.zip (2 kb)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/01/10/undesired-template-specification/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The new and improved acyclic visitor with observer pattern (C++)</title>
		<link>http://limegarden.net/2010/01/04/the-new-and-improved-acyclic-visitor-with-observer-pattern-c/</link>
		<comments>http://limegarden.net/2010/01/04/the-new-and-improved-acyclic-visitor-with-observer-pattern-c/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 12:14:23 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[acyclic visitor]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[design pattern]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/01/04/the-new-and-improved-acyclic-visitor-with-observer-pattern-c/</guid>
		<description><![CDATA[I have improved my &#8220;Acyclic Visitor with Observer&#8221; pattern (here is a link to the old one). Now you can create classes that are derived from two Acyclic visitors, something that was not possible with the previous version. On top of that I have made it less complex to use. On top of that they [...]]]></description>
			<content:encoded><![CDATA[<p>I have improved my &ldquo;Acyclic Visitor with Observer&rdquo; pattern (here is a <a href="/2009/03/23/possible-connector-design-pattern-in-c/">link to the old one</a>). Now you can create classes that are derived from two Acyclic visitors, something that was not possible with the previous version. On top of that I have made it less complex to use. On top of that they no longer have generic names (like &ldquo;INotification&rdquo;). The coolest thing is the registering. Previously you had to create the objects in the user code and also specify the class that should receive it. Now, it's simply done when you define the class.</p>
<p>Anyway just compare the code:</p>
<p><b>The old code</b></p>
<pre class="brush: c++; ">

class HelloWorldReceiver : public IReceiver
{
public:
	HelloWorldReceiver()
	{
		m_Translators.push_back( CTranslator&lt;HelloWorldReceiver, WorldNote&gt;() );
		m_Translators.push_back( CTranslator&lt;HelloWorldReceiver, HelloNote&gt;() );
	}
	void Receive(WorldNote* aWorld) {	}
	void Receive(HelloNote* aHello) {	}
};
</pre>
<p><b>The new code</b></p>
<pre class="brush: c++; ">

class HelloWorldVisitor : public tAcyclicVisitor&lt;HelloWorldVisitor&gt;
public:
	HelloWorldVisitor() {
		RegisterAVObject&lt;Hello&gt;();
		RegisterAVObject&lt;World&gt;();
	}
	void Receive(Hello* obj) {	}
	void Receive(World* obj) {	}
};
</pre>
<p>And here is all the code you need to start using it, it's licensed as I promised in the previous post, but as you can see you all you need to do is keep the license in the code (all 21 lines).</p>
<pre class="brush: c++; ">

// The MIT License
//
// Copyright (c) 2009 Wouter Lindenhof (http://limegarden.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the &amp;quot;Software&amp;quot;), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED &amp;quot;AS IS&amp;quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#ifndef __ACYCLIC_VISITOR_H__
#define __ACYCLIC_VISITOR_H__
#include &lt;list&gt;

/**
 * @brief if set to 1 it will allows the user to combine derived acyclic
 * visitors, but this is likely to have a cost because of virtual inheritance.
 */
#define AV_ALLOW_VIRTUAL_INHERITANCE 1

/**
 * @brief this is the base object
 */
class AVBaseObject
{
public:
	virtual ~AVBaseObject() {}
};

class AcyclicVisitor;

class IAVTranslator
{
public:
	virtual const bool Accept(AVBaseObject* object, AcyclicVisitor* visitor) const = 0;
};

class AcyclicVisitor
{
	typedef std::list&lt;IAVTranslator*&gt; TransList;
protected:
	TransList m_AV_Translators;
public:
	virtual ~AcyclicVisitor() {
		for( TransList::iterator it = m_AV_Translators.begin(); it != m_AV_Translators.end(); ++it )
			delete (*it);

		m_AV_Translators.clear();
	}
	void Visit(AVBaseObject* baseObject)
	{
		for( TransList::iterator it = m_AV_Translators.begin(); it != m_AV_Translators.end(); ++it )
			(*it)-&gt;Accept(baseObject, this);
	}
};

template &lt;typename V, typename O&gt;
class tAVTranslator : public IAVTranslator
{
public:
	const bool Accept(AVBaseObject* object, AcyclicVisitor* visitor) const
	{
		V* original_visitor = dynamic_cast&lt;V*&gt;(visitor);
		O* original_object  = dynamic_cast&lt;O*&gt;(object);
		if(original_object == 0 || original_visitor == 0) return false;
		original_visitor-&gt;Receive(original_object);
		return true;
	}
};

template &lt;typename V&gt;
#if AV_ALLOW_VIRTUAL_INHERITANCE == 1
class tAcyclicVisitor : public virtual AcyclicVisitor
#else
class tAcyclicVisitor : public AcyclicVisitor
#endif
{
protected:
	template &lt;typename O&gt; void RegisterAVObject()
	{
		m_AV_Translators.push_back(new tAVTranslator&lt;V, O&gt;());
	}
};

#endif 
</pre>
<p>I have also uploaded the entire <a href='http://limegarden.net/wp-content/uploads/2010/01/Acyclic-Visitor-V2_0.zip'>example</a> that I have used while testing so that you can some more interesting stuff.</p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/01/04/the-new-and-improved-acyclic-visitor-with-observer-pattern-c/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Rewriting examples: Direct3D tutorial 1 with D3DVERTEXELEMENT9</title>
		<link>http://limegarden.net/2010/01/04/rewriting-examples-direct3d-tutorial-1-with-d3dvertexelement9/</link>
		<comments>http://limegarden.net/2010/01/04/rewriting-examples-direct3d-tutorial-1-with-d3dvertexelement9/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 12:14:06 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[graphics]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/01/04/rewriting-examples-direct3d-tutorial-1-with-d3dvertexelement9/</guid>
		<description><![CDATA[A while ago a friend asked me how to do something with Direct3D (better known as DirectX) about streams. I really enjoyed it since it was sometime I have worked with my favorite 3D API and so&#160;I explained the usage of VertexDeceleration by rewriting the very first tutorial of Direct3D of which you can see [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago a friend asked me how to do something with Direct3D (better known as DirectX) about streams. I really enjoyed it since it was sometime I have worked with my favorite 3D API and so&nbsp;I explained the usage of VertexDeceleration by rewriting the very first tutorial of Direct3D of which you can see the result below</p>
<pre class="brush: c++; ">

#include &lt;windows.h&gt;
#include &lt;d3d9.h&gt;
#pragma comment(lib, &quot;d3d9.lib&quot;)
#include &lt;d3dx9.h&gt;
#pragma comment(lib, &quot;d3dx9.lib&quot;)

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	static TCHAR szAppName[] = TEXT (&quot;DirectXStreamExample&quot;);
	HWND         hwnd;
	MSG          msg;
	WNDCLASSEX   wndclassex = {0};
	wndclassex.cbSize        = sizeof(WNDCLASSEX);
	wndclassex.style         = CS_HREDRAW | CS_VREDRAW;
	wndclassex.lpfnWndProc   = WndProc;
	wndclassex.cbClsExtra    = 0;
	wndclassex.cbWndExtra    = 0;
	wndclassex.hInstance     = hInstance;
	wndclassex.hIcon         = LoadIcon (NULL, IDI_APPLICATION);
	wndclassex.hCursor       = LoadCursor (NULL, IDC_ARROW);
	wndclassex.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH);
	wndclassex.lpszMenuName  = NULL;
	wndclassex.lpszClassName = szAppName;
	wndclassex.hIconSm       = wndclassex.hIcon;

	if (!RegisterClassEx (&amp;amp;wndclassex))
	{
		MessageBox (NULL, TEXT (&quot;RegisterClassEx failed!&quot;), szAppName, MB_ICONERROR);
		return 0;
	}
	hwnd = CreateWindowEx (WS_EX_OVERLAPPEDWINDOW,
		szAppName,
		TEXT (&quot;DirectXStreamExample&quot;),
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		640,
		480,
		NULL,
		NULL,
		hInstance,
		NULL); 

	ShowWindow (hwnd, iCmdShow);
	UpdateWindow (hwnd);

	// Now setup DirectX
	IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
	D3DPRESENT_PARAMETERS presentParameters;
	memset(&amp;amp;presentParameters, 0, sizeof(D3DPRESENT_PARAMETERS));
	presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
	presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
	presentParameters.Windowed = true;
	IDirect3DDevice9* device = 0;
	d3d9-&gt;CreateDevice(0, D3DDEVTYPE_HAL, hwnd, D3DCREATE_MIXED_VERTEXPROCESSING, &amp;amp;presentParameters, &amp;amp;device);

	// Create our custom vertex format
	struct POSCOLORVERTEX
	{
		float X, Y, Z, W;
		DWORD color;
	};
	POSCOLORVERTEX vertices[] = {
		{150.0f,  50.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255,0,0)},
		{250.0f, 250.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0,255,0)},
		{ 50.0f, 250.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0,0,255)},
	};

	// Create a vertex decleration
	// Think of a vertex decleration as an object that describes a single custom
	// vertex.

	// 	typedef struct _D3DVERTEXELEMENT9
	// 	{
	// 		WORD    Stream;     // Stream index
	// 		WORD    Offset;     // Offset in the stream in bytes
	// 		BYTE    Type;       // Data type
	// 		BYTE    Method;     // Processing method
	// 		BYTE    Usage;      // Semantics
	// 		BYTE    UsageIndex; // Semantic index
	// 	} D3DVERTEXELEMENT9, *LPD3DVERTEXELEMENT9;

	// Example 1: Tutorial 1 of the DirectX SDK
	// using weighted position (aka screen coordinates) and colors but without
	// using the Fixed Pipeline
	D3DVERTEXELEMENT9 PosColorVertexElements[] = {
		{0, 0,  D3DDECLTYPE_FLOAT4,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT,	0},
		{0, 16, D3DDECLTYPE_D3DCOLOR,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,		0},
		D3DDECL_END()
	};

#if 0
	// Example 2: If you want to add UV it would become something like this:
	D3DVERTEXELEMENT9 PosColorUVVertexElements[] = {
		{0, 0,  D3DDECLTYPE_FLOAT4,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT,	0},
		{0, 16, D3DDECLTYPE_D3DCOLOR,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,		0},
		{0, 20, D3DDECLTYPE_FLOAT2,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,	0},
		D3DDECL_END()
	};
	// Example 3: And if you want UVs first
	D3DVERTEXELEMENT9 PosColorNormalVertexElements[] = {
		{0, 0,		D3DDECLTYPE_FLOAT2,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,	0},
		{0, 8,		D3DDECLTYPE_FLOAT4,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT,	0},
		{0, 8+16,	D3DDECLTYPE_D3DCOLOR,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,		0},
		D3DDECL_END()
	};
	// Example 4: And if you want to send two UV&#039;s
	D3DVERTEXELEMENT9 PosColorNormalVertexElements[] = {
		{0, 0,  D3DDECLTYPE_FLOAT4,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT,	0},
		{0, 16, D3DDECLTYPE_D3DCOLOR,	D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,		0},
		{0, 20, D3DDECLTYPE_FLOAT2,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,	0}, // Maps to TEXCOORD0 in shader
		{1, 28, D3DDECLTYPE_FLOAT2,		D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,	0},	// Maps to TEXCOORD1 in shader
		D3DDECL_END()
	};
#endif

	IDirect3DVertexDeclaration9* vertexDecleration = 0;
	device-&gt;CreateVertexDeclaration(PosColorVertexElements, &amp;amp;vertexDecleration);
	device-&gt;SetVertexDeclaration(vertexDecleration);

	// Create vertex buffer
	IDirect3DVertexBuffer9*  vertexBuffer;
	device-&gt;CreateVertexBuffer(
		3*sizeof(POSCOLORVERTEX),
		0,
		0,								// DON&#039;T pass the FVF code if you are using vertex decleration
		D3DPOOL_DEFAULT,
		&amp;amp;vertexBuffer,
		0);

	// Fill the vertex buffer
	void* pVertices = 0;
	vertexBuffer-&gt;Lock(0, sizeof(vertices), (void**)&amp;amp;pVertices, 0);
	memcpy(pVertices, vertices, sizeof(vertices));
	vertexBuffer-&gt;Unlock();

	bool keepRunning = true;

	while(keepRunning)
	{
		// Render
		device-&gt;Clear(0, 0, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );
		device-&gt;BeginScene();
		// Rendering of scene objects happens here
		// 1. Set the vertex decleration
		// 2. Set the stream source
		device-&gt;SetVertexDeclaration(vertexDecleration);
		device-&gt;SetStreamSource(0, vertexBuffer, 0, sizeof(POSCOLORVERTEX));
		device-&gt;DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
		// End the scene
		device-&gt;EndScene();
		device-&gt;Present(0,0,0,0);

		if (PeekMessage(&amp;amp;msg, NULL, 0, 0, PM_REMOVE))
		{
			if(msg.message == WM_QUIT) keepRunning = false;
			else
			{
				TranslateMessage (&amp;amp;msg);
				DispatchMessage (&amp;amp;msg);
			}
		}
	}

	vertexBuffer-&gt;Release();
	vertexDecleration-&gt;Release();
	device-&gt;Release();
	d3d9-&gt;Release();

	return msg.wParam;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_DESTROY:
		{
			PostQuitMessage (0);
			return (0);
		}break;
	}
	return DefWindowProc (hwnd, message, wParam, lParam);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/01/04/rewriting-examples-direct3d-tutorial-1-with-d3dvertexelement9/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Donuts! (Procedural Torus in C++)</title>
		<link>http://limegarden.net/2010/01/04/donuts-procedural-torus-in-c/</link>
		<comments>http://limegarden.net/2010/01/04/donuts-procedural-torus-in-c/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 12:13:45 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[code snippit]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[Procedural]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/2010/01/04/donuts-procedural-torus-in-c/</guid>
		<description><![CDATA[Recently I got a mail through the contact form of my website about texture mapping on torus (a donut) who said that D3DXCreateTorus didn't not provide texture coordinates. The reason why DirectX and OpenGL (and GLUT) don't provide texture coordinates with these function is best seen when you generate a cube. A cube has 8 [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I got a mail through the contact form of my website about texture mapping on torus (a donut) who said that <code class="codecolorer cpp geshi"><span class="cpp">D3DXCreateTorus</span></code> didn't not provide texture coordinates. The reason why DirectX and OpenGL (and GLUT) don't provide texture coordinates with these function is best seen when you generate a cube. A cube has 8 vertices, however when you add texture coordinates it will increase because otherwise they will share the same texture coordinate. With normals it is no problem (in fact you would prefer that) but if you have a dice (from 1 to 6) than each vertex would use a single texture coordinate for three sides. Just draw an unfolded dice on paper where each edge is connected, but does not cross another edge. It is simply not possible. These complexities are the reason why those procedural mesh functions are so simple. Adding these functionalities would increase complexity of the function and requires you to explain it. On top of that the developers have no idea how you are going to use that function. Maybe you don't want to use the legal texture range [0...1] but [0...3].</p>
<p>Anyway I have decided to take it on and here is the result. You can download the source code here: <a href='http://limegarden.net/wp-content/uploads/2010/01/TorusDX.zip'>TorusDX.zip</a>.I have not commented it, but it is pretty straight forward. The texture that I used is from Dilbert.</p>
<p><a href="http://limegarden.net/wp-content/uploads/2010/01/Donut.png"><img src="http://limegarden.net/wp-content/uploads/2010/01/Donut.png" alt="" title="Donut" width="500" height="500" class="aligncenter size-full wp-image-265" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2010/01/04/donuts-procedural-torus-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multi Threaded Direct3D</title>
		<link>http://limegarden.net/2009/01/29/multi-threaded-direct3d/</link>
		<comments>http://limegarden.net/2009/01/29/multi-threaded-direct3d/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 02:18:24 +0000</pubDate>
		<dc:creator>Wouter Lindenhof</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://limegarden.net/2009/01/29/multi-threaded-direct3d/</guid>
		<description><![CDATA[In the previous post I mentioned that I would look in to multi threaded rendering and I have done that. The minimal example attached and available for download is really simple sample, that creates a Direct3D device and cleans it. If you would further apply the trick that is described on the 26 slide of [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post I mentioned that I would look in to multi threaded rendering and I have done that. The minimal example attached and available for download is really simple sample, that creates a Direct3D device and cleans it. </p>
<p>If you would further apply the trick that is described on the 26 slide of <a href="http://www.slideshare.net/psteinb/optimizing-direct-x-on-multi-core-architectures">Optimizing Direct X On Multi Core Architectures</a> then I'm certain you can create something very flexible.</p>
<p>For example: If you need a vertex buffer, you lock the RenderingThread using <code class="codecolorer cpp geshi"><span class="cpp">RenderingThread<span style="color: #008080;">::</span><span style="color: #007788;">Lock</span></span></code> which will only be released once the <code class="codecolorer cpp geshi"><span class="cpp">CRITICAL_SECTION</span></code> has been released by another thread. Then you could ask the RenderingThread to create a wrapper of <code class="codecolorer cpp geshi"><span class="cpp">IDirect3DVertexBuffer9</span></code> which has added function that it will buffer everything and only update <code class="codecolorer cpp geshi"><span class="cpp">IDirect3DVertexBuffer9</span></code> inside the RenderingThread. If done correct you can easily multithread without having to worry about the following error message:</p>
<div class="codecolorer-container text geshi" style="border:1px solid #9F9F9F;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Direct3D9: (WARN) :Device that was created without D3DCREATE_MULTITHREADED is being used by a thread other than the creation thread.</div></div>
<p>You can download the source code here: <a href='http://limegarden.net/wp-content/uploads/2009/01/DirectXMultiThreaded.zip'>DirectXMultiThreaded.zip (source only)</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://limegarden.net/2009/01/29/multi-threaded-direct3d/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
