<?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>Martin&#039;s Place</title>
	<atom:link href="http://www.mfoot.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mfoot.com</link>
	<description></description>
	<lastBuildDate>Mon, 23 Jan 2012 15:36:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Choosing a maths library for cross-platform C++ game development</title>
		<link>http://www.mfoot.com/2012/01/choosing-a-maths-library-for-cross-platform-c-game-development/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=choosing-a-maths-library-for-cross-platform-c-game-development</link>
		<comments>http://www.mfoot.com/2012/01/choosing-a-maths-library-for-cross-platform-c-game-development/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 15:35:28 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cmake]]></category>
		<category><![CDATA[CML]]></category>
		<category><![CDATA[eigen]]></category>
		<category><![CDATA[GLM]]></category>
		<category><![CDATA[math]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=280</guid>
		<description><![CDATA[I have recently been looking for a C++ maths library for use in game development projects. There are plenty of posts on websites like gamedev.stackexchange.com with suggestions for libraries but few quantitative comparisons between them. I decided to take three &#8230; <a href="http://www.mfoot.com/2012/01/choosing-a-maths-library-for-cross-platform-c-game-development/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have recently been looking for a C++ maths library for use in game development projects. There are plenty of posts on websites like <a title="Game Development Stackexchange" href="http://gamedev.stackexchange.com/">gamedev.stackexchange.com</a> with suggestions for libraries but few quantitative comparisons between them. I decided to take three of the most popular libraries and run some tests of my own. Below I describe the three libraries I&#8217;ve compared with their advantages and disadvantages and then show the results of some performance tests. It&#8217;s important for me to have cross-platform compatibility, so each library selected is header only and has been tested on Mac, Linux, and Android using the NDK. The code and results are also available <a title="C++ Math library test project" href="https://github.com/mfoo/Math-Library-Test">on GitHub</a> for testing.</p>
<p>The libraries tested are:</p>
<ul>
<li><a href="http://eigen.tuxfamily.org/">Eigen</a></li>
<li><a href="http://glm.g-truc.net/">GLM</a></li>
<li><a href="http://cmldev.net/">CML</a></li>
</ul>
<p>These choices are largely influenced by reading their websites and posts at the <a href="http://gamedev.stackexchange.com/">Game Development StackExchange</a> site:</p>
<ul>
<li><a href="http://gamedev.stackexchange.com/questions/9924/best-c-math-library-for-game-engine">Best C Math Library for Game Engine?</a></li>
<li><a href="http://stackoverflow.com/questions/5935075/high-performance-math-library-for-vector-and-matrix-calculations">High Performance Math Library for Vector And Matrix Calculations</a></li>
<li><a href="http://gamedev.stackexchange.com/questions/8234/complete-math-library-for-use-in-opengl-es-2-0-game">Complete Math Library for use in OpenGL ES 2.0 Game?</a></li>
</ul>
<p><span id="more-280"></span></p>
<h1>Requirements</h1>
<p>I have several requirements for a math library, and when rating them (in no particular order) the <a title="What should be taken into consideration when choosing a math library for C++ game development?" href="http://gamedev.stackexchange.com/questions/21711/what-should-be-taken-into-consideration-when-choosing-a-math-library-for-games">following things are important</a>:</p>
<ul>
<li>License</li>
<li>Portability</li>
<li>Quality and quantity of the documentation</li>
<li>Completeness (or how much can the library do without me having to write my own functions). For game development this includes:</li>
<ul>
<li>Matrix operations</li>
<li>Vector operations</li>
<li>Complex number support</li>
<li>Quaternion operations</li>
</ul>
<li>Extensibility and community contributions (linked directly to the above).</li>
<li>Ease of use (are the concepts simple to understand?)</li>
<li>Performance (are there SIMD optimisations?)</li>
</ul>
<h1>Libraries Overview</h1>
<div id="readme">
<div>
<h2>Configurable Math Library (CML)</h2>
<p>This is a free library designed for games, graphics, and computational geometry applications. Listed <a href="http://cmldev.net/?page_id=8">features</a> include:</p>
<ul>
<li>Vector, matrix, and quarternion classes</li>
<li>Templated headers so can be used for arbitrary types</li>
<li>Arbitrary sized vectors and matrices (fixed or dynamically resizable)</li>
<li>Conversions between polar, cylindrical, spherical, and Cartesian coordinates</li>
<li>A large library of functions for the construction and manipulation of transforms in 2D and 3D</li>
</ul>
<p>CML&#8217;s <a href="http://cmldev.net/?page_id=594">design notes</a> state that it is meant to be cross-platform and portable and therefore doesn&#8217;t contain any platform specific optimisations, but it is possible to include them in the future if there is specific interest.</p>
<p>There&#8217;s only one header file to include, <code>cml/cml.h</code>.</p>
<p>CML contains quite a nice way of creating an abstraction layer between existing math library objects and CML objects, allowing the use of other math library data types in CML library functions. See <a href="http://cmldev.net/?p=424">here</a>.</p>
<p>CML only has a few <a href="http://cmldev.net/?p=402">examples</a>. Hasn&#8217;t been updated in a while. Contains useful functions for working with OpenGL or DirectX though, including replacements for things like gluLookAt().</p>
<p>CML is released under the <a href="http://cmldev.net/?p=430">Boost Software License</a>. This means that you&#8217;re allowed to use and profit from the library as long as when distributing CML or any modifications you have made to CML, you keep the Boost Software License text in each file.</p>
<h2>Eigen</h2>
<p>This library has by far the most detailed and descriptive tutorial section with many code samples. It is also worth noting that it seems to be the most frequently updated and the most up-to-date (at the time of writing the most recent release, 3.0.4, was 3.5 weeks ago).</p>
<p>Like GLM, it is very easy to pass the class objects directly to OpenGL, although in Eigen this is performed by an <a href="http://eigen.tuxfamily.org/dox-devel/unsupported/group__OpenGLSUpport__Module.html">unsupported OpenGL module</a> which provides a few functions such as glTranslate and glRotate.</p>
<pre>// You need to add path_to_eigen/unsupported to your include path.
#include &lt;Eigen/OpenGLSupport&gt;
// ...
Vector3f x, y;
Matrix3f rot;
glVertex(y + x * rot);

Quaternion q;
glRotate(q);</pre>
<p>Provides a large number of array, matrix, and vector types with <a href="http://eigen.tuxfamily.org/dox/QuickRefPage.html#QuickRef_Types">many operators</a>.</p>
<p>Eigen is licensed under the LGPL which is quite restrictive and usually would exclude a library based on my requirements. However, Eigen has a large <a href="http://eigen.tuxfamily.org/index.php?title=Licensing_FAQ">Licensing FAQ</a> which tries to answer any licensing questions people might have. Their main point is that as Eigen is a header only library, it does not count as a &#8220;Combined Work&#8221; under the LGPL it can be therefore used entirely under Section 3. This states that to use Eigen you must:</p>
<ul>
<li>Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. The Eigen FAQ states that &#8216;the bottom of a README file or of a website would be prominent enough for us&#8217;.</li>
<li>Accompany the object code with a copy of the GNU GPL and this license document.</li>
</ul>
<p>This assumes that you&#8217;re using Eigen unmodified. If you are planning to make changes to Eigen and release it, then you must also make the modifications available under the LGPL.</p>
<h2>OpenGL Math Library (GLM)</h2>
<p>GLM&#8217;s main design to be very familiar to those who know GLSL as it uses classes and functions that use the GLSL naming conventions. It also seems to provide all of the functionality that I might need in the future.</p>
<p>Includes several code samples, more than CML. Many more located in the manual.</p>
<p>Includes features such as:</p>
<ul>
<li>Math for splines</li>
<li>Math for colour spaces</li>
<li>Random numbers</li>
<li>Simplex noise generation</li>
<li>Conversion of Euler angles</li>
</ul>
<p>There&#8217;s only one header file to include, <code>glm/glm.hpp</code>. <code>glm/ext.hpp</code> can be included to add extended features (non GLSL features).</p>
<p>The design choice to follow GLSL conventions allows the library to be intuitive and easy to use, especially given that data alignment is compatible with gl functions. E.g:</p>
<pre>glm::vec4 v(0);
glm::mat4 m(0);
glVertex3fv(glm::value_ptr(v));
glLoadMatrixfv(glm::value_ptr(m));</pre>
<p>The manual pdf file link is broken but a slightly out of date version can be found <a href="https://bitbucket.org/alfonse/gltut/src/6332c7f79903/glm-0.9.0.0/doc/glm-manual.pdf">here</a>. I&#8217;ve sent the maintainer an email and hopefully this will be fixed shortly.</p>
<p>GLM is licensed under the <a href="http://en.wikipedia.org/wiki/MIT_License">MIT License</a> (Expat License) which is very permissive and means GLM is a good candidate for any project requiring a math library.</p>
</div>
</div>
<p>To run the tests on Android you will need the <a href="http://developer.android.com/sdk/ndk/index.html">Android NDK</a> and <a href="http://code.google.com/p/android-cmake/">android-cmake</a>. For Ant you will need to specify your Android SDK location in <code>android/local.properties</code>. I have included prebuilt libraries for armeabi and armeabi-v7a so if you don&#8217;t want to compile them yourself you can skip straight to the ant commants.</p>
<h1>Results</h1>
<p>So far I&#8217;ve tested matrix addition and multiplication. <code>src/Main.cpp</code> contains code that will generate two lists of 1 million 4&#215;4 float matrices for each library, populate them with random float values, and then add each one from the first column to the second. It will then do the same for multiplication. It will repeat this step 10 times and print out how long it took for each library.</p>
<p>Results for each library vary greatly with architecture and optimisation level. I have tested standard GCC build on Mac OS X Lion as well as an SSE enabled build, and armeabi, armeabi-v7a and armeabi-v7a with NEON instructions for Android.</p>
<p>Note that all tests use the <code>-O2</code> GCC optimisation flag except the non-SSE laptop build which uses <code>-O0</code>.</p>
<p>Results for addition and multiplication are shown below. Note that the laptop I&#8217;m using is an i7 2.2ghz early 2011 MacBook Pro and the Android device is a Stock HTC Desire (2.2) with a 1 GHz Qualcomm QSD8250. All times are in milliseconds.</p>
<pre>                        laptop  laptop (SSE)  armeabi  armeabi-v7a  armeabi-v7a with neon
Eigen additions         8065    30            9944     2181         2145
Eigen multiplications   22404   86            59460    5143         5113
GLM additions           2375    76            10256    1506         1407
GLM multiplications     7337    400           59008    2189         3108
CML additions           12336   96            9587     2885         2996
CML multiplications     21603   551           58399    5306         5280</pre>
<p>The first column for the laptop doesn&#8217;t have any compile-time optimisations and is included purely for interest. From the other results, Eigen seems to be the fastest for these operations, but GLM is the fastest on the HTC Desire with both ABIs. I am not sure why the NEON times are not much faster (and in some cases, slower) but will update this post when I learn more.</p>
<p>Despite GLM being faster on the mobile devices, I am more inclined to use Eigen due to its speed on the tested Intel CPU and its much better documentation and more active community.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2012/01/choosing-a-maths-library-for-cross-platform-c-game-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MDN Holiday Calendar Link Roundup</title>
		<link>http://www.mfoot.com/2011/12/mdn-holiday-calendar-link-roundup/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mdn-holiday-calendar-link-roundup</link>
		<comments>http://www.mfoot.com/2011/12/mdn-holiday-calendar-link-roundup/#comments</comments>
		<pubDate>Sat, 24 Dec 2011 10:00:02 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=266</guid>
		<description><![CDATA[Through the run-up to Christmas 2011, the Mozilla Developer Network has been posting a link a day in their MDN Holiday Calendar. This post serves as a collection of those posts as a time-saver, but the site is worth checking &#8230; <a href="http://www.mfoot.com/2011/12/mdn-holiday-calendar-link-roundup/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Through the run-up to Christmas 2011, the Mozilla Developer Network has been posting a link a day in their <a title="MDN Holiday Calendar" href="http://thewebrocks.com/calendar/">MDN Holiday Calendar</a>. This post serves as a collection of those posts as a time-saver, but the site is worth checking out. Note that none of this is my work, the calendar was written by Chris Heilmann with additional links provided by Luke Crouch, Robert Nyman and Rob Hawkes. Source code is <a href="https://github.com/codepo8/calendar-tutorial">available on GitHub</a> and there is a making of tutorial: <a href="http://christianheilmann.com/2011/11/29/building-an-advent-calendar-for-mozilla-in-phpjscss-part-1/">Part 1</a> &#8211; <a href="http://christianheilmann.com/2011/11/29/building-an-advent-calendar-for-mozilla-in-phpjscss-part-2/">Part 2.</a></p>
<p>Also note: this isn&#8217;t an error, at the time of writing numbers 2 and 10 point to the same URL. Number 10 also seems to have a broken quote with half missing! Despite this, some of these articles are really interesting!</p>
<p><span id="more-266"></span></p>
<ol>
<li>
<h1><a href="http://www.andismith.com/blog/2011/11/25-dev-tool-secrets/">25 Secrets of the Browser Developer Tools</a></h1>
<p>Superb explanation and introduction to how you use and get the most out of the Developer Tools in web browsers.</li>
<li>
<h1><a href="http://www.davidflanagan.com/2011/10/html-parsing-wi.html">HTML Parsing with JavaScript</a></h1>
<p>Ever thought of implementing the DOM in JavaScript? David Flanagan shows with dom.js how it can be done.</li>
<li>
<h1><a href="http://sixrevisions.com/css/font-face-web-fonts-issues/">How to Bulletproof @font-face Web Fonts</a></h1>
<p>Working with fonts on the web has always been a challenge. This article aims to clarify as much as possible and take you beyond the common pitfalls.</li>
<li>
<h1><a href="http://experiments.brandoncash.net/elements/">Interactive Periodic Table</a></h1>
<p>Beautiful example of using modern web technologies to create a periodic table &#8211; complete with moving atoms.</li>
<li>
<h1><a href="http://www.thecssninja.com/javascript/fullscreen">Fullscreen HTML5 video</a></h1>
<p>Watching video is nice but it is even nicer if you can do it in fullscreen. This explains how to tap into that possibility in web browsers.</li>
<li>
<h1><a href="http://lights.elliegoulding.com/">Lights </a></h1>
<p>Interactive WebGL music experience.</p>
<p>You can also <a href="http://lights.elliegoulding.com/">see it in action here</a>.</li>
<li>
<h1><a href="http://webglplayground.net/">WebGL playground</a></h1>
<p>This is a great resource to see WebGL code in action and play live with the code</li>
<li>
<h1><a href="https://developer.mozilla.org/en/CSS/CSS_transitions">CSS Transitions</a></h1>
<p>The smoothness of this page is very much the result of using CSS transitions. Check the docs to learn all about them.</p>
<p>You can also <a href="https://developer.mozilla.org/samples/cssref/transitions/sample2/">see it in action here</a>.</li>
<li>
<h1><a href="https://wiki.mozilla.org/GamepadAPI">Gamepad API</a></h1>
<p>Gamepad and joystick support is coming to Firefox and Chrome.</p>
<p>You can also <a href="http://vimeo.com/31906995">see it in action here</a>.</li>
<li>
<h1><a href="http://www.davidflanagan.com/2011/10/html-parsing-wi.html">HTML parsing in JavaScript</a></h1>
<p>&#8220;Next time you shout at some browser for doing it wrong</p>
<p>You can also <a href="http://thewebrocks.com/calendar/check%20out%20how%20hard%20it%20is%20to%20parse%20HTML.">see it in action here</a>.</li>
<li>
<h1><a href="http://popcornjs.org/">Popcorn.js</a></h1>
<p>Popcorn is a Mozilla sponsored project to make it dead easy to sync media with web content.</p>
<p>You can also <a href="http://popcornjs.org/demos">see it in action here</a>.</li>
<li>
<h1><a href="http://www.biomotionlab.ca/Demos/webgl_walker/webgl_walker.php">WebGL Walker</a></h1>
<p>A cool and customizable skeleton done with WebGL. I recommend maxing out the sliders!</p>
<p>You can also <a href="http://www.biomotionlab.ca/Demos/webgl_walker/webgl_walker.php">see it in action here</a>.</li>
<li>
<h1><a href="http://medialize.github.com/jQuery-contextMenu/demo/html5-polyfill-firefox8.html">Context menus in browsers</a></h1>
<p>This is a jQuery polyfill to bring native context menus as supported in Firefox 8+ to all browsers.</p>
<p>You can also <a href="http://hacks.mozilla.org/2011/11/html5-context-menus-in-firefox-screencast-and-code/">see it in action here</a>.</li>
<li>
<h1><a href="http://jlongster.com/2011/11/21/canvas.html">Going Fullscreen with Canvas</a></h1>
<p>Nice and simple example how you can utilize the Fullscreen API to create a complete full-screen canvas experience.</p>
<p>You can also <a href="http://jlongster.com/2011/11/21/canvas.html">see it in action here</a>.</li>
<li>
<h1><a href="http://www.eleqtriq.com/2010/11/natural-object-rotation-with-css3-3d/">Natural Object-Rotation with CSS3 3D</a></h1>
<p>Great article on CSS 3D Transforms with beautiful illustrations. Make sure to use the various web browser prefixes in your CSS code to make it work for as many as possible.</p>
<p>You can also <a href="http://www.eleqtriq.com/wp-content/static/demos/2010/rotation/index.html">see it in action here</a>.</li>
<li>
<h1><a href="http://platform.html5.org/">The Open Web platform: Browser technologies</a></h1>
<p>The Open Web is filled with technologies and specifications that offers web developers a lot of choices. This page is an overview of all those technologies.</li>
<li>
<h1><a href="http://www.martani.net/2010/11/encode-javascript-with-japanese-style.html">Encode JavaScript as Japanese emoticons</a></h1>
<p>This is wild but it also shows that when it comes to filtering out your data for malicious injections looking for alert() doesn&#8217;t cut it.</li>
<li>
<h1><a href="http://nodejs.org/">Node.js</a></h1>
<p>&#8220;Node.js lets you to run JavaScript outside of the browser while utilising the full power of your computer. It allows for a whole variety of use-cases; like game and Web servers or simple applications that scrape and manipulate data.</p>
<p>You can also <a href="http://nodejs.org/">see it in action here</a>.</li>
<li>
<h1><a href="http://www.spielzeugz.de/html5/sticky-thing/">HTML5 Sticky Thing</a></h1>
<p>Nice canvas example which shows a playful example of you you can add nice interaction to a cute feature.</p>
<p>You can also <a href="http://www.spielzeugz.de/html5/sticky-thing/">see it in action here</a>.</li>
<li>
<h1><a href="https://developer.mozilla.org/en/API/Mouse_Lock_API">Mouse Lock API</a></h1>
<p>The Mouse Lock API allows you to lock the position of the mouse and hide the cursor. It is perfect for games and visualisations where you need to look around a 3D world and don&#8217;t want to be restricted by traditional mouse movement on the Web.</li>
<li>
<h1><a href="http://learningthreejs.com/">Learning three.js</a></h1>
<p>Learn how to use the three.js WebGL library to create animations and games.</li>
<li>
<h1><a href="http://dochub.io/">Dochub.io</a></h1>
<p>This is a great find-as-you-type interface to the MDN CSS documentation</li>
<li>
<h1><a href="http://robert.ocallahan.org/2011/11/latency-of-html5-sounds.html">HTML5 audio in games</a></h1>
<p>A small trick to fight the latency of HTML5 audio in Games</li>
<li>
<h1><a href="http://html5doctor.com/video-subtitling-and-webvtt/">Video Subtitling and WebVTT </a></h1>
<p>A great introduction by the HTML5 Doctor on a very important part of online video.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/12/mdn-holiday-calendar-link-roundup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cross-compiling FreeType for Android with CMake</title>
		<link>http://www.mfoot.com/2011/12/cross-compiling-freetype-for-android-with-cmake/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=cross-compiling-freetype-for-android-with-cmake</link>
		<comments>http://www.mfoot.com/2011/12/cross-compiling-freetype-for-android-with-cmake/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 15:03:15 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android-cmake]]></category>
		<category><![CDATA[cmake]]></category>
		<category><![CDATA[NDK]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=255</guid>
		<description><![CDATA[Freetype provides a Makefile with a configure utility that makes it fairly easy to cross-compile for other platforms, however there are a lot of examples on the web (as well as some solutions) of people having difficulty in it. My &#8230; <a href="http://www.mfoot.com/2011/12/cross-compiling-freetype-for-android-with-cmake/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Freetype provides a Makefile with a configure utility that makes it fairly easy to cross-compile for other platforms, however there are a lot of examples on the web (as well as some <a title="Cross compile freetype2 for ARM" href="http://zarprime.blogspot.com/2006/08/how-to-cross-compile-freetype.html">solutions</a>) of people having difficulty in it.</p>
<p>My intention is to cross-compile FreeType using the Android NDK into a static library that can ultimately be used by <a title="libRocket HTML and CSS based UI" href="http://librocket.com">libRocket</a> for font rendering in HTML+CSS based UIs in OpenGL applications. I&#8217;m using the <a title="CMake - Home" href="http://cmake.org/">CMake</a> build system for cross-platform builds and the <a title="android-cmake Google Code" href="http://android-cmake.googlecode.com">android-cmake</a> project to create a CMake toolchain for the NDK. This requires creating a CMakeLists.txt for FreeType as it doesn&#8217;t currently provide one.</p>
<p>The CMakeLists.txt file included below is based on the FreeType-2.4.8 release and is a result of converting the Jamfile and Makefile to CMake. Its intention is simply to allow compilation with CMake. For standard build and installs I would recommend following the instructions in the docs/INSTALL file from the FreeType directory. <strong>Note: </strong>This file will try and build *all* of FreeType2&#8242;s modules as defined in include/freetype/config/ftmodule.h. If you don&#8217;t want to build some of these modules please edit that file and remove the macro calls.<span id="more-255"></span>This is a rather brute force method that will compile all the files and modules that are in the default build settings for FreeType. I spent some time trying to add proper CMake style options for each module that also checks their dependencies but didn&#8217;t get too far. You will need to remove files from compilation as needed.</p>
<pre>cmake_minimum_required(VERSION 2.6)

project(FreeType2)

# First, compiler definitions for building the library
add_definitions(-DFT2_BUILD_LIBRARY)
add_definitions("-DFT_CONFIG_MODULES_H=&lt;ftmodule.h&gt;")

# Specify library include directories
include_directories("${PROJECT_SOURCE_DIR}/builds/ansi")
include_directories("${PROJECT_SOURCE_DIR}/include")
include_directories("${PROJECT_SOURCE_DIR}/include/freetype")
#include_directories("${PROJECT_SOURCE_DIR}/include/freetype/config")

# For the auto-generated ftmodule.h file
include_directories("${PROJECT_BINARY_DIR}/include")

include_directories("${PROJECT_SOURCE_DIR}/objs")

#file(GLOB BASE_SRCS "src/base/*.c")

set(BASE_SRCS
    src/base/ftsystem.c
    src/base/ftdebug.c
    src/base/ftinit.c
    src/base/ftbbox.c
    src/base/ftbitmap.c
    src/base/ftcid.c
    src/base/ftadvanc.c
    src/base/ftcalc.c
    src/base/ftdbgmem.c
    src/base/ftgloadr.c
    src/base/ftobjs.c
    src/base/ftoutln.c
    src/base/ftrfork.c
    src/base/ftsnames.c
    src/base/ftstream.c
    src/base/fttrigon.c
    src/base/ftutil.c
    src/base/ftfstype.c
    src/base/ftgasp.c
    src/base/ftglyph.c
    src/base/ftgxval.c
    src/base/ftlcdfil.c
    src/base/ftmm.c
    src/base/ftotval.c
    src/base/ftpatent.c
    src/base/ftpfr.c
    src/base/ftstroke.c
    src/base/ftsynth.c
    src/base/fttype1.c
    src/base/ftwinfnt.c
    src/base/ftxf86.c
    src/truetype/truetype.c
    src/type1/type1.c
    src/cff/cff.c
    src/cid/type1cid.c
    src/pfr/pfr.c
    src/type42/type42.c
    src/winfonts/winfnt.c
    src/pcf/pcf.c
    src/bdf/bdf.c
    src/sfnt/sfnt.c
    src/autofit/autofit.c
    src/pshinter/pshinter.c
    src/raster/raster.c
    src/smooth/smooth.c
    src/cache/ftcache.c
    src/gzip/ftgzip.c
    src/lzw/ftlzw.c
    src/bzip2/ftbzip2.c
    src/psaux/psaux.c
    src/psnames/psmodule.c)

include_directories("src/truetype")
include_directories("src/sfnt")
include_directories("src/autofit")
include_directories("src/smooth")
include_directories("src/raster")
include_directories("src/psaux")
include_directories("src/psnames")

add_library(freetype SHARED ${BASE_SRCS})

set(FREETYPE_LIBRARY freetype CACHE STRING "The FreeType library name")
set(FREETYPE_FOUND TRUE CACHE BOOL "Whether freetype has been found or not")
set(FREETYPE_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include/
    ${PROJECT_SOURCE_DIR}/include/freetype CACHE STRING "FreeType include
    directories")

    set(FREETYPE_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include/
    ${PROJECT_SOURCE_DIR}/include/freetype CACHE STRING "FreeType include
    directories")</pre>
<p>The file sets the variables that FindFreeType.cmake sets, so any dependent sub-projects should use this first. Just remember to use:</p>
<pre># Build FreeType
add_subdirectory(lib/freetype-2.4.8)
include_directories(lib/freetype-2.4.8/include)</pre>
<p>&#8230; before building the dependent projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/12/cross-compiling-freetype-for-android-with-cmake/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Building Boost 1.47 for Android using CMake and the NDK</title>
		<link>http://www.mfoot.com/2011/12/building-boost-1-47-for-android-using-cmake-and-the-ndk/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=building-boost-1-47-for-android-using-cmake-and-the-ndk</link>
		<comments>http://www.mfoot.com/2011/12/building-boost-1-47-for-android-using-cmake-and-the-ndk/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 14:52:32 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android-cmake]]></category>
		<category><![CDATA[boost]]></category>
		<category><![CDATA[cmake]]></category>
		<category><![CDATA[NDK]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=256</guid>
		<description><![CDATA[The Boost library is incredibly useful in cross-platform C++ software development. Building Boost for Android can be a bit troublesome and several patches need to be applied to the code. Mystic Games provides a project on GitHub called Boost for &#8230; <a href="http://www.mfoot.com/2011/12/building-boost-1-47-for-android-using-cmake-and-the-ndk/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <a title="Boost" href="http://www.boost.org/">Boost library</a> is incredibly useful in cross-platform C++ software development. Building Boost for Android can be a bit troublesome and several patches need to be applied to the code. Mystic Games provides a project on GitHub called <a title="Boost for Android - Github" href="https://github.com/MysticTreeGames/Boost-for-Android">Boost for Android</a> which at the time of writing worked with official NDK r5c and Boost version 1.45. See after the break for more information.</p>
<p><span id="more-256"></span>Version 1.47 adds some useful modules such as Boost::Random and Boost::Asio, but the patches from 1.45 don&#8217;t apply. Luckily klayge.org has applied the patches manually (there aren&#8217;t many).</p>
<h2>Patching Boost:</h2>
<ul>
<li>The patched Boost 1.47 files <a title="Boost 1.47 Android NDK r6" href="http://www.klayge.org/2011/11/02/compile-boost-1-47-with-android-ndk-r6/">here</a>.</li>
<li>The Boost 1.47 source <a title="Boost 1.47 Download" href="http://www.boost.org/users/history/version_1_47_0.html">here</a>.</li>
<li><a title="Android-cmake - Google Code" href="android-cmake.googlecode.com">android-cmake</a> installed and configured to use your NDK toolchain.</li>
</ul>
<p><span class="Apple-style-span" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">First, merge (don&#8217;t replace!) the </span><em style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">boost</em><span class="Apple-style-span" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"> and </span><em style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">libs</em><span class="Apple-style-span" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"> folders from the download into the boost directory. You now have a patched version of Boost. Paste the contents of the code below into a file called CMakeLists.txt inside the <em>boost</em> directory. This is a modified version of android-cmake&#8217;s Boost installation script that allows you to either build and install Boost to your NDK directory or build it as a dependency for a project (this has the advantage of being sure you&#8217;re using the same version of Boost on each machine you build on and for each architecture, as well as meaning you don&#8217;t need to manually install Boost on each development machine, but Boost is a very large dependency to add and it is a lot of files to place into a repository).</span></p>
<pre>cmake_minimum_required(VERSION 2.8)

project(android-boost)

#find patched boost directory
set(BOOST_ROOT ${PROJECT_SOURCE_DIR} CACHE PATH  "Boost 1.47.0 patched for android")

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}  -DNO_BZIP2" )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNO_BZIP2")

include_directories(${PROJECT_SOURCE_DIR})

# Build each of the Boost libraries that have compiled components
file(GLOB lib_srcs ${PROJECT_SOURCE_DIR}/libs/system/src/*.cpp)

add_library( boost_system ${lib_srcs})

file(GLOB lib_srcs ${PROJECT_SOURCE_DIR}/libs/filesystem/v2/src/*.cpp)

add_library( boost_filesystem ${lib_srcs})

set(lib_dir ${PROJECT_SOURCE_DIR}/libs/iostreams/src)
set(lib_srcs ${lib_dir}/file_descriptor.cpp   ${lib_dir}/gzip.cpp   ${lib_dir}/mapped_file.cpp   ${lib_dir}/zlib.cpp)
add_library( boost_iostreams ${lib_srcs})

file(GLOB lib_srcs ${PROJECT_SOURCE_DIR}/libs/program_options/src/*.cpp)

add_library( boost_program_options ${lib_srcs})

file(GLOB lib_srcs ${PROJECT_SOURCE_DIR}/libs/regex/src/*.cpp)

add_library( boost_regex ${lib_srcs})

file(GLOB lib_srcs ${PROJECT_SOURCE_DIR}/libs/signals/src/*.cpp)

add_library( boost_signals ${lib_srcs})

file(GLOB lib_srcs ${PROJECT_SOURCE_DIR}/libs/thread/src/pthread/*.cpp)

add_library( boost_thread ${lib_srcs})

set(BOOST_ROOT ${PROJECT_SOURCE_DIR} CACHE PATH "Path to the Boost root directory")
set(BOOST_INCLUDEDIR ${BOOST_ROOT} CACHE PATH "Boost include directory")
set(Boost_INCLUDE_DIRS ${BOOST_ROOT} CACHE PATH "Boost header locations")
set(Boost_LIBRARIES boost_filesystem boost_system boost_program_options
boost_iostreams boost_regex boost_signals boost_thread  CACHE STRING "khkh")

configure_file(${PROJECT_SOURCE_DIR}/BoostConfig.cmake.in
${PROJECT_BINARY_DIR}/BoostConfig.cmake @ONLY)

install(DIRECTORY ${BOOST_ROOT}/boost DESTINATION ${CMAKE_INSTALL_PREFIX}/include)
install(TARGETS boost_system DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
install(TARGETS boost_filesystem DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
install(TARGETS boost_program_options DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
install(TARGETS boost_iostreams DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
install(TARGETS boost_regex DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
install(TARGETS boost_signals DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)
install(TARGETS boost_thread DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)</pre>
<p>Optional: You can then also add Boost 1.47&#8242;s version number to the known versions in FindBoost.cmake (Boost 1.47 is newer than CMake 2.8 that I am using):</p>
<pre>  set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS}
    <strong>"1.47.0" "1.47"</strong> "1.46.0" "1.46" "1.45.0" "1.45" "1.44.0" "1.44" "1.43.0" "1.43" "1.42.0" "1.42"</pre>
<h2>Option: Building Boost for the NDK</h2>
<p>You can then either open a terminal and build Boost using android-cmake and install to the NDK directory:</p>
<pre>$ cd boost_1_47/
$ mkdir build
$ cd build/
$ android-cmake ..
$ make
$ sudo make install</pre>
<p>Boost should now be able to be found by CMake with the standard find_package command:</p>
<pre>find_package(Boost 1.47 COMPONENTS filesystem system thread REQUIRED)</pre>
<h2>Alternative: Adding Boost as a sub-project in CMake</h2>
<p>If you move the boost directory into your third party library directory you can then build boost and be sure you have the correct version all of the time by adding this to your project&#8217;s CMakeLists.txt file:</p>
<pre># Build boost 1.47
add_subdirectory(lib/boost_1_47)</pre>
<p>Just remember to link against ${Boost_LIBRARIES} and include ${Boost_INCLUDE_DIRS} as you usually would.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/12/building-boost-1-47-for-android-using-cmake-and-the-ndk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Notes on Android Graphics and Animations</title>
		<link>http://www.mfoot.com/2011/12/notes-on-android-graphics-and-animations/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=notes-on-android-graphics-and-animations</link>
		<comments>http://www.mfoot.com/2011/12/notes-on-android-graphics-and-animations/#comments</comments>
		<pubDate>Sun, 04 Dec 2011 13:34:33 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Game Development]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=244</guid>
		<description><![CDATA[This post contains my notes on the Youtube Video &#8220;Learn about Android Graphics &#38; Animations from Google&#8217;s Android UI Toolkit Team&#8221; which shows a talk given by Romain Guy and Chet Haase from Google at the San Francisco Android User &#8230; <a href="http://www.mfoot.com/2011/12/notes-on-android-graphics-and-animations/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This post contains my notes on the Youtube Video &#8220;<a title="Learn about Android Graphics &amp; Animations from Google's Android UI Toolkit team" href="http://www.youtube.com/watch?v=duefsFTJXzc">Learn about Android Graphics &amp; Animations from Google&#8217;s Android UI Toolkit Team</a>&#8221; which shows a talk given by Romain Guy and Chet Haase from Google at the San Francisco Android User Group, Nov 20th 2010. Note that at the time of writing the video is already quite old, but much of it is still relevant and it&#8217;s well worth a watch for anybody interested in working with graphics in Android. This post is partly for me to remember and refer back to, but hopefully others will find it useful. The video is embedded below and notes can be found after the break:</p>
<p><iframe width="584" height="329" src="http://www.youtube.com/embed/duefsFTJXzc?fs=1&#038;feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p><span id="more-244"></span>So, summary of the video:</p>
<ul>
<li><strong>Surface</strong> is the name for the buffer that objects are rendered into, whether on-screen or off-screen.</li>
<li>05:23: <strong>PixelFlinger</strong> is the equivalent of a JIT for the software implementation of OpenGL that&#8217;s used in the Android emulator. This is pretty interesting, it generates assembly code at runtime based on what render operations you&#8217;re performing.</li>
<li>06:00: <strong>View</strong>s are the basic UI components, for instance each of the UI widgets inherits from View. <strong>ViewGroup</strong>s contain zero or more views and provide the base class for layouts and view containers, allowing you to modify the contents of the container and set properties for how the view children are displayed. <strong>SurfaceView</strong>s are special Views that allow you to place Surfaces at certain points in the screen. Android also provides classes such as the <a href="http://developer.android.com/reference/android/opengl/GLSurfaceView.html">GLSurfaceView</a> which enables OpenGL to render into the Surface and the <a href="http://developer.android.com/reference/android/widget/VideoView.html">VideoView</a> which allows videos to be rendered as well as providing video playback controls.</li>
<li>06:40 Applications can render via a Canvas (which uses Google&#8217;s Skia library) or via RenderScript (which currently makes OpenGL calls) or via OpenGL directly. Each rendering method eventually renders onto the specified kind of Surface.</li>
<li>07:25 Android supports OpenGL ES 1.x and 2.0, and you can use either of these on a device that supports it, early devices and devices running versions before Android 2.2 will not support OpenGL ES 2.0 &#8211; see <a href="https://secure.wikimedia.org/wikipedia/en/wiki/OpenGL_ES#Usage">here</a> for a list of devices that support each version. If you are using the Android Emulator then you will be using PixelFlinger which only supports OpenGL ES 1.x.</li>
<li>08:15 Whenever a frame is drawn, <strong>SurfaceFlinger</strong> produces a composite from each visible View and renders them to a Surface (frame buffer) via either OpenGL or PixelFlinger depending on whether the software GL implementation is being used or not. Older devices used a 2D blitter called MDP.</li>
<li> 09:20 Android won&#8217;t redraw a View unless it&#8217;s both visible and flagged (&#8216;dirty&#8217;) by calling it&#8217;s <a href="http://developer.android.com/reference/android/view/View.html#invalidate()">invalidate()</a> method. This invalidate call will propagate up to any ViewGroups in the view hierarchy to the <strong>ViewRoot</strong> which will lock the Surface of the window and then call draw() on all of it&#8217;s children. When that&#8217;s done the ViewRoot will unlock the canvas and swap the buffers. All windows on Android are double buffered.</li>
<li>15:00 Demo from Chet about how to add animations and effects on Views. Animations can be used for subtle indications &#8211; for instance to indicate whether an image is selected or not it&#8217;s nice to have an animation/transitioning effect rather than an abrupt change in the UI.</li>
<li>16:56 Unlike Java2D, Android&#8217;s Canvas is virtually stateless and uses <strong>Paint</strong>s to specify font size, text colour, colour, opacity, filtering, dithering, anti-aliasing etc. These objects contain a lot of state information and are therefore fairly heavy-weight. Making a new Paint object every frame is not a good idea as you will soon saturate the heap and cause Garbage Collection.</li>
<li>18:15 <strong>Shaders</strong> specify how to draw horizontal or vertical spans of colours (for example different kinds of gradients), i.e. how to fill a shape. These are not the same as GLSL shaders. <strong>ComposeShader</strong> will blend two shaders together and fill the shape with that. <strong>ColorFilter</strong>s perform operations on each pixel they are applied to.</li>
<li>21:00 <strong>XferModes</strong> or blending modes such as Porter-Duff (scientists who defined 12 equations that explain how transparency affects colours) and Darken, Lighten, Multiply and Screen allow modifying the colours of a Canvas. For instance, a BitmapShader and a LinearGradient can be combined with a ComposeShader to draw a bitmap that fades out.</li>
<li>23:17 Demo from Chet showing some example code for using creating new Bitmaps that arise from applying Shaders on Bitmaps. Shaders are created and then the Paint object is told to use that shader. You can then simply draw a rectangle to the screen using the specified Paint and it will perform the shader operations you specified on that rectangle.</li>
<li>25:00<strong> Bitmap</strong>s are either mutable or immutable and have the concept of resolution. Android allows you to specify different assets for different screen resolutions in the same package, and if you place a drawable in the medium resolution folder and are running on a phone which reports itself as high resolution, Android will use that information to scale the Bitmap automatically when it is displayed. Bitmaps can be large objects so they can be recycled without having to wait for the garbage collector. Supported Bitmap formats are <strong>ALPHA_8 </strong>(for alpha masks), <strong>ARGB_4444</strong> (this isn&#8217;t recommended, uses 4 bits for each component and therefore doesn&#8217;t look very good), <strong>ARGB_8888</strong> (recommended, 32 bit images, allows for transparency), and <strong>RGB_565</strong> (doesn&#8217;t contain alpha channel, limited precision for colours, faster to draw, uses dithering). JPEG images do not contain transparency and pre-Gingerbread were loaded automatically with RGB_565. <strong>This meant that jpg images automatically lost some quality pre-gingerbread</strong>. Post Gingerbread all images are loaded by default as ARGB_8888 (and application memory usage limits are increased to compensate). When loading a Bitmap, make sure to specify the format that you want, otherwise it will be loaded as it&#8217;s default and every time the Bitmap is drawn it will need to be converted. For instance, pre-Gingerbread the default bit depth for a Surface is 16 bits, so a 32 bit image will need to be converted before rendering which can be slow. You can control quality of this rendering by enabling/disabling dithering on the Paint object and the Drawable object that the Bitmap&#8217;s being used by. Blending should be avoided with the alpha channel. If Android detects an image is completely opaque it can perform a faster rendering pass.</li>
<li>30:00 Demo by Romain showing the effects of precision loss when rendering 32 bit images onto a 16 bit window (introduces artefacts, gradients look banded). Enabling dithering removes the banding somewhat and improves the gradient. Using a 32 bit window ARGB_8888 with no dithering looks fine while ARGB_4444 still looks bad (and hence isn&#8217;t recommended anywhere).</li>
<li>33:10 Slide showing performance comparisons for different bitmap image types on different surfaces. Drawing an ARGB_8888 surface is three times faster on a 32 bit surface than a 16 bit surface. ARGB_4444 is slightly faster than ARGB_8888 on a 16 bit surface. RGB_565 is 12 times faster than ARGB_8888 and 8 times faster than ARGB_4444 when rendering to a 16 bit surface (as it&#8217;s essentially a memcpy on a 16 bit surface) but three times slower than ARGB_8888 and almost twice as slow as ARGB_4444 on a 32 bit surface.</li>
<li>35:50 Demo of two different ways to copy a View into a Bitmap.</li>
<li>37:30 Chet takes over, talks about Animations. Animations enable better user experiences and can help users use the application, especially on smaller screens. The current (as of the talk) SDK has an animation superclass which controls timing, repetition, interpolation and ending states. Nonlinear interpolation on animations such as view sliding is important as it looks much better than linear motion.</li>
<li>40:30 Android allows for Transforming operations (translation, rotation, scale), Fading, Sequences (allowing you to choreograph multiple animations), Cross-fading, and Layout animations (ViewGroups can animate the display of their children via animations rather than displaying them instantly).</li>
<li>41:40 Animations are about making things <em>look animated</em> rather than actually <em>being</em> animated. <strong>This means that moving views via animations doesn&#8217;t actually move the view. </strong>If you move a button, you need to move the actual object afterwards to ensure that it will handle input events for the correct position. This is because the ViewGroup, when rendering it&#8217;s children, detects first if an animation is playing on the child before rendering it. If it is, it renders the current state of the animation rather then the View&#8217;s original settings.</li>
<li>43:16 Fading is done by interpolating alpha values, which again is not the transparency of the View, but the transparency that the View will be drawn with (see previous point).</li>
<li>45:30 Layout animations are based on staggering some template animation for each child of the view.</li>
<li>46:50 With animations you can setDrawingCacheEnabled(True) to allow the animation to represent itself as a Bitmap which means that the animated object doesn&#8217;t need to be re-rendered each frame. This is a large performance increase and is used in Android everywhere transparently. <strong>As soon as a finger touches a view (for example a ScrollView) each of the Views in the ViewGroup are transformed into Bitmaps via setDrawingCacheEnabled which allows them to be scrolled quickly without having to re-render them.</strong> When a Bitmap is off the screen it can be recycled and used by another View.</li>
<li>You can follow Romain Guy at @romainguy and curious-creature.org.</li>
<li>You can follow Chet Haase at @chethaase and graphics-geek.blogspot.com.</li>
</ul>
<div>Slides of this talk can be found at <a href="http://marakana.com/f/212">http://marakana.com/f/212</a>.</div>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/12/notes-on-android-graphics-and-animations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding tab-completion to Git commands in Bash</title>
		<link>http://www.mfoot.com/2011/12/adding-tab-completion-to-git-commands-in-bash/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=adding-tab-completion-to-git-commands-in-bash</link>
		<comments>http://www.mfoot.com/2011/12/adding-tab-completion-to-git-commands-in-bash/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 08:35:14 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=239</guid>
		<description><![CDATA[I occasionally use the Git Bash shell in Windows and always miss the ability to tab complete the git commands when in other shells. A couple of days ago I found a bash script that enables this functionality when reading &#8230; <a href="http://www.mfoot.com/2011/12/adding-tab-completion-to-git-commands-in-bash/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I occasionally use the Git Bash shell in Windows and always miss the ability to tab complete the git commands when in other shells. A couple of days ago I found a bash script that enables this functionality when reading a <a href="http://blog.mozilla.com/webdev/2011/11/21/git-using-topic-branches-and-interactive-rebasing-effectively/">post on effectively using topic branches in Git by the mozilla web dev team</a>. It enables tab completion as shown below:</p>
<pre>$ git sta&lt;tab&gt;&lt;tab&gt;
stage    stash    status</pre>
<p>I&#8217;ve added it to my <a href="https://github.com/mfoo/dotfiles/blob/master/.git-completion.bash">dotfiles repository on GitHub</a>, or you can access the latest file in the git release tarball at contrib/completion/git-completion.bash.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/12/adding-tab-completion-to-git-commands-in-bash/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using compressed assets in LibRocket via PhysicsFS</title>
		<link>http://www.mfoot.com/2011/09/using-compressed-assets-in-librocket-via-physicsfs/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-compressed-assets-in-librocket-via-physicsfs</link>
		<comments>http://www.mfoot.com/2011/09/using-compressed-assets-in-librocket-via-physicsfs/#comments</comments>
		<pubDate>Sun, 04 Sep 2011 08:37:45 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[assets]]></category>
		<category><![CDATA[librocket]]></category>
		<category><![CDATA[physfs]]></category>
		<category><![CDATA[physicsfs]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=212</guid>
		<description><![CDATA[LibRocket is a system that allows you to define user interface elements for OpenGL/DirectX applications in HTML and CSS. As well as being easy to get started with and powerful, this is really useful as it means you can load &#8230; <a href="http://www.mfoot.com/2011/09/using-compressed-assets-in-librocket-via-physicsfs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a title="LibRocket" href="librocket.com">LibRocket</a> is a system that allows you to define user interface elements for OpenGL/DirectX applications in HTML and CSS. As well as being easy to get started with and powerful, this is really useful as it means you can load UI elements from files that can be edited without needing to recompile the application. It provides several interface classes that you can customise based on your current platform to allow it to play nice with any other libraries you may be using.</p>
<p>I&#8217;ve been storing compressed project assets using <a title="PhysicsFS" href="icculus.org/physfs/">PhysicsFS</a>, which allows for direct read/write access to compressed files such as zip files. After a little fiddling, I produced the class below that allows LibRocket to read it&#8217;s assets via PhysicsFS.</p>
<p><span id="more-212"></span>RocketFileSystemInterface.h:</p>
<pre class="brush: cpp; title: ; notranslate">
#ifndef _ROCKETFILESYSTEMINTERFACE_H_
#define _ROCKETFILESYSTEMINTERFACE_H_

#include &lt;Rocket/Core/FileInterface.h&gt;

/**
 * A FileInterface for libRocket (http://librocket.com/) that enables the
 * reading of files via PhysicsFS (http://icculus.org/physfs/) directly from a
 * compressed archive.
 *
 * Note: The PhysicsFS system must be initialised before this class is used via
 * PHYSFS_init() and any archives must be made searchable via
 * PHYSFS_addToSearchPath().
 *
 * Author: Martin Foot
 * Date: 4th September 2011
 */
namespace Delta {
class RocketFileSystemInterface : public Rocket::Core::FileInterface {
    public:
        RocketFileSystemInterface();
        ~RocketFileSystemInterface();

        /**
         * Get a read only filehandle to the specified file.
         * @param path  The filename in the compressed archive.
         * @return A Rocket filehandle to the opened file. This can be NULL on
         * failure.
         */
        Rocket::Core::FileHandle Open(const Rocket::Core::String&amp; path);

        /**
         * Close a previously opened file.
         * @param file  The Rocket filehandle to close.
         */
        void Close(Rocket::Core::FileHandle file);

        /**
         * Attempt to read the specified number of bytes into the provided
         * buffer. If the specified number of bytes is greater than the size of
         * the file, only  bytes will be copied.
         * @param buffer    The buffer to read into.
         * @param size  The number of bytes to read.
         * @param file  The Rocket filehandle.
         * @return  The actual number of bytes that was read into the buffer.
         */
        size_t Read(void* buffer, size_t size, Rocket::Core::FileHandle file);

        /**
         * Seek to a point in the previously opened file.
         * @param file  The Rocket filehandle.
         * @param offset    The number of bytes to seek to relative to the
         * supplied origin.
         * @param   One of SEEK_SET (seek relative to the beginning of the file),
         * SEEK_CUR (seek relative to the current position in the file) or
         * SEEK_END (relative to the end of the file).
         * @return  Whether seeking was a success or not.
         */
        bool Seek(Rocket::Core::FileHandle file, long offset, int origin);

        /**
         * Get the length of the file.
         * @param file  The Rocket filehandle.
         * @return  The size in bytes of the file.
         */
        size_t Length(Rocket::Core::FileHandle file);

        /**
         * Get the current read pointer offset.
         * @param file  The Rocket filehandle.
         * @return  The current offset. Returns 0 on failure.
         */
        size_t Tell(Rocket::Core::FileHandle file);
    };
}

#endif // _ROCKETFILESYSTEMINTERFACE_H_
</pre>
<p>RocketFileSystemInterface.cpp:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &quot;RocketFileSystemInterface.h&quot;

#include &lt;Rocket/Core.h&gt;
#include &lt;Rocket/Core/Types.h&gt;
#include &lt;physfs.h&gt;
#include &lt;cstdio&gt;
#include &lt;string&gt;

#include &quot;FileSystemInterface.h&quot;

using Delta::FileSystemInterface;

namespace Delta {

RocketFileSystemInterface::RocketFileSystemInterface() : FileInterface() {};

RocketFileSystemInterface::~RocketFileSystemInterface() {};

Rocket::Core::FileHandle RocketFileSystemInterface::Open(const Rocket::Core::String&amp; path) {
    if (!PHYSFS_exists(path.CString())) {
        return NULL;
    }

    PHYSFS_file* file = PHYSFS_openRead(path.CString());
    return static_cast&lt;PHYSFS_file*&gt;((uintptr_t)file);
}

void RocketFileSystemInterface::Close(Rocket::Core::FileHandle file) {
    PHYSFS_close(static_cast&lt;PHYSFS_file*&gt;((void *)file));
}

size_t RocketFileSystemInterface::Read(void* buffer, size_t size, Rocket::Core::FileHandle file) {
    PHYSFS_file* ptr = static_cast&lt;PHYSFS_file*&gt;((void *) file);

    // Don't read past the end of the file or PhysicsFS will return an error.
    size_t length = PHYSFS_fileLength(ptr);
    if(size &gt; length) {
        size = length;
    }

    size_t read = PHYSFS_read(ptr, buffer, size, 1);

    return read * size;
}

bool RocketFileSystemInterface::Seek(Rocket::Core::FileHandle file, long offset, int origin) {
    PHYSFS_file* ptr = static_cast&lt;PHYSFS_file*&gt;((void *)file);

    int response = 0;

    switch(origin) {
        case SEEK_SET:
            // Seek from the beginning of the file.
            response = PHYSFS_seek(ptr, offset);
            break;
        case SEEK_CUR:
            // Offset from the current position.
            response = PHYSFS_seek(ptr, offset + PHYSFS_tell(ptr));
            break;
        case SEEK_END:
            response = PHYSFS_seek(ptr, PHYSFS_fileLength(ptr));
            break;
    }

    if(response == 0)
        return false;

    return true;
}

size_t RocketFileSystemInterface::Tell(Rocket::Core::FileHandle file) {
    PHYSFS_file* ptr = static_cast&lt;PHYSFS_file*&gt;((void *)file);
    size_t offset = PHYSFS_tell(ptr);
    return offset;
}

size_t RocketFileSystemInterface::Length(Rocket::Core::FileHandle file) {
    PHYSFS_file* ptr = static_cast&lt;PHYSFS_file*&gt;((void *)file);
    return PHYSFS_fileLength(ptr);
}

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/09/using-compressed-assets-in-librocket-via-physicsfs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sending photos to a Python web server with Android</title>
		<link>http://www.mfoot.com/2011/07/sending-photos-to-a-python-web-server-with-android/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sending-photos-to-a-python-web-server-with-android</link>
		<comments>http://www.mfoot.com/2011/07/sending-photos-to-a-python-web-server-with-android/#comments</comments>
		<pubDate>Sun, 17 Jul 2011 08:22:08 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[base64]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Photography]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=196</guid>
		<description><![CDATA[I recently involved in a project where we performed some computer vision object recognition and classification using neural networks and SVMs. It was necessary to use photos taken from an Android phone and it took a little while to get &#8230; <a href="http://www.mfoot.com/2011/07/sending-photos-to-a-python-web-server-with-android/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I recently involved in a project where we performed some computer vision object recognition and classification using neural networks and SVMs. It was necessary to use photos taken from an Android phone and it took a little while to get it working. Below is the solution I used, which involved creating a tiny Android application that took a photo, Base64 encoded it, then sent the data over HTTP POST to a Python BaseHTTPRequestHandler subclass which decoded the file and wrote it to disk.</p>
<p><span id="more-196"></span></p>
<p>The solution uses a slightly modified version of <a title="Android upload an image to a PHP server example" href="http://coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/">this example for Android</a> that uses <a title="Java Base64" href="http://iharder.sourceforge.net/current/java/base64/">this Java Base64 encode/decode class</a>. The Python script is based on <a title="Python Web Server Example" href="http://fragments.turtlemeat.com/pythonwebserver.php">an example by Jon Berg</a>.</p>
<p>The Python web server is below:</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python

import cgi
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        print &quot;Somebody made a POST request.&quot;
        return

    def do_POST(self):
        &quot;&quot;&quot;
        Take the Base64 encoded string that the phone transmit, decode it and
        save it as an image file called phone.jpg.
        &quot;&quot;&quot;
        global rootnode
        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            print ctype
            print pdict
            if ctype == 'multipart/form-data':
                query=cgi.parse_multipart(self.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                length = int(self.headers.getheader('content-length'))
                query = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)

            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            upfilecontent = query.get('upfile')
            self.wfile.write(&quot;POST OK.

&quot;);
            f = open(&quot;phone.jpg&quot;, &quot;wb&quot;)
            f.write(upfilecontent[0].decode('base64'))
            f.close()
            print(&quot;File received.&quot;)

            return
        except Exception, err:
            print Exception, err
            pass

def main():
    try:
        server = HTTPServer(('', 8000), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()
</pre>
<p>And here&#8217;s the Android Activity (remember to add the <a title="Android Manifest CAMERA Permission" href="http://developer.android.com/reference/android/Manifest.permission.html#CAMERA">CAMERA permission</a> to your manifest and add the above linked Base64 encoding class to your workspace and package).</p>
<pre class="brush: java; title: ; notranslate">
package com.elec6024.eardetection;

/**
 * This Android Activity takes a photo and uploads it to a server.
 * The server upload HTTP POST code is modified from this:
 * http://coderzheaven.com/index.php/2011/04/android-upload-an-image-to-a-server/
 */
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private Uri outputFileUri;
	private InputStream inputStream;
	public static final int PICTURE_ACTIVITY = 35434;

    /* Override the onCreate method */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
		final Button cameraButton = (Button)findViewById(R.id.camera_button);
		cameraButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v){
				// Check if there's external storage available and that it's writeable.
				boolean mExternalStorageAvailable = false;
				boolean mExternalStorageWriteable = false;
				String state = Environment.getExternalStorageState();

				if (Environment.MEDIA_MOUNTED.equals(state)) {
				    // We can read and write the media
				    mExternalStorageAvailable = mExternalStorageWriteable = true;
				} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
				    // We can only read the media
				    mExternalStorageAvailable = true;
				    mExternalStorageWriteable = false;
				} else {
				    // Something else is wrong. It may be one of many other states, but all we need
				    //  to know is we can neither read nor write
				    mExternalStorageAvailable = mExternalStorageWriteable = false;
				}

				if(mExternalStorageAvailable &amp;&amp; mExternalStorageWriteable){
					Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Normally you would populate this with your custom intent.
					File file = new File(Environment.getExternalStorageDirectory(),&quot;imagefile.jpg&quot;);
					outputFileUri = Uri.fromFile(file);
					cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
					startActivityForResult(cameraIntent, PICTURE_ACTIVITY);
				}
			}
		});
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if (requestCode == PICTURE_ACTIVITY &amp;&amp; resultCode == Activity.RESULT_OK) {

			File file = new File(Environment.getExternalStorageDirectory(),&quot;imagefile.jpg&quot;);
			if(file.exists()){
				ByteArrayOutputStream stream = new ByteArrayOutputStream();

				// Enclose this in a scope so that when it's over we can call the garbage collector (the phone doesn't have a lot of memory!)
				{
					Bitmap image = BitmapFactory.decodeFile(file.getPath());
					Bitmap scaled = Bitmap.createScaledBitmap(image, (int)(image.getWidth() * 0.3), (int)(image.getHeight() * 0.3), false);
					scaled.compress(Bitmap.CompressFormat.JPEG, 90, stream);
				}

				System.gc();

			    byte [] byte_arr = stream.toByteArray();
			    String image_str = Base64.encodeBytes(byte_arr);
			    ArrayList nameValuePairs = new ArrayList();

			    nameValuePairs.add(new BasicNameValuePair(&quot;upfile&quot;,image_str));

			    try {
			        HttpClient httpclient = new DefaultHttpClient();
			        final String URL = &quot;http://192.168.2.3:8000&quot;;
			        HttpPost httppost = new HttpPost(URL);
			        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			        HttpResponse response = httpclient.execute(httppost);
			        String the_string_response = convertResponseToString(response);
			        Toast.makeText(MainActivity.this, &quot;Response &quot; + the_string_response, Toast.LENGTH_LONG).show();
			    } catch(Exception e){
			          Toast.makeText(MainActivity
			        		  .this, &quot;ERROR &quot; + e.getMessage(), Toast.LENGTH_LONG).show();
			          System.out.println(&quot;Error in http connection &quot;+e.toString());
			          e.printStackTrace();
			    }
			}
		}
	}

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
        String res = &quot;&quot;;
        StringBuffer buffer = new StringBuffer();
        inputStream = response.getEntity().getContent();
        int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
	        Toast.makeText(MainActivity.this, &quot;contentLength : &quot; + contentLength, Toast.LENGTH_LONG).show();
        if (contentLength &lt; 0){         }         else{                byte[] data = new byte[512];                int len = 0;                try                {                    while (-1 != (len = inputStream.read(data)) )                    {                        buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..                    }                }                catch (IOException e)                {                    e.printStackTrace();                }                try                {                    inputStream.close(); // closing the stream…..                }                catch (IOException e)                {                    e.printStackTrace();                }                res = buffer.toString();     // converting stringbuffer to string…..                Toast.makeText(MainActivity.this, &quot;Result : &quot; + res, Toast.LENGTH_LONG).show();                //System.out.println(&quot;Response =&gt; &quot; +  EntityUtils.toString(response.getEntity()));
        }
        return res;
   }
}
</pre>
<p>You&#8217;ll also need the layout file for the application:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    &gt;
    &lt;ImageView android:layout_weight=&quot;2&quot;
        android:id=&quot;@+id/imageview&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot; /&gt;
    &lt;Button
	android:id=&quot;@+id/camera_button&quot;
	android:layout_weight=&quot;1&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;wrap_content&quot;
	android:text=&quot;@string/camera_button_text&quot;
	android:textSize=&quot;@dimen/big_text&quot;/&gt;
&lt;/LinearLayout&gt;
</pre>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/07/sending-photos-to-a-python-web-server-with-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Doxygen and Google C++ Testing Framework with CMake</title>
		<link>http://www.mfoot.com/2011/07/using-doxygen-and-google-c-testing-framework-with-cmake/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-doxygen-and-google-c-testing-framework-with-cmake</link>
		<comments>http://www.mfoot.com/2011/07/using-doxygen-and-google-c-testing-framework-with-cmake/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 13:35:52 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cmake]]></category>
		<category><![CDATA[ctest]]></category>
		<category><![CDATA[doxygen]]></category>
		<category><![CDATA[googletest]]></category>
		<category><![CDATA[gtest]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=169</guid>
		<description><![CDATA[What is CMake? CMake is a build system that makes it incredibly easy to distribute and compile source code packages on multiple platforms. It will automatically scan dependencies, searching in the correct (for standard installs) places for each platform and warning &#8230; <a href="http://www.mfoot.com/2011/07/using-doxygen-and-google-c-testing-framework-with-cmake/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong>What is CMake?</strong></p>
<p><a title="CMake" href="http://www.cmake.org">CMake</a> is a build system that makes it incredibly easy to distribute and compile source code packages on multiple platforms. It will automatically scan dependencies, searching in the correct (for standard installs) places for each platform and warning if they are not met. Once it has calculated what&#8217;s necessary to build the project it can generate build scripts and project files for several popular IDEs including Eclipse, XCode, Unix Makefiles, and Visual Studio (<a title="CMake About Page" href="http://www.cmake.org/cmake/project/about.html">read their about page to learn more</a>).</p>
<p><span id="more-169"></span></p>
<p><strong>CMake with Doxygen</strong></p>
<p>As well as building your source, CMake can also run <a title="Doxygen Documentation Generation" href="http://www.stack.nl/~dimitri/doxygen/">Doxygen</a> to generate documentation after a build. Here&#8217;s a sample that I use based on the example <a title="CMake Doxygen" href="http://majewsky.wordpress.com/2010/08/14/tip-of-the-day-cmake-and-doxygen/">here</a>:</p>
<pre class="brush: plain; title: ; notranslate">
################################################################################
# Documentation Generation
#
# Build documentation using Doxygen (www.doxygen.org)
# Builds the docs in the docs/ directory (HTML and LaTeX formats for a .pdf)
################################################################################
find_package(Doxygen)

if(DOXYGEN_FOUND)
    configure_file(${PROJECT_SOURCE_DIR}/doc/Doxyfile.in ${PROJECT_SOURCE_DIR}/doc/Doxyfile @ONLY)
    add_custom_target(doc ALL ${DOXYGEN_EXECUTABLE} ${PROJECT_SOURCE_DIR}/doc/Doxyfile  COMMENT &quot;Generating API documentation with Doxygen&quot; VERBATIM)
endif(DOXYGEN_FOUND)
</pre>
<p>This will take a file called Doxyfile.in (rename your Doxyfile if you&#8217;re just getting started) and substitute any values that you&#8217;ve specified into the file. This means that by changing a variable in the CMakeLists.txt you can have that change show up in your documentation. Inside the Doxyfile.in file you can specify things like this:</p>
<pre class="brush: plain; title: ; notranslate">
PROJECT_NAME = &quot;@PROJECT_NAME@&quot;
PROJECT_NUMBER = &quot;@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@&quot;
PROJECT_LOGO = @CMAKE_CURRENT_SOURCE_DIR@/assets/project_logo.png
OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@/doc
INPUT                  = @CMAKE_CURRENT_SOURCE_DIR@/src @CMAKE_CURRENT_SOURCE_DIR@/test/src @CMAKE_CURRENT_SOURCE_DIR@/src/Core.h.in
EXAMPLE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/examples
IMAGE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/assets
</pre>
<p><strong>CMake and CTest with Google C++ Testing Framework</strong></p>
<p>CMake makes it very easy to add other projects that use CMake to the build as a dependency. <a title="Google C++ Testing Framework" href="http://code.google.com/p/googletest/">Google&#8217;s C++ Testing Framework</a> provides a CMakeLists.txt, so all you need to do in order to add gtest to your project is point your CMakeLists.txt to the gtest folder. Mine&#8217;s in the &#8216;lib&#8217; folder:</p>
<pre class="brush: plain; title: ; notranslate">
################################################################################
# Testing
#
# Build GTest (See http://code.google.com/p/googletest/)
# Run different GTest test programs.
################################################################################

enable_testing(true)

# Build GTest
add_subdirectory(lib/gtest-1.6.0)

include_directories(${gtest_SOURCE_DIR} ${gtest_SOURCE_DIR}/include)

# Compile the test sources.
add_executable(runTests test/src/test.cpp)

# Link the test sources to the gtest libraries.
target_link_libraries(runTests ${LIB} gtest gtest_main)

# Add that executable to the CTests testing framework.
add_test(
    FixedSizeArrayTests runTests
)
</pre>
<p>The only problem here is that while in GTest you don&#8217;t need to enumerate each file, using CMake&#8217;s CTest facility you will do. This could be fixed by defining a simple macro that will add all the tests in a folder. <a title="OpenCV CMake Macro" href="https://code.ros.org/svn/opencv/trunk/opencv/samples/cpp/CMakeLists.txt">This is a good starting point.</a> The above code will enable the &#8216;test&#8217; build target in the Makefile.</p>
<p>In addition, gtest provides the option to output it&#8217;s test results to JUnit-compliant XML files. In order to do this you need to have a minimum of CMake version 2.8 (so set cmake_minimum_required(VERSION 2.8)) and then you can set the CTest environment variable &#8220;xml&#8221; like this:</p>
<pre class="brush: plain; title: ; notranslate">
set_tests_properties(FixedSizeArrayTests PROPERTIES ENVIRONMENT &quot;GTEST_OUTPUT=xml&quot;)
</pre>
<p>This is especially useful if you&#8217;re using a build system such as <a title="Jenkins Continuous Integration" href="http://www.jenkins-ci.org">Jenkins</a> (if so, be sure to look at the <a title="CMake Builder Plugin for Jenkins" href="https://wiki.jenkins-ci.org/display/JENKINS/cmakebuilder+Plugin">CMakebuilder plugin</a>) as you can set Jenkins to perform testing and then display JUnit test results with each build.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/07/using-doxygen-and-google-c-testing-framework-with-cmake/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatically download National Geographic&#8217;s Photo of the Day and set it as your desktop background</title>
		<link>http://www.mfoot.com/2011/07/automatically-download-national-geographics-photo-of-the-day-and-set-it-as-your-desktop-background/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=automatically-download-national-geographics-photo-of-the-day-and-set-it-as-your-desktop-background</link>
		<comments>http://www.mfoot.com/2011/07/automatically-download-national-geographics-photo-of-the-day-and-set-it-as-your-desktop-background/#comments</comments>
		<pubDate>Fri, 08 Jul 2011 13:14:04 +0000</pubDate>
		<dc:creator>Martin</dc:creator>
				<category><![CDATA[Photography]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[national geographic]]></category>
		<category><![CDATA[photo of the day]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[wallpaper]]></category>

		<guid isPermaLink="false">http://www.mfoot.com/?p=152</guid>
		<description><![CDATA[National Geographic is an exceptional source of photos and imagery. I wrote a short Python script that&#8217;s been tested on Linux and Mac OS X to read the @NatGeo Twitter stream and automatically download their Photo of the Day featured &#8230; <a href="http://www.mfoot.com/2011/07/automatically-download-national-geographics-photo-of-the-day-and-set-it-as-your-desktop-background/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>National Geographic is an exceptional source of photos and imagery. I wrote a short Python script that&#8217;s been tested on Linux and Mac OS X to read the <a title="National Geographic Twitter Stream" href="http://twitter.com/#!/NatGeo">@NatGeo</a> Twitter stream and automatically download their Photo of the Day featured image. Occasionally the photo of the day is provided by a National Geographic reader and these don&#8217;t provide high-res download links (likely due to licensing and permissions) so the script ignores these.</p>
<p><span id="more-152"></span> If you&#8217;re running Linux, it will attempt to set the Gnome background wallpaper to the downloaded image, and by default it downloads to ~/Dropbox/Wallpapers. This can be changed by modifying the DOWNLOAD_FOLDER variable. The bonus of it downloading to Dropbox is that I can run the script in a cron job on my Linux desktop and have the wallpapers appear on all my other machines &#8212; especially nice as my laptop displays wallpapers randomly from the Wallpapers folder.</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python

&quot;&quot;&quot;
natgeowp.py

Fetches the National Geographic Photo of the Day from the @NatGeo Twitter
stream, downloads it, and tries to set it as the background wallpaper.

Can be scheduled to run in a cron job with crontab.

Martin Foot &lt;martin@mfoot.com&gt;

This is a cleaned up version of my original script after seeing Christian
Stefanescu's NASA image of the day wallpaper script -

http://0chris.com/nasa-image-day-script-python.html

&quot;&quot;&quot;

try:
    from urllib.request import urlopen
except ImportError:
    # We're using Python 2.x, not Python 3.x
    from urllib import urlopen

import json
import re
import os
import commands
import platform

# Configurable settings
FEED_URL = 'http://twitter.com/statuses/user_timeline.json?id=NatGeo'
DOWNLOAD_FOLDER = os.path.join(os.getenv('HOME'), 'Dropbox', 'Wallpapers')

def fetch_tweets(feed_url):
    &quot;&quot;&quot;
    Return JSON object of the Twitter stream.
    &quot;&quot;&quot;
    # Don't edit below
    twitter = urlopen(feed_url)
    tweets = twitter.read()
    twitter.close()
    tweets = json.loads(tweets)
    return tweets

def filter_tweets(haystack):
    &quot;&quot;&quot;
    Filter out any tweets that don't contain the words &quot;Photo of the Day&quot;
    &quot;&quot;&quot;
    needle = 'Photo of the Day'

    found = []

    # Loop through tweets, newest last.
    for tweet in haystack:
        if tweet['text'].startswith(needle):
            # We've found a photo, extract the URL (tweet seems to be
            # automated, we can assume there will be one).
            pic_url = re.search(&quot;(http://\S+)&quot;, tweet['text'])#.groups()[0]

            if pic_url != None:
                pic_url = pic_url.groups()[0]
                found.append(pic_url)

    return found

def check_downloadable(urls):
    &quot;&quot;&quot;
    Loop through a list of National Geographic Photo of the Day URLs, and if
    they provide a download link, record it. Some images such as
    reader-submitted images don't provide a link, likely due to licensing
    issues. We won't download these.
    &quot;&quot;&quot;
    found = []

    for pic_url in urls:
        text = str(urlopen(pic_url).read())
        pic_url = re.search('a href=&quot;(\S+)&quot;&gt;Download Wallpaper', text)

        # Not all photos have a download link
        if pic_url != None:
            pic_url = pic_url.groups()[0]

            found.append(pic_url)

    return found

def download_photos(urls):
    &quot;&quot;&quot;
    Download the list of files to the DOWNLOAD_FOLDER directory.
    &quot;&quot;&quot;
    for url in urls:
        print 'Downloading ' + url
        filename = re.search(&quot;.*/(.+)&quot;, url).groups()[0]
        path = os.path.join(DOWNLOAD_FOLDER, filename)

        imageFile = open(path, &quot;wb&quot;)
        imageFile.write(urlopen(url).read())
        imageFile.close()

    return path

def set_gnome_wallpaper(file_path):
    command = &quot;gconftool-2 --set \
            /desktop/gnome/background/picture_filename \
            --type string '%s'&quot; % file_path
    status, output = commands.getstatusoutput(command)
    return status

if __name__ == '__main__':
    tweets = fetch_tweets(FEED_URL)
    image_urls = filter_tweets(tweets)
    downloadable_urls = check_downloadable(image_urls)

    if len(downloadable_urls) &gt; 0:
        most_recent = download_photos(downloadable_urls)

        osplatform = platform.system()

        # If we're on Linux, try and set the desktop wallpaper with gconftool
        # (TODO: Non-Gnome desktop environments).
        if osplatform == &quot;Linux&quot;:
            set_gnome_wallpaper(most_recent)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.mfoot.com/2011/07/automatically-download-national-geographics-photo-of-the-day-and-set-it-as-your-desktop-background/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

