<?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>CodeMii &#187; Wii Programming Tutorials</title>
	<atom:link href="http://www.codemii.com/category/wii-programming-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codemii.com</link>
	<description>Home of the Homebrew Browser and Wii tutorials</description>
	<lastBuildDate>Tue, 31 Aug 2010 13:48:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tutorial 13: Loading and saving simple XML files</title>
		<link>http://www.codemii.com/2009/06/21/tutorial-13-loading-and-saving-simple-xml-files/</link>
		<comments>http://www.codemii.com/2009/06/21/tutorial-13-loading-and-saving-simple-xml-files/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 06:57:15 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=597</guid>
		<description><![CDATA[XML files are used as an easy way to read and store data which is useful for storing configuration settings from applications. It’s always good practice to allow your application to be customised by the user, be it by turning off the Wiimote rumble, enabling background music, disabling prompts, etc. In this tutorial we’ll learn [...]]]></description>
			<content:encoded><![CDATA[<p>XML files are used as an easy way to read and store data which is useful for storing configuration settings from applications. It’s always good practice to allow your application to be customised by the user, be it by turning off the Wiimote rumble, enabling background music, disabling prompts, etc. In this tutorial we’ll learn how to load and save simple settings by using XML files. You can grab the PDF of this tutorial here: <a href="http://www.codemii.com/wp-content/uploads/2009/06/codemii-tutorial-13.pdf">codemii-tutorial-13</a><br />
<span id="more-597"></span></p>
<p><strong>Understanding XML files</strong></p>
<p>If you don’t know what an XML file looks like here is an example:</p>
<pre class="brush: c">&lt;?xml version=&quot;1.0&quot; ?&gt;
&lt;app version=&quot;1&quot;&gt;
&lt;name&gt;Homebrew Browser&lt;/name&gt;
&lt;coder&gt;teknecal&lt;/coder&gt;
&lt;version&gt;0.3.1&lt;/version&gt;
&lt;release_date&gt;200905010000&lt;/release_date&gt;
&lt;short_description&gt;Browse homebrew apps&lt;/short_description&gt;
&lt;/app&gt;</pre>
<p>As you can tell, it’s well structured and easily readable. You firstly have the root element which tells the XML parser that this is an XML document. This isn’t much importance to us but note that all valid XML files must have this root element.</p>
<pre class="brush: c">&lt;?xml version=&quot;1.0&quot; ?&gt; </pre>
<p>Next we have “app” as an element with an attribute of “version” and the attribute value of “1”. Elements are defined as being the text after the &lt;. The attribute is the text that is inside the element and is equal to something, in this case it’s version = 1.</p>
<pre class="brush: c">&lt;app version=&quot;1&quot;&gt; </pre>
<p>Moving on, we have an element beneath the “app” element.</p>
<pre class="brush: c">&lt;name&gt;Homebrew Browser&lt;/name&gt;</pre>
<p>This means that this element belongs to the “app” element. In this case the element is “name” and this time the element has a content of “Homebrew Browser”. We need to close off this element by using the / and the elements name.</p>
<p>The next few elements we can skip as they require the exact same processing as above. We then reach the end of our app element.</p>
<pre class="brush: c">&lt;/app&gt;</pre>
<p>You can either end the file or keep adding more elements at the end such as:</p>
<pre class="brush: c">
Homebrew Browser 2
teknecal2
…
&lt;/app&gt;</pre>
<p>You will firstly need to download libxml which can be found here: <span style="text-decoration: line-through;"><a href="http://wiichat.googlecode.com/files/mxml-wii.tgz">http://wiichat.googlecode.com/files/mxml-wii.tgz</a></span> <a href="http://sourceforge.net/projects/devkitpro/files/portlibs/mxml-2.6-ppc.tar.bz2/download" target="_blank">http://sourceforge.net/projects/devkitpro/files/portlibs/mxml-2.6-ppc.tar.bz2/download</a></p>
<p>Extract and then copy mxml-wii\mxml\lib\libmxml.a to C:\devkitPro\libogc\lib\wii and mxml-wii\mxml\lib\include\mxml.h to C:\devkitPro\libogc\include. Thanks to Beardface for porting this XML library.</p>
<p>You’ll need to add –lxmxl to LIBS: in your makefile and also add #include  in your main.c file. Also make sure you have #include  and the other necessary fat initialisation functions.</p>
<p>Here is our source code for both saving and loading XML files: <a href="http://www.codemii.com/wp-content/uploads/2009/06/tutorial13.zip">tutorial13.zip</a></p>
<p><strong>Saving XML files</strong></p>
<p>So now we have a very basic understanding of how XML files are structured and can now proceed to save our own XML files. We’ll be saving our data as attributes.</p>
<p>Going on the simple settings theme, let’s assume we only have either a 0 or a 1 to store in our XML file and that we have 3 variables which are setting_background_music, setting_rumble and setting_tips. We have our function below which saves our settings which I’ll explain below.</p>
<pre class="brush: c">void update_settings() {
mxml_node_t *xml;
mxml_node_t *data;
xml = mxmlNewXML(&quot;1.0&quot;);

data = mxmlNewElement(xml, &quot;settings&quot;);

char set1[1];
sprintf(set1, &quot;%i&quot;, setting_background_music);
mxmlElementSetAttr(data, &quot;setting_background_music&quot;, set1);
char set2[1];
sprintf(set2, &quot;%i&quot;, setting_rumble);
mxmlElementSetAttr(data, &quot;setting_rumble&quot;, set2);
char set3[1];
sprintf(set3, &quot;%i&quot;, setting_tips);
mxmlElementSetAttr(data, &quot;setting_tips&quot;, set3);

FILE *f;
f = fopen(&quot;sd:/settings.xml&quot;, &quot;wb&quot;);

if (f == NULL) {
fclose(f);
printf(&quot;Settings could not be written.\n&quot;);
}
else {
mxmlSaveFile(xml, f, MXML_NO_CALLBACK);
fclose(f);
mxmlDelete(data);
mxmlDelete(xml);
printf(&quot;Settings Saved\n&quot;);
}
}</pre>
<p>The first three items are just standard XML things which we do. We will be creating a XML file in memory at this point in time.</p>
<pre class="brush: c">mxml_node_t *xml;
mxml_node_t *data;
xml = mxmlNewXML(&quot;1.0&quot;);</pre>
<p>We now create a new element with the name settings which would look like  in the file.</p>
<pre class="brush: c">data = mxmlNewElement(xml, &quot;settings&quot;);</pre>
<p>Then we start adding our attributes, but before we do so, these attributes are of type strings and our 0 or 1 (integer) needs to be changed into a string, so we use sprintf. We create an empty char array with a length of 1. We then sprintf to set1 the value of setting_background_music.</p>
<pre class="brush: c">char set1[1];
sprintf(set1, &quot;%i&quot;, setting_background_music); </pre>
<p>Now our char array has the value of either “0” or “1”. We can then set an attribute in our element settings to show this. We’ll call our attribute the same name as our variable which is setting_background_music for simplicity. Our setting element would like:  (assuming we had the variable set to 1).</p>
<pre class="brush: c">mxmlElementSetAttr(data, &quot;setting_background_music&quot;, set1); </pre>
<p>Now we just repeat this to the rest of our variables.</p>
<pre class="brush: c">char set2[1];
sprintf(set2, &quot;%i&quot;, setting_rumble);
mxmlElementSetAttr(data, &quot;setting_rumble&quot;, set2);
char set3[1];
sprintf(set3, &quot;%i&quot;, setting_tips);
mxmlElementSetAttr(data, &quot;setting_tips&quot;, set3); </pre>
<p>Ok, so now we are done we can begin writing the file. As normal we open the file for writing, check if we can write to the file, etc.</p>
<pre class="brush: c">FILE *f;
f = fopen(&quot;sd:/settings.xml&quot;, &quot;wb&quot;);

if (f == NULL) {
fclose(f);
printf(&quot;File could not be written to\n&quot;);
}</pre>
<p>Now we can save our XML to file with just one line. After we have saved the file we close our file and then delete the XML in memory.</p>
<pre class="brush: c">else {
mxmlSaveFile(xml, f, MXML_NO_CALLBACK);
fclose(f);
mxmlDelete(data);
mxmlDelete(xml);
printf(&quot;XML Saved\n&quot;);
}</pre>
<p><strong>Loading XML files</strong></p>
<p>So now we know what we’ve saved in the XML file and what it will look like this:</p>
<p>We can parse our XML file and find out what our settings for each variable are; we can use the below code to do this.</p>
<pre class="brush: c">void load_settings() {
mxml_node_t *tree;
mxml_node_t *data;

FILE *fp = fopen(&quot;sd:/settings.xml&quot;, &quot;rb&quot;);
if (fp == NULL) {
fclose(fp);
}
else {
fseek (fp , 0, SEEK_END);
long settings_size = ftell (fp);
rewind (fp);

if (settings_size &gt; 0) {

tree = mxmlLoadFile(NULL, fp, MXML_NO_CALLBACK);
fclose(fp);

data = mxmlFindElement(tree, tree, &quot;settings&quot;, NULL, NULL, MXML_DESCEND);

if (mxmlElementGetAttr(data,&quot;setting_background_music&quot;)) {
setting_background_music = atoi(mxmlElementGetAttr(data,&quot;setting_background_music&quot;));
printf(&quot;Setting for background music loaded\n&quot;);
}
if (mxmlElementGetAttr(data,&quot;setting_rumble&quot;)) {
setting_rumble = atoi(mxmlElementGetAttr(data,&quot;setting_rumble&quot;));
printf(&quot;Setting for rumble loaded\n&quot;);
}
if (mxmlElementGetAttr(data,&quot;setting_tips&quot;)) {
setting_tips = atoi(mxmlElementGetAttr(data,&quot;setting_tips&quot;));
printf(&quot;Setting for tips loaded\n&quot;);
}

mxmlDelete(data);
mxmlDelete(tree);
printf(&quot;Settings loaded.\n&quot;);
}
else {
fclose(fp);
unlink(&quot;sd:/settings.xml&quot;);
}
}
}</pre>
<p>We start almost the same as before when saving our XML file, we initialise variables to store the XML and then we just use our standard fopen to read our XML file.</p>
<pre class="brush: c">void load_settings() {
mxml_node_t *tree;
mxml_node_t *data;

FILE *fp = fopen(&quot;sd:/settings.xml&quot;, &quot;rb&quot;);
if (fp == NULL) {
fclose(fp);
}</pre>
<p>It’s a good idea to check that this file has content otherwise we’ll have some errors, so we can do so using ftell to tell us the file size, if it’s over 0 bytes, the file has some content.</p>
<pre class="brush: c">	else {
fseek (fp , 0, SEEK_END);
long settings_size = ftell (fp);
rewind (fp);

if (settings_size &gt; 0) {</pre>
<p>Next we’ll load our file to our XML variable which we created at the start and then close the file, read all our “settings” elements and store them in the variable data.</p>
<pre class="brush: c">			tree = mxmlLoadFile(NULL, fp, MXML_NO_CALLBACK);
fclose(fp);

data = mxmlFindElement(tree, tree, &quot;settings&quot;, NULL, NULL, MXML_DESCEND); </pre>
<p>Now we start reading our settings one by one. We make reference to our data variable which contains all the settings and say that we only want to read the element value for the element called “setting_check_size”.</p>
<p>It’s important to have this check, otherwise if our settings XML file didn’t contain the element we were trying to read, it would cause some issues. If this element is present, it’s stored as a string so we use atoi to convert it to an int and store it in our variable “setting_check_size”.</p>
<pre class="brush: c">			if (mxmlElementGetAttr(data,&quot;setting_check_size&quot;)) {
setting_check_size = atoi(mxmlElementGetAttr(data,&quot;setting_check_size&quot;));
}</pre>
<p>We do the same for the rest of our settings.</p>
<pre class="brush: c">			if (mxmlElementGetAttr(data,&quot; setting_rumble &quot;)) {
setting_rumble = atoi(mxmlElementGetAttr(data,&quot;setting_rumble&quot;));
}
if (mxmlElementGetAttr(data,&quot;setting_tips&quot;)) {
setting_tips = atoi(mxmlElementGetAttr(data,&quot;setting_tips&quot;));
}</pre>
<p>We can remove the XML file from memory and we are done.</p>
<pre class="brush: c">			mxmlDelete(data);
mxmlDelete(tree);
printf(&quot;Settings loaded.\n&quot;);
}
else {
fclose(fp);
}
}
}</pre>
<p>We’ve now successfully read all our settings from the XML we saved and that wraps up this tutorial. You can now save and load your applications simple settings using XML files.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2009/06/21/tutorial-13-loading-and-saving-simple-xml-files/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>Tutorial 12: Using Mod music / sound</title>
		<link>http://www.codemii.com/2009/04/21/tutorial-12-using-mod-music-sound/</link>
		<comments>http://www.codemii.com/2009/04/21/tutorial-12-using-mod-music-sound/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 12:24:06 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=509</guid>
		<description><![CDATA[In this tutorial you’ll learn about adding music/sounds to the Wii. It’s a fairly simple thing to do and we’ll use Mod files. I assume everyone knows MP3s but you might not know about Mod files which are a little bit like midi files. Mod files in a sense have “samples” which can be used [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial you’ll learn about adding music/sounds to the Wii. It’s a fairly simple thing to do and we’ll use Mod files. I assume everyone knows MP3s but you might not know about Mod files which are a little bit like midi files. Mod files in a sense have “samples” which can be used in different ways to produce sounds. You can grab the PDF of this tutorial here: <a href="http://www.codemii.com/wp-content/uploads/2009/04/codemii-tutorial-12.pdf">codemii-tutorial-12</a></p>
<p>There are two ways which you can load music, either from the SD card or from your source. If you aren’t going to allow users to change your music or sounds, I’d recommend loading from your source, it just saves time and it’s nicer not have lots of files on the SD card.</p>
<p><span id="more-509"></span>Let’s get started. You’ll need to add –lmodplay to LIBS: in your makefile and also add #include  in your main.c file.</p>
<p>So now you have a standard main.c file and your modified makefile like this zip file: <a href="http://www.codemii.com/wp-content/uploads/2009/04/tutorial12-makefile.zip">tutorial12-makefile.zip</a>. Copy this <a href="http://www.codemii.com/wp-content/uploads/2009/04/loop.mod">loop.mod</a> file to your SD card’s root or use ftpii to transfer it across.</p>
<p><strong>Loading mods from the SD card</strong></p>
<p>Before we begin, we need to also add libfat to our libraries in the makefile as below.</p>
<pre class="brush: c">LIBS	:=	-lwiiuse -lbte -lfat -logc -lmodplay –lm</pre>
<p>We also need to include fat.h in our source code.</p>
<p>As well as the standard initialisation of the SD card:</p>
<pre class="brush: c">if (!fatInitDefault()) {
printf(&quot;Unable to initialise FAT subsystem, exiting&quot;);
exit(0);
}</pre>
<p>We have to initialise modplay, so we add the below in our initialise function.</p>
<pre class="brush: c">void Initialise() {
. . .
AUDIO_Init(NULL);
MODPlay_Init(&amp;play);
}</pre>
<p>Now we can move on to the source code which will load one MOD file from the SD card as the background music.</p>
<pre class="brush: c">// Modplay
static MODPlay play;
long mod_size;
char * buffer;
size_t result; </pre>
<p>Above we just assign some globals. Play is the object which we will reference when wanting to play our mod file. mod_size will store the file size of our mod file, buffer will point to where the file is stored in memory and result is sort of just like mod_size except it will check to make sure the whole file is copied successfully to memory.</p>
<pre class="brush: c">FILE *f = fopen(&quot;/loop.mod&quot;, &quot;rb&quot;); // change to “SD:/loop.mod” if using r16

if (f == NULL) {
fclose(f);
}
else {
fseek (f , 0, SEEK_END);
mod_size = ftell (f);
rewind(f); </pre>
<p>So firstly we open the file that we have in our SD card’s root directory. We do the usual check to make sure the file exists and then use ftell to give us the file size of the loop.mod file.</p>
<pre class="brush: c">	// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*mod_size);
if (buffer == NULL) { perror (&quot;Memory error\n&quot;); }</pre>
<p>As you might recall buffer is the pointer to where the file will be stored in memory. We use malloc to assign a block of memory the size of our mod file and do a check to make sure the memory was assigned properly.</p>
<pre class="brush: c">	// copy the file into the buffer:
result = fread (buffer,1,mod_size,f);
if (result != mod_size) { perror (&quot;Reading error\n&quot;); }

fclose(f); </pre>
<p>If everything was fine, we copy the entire mod file into memory using fread to store it to the buffer. Result stores the number of bytes read. If result matches mod_size this means that it successfully read the entire file. We can then close the file.</p>
<pre class="brush: c">	MODPlay_SetMOD(&amp;play, buffer);
MODPlay_Start(&amp;play);
}</pre>
<p>Now the important part, we have our file loaded in buffer and we use MODPlay_SetMOD to make reference to our play global variable that contains which mod file is loaded to it which we set our buffer to. MODPlay_Start is then used to start playing our mod file; again we make reference to the play variable.</p>
<pre class="brush: c">while(1) {
. . .
if (pressed &amp; WPAD_BUTTON_HOME) {
MODPlay_Stop(&amp;play);
exit(0);
}
. . .
}</pre>
<p>Our mod file will keep on playing in a loop until we specific to stop playing the mod file with MODPlay_Stop(&amp;play) and that’s that. You can view the complete source and try out <a href="http://www.codemii.com/wp-content/uploads/2009/04/tutorial12-mod-sdcard.zip">tutorial12-mod-sdcard.zip</a></p>
<p><strong>Loading Mods from source</strong></p>
<p>Now we can move onto loading mod files from our source which I find easier.</p>
<p>You need to modify your makefile to add a rule which will convert all your .mod files in a specific folder to a ‘compiled’ state which is usable; it also generates a header file (an include file) which we will use.</p>
<p>Below is what you need to add to your makefile after “# main targets” as below.</p>
<pre class="brush: c">#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(OUTPUT).dol: $(OUTPUT).elf
$(OUTPUT).elf: $(OFILES)

%.mod.o	:	%.mod
#---------------------------------------------------------------------------------
@echo $(notdir $&lt;)
@$(bin2o)

-include $(DEPENDS) </pre>
<p>You now need to specify the folder in which your mods will be stored, so modify or add the below line after “SOURCES		:=” and make sure you create the /data subdirectory where your makefile is located.</p>
<pre class="brush: c">DATA		:=	data</pre>
<p>So now you have our standard main.c file again and your newly modified makefile like this zip file: <a href="http://www.codemii.com/wp-content/uploads/2009/04/tutorial12-makefile2.zip">tutorial12-makefile2.zip</a>. Once extracted, go ahead and compile the project. You’ll see there is a loop.mod file in the /data directory. Once compiled, go to the build folder and you can see loop_mod.o and loop_mod.h, which shows the mod file converted to a ‘compiled’ state and the header file.</p>
<p>Again, we have to initialise modplay, so we add the below in our initialise function.</p>
<pre class="brush: c">void Initialise() {
. . .
AUDIO_Init(NULL);
MODPlay_Init(&amp;play);
}</pre>
<p>We can now edit our source code as below.</p>
<pre class="brush: c">#include &quot;loop_mod.h&quot;</pre>
<p>Since we have the header file loop_mod.h, we just need to include that in our source code.</p>
<pre class="brush: c">// Modplay
static MODPlay play; </pre>
<p>We add the play variable as a global like last time.</p>
<pre class="brush: c">MODPlay_SetMOD(&amp;play, loop_mod);
MODPlay_Start(&amp;play); </pre>
<p>Then simply we can play the file as we did previously, this time having the loop variable when calling SetMOD. We don’t need any more code as this mod file is already in memory.</p>
<p>The next thing you can do is add more .mod files to your /data directory and re-compile. When you wish to change the mod file being played all you need to do is run MODPlay_Stop(&amp;play); and then run MODPlay_SetMOD(&amp;play, different-sound_mod); and MODPlay_Start(&amp;play); as usual. You can view the complete source and try out <a href="http://www.codemii.com/wp-content/uploads/2009/04/tutorial12-mod-embedded.zip">tutorial12-mod-embedded.zip</a></p>
<p>And this concludes our tutorial about using Mod files, easy wasn’t it?</p>
<p>Others things you can try out is and make a different sound play every time a button is pressed on the Dpad, playing a mod file and pressing a button to stop and if you combine these tutorials making a sound when a button is pressed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2009/04/21/tutorial-12-using-mod-music-sound/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>Tutorial 11: Structures</title>
		<link>http://www.codemii.com/2009/03/15/tutorial-11-structures/</link>
		<comments>http://www.codemii.com/2009/03/15/tutorial-11-structures/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 04:16:19 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=422</guid>
		<description><![CDATA[So you&#8217;re starting to learn more and more about coding for the Wii and you&#8217;ve come to the point where you your variables to be more organised. This may be the cause if you have multiple objects on the screen that need to move around, etc. You can grab the PDF of this tutorial here: [...]]]></description>
			<content:encoded><![CDATA[<p>So you&#8217;re starting to learn more and more about coding for the Wii and you&#8217;ve come to the point where you your variables to be more organised. This may be the cause if you have multiple objects on the screen that need to move around, etc. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2009/03/codemii-tutorial-11.pdf'>codemii-tutorial-11</a></p>
<p>You are actually able to put variables in structures, which mean you can have multiple variables in the one element of the structure.<br />
<span id="more-422"></span></p>
<p>For example, if you wish to have an object&#8217;s x / y co-ordinates as well as if the objects are on the screen, you can use the example below.</p>
<pre class="brush: c">struct object_struct {
	int x;
	int y;
	bool on_screen;
};</pre>
<p>Then you just assign this structure to a variable (10 elements of x, y and on_screen for this array)</p>
<pre class="brush: c">struct object_struct objects[10]; </pre>
<p>And now you can perform the following assignments.</p>
<pre class="brush: c">object[0].x = 42;
object[0].y = 78;
object[0].on_screen = true;
object[1].x = 342;
object[1].y  = 123;
object[1].on_screen = true; </pre>
<p>You can then just use a “for” loop which will loop to 10 and assign random values to the x and y co-ordinates and make them move around easily as below.</p>
<pre class="brush: c">// Assign random x and y co-ordinates
int i;
for (i = 0; i &lt; 10; i++) {
	object[i].x = rand() % 640 + 1;
	object[i].y = rand() % 480 + 1;
	object[i].on_screen = true;
}

// Make them move around randomly and disappear once they are off the screen
int on_screen_counter = 10;

while (on_screen_counter &gt;= 1) {
	for (i = 0; i &lt; 10; i++) {
		if (object[i].on_screen == true) {
			// Random true or false
			if ((rand() % 1) == 1) {
				object[i].x += rand() % 3 + 1;
				object[i].y += rand() % 3 + 1;
			}
			else {
				object[i].x -= rand() % 5 + 1;
				object[i].y -= rand() % 5 + 1;
			}

			// Outside the screen
			if (object[i].y &gt; 480 || object[i].y &lt; 0 || object[i].x &gt; 640 || object[i].x &lt; 0) {
				object[i].on_screen = false;
				on_screen_counter--;
			}

			// Print your image on the screen here E.g:
			// DrawImg (object[i].x, object[i].y, test_img);
		}
	}
}</pre>
<p>That wraps up this quick tutorial on using structures in your code. You are also able to have structures inside structures too. See you next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2009/03/15/tutorial-11-structures/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Tutorial 10: Using the filesystem</title>
		<link>http://www.codemii.com/2009/03/02/tutorial-10-using-the-filesystem/</link>
		<comments>http://www.codemii.com/2009/03/02/tutorial-10-using-the-filesystem/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 12:59:55 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=412</guid>
		<description><![CDATA[It&#8217;s been a while since I put up a tutorial and I hope that by now you have a basic understanding of programming for the Wii. So that I&#8217;m able to keep producing these tutorials I&#8217;ll try to focus on small pieces of code instead of the whole application and how the code can be [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I put up a tutorial and I hope that by now you have a basic understanding of programming for the Wii. So that I&#8217;m able to keep producing these tutorials I&#8217;ll try to focus on small pieces of code instead of the whole application and how the code can be applied. The explanation of Simon was a bit too long <img src='http://www.codemii.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . This tutorial is also a bit longer than I expected. You can grab the PDF of this tutorial here: <a href="http://www.codemii.com/wp-content/uploads/2009/03/codemii-tutorial-10.pdf">codemii-tutorial-10</a></p>
<p>In this tutorial we&#8217;ll cover initialising the filesystem, creating/deleting directories/files and reading/writing files. Thanks to joedj for his FAT init code from FTPii v0.0.5.<br />
<span id="more-412"></span></p>
<p>Note: This tutorial is for DevKitPPC r15. Users of r16 will have to prepend SD:/ whenever accessing the filesystem.</p>
<p>You need to begin firstly with adding -lfat to your LIBS: in your makefile. The second step is including &lt;fat.h&gt; in your makefile.</p>
<p><strong>Initialising the filesystem</strong></p>
<p>First things first, before we can start reading/writing files or creating/deleting directories we need to initialise the filesystem (FAT in this case). It&#8217;s just a simple piece of code which does this for us.</p>
<pre class="brush: c">if (!fatInitDefault()) {
printf(&quot;Unable to initialise FAT subsystem, exiting.\n&quot;);
exit(0);
}</pre>
<p>The above just reads, if we can&#8217;t initialise the FAT filesystem, then print an error message and exit.</p>
<p>The next thing to check (which isn&#8217;t mandatory) is to see if we can open the filesystem which is done with the code below.</p>
<pre class="brush: c">if (!can_open_root_fs()) {
printf(&quot;Unable to open root filesystem, exiting.\n&quot;);
exit(0);
}

bool can_open_root_fs() {
DIR_ITER *root = diropen(&quot;/&quot;);
if (root) {
dirclose(root);
return true;
}
return false;
}</pre>
<p>We use diropen to check if we are able to open the root directory and if so it returns true.</p>
<p>Ok, so we can open the filesystem. We can add another check to make sure that we can actually change the current working directory to the root (/).</p>
<pre class="brush: c">if (chdir(&quot;/&quot;)) {
printf(&quot;Could not change to root directory, exiting.\n&quot;);
exit(0);
}</pre>
<p>And now we&#8217;re done with the initialisation. We can place this all in a function to make things a bit cleaner. We call our own die() function if something has failed.<br />
It&#8217;s always good practise to unmount the filesystem when exiting your application. This can be done by calling fatUnmount(0);.</p>
<pre class="brush: c">void initialise_fat() {
if (!fatInitDefault()) die(&quot;Unable to initialise FAT subsystem, exiting.\n&quot;);
if (!can_open_root_fs()) die(&quot;Unable to open root filesystem, exiting.\n&quot;);
if (chdir(&quot;/&quot;)) die(&quot;Could not change to root directory, exiting.\n&quot;);
}

bool can_open_root_fs() {
DIR_ITER *root = diropen(&quot;/&quot;);
if (root) {
dirclose(root);
return true;
}
return false;
}

void die(char *msg) {
perror(msg);
sleep(5);
fatUnmount(0);
exit(0);
}</pre>
<p>As you can see above the die function accepts a string of characters (denoted by char *) and then prints out the string using perror(). The thing about perror is it will print out the string supplied as well as any error that has occurred. For example if you are trying to open a file and it doesn&#8217;t exist, perror might print something like &#8220;No such file or directory&#8221; which is always helpful.</p>
<p>After that we just pause for 5 seconds, unmount the filesystem and exit the application.</p>
<p><strong>Creating Directories</strong></p>
<p>We can create a directory by using mkdir. mkdir takes two arguments, the directory to create and the permissions to set on the directory. We can ignore the permissions and just set them as 0777 (everyone has access to read, write and delete).</p>
<pre class="brush: c">mkdir(&quot;/test&quot;, 0777); </pre>
<p>The above would create a directory called /test on the root of the device we are accessing. mkdir returns 0 if the directory was created successfully otherwise it returns -1.</p>
<p>We can check for errors by doing the below.</p>
<pre class="brush: c">if (mkdir(&quot;/test&quot;, 0777) == -1) {
die(&quot;Could not create /test directory.\n&quot;);
}</pre>
<p>This will run the mkdir command and if it returns -1 it will print the string specified and perror() will print out the error message.</p>
<p><strong>Removing Directories/Files</strong></p>
<p>We can remove a directory or a file by using unlink(path);</p>
<pre class="brush: c">unlink(&quot;/test/myfile.txt&quot;);
unlink(&quot;/test&quot;);</pre>
<p>The above would remove the file called myfile.txt and then the directory /test.</p>
<p>We can also check for errors exactly the same as mkdir.</p>
<pre class="brush: c">if (unlink(&quot;/test&quot;) == -1) {
die(&quot;Could not delete directory/file.\n&quot;);
}</pre>
<p><strong>Reading Files</strong></p>
<p>There are various ways to read files. We&#8217;ll stick to the easiest way which is reading the file one line at time so that we may process each line. This might be useful say if you&#8217;re developing a game that has multiple levels and each line might represent an object&#8217;s x and y co-ordinates.</p>
<p>First we need to open the file in read mode as below.</p>
<pre class="brush: c">FILE *f = fopen (&quot;myfile.txt&quot;, &quot;rb&quot;);</pre>
<p>Next we check if the file was able to be opened for reading.</p>
<pre class="brush: c">// If file doesn&#039;t exist or can&#039;t open it then we can grab the latest file
if (f == NULL) {
die(&quot;Could not open myfile.txt file for reading.\n&quot;);
}</pre>
<p>Otherwise if it was fine, we can continue.</p>
<pre class="brush: c">else {
char file_line [20];
int line_number = 0;
while (fgets (file_line, 20, f)) {
printf(&quot;Line %i: %s\n&quot;,line_number, file_line);
line_number++;
}
fclose(f);
}</pre>
<p>We need store each line to a variable so that we are able to process the line. This variable is file_line and is an array of characters which holds 20 characters (I&#8217;m assuming that our x and y co-ordinates are between 1 to 3 characters in length, so 20 is more than enough). If say you had a long line of text, you would have to change 20 to say 500 or more depending on how long each line was.<br />
After that we just have the line_number which just counts the number of lines.</p>
<p>Now we reach the while loop, here we use the fgets function. fgets allows us to specify the amount of characters to read in the line or until the line ends. The first argument is a pointer to our array of characters which is where the information from the file will temporarily be stored. The second argument is the number of characters to read, again we use 20. The third argument is the pointer to the file, which is f in this case.</p>
<p>In every loop, file_line will be updated with the next line from the myfile.txt file. This continues until we reach the end of the file. We then print out the line number and the contents of the line at each loop.</p>
<p>After we have reached the end of the file, we can close the file by using fclose(f);</p>
<p>So let’s say that our file contains the following data which represents x and y co-ordinates:<br />
32 58<br />
34 48<br />
234 99<br />
385 234<br />
453 347</p>
<p>We need a place to store the x and y co-ordinates, a simple example is:</p>
<pre class="brush: c">int x_pos[] = { 0, 0, 0, 0, 0};
int y_pos[] = { 0, 0, 0, 0, 0};</pre>
<p>We would need to modify our while loop to break up each line, as we need the x and y co-ordinates in different variables.</p>
<p>Here we can use the string tokenizer (strok) to break up the line. strtok takes 2 arguments, the string to tokenize and a list of delimiters; which just means the characters to find that will determine a split in the string.</p>
<p>For our example the delimiters would just be a space (&#8221; &#8220;) which would break the line into 2 parts. The delimiter isn&#8217;t included in any of the parts.</p>
<p>Now if we where to store each part directory into the integer variable the compiler would complain (char being stored in an int), so we need to change the string of characters to an int. This can be done using atoi(string) which just converts the string into an integer.</p>
<pre class="brush: c">while (fgets (file_line, 20, f)) {
char *temp_string;
temp_string = strtok (file_line, &quot; &quot;);
if (temp_string != NULL) {
x_pos[line_number] = atoi(temp_string);
temp_string = strtok (NULL, &quot; &quot;);
if (temp_string != NULL) {
y_pos[line_number] = atoi(temp_string);
}
}
line_number++;
}</pre>
<p>We firstly assign a blank pointer. We run strtok on our file_line variable which contains the line of text.</p>
<p>temp_string would then be equal to the first token in the line of text, which is &#8220;32&#8243;. Since temp_string has a value, we assign element 0 of x_pos with the integer value of 32.</p>
<p>We run strtok again, this time with the first argument of NULL. You use the NULL argument in strtok if you wish to continue breaking up a string.</p>
<p>The next token is &#8220;58&#8243; which we assign the integer value of 58 to element 0 of y_pos.<br />
We then increase the line_number, and so on.</p>
<p><strong>Writing files</strong></p>
<p>As with reading files, writing files can be done in different ways. A simple way of writing files would use the fputs function which takes 2 arguments, the string to write to the file and the pointer to the file.</p>
<pre class="brush: c">FILE *f = fopen (&quot;myfile.txt&quot;, &quot;wb&quot;);

if (f == NULL) {
die(&quot;Could not open myfile.txt file for writing.\n&quot;);
}
else {
int x;
for (x = 0; x &lt; line_number; x++) {
char temp_string[20];
sprintf(temp_string, &quot;%i %i&quot;, x_pos[x], y_pos[x]);
fputs (temp_string ,f);
}
fclose(f);
}</pre>
<p>Note that &#8220;rb&#8221; has changed to &#8220;wb&#8221; (the w means write).</p>
<p>We&#8217;ll use the same example as in the reading example, except in this case we wish to write our x and y co-ordinates to the file.<br />
We&#8217;ll assume that you have the line_number variable and that it equals 5. We do a for loop until we reach line_number (5).</p>
<p>So we need to do the opposite of strtok, so that we are able to add the two numbers and a space in between. We also need to change the integer values of x and y into strings.</p>
<p>We can do this using sprintf which has 3 arguments and is just like printf except it prints the output to a string. The arguments are the string to output to, the text to print and the variables to print.</p>
<p>We have the temp_string variable which is empty, we do a sprintf which converts &#8220;%i %i&#8221; to &#8220;32 58&#8243;. After we convert the integers to a string, we write this temp_string to our file and repeat until we are done.</p>
<p>Note: I have experienced issues when using sprintf multiple times in a row which can cause issues with the variables sprintf is writing to.</p>
<p>And that’s it; we’re done for this tutorial. You should now know how to preform different functions on files/folders which should make your life easier if you are say making a multi-level game or wish to save some simple settings to a file. Remember that there is a lot more error checking that could be done but for the purposes of this tutorial it’s just too much to do.</p>
<p>See you next time…</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2009/03/02/tutorial-10-using-the-filesystem/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Tutorial 9: Simon explained</title>
		<link>http://www.codemii.com/2008/12/30/tutorial-9-simon-explained/</link>
		<comments>http://www.codemii.com/2008/12/30/tutorial-9-simon-explained/#comments</comments>
		<pubDate>Tue, 30 Dec 2008 13:19:42 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=315</guid>
		<description><![CDATA[By now you should have the skills needed to start coding or modifying small games and utilities. In this Wii programming tutorial we will go through the Simon game and give a brief explanation of what things do. In this tutorial we focus on how to use the code we know to achieve certain the [...]]]></description>
			<content:encoded><![CDATA[<p>By now you should have the skills needed to start coding or modifying small games and utilities. In this Wii programming tutorial we will go through the Simon game and give a brief explanation of what things do. In this tutorial we focus on how to use the code we know to achieve certain the things that we are after. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2009/01/codemii-tutorial-9.pdf'>codemii-tutorial-9</a></p>
<p>Lets begin by firstly downloading the <a href='http://www.codemii.com/wp-content/uploads/2008/12/simon-source-code.zip'>simon source code</a> and opening up main.c. This version of Simon is intended to run on gcube. You can load the dol file with gcube and have a little play around.</p>
<p>Simon is a basic game; you have 4 colours and the computer generates a sequence of colours which you need to press correctly to win. The computer shows you one colour and when you press the correct colour the computer then shows you the next colour and so on.<br />
<span id="more-315"></span></p>
<p>A quick summary of this Simon game would be:</p>
<pre class="brush: c">Show current sequence colour
	If sequence_counter is less than level_counter then increment sequence_counter
	If sequence_counter equals level_counter then wait for user input

Wait for user input
	If colour correct, increment user_counter
		If user_count equals level_counter then increment level_counter and show new sequence
	If colour incorrect, return to main menu
	If user_counter equals sequence_length, game won</pre>
<p>As usual we start off with our standard includes and also our graphical files. These graphic files were made with a program called bmp2gc which converts .bmp images to .h files which can be used with the gamecube/Wii. I would recommend you stick with using JPEGs instead of using bmp2gc.For the purpose of understanding the Simon game as it was coded, I’ve left most things as it was.</p>
<pre class="brush: c">#include &lt;gccore.h&gt;
…
#include &quot;main.h&quot;

// Graphics
#include &quot;simon.h&quot;
…</pre>
<p>Next up we define how long we want the sequence to be, in this case 15. So the user will have to get the colours right until they reach 15 colours in a row.</p>
<pre class="brush: c">#define SEQ_LENGTH 15</pre>
<p>Our standard video variables</p>
<pre class="brush: c">// 2D Video Globals
static u32 *xfb;
static GXRModeObj *rmode; </pre>
<p>Now we declare our global variables. Firstly we define an array of characters that is 15 elements long. The next variable defined is the different colours; there are 4 colours. Red is 0, Green is 1, Blue is 2 and Yellow is 3.</p>
<p>Next up we have the sequence counters, the first seqnum is used when we are animating simon to show the user and seqlevel stores the ‘level’ the user is on. If the user has a sequence to play back of 210, they are up to level 3. If the sequence is up to 2102, they are up to level 4, etc.</p>
<p>Userseqnum stores where the user is up to in the sequence. The next booleans are to be used when we allow the user to press a button &#8211; userinput, if the user entered the correct input – correctinput and if the user is in the game – ingame.</p>
<pre class="brush: c">// Vars
char seq [SEQ_LENGTH];
char color [4] = &quot;0123&quot;;
int seqnum, seqlevel, userseqnum;
bool userinput, correctinput, ingame; </pre>
<p>We then have the usual initialise function.</p>
<pre class="brush: c">void Initialise() {
	…
}</pre>
<p>We have a SetScreen function which just flushes everything we wrote to the framebuffer to the screen. Note that in this Simon game things aren’t done as correctly as they should be. Generally you should clear the screen and then write to the framebuffer and display it but since there aren’t any cursors or moving objects it’s not really needed.</p>
<pre class="brush: c">void SetScreen() {
	VIDEO_SetNextFramebuffer(xfb);
	VIDEO_Flush();
	VIDEO_WaitVSync();
}</pre>
<p>Now we’ll jump right down the bottom to the main function which is quite short. We call initialise, initialise the controller and call another function which handles restarting our gamecube but as we aren’t running this on a gamecube it doesn’t really matter. </p>
<p>Below that we have our drawpic function which has a similar concept as display_jpeg in tutorial 5. drawpic takes the x position (93), y position (0), the images height (48), the images width (120) and the actual picture to display (simontext) which is the title screen image. After that we call our game function and return 0 if the user ever decides to quit.</p>
<pre class="brush: c">int main () {

	Initialise();
	PAD_Init();
	SYS_SetResetCallback (reset_cb);

	drawpic(93, 0, 48, 120, simontext);

	game();

	return 0;
}</pre>
<p>Before exploring the game function we need to animate the title screen and initialise our variables. In the first run of the game function all our ingame variable is false so it skips all the code in game() and runs animate_simon().</p>
<pre class="brush: c">void game() {
	u32 button = 0;

	while (1) {
		while (ingame == true) {
			…
	…

	// First run or Game over? Then go back to menu
	animate_simon();
	restart_game();
}</pre>
<p>Animate simon makes the lights spin on Simon and it acts as a menu screen waiting for the user to press A to begin. So we firstly need to know what colour light is currently lit, a variable which we can use to make the spinning go faster or slower and if this menu screen is running.</p>
<pre class="brush: c">// Animate the &quot;spinning&quot; lights on simon
void animate_simon() {
	int count = 0;
	int multipler = 0;
	bool running = true;
	u32 button = 0; </pre>
<p>We display our starting text which says “Press A to start” and begin our while loop. We use our light counter (count) and if it’s 0 we show the red light, if it’s 1 we should the green light, etc. We then increment this counter and when it reaches a count of 3 it will be reset to -1 which then is incremented immediately to 0.</p>
<pre class="brush: c">
	drawpic(96, 410, 27, 120, starttext);

	while (running == true) {
		if (count == 0) {
			drawpic(60, 60, 336, 192, simonred);
		}
		if (count == 1) {
			drawpic(60, 60, 336, 192, simongreen);
		}
		if (count == 2) {
			drawpic(60, 60, 336, 192, simonyellow);
		}
		if (count == 3) {
			drawpic(60, 60, 336, 192, simonblue);
			count = -1;
		}

		count++;</pre>
<p>Now when we are animating Simon we need a pause between each light and we can do this using the usleep function. Usleep sleeps for x amount of microseconds. Now when we are sleeping it’s basically just pausing our whole program. But what if the user presses the A button when the program is sleeping? Nothing would happen. </p>
<p>We can avoid this in two ways, either use threads or possibly make the sleep times shorter and then query the user input in-between sleeps. I went with the easier second option. You can see below that we sleep in 20 short times. We have our multiplier which can speed up the animation if it’s increased and we query if the A button was pressed.</p>
<pre class="brush: c">
		// Sleep a little bit in the for loop so we can grab user input
		int i = 0;
		for (i = 0; i&lt; 20; i++) {
			usleep(25000 - (multipler * 100));
			PAD_ScanPads();
			button = PAD_ButtonsDown(0);
			if (button == PAD_BUTTON_A) {
				running = false;
			}</pre>
<p>After that we have the controller input code which works for either joystick, if it’s pushed up the animation speeds up and if pushed down the animation decreases.</p>
<pre class="brush: c"> 		// Go faster or slower according to user input
			else if ((PAD_StickY(0) &gt; 18 || PAD_SubStickY(0) &gt; 18) &amp;&amp; multipler &lt;= 245) {
				multipler++;
			}
			else if ((PAD_StickY(0) &lt; -18 || PAD_SubStickY(0) &lt; -18) &amp;&amp; multipler &gt;= 1) {
				multipler--;
			}
		}</pre>
<p>We then have our normal handling reboot/poweroff code which isn’t important and then we display what we have in our framebuffer with SetScreen().</p>
<pre class="brush: c"> 	// Handle reboot/poweroff
		if (event == 1) {
			printf(&quot;POWER!\n&quot;);
			reload();
		} else if (event == 2) {
			printf(&quot;RESET!\n&quot;);
			reload();
		}
		if (button == PAD_BUTTON_START)
			reload();

		//printf(&quot;multipler = %i \n&quot;,multipler);

		SetScreen();
	}
}</pre>
<p>So lets say that the user now wants to play, they press A and then running variable turns false which causes us to end the animate_simon function and move on to the restart_game function.</p>
<p>The restart game function just initialises all of our variables, sets the userinput to false as we will firstly show the user the sequence, set the correctinput to true and when they get the colour wrong we’ll set it to false and they are in the game so we ingame to true.</p>
<p>As you might remember we don’t clear the screen so and we don’t want to display the Press A to start text anymore so what we show is a blank black image and then show a Simon image which doesn’t have any lights showing.</p>
<pre class="brush: c">// Reset the variables and text
void restart_game() {
	seqnum = 0;
	seqlevel = 0;
	userseqnum = 0;
	userinput = false;
	correctinput = true;
	ingame = true;

	drawpic(96, 410, 28, 120, blanktext);
	drawpic(60, 60, 336, 192, simon); </pre>
<p>Now we need to make the sequence that the user has to copy, it’s not something that we want to hardcode so we need to randomise it instead. We can use the current time to provide us with a ‘key’ and we’ll use the rand feature to generate us a random number from 0 to 3 which is our colours (rand() % 4). </p>
<p>Our sequences needs to be a of type char because we can’t have a sequence like 01230102321 because it starts with a 0 and it would be hard to say give me the second digit of this number without converting this number to a char. So we add ‘0’ to our rand() % 4 so that it will convert the 0 to 3 number into type char. We’ll then generate 15 of these numbers and add the number to the sequence.</p>
<pre class="brush: c">
	// Randomise the sequence
	srand((unsigned)time(0)); 

	int q;
	for(q=0; q&lt;SEQ_LENGTH; q++){
		char random_integer = &#039;0&#039; + rand() % 4;
		seq[q] = random_integer;
		//printf(&quot;%c \n&quot;, random_integer);
	}
	printf(&quot;Sequence is %s \n&quot;,seq);
}</pre>
<p>Now we can explore the game function. As the variable userinput is still false we can skip this part and go onto the part that shows the user which colour the first level of our sequence is. In our example we will use the sequence below:</p>
<pre class="brush: c">
Sequence	0 3 1 1 2 3 2 0 2  1  0  1  2  1  3
Level		1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Seqlevel	0 1 2 3 4 5 6 7 8  9 10 11 12 13 14
</pre>
<p>Seqlevel would equal 0 and seqnum (our counter) would be 0 as well. We now need a way to increase the speed of the animation of Simon when the level increases. We use usleep again and this time use seqlevel as the multipler. As you recall the seq variable has our sequence stored. As seq is of type char we can request the x position of this variable like seq[0] would be 0, seq[1] would be 3, seq[2] would be 1, etc.</p>
<p>In our first run we would sleep, compare seq[0] with colour[0] which are both 0 and that would make the if statement true and then we would display the Simon red light. After that’s done we check to see if our counter is equal to the level the user is on and if it is we set userinput to true and reset the seqnum to -1 which will be incremented back to 0. We will sleep again for a while, draw the blank Simon image and increment seqnum so we can show the next colour to the user if needed.</p>
<pre class="brush: c">
			// If we are playing the sequence to the user
			if (userinput == FALSE) {
				usleep(1000000 - (seqlevel * 50000)); // Lower time every incrementation

				if (seq[seqnum] == color[0]) {
					drawpic(60, 60, 336, 192, simonred);
				}
				if (seq[seqnum] == color[1]) {
					drawpic(60, 60, 336, 192, simongreen);
				}
				if (seq[seqnum] == color[2]) {
					drawpic(60, 60, 336, 192, simonblue);
				}
				if (seq[seqnum] == color[3]) {
					drawpic(60, 60, 336, 192, simonyellow);
				}				

				if (seqnum == seqlevel) {
					userinput = TRUE;
					seqnum = -1;
				}

				// Sleep a while and then show blank simon
				usleep(1000000 - (seqlevel * 50000));
				drawpic(60, 60, 336, 192, simon);

				seqnum++;
			}</pre>
<p>So now that we’ve shown the sequence to the user, all we need to do is check for which buttons the user presses, Y, X, B, or A. So say the user presses the A button which would be correct for the first level (userseqnum equals 0). Colour[0] is 0 and seq[userseqnum] is 0 so then correctinput stays as true.</p>
<pre class="brush: c">
		while (ingame == true) {
			PAD_ScanPads();
			button = PAD_ButtonsDown(0);

			// If we are waiting for user input
			if (userinput == TRUE) {
				if (button == PAD_BUTTON_Y) {
					drawpic(60, 60, 336, 192, simonred);
					if (color[0] != seq[userseqnum]) {
						correctinput = false;
					}
				}
				if (button == PAD_BUTTON_X) {
					drawpic(60, 60, 336, 192, simongreen);
					if (color[1] != seq[userseqnum]) {
						correctinput = false;
					}
				}
				if (button == PAD_BUTTON_B) {
					drawpic(60, 60, 336, 192, simonblue);
					if (color[2] != seq[userseqnum]) {
						correctinput = false;
					}
				}
				if (button == PAD_BUTTON_A) {
					drawpic(60, 60, 336, 192, simonyellow);
					if (color[3] != seq[userseqnum]) {
						correctinput = false;
					}
				}</pre>
<p>So now we detect if any button of the A, B, X, Y buttons were pressed. We check that correctinput still equals true which in this case it does. If the userseqnumber (0) is less than the seqlevel (0) then it would increase the userseqnum. In this case it’s not true so we skip that and go to the next if statement which is true. We reset the userseqnum, increment the seqlevel (to 1) and set userinput to false as we would like to show the user the new sequence.</p>
<p>As seqlevel doesn’t equal SEQ_LENGTH (15) we’ll skip that part for now.</p>
<pre class="brush: c">
				if (button == PAD_BUTTON_A || button == PAD_BUTTON_B || button == PAD_BUTTON_X || button == PAD_BUTTON_Y) { 

					usleep(500000);

					drawpic(60,60, 336, 192, simon);

					//printf(&quot;userseq %i seqlevel %i \n&quot;,userseqnum, seqlevel);

					// If they entered the correct sequence
					if (correctinput == TRUE) {

						// Increment the users seq number
						if (userseqnum &lt; seqlevel) {
							userseqnum++;
						}

						// If user has matched the seq level, increase the seq level and show the new sequence to the user
						else if (userseqnum &gt;= seqlevel) {
							userseqnum = 0;
							seqlevel++;
							userinput = false;

							// Wait a little while
							usleep(500000);

							// If user has won
							if (seqlevel == SEQ_LENGTH) {
								…
							}
						}
					}</pre>
<p>We show the new sequence to the user and then wait for their input again. This time around the if statement (userseqnum < seqlevel) is true so we increment userseqnum and wait for the user’s next input if they were correct. </p>
<p>We’ll assume that one time that they were incorrect, we need to find what the correct colour was and show that to the user. So we compare seq[userseqnum] with 0, 1, 2, 3 until we find the right colour and then display that colour light. We then display the “You Lost” text, pause for a while and then show the blank simon and set ingame to false so we go back to the menu screen.</p>
<pre class="brush: c">
					// Incorrect sequence
					else if (correctinput == FALSE) {
						//printf(&quot;Sorry wrong key&#8230;. \n&quot;);
						usleep(1000000);

						//printf(&quot;Right key was %c \n&quot;,seq[userseqnum]);
						//printf(&quot;You lost! \n&quot;);

						if (seq[userseqnum] == &#039;0&#039;) {
							drawpic(60, 60, 336, 192, simonred);
						}
						if (seq[userseqnum] == &#039;1&#039;) {
							drawpic(60, 60, 336, 192, simongreen);
						}
						if (seq[userseqnum] == &#039;2&#039;) {
							drawpic(60, 60, 336, 192, simonblue);
						}
						if (seq[userseqnum] == &#039;3&#039;) {
							drawpic(60, 60, 336, 192, simonyellow);
						}

						drawpic(96, 410, 27, 120, youlost);

						usleep(15000000);
						SetScreen();

						drawpic(60, 60, 336, 192, simon);
						drawpic(96, 410, 28, 118, blanktext);

						usleep(500000);
						SetScreen();

						ingame = false;
					}</pre>
<p>Lets assume that the user has won the game by getting all the sequence correct. We check this by comparing seqlevel to SEQ_LENGTH (15) and if equal they have won. We display the “You Won” text and display the winning square by comparing the last level in the sequence with 0, 1, 2, and 3. We have a for loop to display the winning square, sleep a bit and then display the blank Simon image a few times so it’s shown as a blinking colour light. We pause for a while and then show the blank simon and set ingame to false so we go back to the menu screen.</p>
<pre class="brush: c">
							// If user has won
							if (seqlevel == SEQ_LENGTH) {
								//printf(&quot;You win! \n&quot;);
								drawpic(96, 410, 27, 120, youwin);

								// Blink the winning square
								int a;
								for (a = 0; a &lt; 10; a++) {
									if (seq[SEQ_LENGTH-1] == &#039;0&#039;) {
										drawpic(60, 60, 336, 192, simonred);
									}
									if (seq[SEQ_LENGTH-1] == &#039;1&#039;) {
										drawpic(60, 60, 336, 192, simongreen);
									}
									if (seq[SEQ_LENGTH-1] == &#039;2&#039;) {
										drawpic(60, 60, 336, 192, simonblue);
									}
									if (seq[SEQ_LENGTH-1] == &#039;3&#039;) {
										drawpic(60, 60, 336, 192, simonyellow);
									}
									usleep(100000);
									SetScreen();

									drawpic(60, 60, 336, 192, simon);
									usleep(100000);
									SetScreen();
								}

								drawpic(96, 410, 28, 120, blanktext);
								usleep(500000);
								SetScreen();

								//printf(&quot;Press A to play again \n&quot;);
								ingame = false;
							}</pre>
<p>And there we have it, the Simon game explained in detail. All together it looks like a lot but there’s a few repeated if statements, functions, etc. It’s about programming in small components; you might start off with making the colour light up when you press a key. Then you might move on to comparing the key pressed to a certain colour and then move on to comparing the key pressed to a certain position in a character array, etc.</p>
<p>I hoped this tutorial has helped you understand the Simon game and how things were done. There are plenty of ways that this Simon game can be improved so feel free to modify the code and show us how you’ve improved the game. I didn’t expect this tutorial to be this long but what can you do. If you have any questions or comments feel free to post them.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2008/12/30/tutorial-9-simon-explained/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Tutorial 8: Image changes</title>
		<link>http://www.codemii.com/2008/11/09/tutorial-8-image-changes/</link>
		<comments>http://www.codemii.com/2008/11/09/tutorial-8-image-changes/#comments</comments>
		<pubDate>Sun, 09 Nov 2008 10:38:10 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=271</guid>
		<description><![CDATA[In this Wii programming tutorial we will modify the button detection tutorial and as requested show you how you can easily change a button from yes to no based on the user’s input. You can grab the PDF of this tutorial here: codemii-tutorial-8
Firstly download this tutorial8-blank which will contain the required files to get us [...]]]></description>
			<content:encoded><![CDATA[<p>In this Wii programming tutorial we will modify the button detection tutorial and as requested show you how you can easily change a button from yes to no based on the user’s input. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2009/01/codemii-tutorial-8.pdf'>codemii-tutorial-8</a></p>
<p>Firstly download this <a href='http://www.codemii.com/wp-content/uploads/2008/11/tutorial8-blank.zip'>tutorial8-blank</a> which will contain the required files to get us started. Include in the zip are two images and they have been given added to the main.c file. Shown below are the important parts of the source code. I assume you know the rest from our other tutorials.<br />
<span id="more-271"></span></p>
<pre class="brush: c">int main() {

	JPEGIMG yes;
	JPEGIMG no;

	memset(&amp;yes, 0, sizeof(JPEGIMG));
	memset(&amp;no, 0, sizeof(JPEGIMG));

	yes.inbuffer = picdata;
	yes.inbufferlength = piclength;
	no.inbuffer = picdata1;
	no.inbufferlength = piclength1;

	JPEG_Decompress(&amp;yes);
	JPEG_Decompress(&amp;no);

	Initialise();

	int cursor_x = 100;
	int cursor_y = 100;

	while(1) {

		VIDEO_ClearFrameBuffer (rmode, xfb, COLOR_BLACK);

		PAD_ScanPads();

		if (PAD_StickY(0) &gt; 18) {
			cursor_y -= 5;
		}
		if (PAD_StickY(0) &lt; -18) {
			cursor_y += 5;
		}
		if (PAD_StickX(0) &gt; 18) {
			cursor_x += 5;
		}
		if (PAD_StickX(0) &lt; -18) {
			cursor_x -= 5;
		}

		u16 buttonsDown = PAD_ButtonsDown(0);

		if(buttonsDown &amp; PAD_BUTTON_A) {
			if (cursor_x &gt;= 105 &amp;&amp; cursor_x &lt;= 155 &amp;&amp; cursor_y &gt;= 70 &amp;&amp; cursor_y &lt;= 95) {
				printf(&quot;Button pressed\n&quot;);
			}
			printf(&quot;x = %i. y = %i\n&quot;, cursor_x, cursor_y);
			usleep(500000);
		}

		display_jpeg(yes, 50, 50);

		DrawBox (cursor_x, cursor_y, cursor_x + 1, cursor_y + 1, COLOR_WHITE);

		VIDEO_WaitVSync();

	}

	return 0;
}</pre>
<p>It’s pretty much the same as tutorial 6 except we now have two JPEG images defined which are “yes” and “no”. Now all we need to do is remove the print statements, add in a variable which can keep track of the button pressing and an if statement. </p>
<p>First thing to do is create a variable which will handle the button, since there will only be two options (yes and no) we can simply have this variable set as a boolean (bool yes_no_button = true;)</p>
<p>There is a long way and a simple way to do this. I’ll show you the longer way first.</p>
<p>Now we just set an if statement after the user has pressed the button and it is in our buttons range, if the yes_no_button is equal to true then change it to false otherwise change it to true (since we know it would be false).</p>
<pre class="brush: c">if (yes_no_button == true) {
	yes_no_button = false;
}
else {
	yes_no_button = true;
}</pre>
<p>The next thing to do is determine which image to display. Another simple if statement covers this exactly the same as above except it shows the image.</p>
<pre class="brush: c">if (yes_no_button == true) {
display_jpeg(yes, 50, 50);
}
else {
	display_jpeg(no, 50, 50);
}</pre>
<p>Only relevant code is shown below, our code now looks like this:</p>
<pre class="brush: c">…
	int cursor_x = 100;
	int cursor_y = 100;
	bool yes_no_button = true;

	while(1) {

		…

		u16 buttonsDown = PAD_ButtonsDown(0);

		if (buttonsDown &amp; PAD_BUTTON_A) {
			if (cursor_x &gt;= 105 &amp;&amp; cursor_x &lt;= 155 &amp;&amp; cursor_y &gt;= 70 &amp;&amp; cursor_y &lt;= 95) {
				if (yes_no_button == true) {
					yes_no_button = false;
				}
				else {
					yes_no_button = true;
				}
			}
		}

		if (yes_no_button == true) {
			display_jpeg(yes, 50, 50);
		}
		else {
			display_jpeg(no, 50, 50);
		}

		…</pre>
<p>Compile and test it, when pressing the A key (q) in gcube over the image it will change from yes to no to yes, etc. <a href='http://www.codemii.com/wp-content/uploads/2008/11/tutorial8-yes-no-long.zip'>tutorial8-yes-no-long</a></p>
<p>Now for the quicker way which is simply to replace the code that determines whether the variable is true or false with one line:<br />
yes_no_button ^= 1;</p>
<p>This basically just gives the opposite of what is in the variable and is commonly used to flip the framebuffer. The code now looks like:</p>
<pre class="brush: c">		if (buttonsDown &amp; PAD_BUTTON_A) {
			if (cursor_x &gt;= 105 &amp;&amp; cursor_x &lt;= 155 &amp;&amp; cursor_y &gt;= 70 &amp;&amp; cursor_y &lt;= 95) {
				yes_no_button ^= 1;
			}
		}</pre>
<p>There you have it a simple example on how to change an image from saying yes to no. <a href='http://www.codemii.com/wp-content/uploads/2008/11/tutorial8-yes-no-short.zip'>tutorial8-yes-no-short </a></p>
<p>Coding requires patience and can require changing one thing at a time and re-testing your code. You need to be able to use what you’ve got and explore doing other things with it. Are you able to make this button tutorial change between 3 buttons? Can you make the yes and no buttons appear on the screen and then print out which one the user choose? Can you make a question appear, the user choose yes or no and then have the question change to another one?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2008/11/09/tutorial-8-image-changes/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Tutorial 7: Using arrays</title>
		<link>http://www.codemii.com/2008/09/28/tutorial-7-using-arrays/</link>
		<comments>http://www.codemii.com/2008/09/28/tutorial-7-using-arrays/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 11:29:48 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=230</guid>
		<description><![CDATA[In this Wii programming tutorial we will quickly cover how we can utilise arrays for holding information about games like in card games or other games were the positions of objects remains static. You can grab the PDF of this tutorial here: codemii-tutorial-7
An array as you should know can hold multiple elements. By utilising these [...]]]></description>
			<content:encoded><![CDATA[<p>In this Wii programming tutorial we will quickly cover how we can utilise arrays for holding information about games like in card games or other games were the positions of objects remains static. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2008/10/codemii-tutorial-7.pdf'>codemii-tutorial-7</a></p>
<p>An array as you should know can hold multiple elements. By utilising these elements we can arrange them however we like. For example, if we were to do a tic tac toe game, we know there are 9 cells in 3 x 3. We can declare an array with 8 elements and set all those elements to 0 as shown below.<br />
<span id="more-230"></span></p>
<pre class="brush: c">int cells[] =  {0, 0, 0,
				0, 0, 0,
				0, 0, 0};</pre>
<p>So we have our 9 cells, 0 is for empty, 1 could stand for a cross and 2 could stand for a circle. As you can see we haven’t defined how many elements are in the array cells, because we are initialising the array whilst declaring it. Then all we need to do is display the crosses, circles and empty cells. I won’t be providing the code but rather just providing some quick pseudocode.</p>
<p>Pseudocode is a way of writing code but in a briefer level where you don’t need to care about writing the exact code, but rather paraphrasing what it will do. </p>
<p>Something like this will do:</p>
<pre class="brush: c">For all elements of the cells array
	If element equals 1, display a cross
	Else if element equals 2, display a circle</pre>
<p>Our code could then look something like this:</p>
<pre class="brush: c">int x = 0;
for (x = 0; x &lt;= 8; x++) {
	if (cells[x] == 1) {
		display_cells (x, 1);
	}
	else if (cells[x] == 2) {
		display_cells (x, 2);
	}
}</pre>
<p>It’s up to you how you derive the code from the pseudocode. So we now have some example code, although what I haven’t shown you is the display_cells function.</p>
<p>The display_cells function could take the position in the array which is denoted by x and whether it’s a cross or circle (1 or 2).</p>
<p>Our pseudocode could look like:</p>
<pre class="brush: c">Initialise a temporary x and y position
If array position divided by 3 is more or equal to 1, add 100 to y position
	Use that divided figure and multiply by 100 to x position
Else multiply 100 to x position by the array position
If element equals 1, use x and y position and draw a circle
Else if element equals 2, use x and y position and draw a cross</pre>
<p>What we are doing above is converting a number from 0 to 9 (the array position) to a certain position on the screen. Say we have the number 5 as the array position; we divide 5 by 3 which is about 1.67. As this figure is more than 1, we add 100 to the y position to move it down to the next row and then multiply the remaining result (2) by 100 so it will end up in the centre of the screen. We then check to see if the element is a 1 or 2 and then display the cross or circle.</p>
<p>The next thing you would have to do is how to select cells with the Wiimote. From our previous tutorials we know how to do this. So we just need to split all 9 cells into buttons. As the cells positions remains the same, we can apply a formula to working out which cell we are clicking on. </p>
<p>It’s similar to the formula above. If we moved our cursor to say 130 x and 160 y, it would fall right in the centre. All we need to do is divide both the x and y by 100 and we have a single digit value with our x and y values which would give us 1 x and 1 y (remember 0 x and 0 y is the top left cell). So then we just need to do y * 3 + x and we have our position in the array which would be 4.</p>
<p>Now all you would need is the graphics, the 3 way cross/circle detection, simple AI, a function to restart the game and you should be set.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2008/09/28/tutorial-7-using-arrays/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Tutorial 6: Button detection</title>
		<link>http://www.codemii.com/2008/09/14/tutorial-6-button-detection/</link>
		<comments>http://www.codemii.com/2008/09/14/tutorial-6-button-detection/#comments</comments>
		<pubDate>Sun, 14 Sep 2008 10:01:53 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=206</guid>
		<description><![CDATA[In this Wii programming tutorial we will cover displaying an image as the mouse cursor and how to detect button clicking. You can grab the PDF of this tutorial here: codemii-tutorial-6.
Firstly download this tutorial6-image which will contain the required files to get us started. This zip file also contains the JPEG code required to display [...]]]></description>
			<content:encoded><![CDATA[<p>In this Wii programming tutorial we will cover displaying an image as the mouse cursor and how to detect button clicking. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2008/09/codemii-tutorial-6.pdf'>codemii-tutorial-6</a>.</p>
<p>Firstly download this <a href='http://www.codemii.com/wp-content/uploads/2008/09/tutorial6-image.zip'>tutorial6-image</a> which will contain the required files to get us started. This zip file also contains the JPEG code required to display images which you should have learnt about in the last tutorial. Extract this zip file in C:\devkitPro\examples\gamecube and open up tutorial6.pnproj.</p>
<p>As you should recall, we displayed a cursor which we could control on the gamecube by using the following code:<br />
<span id="more-206"></span></p>
<pre class="brush: c">int cursor_x = 300;
int cursor_y = 250;

while(1) {

	PAD_ScanPads();

	if (PAD_StickY(0) &gt; 18) {
		cursor_y--;
	}
	if (PAD_StickY(0) &lt; -18) {
		cursor_y++;
	}
	if (PAD_StickX(0) &gt; 18) {
		cursor_x++;
	}
	if (PAD_StickX(0) &lt; -18) {
		cursor_x--;
	}

	VIDEO_ClearFrameBuffer (rmode, xfb, COLOR_BLACK);

	DrawBox (cursor_x, cursor_y, cursor_x + 1, cursor_y + 1, COLOR_WHITE);

	VIDEO_WaitVSync();

}</pre>
<p>So all that’s required for us to do is change DrawBox to use display_jpeg instead.</p>
<pre class="brush: c">display_jpeg(about, cursor_x, cursor_y); </pre>
<p>Compile your source and there we have it; your cursor is now showing up as an image.</p>
<p><strong>Detecting button clicking</strong></p>
<p>In order to detect button clicking we have to know our button’s four co-ordinates; x1, x2, y1 and y2. The simplest way to figure this out is to just print the location of your cursor to the screen when you press A so you can see the x and y co-ordinates as when you are displaying an image it’s not the same as the x and y of the cursor. I know that there has to be a better way for doing this, but I’m just showing you what worked for me.</p>
<p>Put change display_jpeg back to DrawBox as we’ll need to find the x and y co-ordinates. </p>
<p>You can then add the following code to print out the x and y co-ordinates of the cursor:</p>
<pre class="brush: c">u16 buttonsDown = PAD_ButtonsDown(0);

if( buttonsDown &amp; PAD_BUTTON_A ) {
	printf(&quot;x = %i. y = %i\n&quot;, cursor_x, cursor_y);
	usleep(500000);
}</pre>
<p>We have used printf before, which prints something to the screen but in this case we are using printf to print out two integers; x and y. The way the statement works is we say to printf that we will be passing an integer in the first argument which is denoted by %i. After we have finished the text to print (“ “), we pass the first argument; cursor_x which is an integer. Printf grabs this integer and displays it when it prints “x = 100”. You can print a double (%d), long (%l), characters (%c) and so on.</p>
<p>Usleep as the name suggests, makes the whole application pause for a specified amount of time. The argument usleep takes is a integer and is in microseconds. 500000 would be 500 milliseconds which is ½ of a second.</p>
<p>Before using usleep you need to include
<pre class="brush: c">#include &lt;unistd.h&gt;</pre>
<p> in your headers. Unistd includes miscellaneous functions. If you didn’t include unistd, it would still compile but throw an error saying it can’t find the usleep function, but lucky for us it would still work.</p>
<p>So now if we compile and run our code (<a href='http://www.codemii.com/wp-content/uploads/2008/09/tutorial6-mouse-image.zip'>tutorial6-mouse-image</a>), we can move the cursor around the about image. What we need to do is find the x, y co-ordinates of the top left and bottom right of the image. So if you were to go ahead and do this yourself you would find that they would roughly be 202, 120 (top left) and 254, 141 (bottom right).</p>
<p>We have our image’s co-ordinates and now all that’s left to do is produce code that will identify if our cursor is in our images co-ordinates. Something as found below works nicely:</p>
<pre class="brush: c">if (cursor_x &gt;= 202 &amp;&amp; cursor_x &lt;= 254 &amp;&amp; cursor_y &gt;= 120 &amp;&amp; cursor_y &lt;= 141) {
	printf(&quot;Button pressed\n&quot;);
}</pre>
<p>Place the above code in the if (buttonsDown &#038; PAD_BUTTON_A) { statement and recompile your code (<a href='http://www.codemii.com/wp-content/uploads/2008/09/tutorial6-button-detection.zip'>tutorial6-button-detection</a>). Once you’ve run it with gcube, try pressing the A button (Q key) around the button and inside the button. You’ll see it works quite well and correctly detects when the button is pressed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2008/09/14/tutorial-6-button-detection/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Tutorial 5: JPEG images</title>
		<link>http://www.codemii.com/2008/09/07/tutorial-5-jpeg-images/</link>
		<comments>http://www.codemii.com/2008/09/07/tutorial-5-jpeg-images/#comments</comments>
		<pubDate>Sun, 07 Sep 2008 05:23:56 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=190</guid>
		<description><![CDATA[This fifth Wii programming tutorial will cover how to display JPEG images. As usual, I’m assuming you’ve read all the other tutorials. You can grab the PDF of this tutorial here: codemii-tutorial-5
Firstly download this tutorial5-blank which will contain the required files to get us started. Extract this zip file in C:\devkitPro\examples\gamecube. Open up tutorial5.pnproj and [...]]]></description>
			<content:encoded><![CDATA[<p>This fifth Wii programming tutorial will cover how to display JPEG images. As usual, I’m assuming you’ve read all the other tutorials. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2008/09/codemii-tutorial-5.pdf'>codemii-tutorial-5</a></p>
<p>Firstly download this <a href='http://www.codemii.com/wp-content/uploads/2008/09/tutorial5_blank.zip'>tutorial5-blank</a> which will contain the required files to get us started. Extract this zip file in C:\devkitPro\examples\gamecube. Open up tutorial5.pnproj and then click on main.c to show the source code.</p>
<p>Included in the download are two files, one called picture.s and a JPEG picture. The picture.s file defines all our variables for the picture and the link to the picture itself. If you open the image file “about.jpg” you’ll see the image with a black background. It’s important to remember that JPEGs aren’t transparent like PNGs are.<br />
<span id="more-190"></span></p>
<p>The next step needed is to download this <a href='http://www.codemii.com/wp-content/uploads/2008/09/libogc_jpeg.zip'> libogc_jpeg</a> zip file which contains the required JPEG library. You’ll need to extract it to C:\devkitPro\devkitPPC\powerpc-gekko and let it overwrite any directories.</p>
<p>Now we need to modify our makefile to add in the JPEG library:</p>
<pre class="brush: c">LIBS	:=	-logc -lm -ljpeg</pre>
<p>We can now focus on editing the main.c file. Firstly we’ll need to include the jpeg header file so we can access the jpeg functions.</p>
<pre class="brush: c">#include &lt;jpeg/jpgogc.h&gt;</pre>
<p>Two variables need to be defined are piclength and picdata which are both found in the picture.s file. We define these two variables as exern which tells the compiler that we have defined these two variables elsewhere (picture.s) and these variables will be able to be accessed globally.</p>
<pre class="brush: c">extern char picdata[];
extern int  piclength; </pre>
<p>The next thing we add is a jpeg function which I have hacked together:</p>
<pre class="brush: c">void display_jpeg(JPEGIMG jpeg, int x, int y) {

	unsigned int *jpegout = (unsigned int *) jpeg.outbuffer;

	int i,j;
	int height = jpeg.height;
	int width = jpeg.width/2;
		for(i=0;i&lt;=width;i++)
			for(j=0;j&lt;=height-2;j++)
				xfb[(i+x)+320*(j+16+y)]=jpegout[i+width*j];

	free(jpeg.outbuffer);

}</pre>
<p>The above function takes a JPEGIMG structured variable and two integers which will be used to determine where on the screen we want our image to be displayed.</p>
<p>The first line in the function is related to how the jpeg library works. Later on you’ll see that we decompress the jpeg images and when doing so, the jpeg.outbuffer is where the image is stored.</p>
<p>The next few lines define some local variables for the height and width and then copy the jpeg image to out video frame buffer (the screen) to the co-ordinates that we have defined in as x and y. The last line in the function ensures that we clear the space in memory that we made a local copy of the jpeg image (unsigned int *jpegout = (unsigned int *) jpeg.outbuffer; )</p>
<p>We can now start adding jpeg functions the main() function. First things first we define the variable to use that will use the JPEGIMG data structure.</p>
<pre class="brush: c">JPEGIMG about; </pre>
<p>After that we assign memory to our “about” variable.</p>
<pre class="brush: c">memset(&amp;about, 0, sizeof(JPEGIMG)); </pre>
<p>According to our picture.s file, it contains two variables; the picture data and the length of the picture. We define our “about” variable inbuffer and inbufferlength with both the global variables.</p>
<pre class="brush: c">about.inbuffer = picdata;
about.inbufferlength = piclength; </pre>
<p>We then need to decompress the jpeg, by passing the “about” variable.</p>
<pre class="brush: c">JPEG_Decompress(&amp;about); </pre>
<p>Our last step is to run the display_jpeg function and pass our variable “about” and any x and y co-ordinates we want.</p>
<pre class="brush: c">display_jpeg(about, 60, 100); </pre>
<p>Our main function now looks like:</p>
<pre class="brush: c">int main() {

	JPEGIMG about;

	memset(&amp;about, 0, sizeof(JPEGIMG));

	about.inbuffer = picdata;
	about.inbufferlength = piclength;

	JPEG_Decompress(&amp;about);

	Initialise();

	display_jpeg(about, 60, 100);

	return 0;
}</pre>
<p><a href='http://www.codemii.com/wp-content/uploads/2008/09/tutorial5_jpeg.zip'>tutorial5-jpeg</a> is what our source now looks like. Compile the source and run tutorial5.dol with gcube. You’ll see the image displayed on the screen. I won’t convert this to the Wii as there won’t be any difference between them. </p>
<p><a href="http://www.codemii.com/wp-content/uploads/2008/09/tutorial_5_pic_1.png"><img class="alignnone size-medium wp-image-193" title="tutorial_5_pic_1" src="http://www.codemii.com/wp-content/uploads/2008/09/tutorial_5_pic_1-300x235.png" alt="" width="300" height="235" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2008/09/07/tutorial-5-jpeg-images/feed/</wfw:commentRss>
		<slash:comments>94</slash:comments>
		</item>
		<item>
		<title>Tutorial 4: Cursors</title>
		<link>http://www.codemii.com/2008/08/31/tutorial-4-cursors/</link>
		<comments>http://www.codemii.com/2008/08/31/tutorial-4-cursors/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 11:02:41 +0000</pubDate>
		<dc:creator>teknecal</dc:creator>
				<category><![CDATA[Wii Programming Tutorials]]></category>

		<guid isPermaLink="false">http://www.codemii.com/?p=164</guid>
		<description><![CDATA[In this fourth Wii programming tutorial, I will cover displaying a cursor by drawing a small square, movement of the cursor and then using the Wii IR to move the cursor. Before reading this tutorial I’m assuming you have picked up a few things and therefore I won’t be re-explaining the common code in the [...]]]></description>
			<content:encoded><![CDATA[<p>In this fourth Wii programming tutorial, I will cover displaying a cursor by drawing a small square, movement of the cursor and then using the Wii IR to move the cursor. Before reading this tutorial I’m assuming you have picked up a few things and therefore I won’t be re-explaining the common code in the zip file or initial steps in detail. You can grab the PDF of this tutorial here: <a href='http://www.codemii.com/wp-content/uploads/2008/09/codemii-tutorial-4.pdf'>codemii-tutorial-4</a></p>
<p>Firstly download this <a href='http://www.codemii.com/wp-content/uploads/2008/08/tutorial4-blank.zip'>tutorial4-blank</a> which will contain the required files to get us started. Extract this zip file in C:\devkitPro\examples\gamecube. Open up tutorial4.pnproj and then click on main.c to show the source code.</p>
<p>From tutorial 3, we know how to incorporate the controller in our source code, so now all we need to use a cursor in our application, is to draw one. The source code below is our drawing functions. I’m not sure whose code it but thanks to the person whom made it.<br />
<span id="more-164"></span></p>
<pre class="brush: c">void DrawHLine (int x1, int x2, int y, int color) {
    int i;
    y = 320 * y;
    x1 &gt;&gt;= 1;
    x2 &gt;&gt;= 1;
    for (i = x1; i &lt;= x2; i++) {
        u32 *tmpfb = xfb;
        tmpfb[y+i] = color;
    }
}

void DrawVLine (int x, int y1, int y2, int color) {
    int i;
    x &gt;&gt;= 1;
    for (i = y1; i &lt;= y2; i++) {
        u32 *tmpfb = xfb;
        tmpfb[x + (640 * i) / 2] = color;
    }
}

void DrawBox (int x1, int y1, int x2, int y2, int color) {
    DrawHLine (x1, x2, y1, color);
    DrawHLine (x1, x2, y2, color);
    DrawVLine (x1, y1, y2, color);
    DrawVLine (x2, y1, y2, color);
}</pre>
<p>Place the above code after the Initialise function. We will be calling the DrawBox function and passing 5 parameters to it. The parameters of DrawBox are the first x co-ordinate, the first y co-ordinate, the second x co-ordinate, the second y co-ordinate and the colour of the lines as shown below:</p>
<pre class="brush: c">DrawBox (5, 20, 50, 200, COLOR_WHITE); </pre>
<p>When drawing things on the screen, x = 0 and y = 0 means that we would be at the top left of the screen. If we put the following code as shown above, we would get a line that looks something like:</p>
<p><a href="http://www.codemii.com/wp-content/uploads/2008/08/tutorial_4_pic_1.png"><img src="http://www.codemii.com/wp-content/uploads/2008/08/tutorial_4_pic_1.png" alt="" title="tutorial_4_pic_1" width="282" height="225" class="alignnone size-medium wp-image-168" /></a></p>
<p>Once we call the DrawBox function, it breaks the square that we want to draw into 4 lines, which are 2 horizontal and 2 vertical lines. The DrawHLine and DrawVLine functions write to the frame buffer which will be displayed on the screen that we want a certain dot on the screen to be a certain colour. The loop is used so that we go through every dot that we want to change to a certain colour. </p>
<p><a href='http://www.codemii.com/wp-content/uploads/2008/08/tutorial4-draw-square.zip'>tutorial4-draw-square</a> is the finished source code if you need it. Compile the source code (Alt + 1) and run the dol file with gcube. You should see a similar screen to the one shown below.</p>
<p><a href="http://www.codemii.com/wp-content/uploads/2008/08/tutorial_4_pic_2.png"><img src="http://www.codemii.com/wp-content/uploads/2008/08/tutorial_4_pic_2-300x120.png" alt="" title="tutorial_4_pic_2" width="300" height="120" class="alignnone size-medium wp-image-167" /></a></p>
<p><strong>Moving the Cursor</strong></p>
<p>We now wish to draw a smaller square which will represent our cursor. You can use something like:</p>
<pre class="brush: c">DrawBox (300, 250, 301, 251, COLOR_WHITE); </pre>
<p>Now that we’ve got our cursor set up, we need to be able to use the controls to move the cursor. To do this we need to use variables to control the cursor’s x and y co-ordinates on the screen.</p>
<p>We can have two variables, one for the x axis named cursor_x and one for the y axis named cursor_y. These variables will have the default value of 200 and 200, so that it’s near the centre of the screen.</p>
<pre class="brush: c">int cursor_x = 300;
int cursor_y = 250; </pre>
<p>The next thing to do is to capture the movement of the joystick, so when we move the joystick up or down it modifies the cursor_y variable and when we move it left or right it modifies the cursor_x variable. We can do this by either de-incrementing (subtracting 1) or incrementing (adding 1 to) the variables. </p>
<pre class="brush: c">if (PAD_StickY(0) &gt; 18) {
	cursor_y--;
}
if (PAD_StickY(0) &lt; -18) {
	cursor_y++;
}
if (PAD_StickX(0) &gt; 18) {
	cursor_x++;
}
if (PAD_StickX(0) &lt; -18) {
	cursor_x--;
}</pre>
<p>The &#8212; means de-increment and the ++ means increment. As an example, if we move the joystick up, we would de-increment cursor_y. So if cursor_y was 200 and we moved the joystick up, cursor_y’s value would be 199.</p>
<p>All that’s left now is to change where the image is being displayed every time we move the cursor. This is easily accomplished by using our variables with the DrawBox function as shown below:</p>
<pre class="brush: c">DrawBox (cursor_x, cursor_y, cursor_x + 1, cursor_y + 1, COLOR_WHITE); </pre>
<p>What we’ve done is used our cursor_x and cursor_y in place instead of the 300 (x1) and 250 (y1) values and have added 1 to the cursor to that the values will be 301 (x2) and 251 (y2) in order to draw a square.</p>
<p>The next thing to do is to clear the screen to black before showing the cursor and then using waiting for vertical sync. The reason we are clearing the screen is so that our cursor is cleared every time we move it. If we didn’t clear the screen, then you will see the movement of the cursor stay on the screen.</p>
<p>The code below shows the complete controller code in a while loop with the screen being cleared:</p>
<pre class="brush: c">int cursor_x = 300;
int cursor_y = 250;

while(1) {

	PAD_ScanPads();

	if (PAD_StickY(0) &gt; 18) {
		cursor_y--;
	}
	if (PAD_StickY(0) &lt; -18) {
		cursor_y++;
	}
	if (PAD_StickX(0) &gt; 18) {
		cursor_x++;
	}
	if (PAD_StickX(0) &lt; -18) {
		cursor_x--;
	}

	VIDEO_ClearFrameBuffer (rmode, xfb, COLOR_BLACK);

	DrawBox (cursor_x, cursor_y, cursor_x + 1, cursor_y + 1, COLOR_WHITE);

	VIDEO_WaitVSync();
}</pre>
<p>The reason behind placing VIDEO_ClearFrameBuffer before DrawBox is so we don’t clear the screen and then waste time doing other functions and then draw the cursor. If you had a lot of code which took a considerable amount of time to execute, you wouldn’t see your cursor all of the time and it would be blinking. Instead we do the functions, clear the screen, draw the cursor and repeat the while loop, so therefore the cursor will stay on the screen all the time.</p>
<p><a href='http://www.codemii.com/wp-content/uploads/2008/08/tutorial4-moving-cursor.zip'>tutorial4-moving-cursor</a> is what our source now looks like. Go ahead and re-compile the source and run the dol with gcube and use the Numpad up, down, left and right to move the small square which is our cursor. </p>
<p><strong>Converting source to use Wii IR</strong></p>
<p>We are now good to change our project to compile on the Wii instead of the gamecube. As per the last tutorial open your makefile and change the gamecube_rules to wii_rules in line that reads:</p>
<pre class="brush: c">include $(DEVKITPPC)/gamecube_rules</pre>
<p>Add the Wii and the Bluetooth libraries to our compiler as shown below:</p>
<pre class="brush: c">LIBS	:=	-lwiiuse -lbte -logc -lm</pre>
<p>In main.c include section include the wiiuse file:</p>
<pre class="brush: c">#include &lt;wiiuse/wpad.h&gt;</pre>
<p>As usual we will need to add a W in front of all the PAD_ commands and remove references to PAD_Substick.</p>
<p>When using the Wiimote, we firstly have to tell the system that we want to capture all the Wiimote’s functionality which includes the Infra-red (IR) and the accelerometer. Another thing to tell the system is the resolution we want to bound the IR to. Both these commands are shown below and should be after the WPAD_Init function:</p>
<pre class="brush: c">WPAD_SetVRes(0, 640, 480);
WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR); </pre>
<p>The Wiimote’s IR has a data structure which tells us things like are the co-ordinates valid, the x and y axis, the rotation and so forth. This information can be found in “C:\devkitPro\libogc\include\wiiuse\wiiuse.h”.</p>
<p>We need to assign a variable to hold this data structure. We do this by naming the data structure which is ir_t and then assigning that data structure to our variable which is ir. The code below needs to be placed below the #includes which are at the top. </p>
<p>The reason we place the variable up the top is so that our variable will be a global which means it can be called and accessed from anywhere within our source code. If we were to assign it within a function, then the variable would only exist whilst inside that function and could not be called from anywhere else.</p>
<pre class="brush: c">ir_t ir; </pre>
<p>So now that we have assigned ir as the data structure ir_t, we need to constantly update the ir variable to get the latest readings from the Wiimote. This is done by using the below code:</p>
<pre class="brush: c">WPAD_IR(0, &amp;ir); </pre>
<p>We are updating channel 0 (the first Wiimote’s) IR data and feeding all that information into our ir variable.</p>
<p>The final step involved is to change the variables in the DrawBox function to use ir.x and ir.y instead of cursor_x and cursor_y. As you recall ir is our variable which contains different data structures, one of them being the x and y co-ordinates. As these are like variables in the ir variable, we reference them by using a dot between our main variable (ir) and the data structure variable (ir.x or ir.y).</p>
<pre class="brush: c">DrawBox (ir.x, ir.y, ir.x + 1, ir.y + 1, COLOR_WHITE); </pre>
<p>We can remove the cursor_x and cursor_y variables. The while loop looks as shown below:</p>
<pre class="brush: c">while(1) {

	WPAD_ScanPads();
u32 pressed = WPAD_ButtonsDown(0);

	// IR Movement
	WPAD_IR(0, &amp;ir);

if (pressed &amp; WPAD_BUTTON_HOME) {
		exit(0);
	}

	VIDEO_ClearFrameBuffer (rmode, xfb, COLOR_BLACK);

	DrawBox (ir.x, ir.y, ir.x + 1, ir.y + 1, COLOR_WHITE);

	VIDEO_WaitVSync();
}</pre>
<p><a href='http://www.codemii.com/wp-content/uploads/2008/08/tutorial4-wii-ir.zip'>tutorial4-wii-ir</a> is what our source now looks like. Clean the source code, re-compile and tutorialr.elf to boot.elf and place it in a directory called tutorialr under the /apps/ directory of your SD card and load it with the homebrew channel. You will be able to control the dot on your screen with the Wiimote.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codemii.com/2008/08/31/tutorial-4-cursors/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
	</channel>
</rss>
