My Arduino based Cruise Control build indicator lights have been up and running for a couple of months now and so far so good. It’s time to post the source code for the Arduino sketch and the Java app that runs on the machine that the build lights are connected to.
First, here’s a very short video of a successful build. While a build is in progress, all 3 lights turn on, and at the end of the build, you get either solid red or solid green (hopefully), depending upon success!
The lights are connected via USB to a machine that sits nearby. On that machine runs a Java program that attaches to the USB serial port and sends commands to the Arduino sketch to turn any of the 3 coloured lights on or off. The sketch is very simple with no clever logic at all. All it does is read the serial port and based on the value of 3 bytes, turns the lights on or off. All the logic is contained in the Java program.
The Java program running on the attached PC connects to a Cruise Control server using the JMX protocol and waits for status updates for a given project. These status updates occur when builds are started, and when they end. There are also various informational properties that can be obtained from the build server, such as what time the last successful build was. With this information, the lights can be set to show green for a good build less than 2 days old, amber for a build less than 4 days old but older than 2 days, and red for a build that’s older than 4 days (or a failed build).
I won’t go into a long post detailing the code now. It’s a single Java source file with everything in (including the Arduino sketch in the comments), with a section for the command line handling, the JMX connection and the serial port code. It uses the RXTX serial I/O library, so if you want to compile and run it, you’ll need to download that first. I’m happy to answer any questions about the code, and of course, it’s free for you to do whatever you like with (WTFPL). There’s not a lot of documentation specific to the Cruise Control JMX interface, but if you read through the actual Cruise Control source at sourceforge, you get a pretty good idea of all the properties available. The methods to get the properties and the JMX events are fairly standard and the details from Sun here (PDF) helped too.
It ‘s a lovely Sunday afternoon, and my week of soldering, Dremeling and programming has ended! Actually, my lights were complete by Friday lunchtime, but I had to do a bit of work on Friday afternoon and the weekend has been too nice to type up my activities. Here though are the best of the photos I took, and I’ll try and expand on them when I get a chance to write more blog posts.
Things aren’t quite complete yet though. The construction of the lights is finished, and they are installed on our offices (video to follow soon). However, the continuous integration build server isn’t yet hooked into the lights, and there is a bit of debugging to do with the serial to TCP/IP proxy I ended up writing. Unfortunately, the Arduino Ethernet Shield proved to be a bit of a problem in ‘production’ so I ended up reverting to my original plan of hooking the Arduino up straight to a PC using the USB/Serial connection.
Anyway, on to the pictures and an approximate timeline for the week.
Starting out
Here are the internals of the Ikea lights, and as you can see, they are predictably simple. The incoming 240V supply cable is attached to a nice chunky wiring block, and from there each bulb is attached to a toggle switch conncted to the live wire. These push switches are activated by pressing the spring loaded coloured bulb covers mounted into the front panel, so you can turn on and off each individual bulb.
Do all the bits work?
On the first day, I mainly pottered about checking that all the things I’d bought worked ok, my soldering iron still worked, I still remembered how to use my multimeter, etc. All those things that bite you in the backside if you don’t double check before you start. Luckily, everything was good so far. I hooked the Arduino up to the my PC and followed some basic tutorials to get some LEDs flashing. I also tried out the Ethernet Shield to see how it worked. Lastly, when I ordered the bits from Sparkfun, I included a ‘Screw Shield‘ which allows you to more permanently attach wires to the Arduino pins. It comes in kit form and was the perfect re-introduction to soldering, with no active components. Here you can see the 3 shields connected together and a couple of LEDs hooked in too. I was amazed at how easy everything was so far.
Relay boards, more soldering and some network progamming
The next day I soldered up the Sparkfun relay boards. These were very easy to solder together with literally only 6 small components, 2 screw terminals and the relay itself, a totaly of 22 solder points. After these were done I plugged them into the Arduino and tested them, each one worked fine. There’s a nice loud click as the relays switch, although they weren’t connected to any load at this point.
The rest of the day I spent looking into the Arduino libraries for networking. In particular, I discovered that Georg Kaindl had created both DHCP and Zeroconf/Bonjour libraries for the Arduino that he’d documented very well. This is awesome and meant that the networking side of things would be pretty much plug and play. I wrote some code that got all this working, and included the Webduino web server code to handle requests. This was both easy and exciting, but unfortunately, later on, the Ethernet Shield proved a bit of a problem and I had to ditch all the work I’d done.
Dremel day
Now it was time to actually butcher the Ikea lamp housing and install all the electronics I’d soldered up. Here’s my workbench before anything is removed:
Now after 2 switch mounts have been removed.
I decided to leave one switch in place, the ‘green’ lamp switch. I realised that after everything else was mounted inside the case, I could use the remaining switch as a master power on/off switch for the 240V supply. Something that might be quite handy.
After removing the switch mounting, I needed to create mounts for the 3 relay boards and the Arduini board itself. PC Motherboard risers are excellent for this sort of thing, and I had loads sitting around in my PC kit drawers!
After all the mountings were in place, again using the Dremel to drill out the plastic, I screwed the 3 relay boards and the Arduino board in place. The gap in the middle will be for the Arduino power supply later on.
Ethernet Shield Problems
After I’d mounted all the relays and done all the Dremeling work in the case, I naturally wired everything up and started testing. Unfortunately, the Ethernet Shield seemed to be reducing the power the Arduini could supply to it’s IO pins. The relays needed 5V to switch, but with the Ethernet Shield connected, and all the DHCP, Zeroconf and web server code running, I was only getting 3.9V on the output pins, and the relay switching was unreliable. I was also having problem with the shield reseting and starting up properly under external power. It seems there are some problems in this area, and I didn’t have time to look too deeply, so I decided to ditch the idea of the TCP/IP connection and instead focus on my original plan of just the Arduino connected to a USB port on PC.
Final Assembly
Thursday was the final assembly day, wiring up the relay boards, and mounting the power supply. The power supply I was using was this one from Maplin, and it’s nice and light, being switched mode. It fits just nicely in the gap between the two bulbs, and I chopped off the barrel adapter to wire it straight into the Arduino input terminals. None of the original bulb wiring needed to be cut at all, with each of the points that originally went into the manual switches fitting nicely into the relay terminals. I used a couple of extra wiring blocks to route all the external mains power into both the bulbs and the power adapter, through the one remaining switch. This gives the whole unit a master power on/off switch if I need it. You could leave the switch in place and wire it up to one of the free Arduino IO pins if you like. It would make a handy mode switcher or something.
All lit up
The one last thing to do was to Dremel a hole in the top of the front casing for the USB cable to go. The power cord drops out of a hole in the base (on the left of the picture above), but the way I’d mounted the Arduino meant that the USB socket was right against the top edge of the unit. Since the unit was going to be mounted on a wall anyway, having a cut out at the top wouldn’t be noticable by anyone, luckily for me!
So, here’s the final unit put back together again, with one of the lamps on. You can see both cables (power and USB) can be routed out of the top of the unit, buy running the power cable underneath it.
That’s a brief summary of my weeks work then. As I said, there were problems with the Ethernet Shield that caused me to waste a days programming, but it wasn’t so bad really. Apart from that though, I’m well pleased with the results. The lights are now mounted on a wall in our office, and I’m going to elaborate on the code and the problems in more details soon, I just wanted to get all my pictures onto the blog and uploaded as soon as I could. I’ll probably update this post with links to the high res images soon too.
Well, my hope is that I can get our whole office engaged in the work us programmers do as part of the development process for our games.
I am making a network connected indicator light for the continuous integration build process that I’m going to put our next product under.
Some time ago, I was inspired by an article I read about using lava lamps as success/failure indicators for an automated build process. An automated build process has a host of benefits in it’s own right. Those benefits are further realised when the relevent people know immediately when a build has completed, where to get it and what’s in it that’s new. The first part then to make everyone aware when builds are ready, and a whopping great big green light stuck to a prominent wall in the office should do the trick.
I originally planned just to attach the lights using the Arduino USB port to the build machine. Then I looked into the Ethernet Shield, available as a simple plug on module, it looked so simple to get working that I couldn’t resist it! There’s much more flexibility in terms of programmatic access and physical positioning if the lights aren’t tied to a host with a USB cable. You can go Wi-Fi with the Arduino (you can even go Bluetooth or GSM if you like) but that was a little costlier, and who needs Wi-Fi in an office with Ethernet ports all over the place!
Obviously there’s a bunch of components to solder together, tutorials to follow, embedded code to learn and some assembly with extreme care, the traffic light has 3 bulbs run directly from the UK 240Volt mains!
Everything I ordered for the project is working well so far, and I have a small breadboard with LEDs on wired up like a traffic light and the Arduino board is turning them on and off. I’ll post more as I carry on!
It’s finally out… The game I and others at FinBlade have been working on for the last 7 months is available to buy on the iTunes App Store, just in time for the new series of Deadliest Catch too. Of course, 7 months doesn’t just get you an iPhone game, there’s Android, J2ME, BREW, Blackberry and others coming.
I’ve been so busy at work over the last couple of months I’ve not managed any postings to this blog, as you can of course see from the sorry state of the updates. My logs show that people are actually looking at this site, and the numbers have remained small but steady, so I will be continuing postings as I can.
I have a week off work at this very moment with an interesting project I’m actually excited to be doing, so I shall be posting updates on that as I go. There are also plenty of things still to write about on my list, so with some nice weather finally here, maybe I can get a bit of posting momentum going again.
According to site stats, my Sky Diver article is one of the popular ones so far, and in particular, people seem to hit it after searching for Liang-Barsky clipping. Since I’ve not had any comments or contacts relating to the code I posted, I don’t know if it’s what people are expecting or not. However, I do know that it’s not immediately usable without some thought, and I’ve wanted to provide a complete example for a while.
So, here it is. I’ve taken the Liang-Barsky polygon clip code I posted, and worked it into an example Java Applet, which you can hopefully see below if you have Java enabled in your browser. The code has only been changed to remove it’s fixed point nature (no more ‘<< 8′ to confuse things), and I’ve added a framework around it that calls the clip method, so you can hopefully see what’s going on.
I’ve not written up a complete tutorial on how the clipping works, like I said before, for that you need to read Computer Graphics, Principles and Practice by Foley, Van Dam, et. al. or search the internet for tutorials like this good one at Skytopia.
Here’s the applet for you to play with. Click on the image below to load and start it, then use the arrow keys to adjust the clip boundaries.
Note that I’ve used a little bit of Javascript to start the applet with a click on the image so that the full Java environment isn’t loaded every time this post is shown. You need Java and Javascript enabled for it all to work.
Finally, here’s the last of the embedded Nokia Series 40 “Games I’ve Coded”, Adventure Race (AR).
Originally available on the Nokia 5140i, a beefed up successor to the 5100 that came with Sky Diver. The 5140i was one of the newer breed of Series 40 2nd Edition devices, which included increased heap memory (up from 200k to 500k), bigger jar file size limits (up from 64k to 128k) and the MIDP 2.0 specification programming interfaces. It still had a 128×128 pixel display with a pretty slow refresh, but we’d gotten used to that by now!
The device was aimed at outdoor type people, with a splash proof case, digital compass, thermometer and built in flash-light. Nokia at the time were sponsoring and entering teams into Adventure Sports events, and wanted a game on their ‘sporty’ device to reflect this, so we (Iomo) proposed Adventure Race, and it was my job to code it. From the outset, with the extra memory to fill, the scope of AR was bigger than my previous games, and this was the first one that I was going to code completely from scratch. Almost none of the game’s ideas had been prototyped by someone else first, or coded for other devices, so this was my first completely ‘solo’ programming project.
The game concept involved bringing together 3 sports, cycling, running and kayaking, into ‘iron man’ like events, with some orienteering thrown in for good measure. I’ll write about each sport game here including any coding high (and low) points that I can remember. But first, here’s a video…
There’s another video at the end of the post if you’d like to see some more
Cycling
The cycling game was based around rhythmic button presses to move the bike forward (pedalling), with interspersed downhill sections (free-wheeling) where the player was required to move left and right, or in and out of the screen, avoiding obstacles. At the bottom of the hills the action back to the rhythmic pedalling again. The correct rhythm was key to moving along at a decent pace, and avoiding obstacles so as to not crash got you the best time for the section.
The interesting bit of code that came out of this game was the algorithm to generate a terrain to cycle along, with hills and flats. I found details on the net for midpoint displacement, and it was so simple, and exactly what I wanted for a 2D terrain that coding it was a no brainer. The concept is simple:
Take a straight horizontal line.
Find the mid point, then displace that point vertically by a random amount.
Then repeat for the two new line segments, and so on.
By varying the ranges of the random numbers, and the number of times you repeat the iteration, you end up with very realistic looking mountain ridge lines, it’s awesome. Here’s the code I ended up with:
course_line_segments = 1;
course_map = new int[4];
course_map[course_map_x1] = 0;
course_map[course_map_h1] = 0;
course_map[course_map_x2] = (256<<8);
course_map[course_map_h2] = 0;
int roughness = 32; // Should be between 0 and 128
int iterations = 4; // 4 gives a good value
int displace = 32768; // +/-
for(i = 0; i < iterations; i++) {
new_course_map = new int[course_line_segments << 3]; // (course_line_segments*2) * 4
// for each course line segment, we output 2 new segments
for(int j = 0; j < course_line_segments; j++) {
int x1 = course_map[(j<<2)+course_map_x1];
int h1 = course_map[(j<<2)+course_map_h1];
int x2 = course_map[(j<<2)+course_map_x2];
int h2 = course_map[(j<<2)+course_map_h2];
// first new segment
new_course_map[(j<<3)+course_map_x1] = x1;
new_course_map[(j<<3)+course_map_h1] = h1;
new_course_map[(j<<3)+course_map_x2] = x1 + ((x2-x1)>>1);
int rn = random(displace);
int mid_height = (h2>h1?h2-h1:h1-h2)>>1;
new_course_map[(j<<3)+course_map_h2] = mid_height + (rn - (displace>>1));
// second new segment
new_course_map[4+(j<<3)+course_map_x1] = new_course_map[(j<<3)+course_map_x2];
new_course_map[4+(j<<3)+course_map_h1] = new_course_map[(j<<3)+course_map_h2];
new_course_map[4+(j<<3)+course_map_x2] = x2;
new_course_map[4+(j<<3)+course_map_h2] = h2;
}
course_map = new_course_map;
new_course_map = null;
course_line_segments <<= 1;
displace = (displace*(roughness+128))>>8;
}
I’ve created a simple demo using this code and packaged it up into a Java class that just displays a window on the screen 128×128 pixels in size, and continuously creates new displacement ridge lines. It looks a bit like an audio monitor or something! Change the iterations to 8 and you get something even more like the output from a speech synthesizer.
Drawing the terrain in the game turned out to be pretty easy too. After scaling the data to something appropriate (smoothing out steep slopes, that sort of thing), simply draw a rectangle on the right hand side of the screen, shift the screen buffer left by the width of the rectangle, then draw another one a bit taller or shorter, depending upon the current slope. This approach is very easy to tune for performance too. By drawing larger rectangles, you need fewer of them (which means drawing a screen is faster), however the trade off is that the terrain looks blockier. If you look at the screenshot below, you can see all the rectangles for a screen coloured differently. The best speed/visual trade off turned out to be about 24 rectangles or so by the looks of things.
Running
Having sorted out the terrain for the cycling game, reusing it for the running was the obvious thing to do. Rather than duplicate the rhythm mechanic though, we decided to go with a more resource management approach. The runner has energy that gets used up the faster he runs, and the faster he runs uphill, running downhill uses less energy. You directly control the speed of the runner, and have to manage his energy so he gets to the finish line in the best time. Obviously sprinting flat out isn’t going to work because he’ll quickly get tired and slowly jog along knackered! Since the running mechanic doesn’t involve constantly pressing keys, we reused the left/right dodge oncoming objects idea from the cycling game and made it a core part of the running, so the player can’t just sit back and watch. There are also sprint sections where other runners come up and attempt to overtake you, and you must button bash to keep ahead of them. For fairness, the sprint sections work independently of the energy levels, and there are also energy drinks you can collect on the way.
From the code point of view, there is lots of reuse between the cycling and running games. The colour palettes are changed, and the control schemes differ, but due to both games using the same core, the game specific bits are quite small. Even combined, they are still smaller than the kayaking game!
Kayaking
The 3rd game in the sequence was a top down, vertically scrolling kayak game. I’m pretty sure that this was the 3rd game I implemented too, sorting out the running and cycling first with their similar code, then moving onto the more involved kayaking. I say more involved because there turned out to be several elements to this game that were (at the time) new to me and things I’d not done before.
As you might be able to see from the screenshot (and the earlier video), this game needed the following major elements:
Collision detection for both the water obstacles and the river bank edges.
A procedurally generated river bank.
A large number of animated sprites.
Collision Detection
The front of the kayak sprite is pointed, and as it’s moving down the river, simple bounding rectangle collision didn’t look all that great. It was frustrating to get stuck on objects when the point of the kayak was clearly free. I ended up creating a pixel perfect collision system based on pre-generated bit masks for all the sprites. Using bit masks, and performing shifts and logical & operations after two sprites had failed a bounding rectangle collision test worked very well. All I had to do was write a simple tool that took a sprite PNG file and generated mask bytes for each pixel row based on the non-transparent pixels. Skimming edges of the river and the rocks felt nice after that.
Spline Curve River Bank
The best way to generate the river bank turned out to be using two natural cubic spline curves (one for each bank). By generating the curve in sections as the river scrolled up the screen, only a few calculations needed to be performed each frame to keep things moving along. Obviously the first screen had to all generated before display, but that was done during the loading phase. To get the graduated blue to yellow effect, I simple scaled the x value of the spline calculation, so getting a decent looking ‘shallows’ effect.
I was really proud of that spline curve shoreline. It’s segmented calculation and subsequent rendering using only (fast) horizontal lines worked really well. I’d like to post some of the spline code, but it’s quite awkward to understand with all the fixed point maths, and the specialised segmented calculations. If I get any requests to see it, and I can be bothered to tidy it into something I’d be prepared to post (like the midpoint displacement example above) then I might do it!
Animated Sprites
The kayak sprite itself has 52 frames of animation, the wake 24, rolling log 16 (+16 for it’s water splash), 6 frames for the weir, 9 leaping fish frames 15 different rock frames and an 8 frame finish line flag animation. Not only is that a lot of pixels for one quarter of a 4 game pack that needs to fit into a 128k jar file, but that’s a lot of runtime heap when you needs 2 bytes per pixel. Here is the kayak sprite animation the artist created:
It’s only pointing one direction since the Nokia UI was used to draw the sprite horizontally flipped when moving to the right.
I ended up compressing the sprites into a palettised format that squashed 3 or 4 pixels into a byte depending upon the number if colours in the image, then RLE compressing this data. Then, rather than loading the data into individual pixel buffers for each sprite, which would take up 2 * width * height bytes for each sprite, I actually decompressed each sprite frame into a single small buffer as it needed drawing, each render cycle. Because the actual number of operations to decode a sprite wasn’t huge, and there weren’t very large numbers of sprites on the screen at any one time, the 5140i coped perfectly well. This technique saved loads of heap memory and I allowed for a really richly animated game in total, not just for the kayaking section.
Orienteering
Finally, the ‘filler’ section was a bit of orienteering. This involved seeing a sort of first person view from a position on a map, and you had to guess where you were. The concept had already been done by iomo as a WAP game, and I found a screen grab!
The code for this was a simple perspective projection of a 2D bitmap I borrowed from one of the other programmers at iomo. Since this was done last, it ended up being a bit squeezed for development time and only 4 maps were included in the end, with some rotation for variation. Still, it was a nice enough short diversion in between the other fairly long and involved sections of the game.
Finally
Whilst looking over the bits of my old project (remember this dates back to around mid 2003) I also happened upon probably the most reused bit of code I’ve ever wrote. The ending sequence for AR was a podium animation with the player getting 1st, 2st or 3rd, and a failure screen where they were weeping for their loss. In the background of the podium animation I added some simple particle fireworks, which you can see in this video:
That small particle routine has been reused in a considerable number of my games since then, and it’s still included in my very latest project, that’s being coded this minute. Having also showed it to Mike Tucker, another iomo original programmer and all round awesome guy, he reused it all over the place too. I wouldn’t be surprised if the same code is the basis for the particles you see in the very latest Flash stuff Mike does!
Finally finally, thanks for reading this far and as a treat here’s my original programmer art splash screen. Much better than the professional artist created one if you ask me