Dean's Blog Development blog of Dean Harding. en-us Sun, 22 Feb 2015 12:21:59 GMT What's the deal with USB headphones? Sun, 22 Feb 2015 12:21:59 GMT <p>Why do these things exist? A while back, I bought a pair of Logitech&nbsp;H390 headphones. This is what they look like:</p><p style="text-align: center;"><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGg0LmdncGh0LmNvbS9uSEVFNklzRDFBUUlRVFBVTmM4ZGVVMkZZZUNrUS1fSEhXWDlyWjY0ZDVVSVVHT1VZT280bzM0VTcwTEEwTDRtVHVrM0Y0VzhZaHowMDF4eVljVTE9czEwMCIsImJsb2Jfa2V5IjoiQU1JZnY5NlkxWG9DSnFEajVsTnlqSUZlNGc1NUJVY0pqNElNNnlEWHdfeE1nQUctQkZnYXhtNG1HWk5lX3o4RlBfRU5fRWEwVmU0ejFGVWNFZDBGNHk4cVVaTFJUbWJwbXFVRy1ES1N5aUE0OWhYUWNSSWctNWY5MXdzb0hvX19uRUZWbHVhVkN3Z29YYksyTlBlamRzZ19TSXlpR0p0akZnIiwiaGVpZ2h0IjozMjAsIndpZHRoIjo0MjksImZpbGVuYW1lIjoibWVkaXVtLnBuZyIsInNpemUiOjI2MjU3MX0=" src="" /></p><p>When I bought them, I didn&#39;t really spend a whole lot of time looking at the box, but the fact that the interface is USB is shown in that little info panel on the bottom-left. In retrospect, I probably should have spend more time reading that box because it turns out, USB is a horrible, weird interface for headphones and I can&#39;t for the life of me understand why they exist.</p><h2>Cons of USB headphones</h2><p>These are just the ones I ran into while using my headphones over the last year or so:</p><ul><li>They only work in a couple of places. PC, sure. Maybe I could plug them into my Android phone with a USB-A to micro-USB adapter, but I never bothered to buy one in case it didn&#39;t work. A Ninentdo DS or practically anything else that&#39;s not a PC? Forget it!</li><li>Even when it works, because the headset shows up as a separate device, you can get yourself into weird situations where audio would continue routing to your main speakers and not the headphones. Both Windows (as of version 7, I haven&#39;t tried newer versions) and Linux have fairly clunky interfaces for choosing which output device to use. In most cases, with regular headphones, once you plug in all audio is automatically routed to the headphones.</li><li>Because the DAC happens inside the headphones, you can be pretty sure the quality of that hardward is nowhere near the quality of the hardware in your desktop computer.</li></ul><h2>Pros of USB headphones</h2><p>&macr;\_(ツ)_/&macr;</p><p>Oh wait, I can think of one &quot;pro&quot;. The <a href="">Creative Tactic3D Rage</a> headphones has illuminated ear cups. For some reason.</p><p style="text-align: center;"><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGg0LmdncGh0LmNvbS9samZtMjZBeldrN2tjcWpkOE1WeXJoY0poRnF1dFY4cTQ0dTAzbzFNamU4OFNzWkpDQ2drbmNwS0l4UXY2NHNEeDNtTVp5YlFPcFpMa0dBdTdZYzlJX3c9czEwMCIsImJsb2Jfa2V5IjoiQU1JZnY5NTFBM0xWWWNyNERITVpWekFzeEJKcEkxeVQ2WGZWMTlCZFc3SEtrM2hlYmpGanZ3MlBMVDgyZ2dnSHpGQzhKQnZJVl9GckJ6QTlrWGRvOV9sZlg5d0Z0OVZnSXpwN09HUjlDM19FV2tNSXBTa3E3U0NDUllLX3ByTnJMTTBaVDBYX2x1WUpoemRCdm0zQXhnSnpZZktJdXg2cWhBIiwiaGVpZ2h0IjoxODgsIndpZHRoIjo5NDQsImZpbGVuYW1lIjoiU2NyZWVuc2hvdCBmcm9tIDIwMTUtMDItMjIgMjM6MTk6MjYucG5nIiwic2l6ZSI6MTMwODM2fQ==" src="" /></p> Connecting from your Android device to your host computer via adb Sat, 22 Nov 2014 20:45:00 GMT <p>Sometimes when I&#39;m on the road, and using someone else&#39;s Wi-Fi (typically when I&#39;m in a hotel), they will allow you to connect your phone and your laptop to the internet via their Wi-Fi. But, for security reasons, they typically won&#39;t allow your phone to connect to your computer over the Wi-Fi network. This make debugging certain applications quite difficult: I can&#39;t run a server on my laptop and have my phone connect to it.</p><p>But luckily, in recent versions of adb, a new command has been added: adb reverse. It&#39;s basically the opposite of <a href="">adb forward</a>, which lets you forward ports from the host to your device, adb reverse allows you to forward ports from your device to your host.</p><p>So let&#39;s say I have a server running on my host computer, listening on port 8080. I want my phone to connect to it, so I run:</p><pre class="brush: text">$ adb reverse tcp:8080 tcp:8080</pre><p>And then connect to on the phone and problem solved!</p><p>Like adb forward, the parameters correspond to server/destination ports. But in the case of adb reverse, the first parameter is the port on the device and the second is the port on the host you want to forward to.</p> A battery widget with support for monitoring your wearable battery level Tue, 09 Sep 2014 13:59:00 GMT <p>I released the first version of &quot;<a href="">Advanced Battery Monitor</a>&quot; towards the end of last year, to not much fanfare at all. I used it and a couple of my friends used it, and that&#39;s about it.</p><p>But since getting my hands on an Android Wear watch (Moto 360, to be precise), I added a new feature to my graph to also monitor the battery <em>on the watch</em>.</p><p>Here you can see my phone + watch battery level thoughout the day today:</p><p style="text-align: center;"><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGg2LmdncGh0LmNvbS9lWnpxTFRLWVNUOEk1UHJlTFV1MzZwTnNNSDdHOGh0eXZBLVYyMWxHZnN6ZEFldml4TlF0MENCbkpZUFB2bEZyYVRQYlczNEVUN1o0bFhXdzdRa3M9czEwMCIsImJsb2Jfa2V5IjoiQU1JZnY5NVoyckN3a1hsVEFNclF3MkFKVUpqSjA3SDRfbm44LTdlMy14VVpYc0hYXzlUa2E1ZW15MEd5MVVBSDUyeHFOU0duZmtVWXVKM3RMaTBOMjJBd1RFYkxhanRJUXlBQk5oTW5FLWljS2RRZVFrZnJmOUdDQmpqZFJLcmJYLV82U1RaZFVjVndEWmExVUozQ2p3WFdOSXhqbGZJeXJ3IiwiaGVpZ2h0IjoyNjQsIndpZHRoIjoxMDgwLCJmaWxlbmFtZSI6IlNjcmVlbnNob3RfMjAxNC0wOS0wOS0yMy0zMC0yMS5wbmciLCJzaXplIjo1MzA3NzJ9" src="" /></p><p>The green line represents my phone&#39;s battery, the blue my watch&#39;s. I use both devices fairly heavily throughout the day, so I&#39;ll let you make of these graphs as you will.</p><p>The other feature I&#39;ve added is the ability to export your battery data. The app only keeps battery data for up to a week, but you can export the whole data by tapping the widget to get into the &quot;settings&quot; and using the Export option.</p><p style="text-align: center;"><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGg2LmdncGh0LmNvbS9ha3BqQ0VSTUhjT1ZLandBUUoyQzAtOHJhQ20xY00tRUxWbVltUWloQlVLcEl2RmM0OENoUG9tVm1jbHpTbU4yckFpOWVYN2x4Vm9oSy1ieV9sbzRjdz1zMTAwIiwiYmxvYl9rZXkiOiJBTUlmdjk0U1hyMjJPNXpjRzdVdXk0ekM0NERTVGZOdWRmUXN1NHp2ZlZWOWszUlVzSkJZX1dKcHp4YUJrTTJDaXNzazBGQVpoSThydG1LVmlhQVRnTF9ybkdSUkJVNU9QT29OaUkwTWRyVjc5TU1peTQyVkxSdTV4Tjc5ZUpkd3dGWlQxQzlDWW1mUGZPaTlFYzFEb0Q0WElrYzdlX19nY3ciLCJoZWlnaHQiOjEyODAsIndpZHRoIjo3NjgsImZpbGVuYW1lIjoiU2NyZWVuc2hvdF8yMDE0LTA5LTA5LTIzLTU2LTE2LnBuZyIsInNpemUiOjEwODQxOH0=" src="" /></p><p>The source code for the widget is available on github:&nbsp;<a href=""></a></p><p>And of course, the widget itself can be downloaded from the <a href="">Play Store</a>:</p><p style="text-align: center;"><a href=""><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGgzLmdncGh0LmNvbS8zdjJ3MGl2STU3VUhKSExILVlxYTVKQTVOeDhHSmpYcmdHSlN6QUlMMWE4WTQ0czRPREpaWXpFUm5fLW96T0U0bkd3RFdlYkt3d1FwYWg5UC1OTVRZUkE9czEwMCIsImJsb2Jfa2V5IjoiQU1JZnY5NXpFR0RvVS1ZODkzbDNKTW45OE1IelBET3Vncmc2U1JNbnF2SUt6VmtEQTJrWkUzTjZMY0Z6NlpZclVjSVpoTHNpdjNNWmpudGM2aEFCMkhqX005UXJDcl9YSUhLaVVyOURTS3BUVTExTmliZ3BsWFd4U2FmbzBsYUF1X0JsZDY0U1BfNmJaZjlLY3RRTWNQRnozbzcxZnZCYk5RIiwiaGVpZ2h0Ijo0NSwid2lkdGgiOjEyOSwiZmlsZW5hbWUiOiJlbl9nZW5lcmljX3JnYl93b180NS5wbmciLCJzaXplIjo4MTcxfQ==" src="" /></a></p><p>&nbsp;</p> Playing around with a random level generator Mon, 25 Aug 2014 11:09:00 GMT <p>So, one of the things I&#39;ve been toying with recently is the idea of a Diablo-style hack &amp; slash. One of the most important aspects of the hack &amp; slash is level generation. There&#39;s lots of ways you can generate levels and lots of different &quot;looks&quot; you can give your levels. I plan to explore a few different techniques over the next few weeks. My first attempt, which I&#39;ve included below, gives a sort of cavernous look that I think would be good for boss levels:</p><script src="/blob/AMIfv94WoAkp7jGjPq2RvIBgpJ5q5L7ScKOlWgYXTSJ2TBKJjzo_gYWcDv8kslnr_Hau-UBSb_FxYS5-q7EZOHmyTPiK-LrFJmSejrjc7bZ0U6tcMgYbdJUhN2a96s4R9kcQTf11jtqF68sEL1OWZRaS7Ht_Au3YhA"></script><p>The technique is quite simple, I &quot;borrowed&quot; the idea from <a href="">this page</a>. Basically, the algorithm runs as:</p><ol><li>Fill the board with random walls. Each square starts with a 45% chance of being filled.</li><li>Each iteration, for each square, count the number of walls around that square. If there is more than 5, fill the wall in a new version of the map.</li><li>Repeat step 2 until the map is &quot;stable&quot; (that is, until two iterations produce the same map).</li></ol><p>In the example above, you just let it run normally, it&#39;ll do a few iterations, then complete the run in one go and pause for a few seconds so you can see the outcome. You can click &quot;stop&quot; then use the &quot;reset&quot; and &quot;step&quot; buttons to manually progress through the iterations.</p><p>There&#39;s a couple of problems with this, though. Firstly, it tends to make very open levels. I guess depending on the game, that may or may not be OK, but for our purposes, I think I&#39;d like something a little more close-quarters. Another problem is that it produces overly &quot;smooth&quot; walls, that is, there are no sharp corners and no sharp points. Again, depending on your level design, that may or may not be OK, but I&#39;d like to do something about it.</p><p>For the second problem, the solution is actually quite simple: just don&#39;t run the algorithm so many times. If we cap the number of iterations to, say, 10, then we end up with more jagged walls. But that introduces an extra problem: sometimes it will leave behind very tiny &quot;islands&quot; of walls, which the old alorithm would have smoothed away. That can be fixed by a &quot;manual&quot; cleanup afterward where we simply remove the small islands.</p><p>For the first problem, we modify the algorithm slightly:</p><pre class="brush: js"> Map.prototype.iterate = function() { var newMap = new Map(this.width, this.height); newMap.clearMap(); for (var x = 0; x &lt; this.width; x++) { for (var y = 0; y &lt; this.height; y++) { if (this.numWallsWithinSteps(x, y, 1) &gt;= 5) { newMap.setCell(x, y, 1); } else if (this.stepNo &lt; 6 &amp;&amp; this.numWallsWithinSteps(x, y, 2) &lt; 2) { newMap.setCell(x, y, 1); } } } newMap.stepNo = this.stepNo + 1; return newMap; };</pre><p><span style="font-size: 12pt;">The above algorithm can be seen in the map below:</span></p><script src="/blob/AMIfv96VjhYKBIbPWrx-x3ymC5un3cwHUGZxA9mA24gv2atCpzBDuA9R1YUmCc3YuQ35g_MGiMskeW-2PMXONeBg2irdRbI5KzfEpE15qbeNLU59szNRU3zXP2L62VbjzBh4onxaOSmK0eqezFdsc2i70MwD99lTFQ"></script><p>As you can see, this version results in much more &quot;cramped&quot; level than the first version. You can download the full code for the final version <a href="">here</a>.</p><p>This is a pretty simple algorithm and produces nice levels for boss fights, but next time, we&#39;ll want to try a slightly more complicated algorithm for generating the room/corridor style levels that you come to expect.</p> Detecting leaked Activities in Android Sun, 22 Jun 2014 13:27:00 GMT <p>So <a href="">War Worlds</a>&nbsp;has, for quite some time, been plagued with various memory issues. One of the problems is that Android in general is pretty stingy with the heap memory it gives to programs, but the other is that it&#39;s actually very easy to &quot;leak&quot; large chunks of memory by accidentally leaving references to Activity objects in static variables.</p><p>There&#39;s not much that can be done about the former, but the latter can be fairly easily debugged using a couple of tools provided by Android and Java.</p><h2>Detecting leaked Activties</h2><p>The first step is figuring out when Activties are actually leaked. In API Level 11 (Honeycomb), Android added the&nbsp;detectActivityLeaks()&nbsp;method to StrictMode.VmPolicy.Builder class. All this method does is cause Android to keep an internal count of the number of instances of each Activity class that exist on the heap, and let you know whenever it hits 2.</p><p>When you get a StrictMode violation, there&#39;s a few things you can do, you can have Android kill your process, you can log a message, or you can do both. To be honest, neither of those things is particularly helpful because when you&#39;ve got a leak what you&nbsp;<em>really</em>&nbsp;want is a dump of the heap so that you can analyse it later.</p><p>Luckily for us, the StrictMode class writes a message to System.err just before it kills the process, so we can do this little hack to hook in just before that happens and get a HPROF dump just in time:</p><pre class="brush: java">private static void enableStrictMode() { try { StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectActivityLeaks().detectLeakedClosableObjects() .detectLeakedRegistrationObjects().detectLeakedSqlLiteObjects() .penaltyLog().penaltyDeath().build()); // Replace System.err with one that&#39;ll monitor for StrictMode &nbsp; // killing us and perform a hprof heap dump just before it does. System.setErr (new PrintStreamThatDumpsHprofWhenStrictModeKillsUs( &nbsp; System.err)); } catch(Exception e) { // ignore errors } } private static class PrintStreamThatDumpsHprofWhenStrictModeKillsUs &nbsp; extends PrintStream { public PrintStreamThatDumpsHprofWhenStrictModeKillsUs(OutputStream outs) { super (outs); } @Override public synchronized void println(String str) { super.println(str); if (str.startsWith(&quot;StrictMode VmPolicy violation with POLICY_DEATH;&quot;)) { // StrictMode is about to terminate us... do a heap dump! try { File dir = Environment.getExternalStorageDirectory(); File file = new File(dir, &quot;strictmode-violation.hprof&quot;); super.println(&quot;Dumping HPROF to: &quot; + file); Debug.dumpHprofData(file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } } } }</pre><p><span style="font-size: 12pt;">Essentially, what we do is, we set up StrictMode to kill us, the replace System.err with a hack subclass of PrintSteam that checks for the message StrictMode prints and generates a heap dump right then and there.</span></p><p><span style="font-size: 12pt;">It&#39;s ugly, but we only have to do it in debug mode anyway, so I think it&#39;s OK.</span></p><h2><span style="font-size: 12pt;">Analysing the dump</span></h2><p>Next, we have to copy the .hprof file off the device (you could use adb pull for that, but I like <a href=";hl=en">ES File Explorer</a>). One important step is converting the .hprof file from Dalvik format to normal Java format. There&#39;s a handy-dandy tool called <a href="">hprof-conv</a> in the Android SDK which does the conversion for you.</p><p>Once you&#39;ve got a HPROF file a format that can be read by the standard Java tools, the next step is actually analysing it. I was using the <a href="">Eclipse Memory Analyzer</a> tool, but anything will do, really. The first thing we need to do is find out which objects are leaking. Luckily for us, StrictMode prints out which activity is leaking, so we can start there:</p><pre>01-15 17:24:23.248: E/StrictMode(13867): class; instances=2; limit=1 01-15 17:24:23.248: E/StrictMode(13867): android.os.StrictMode$InstanceCountViolation: class; instances=2; limit=1</pre><p><span style="font-size: 12pt;">So it&#39;s detected two copies of the EmpireActivity class. We fire up the Memory Analysis tool in Eclipse, and go to &quot;List objects ... with incoming references&quot; and enter our offending class, &quot;;. And just as StrictMode said, there&#39;s our two instances:</span></p><p style="text-align: center;"><a title="" class="lightbox" href=""><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGg0LmdncGh0LmNvbS9zZlZlNmlBWW80N29lbzBzM1lnOU9TQkEtQktaT2dDTnB3azRodTRSeEVqQ0U4SS11WXQxVERQUUVEb1FpeXluM3dvd00tZ21VbUp2aXFISUp1d1lIUT1zMTAwIiwiYmxvYl9rZXkiOiJBTUlmdjk3Q1VzZm4yc01lMTRzYzJXZ0k4SzM1Vzd4QVJjQ2VIcnFqd295bGduR3BOM3ZubkFMN3JTRGYwWFBJR2dYRU1DM0g1WUtEdDVxZDR2WUhzUGxTWVlJRkRHd2hyYm8zVGFJbk14NnZnNzhlTHhScHR2LVh5eDd0QnZldnB2YjdGUDV1MnoyTVBmazJELTEyY0c0M3RMLWdVdlFrcFEiLCJoZWlnaHQiOjIyNSwid2lkdGgiOjkyNiwiZmlsZW5hbWUiOiJ0d28taW5zdGFuY2VzLnBuZyIsInNpemUiOjI4OTUzfQ==" src="" /></a></p><p><span style="font-size: 12pt;">Now, how do we determine where they&#39;re being held? Right-click one of them and select &quot;Path to GC Roots ... with all references&quot;, which will bring up something like this:</span></p><p style="text-align: center;"><a title="" class="lightbox" href=""><img alt="" data-resp="eyJzdWNjZXNzIjp0cnVlLCJ1cmwiOiJodHRwOi8vbGg0LmdncGh0LmNvbS9qRzNIZ1Rvb1FHQUhzUWRlclY5NEN1QVZRVXlDejg4V1hJemRwZW00YU9DWS01Ql81NjQ2T1hCZlNrQ0toNzlwTlQzSWRncGhfS0hLMDlCcFZFUHRfUT1zMTAwIiwiYmxvYl9rZXkiOiJBTUlmdjk2bTZxQVRSeExOdDQ5Wm1VSjc2V2xNcFptM3llZF9qbzJKaG1oQXVZbVpXdHJUZ2VGWnRHZ0VfaFdzZ1BFWklkc3VUcWhlb3FYM3NqdW5iYXhlZ1hzM2FBNFBwOGloS05sX21BcnRKYmxCOGM5cE1VNmtqZ0QxdS1hVjdNcFY1RWNwSUhLbkYtNzczRl9kWDRPMHBaZ0N0czg0Z2ciLCJoZWlnaHQiOjQzNiwid2lkdGgiOjkyNywiZmlsZW5hbWUiOiJpbnRlcmVzdGluZy5wbmciLCJzaXplIjo2OTc1NX0=" src="" /></a></p><p><span style="font-size: 12pt;">If we go with the assumption that the leak happens in our code and not in the framework (usually a pretty good assumption) the only object holding a reference to this activity is our FleetList class. If we expand that out a few times, we can follow the references all the way back to the mSpriteGeneratedListeners member of StarImageManager.</span></p><p><span style="font-size: 12pt;">What the StarImageManager class does is it generates (or loads from disk) the bitmaps used to display stars. It has a list of objects that are interested in knowing when the star images are updated (generating them can take a while). What was happening here is that the FleetListAdapter class was adding itself to the list of classes interested in receiving updates from StarImageManager, but <em>never removing itself from that list</em>.</span></p><p><span style="font-size: 12pt;">By fixing that bug, I managed to squash one the biggest memory leaks in the game.</span></p><h2>Further work</h2><p>One thing this has highlighted to me is that my system of highly manual event pub/sub is probably not a great idea. Scattered all throughout the code are lots of these &quot;lists of classes who want to subscribe to my event&quot;. Management of those lists is all manual, firing the events is manual, and it&#39;s actually been a bit of a source of problems in the past (e.g. with events firing on random threads and whatnot).</p><p>So the next big chunk of work will be replacing all of these with some kind of unified <a href="">EventBus pattern</a>. I quite like the implimentation of <a href=""></a>, in particular I like how it uses WeakReferences to hold the event subscribers (which would make the above memory leak non-existent).</p>