Article interruption

Friday, August 28, 2009

I know I've been publishing an article every Tuesday and Friday since I started this blog, but there's been a death in the family, so I've been a bit preoccupied. I'll try to get a new article out soon, probably related to that particular situation.

SpaceRat - an exercise in game programming

Tuesday, August 25, 2009

Almost entirely throughout my life, I’ve had access to computers. In most of that time I’ve wanted to write computer games. Most of my attempts have been aborted early on, before even getting code written. Stacks and stacks of paper have been used to sketch characters and scenery. One day in 2001 I decided to put together a small Space Invaders-like game named SpaceRat.

SpaceRat began as a set of graphics I had created for a friend’s clone of Space Invaders. I had drawn a “hero” space ship and some enemy ships. There were a number of enemy sprites that I did not use in SpaceRat, simple because they did not fit the look I was going for.

Starting off with pre-made graphics gave me the push I needed and gave me the opportunity to jump straight into programming the game. I was still in university, but was then employed in a co-operative education placement for discreet, a division of AutoDesk. Health problems prevented me from actually working at the time, and so to judge my ability to return to work, I decided that writing a game would be a good gauge.

Since I had been working at co-operative placements for my third year, and been a programmer before I had even entered university, I was able to develop a certain affinity for object-oriented design and clean code. It was with that premise that I set down the basic classes for the game’s mechanics. While the view and model aspects are not entirely factored out, the size of the codebase made that sort of thing overkill.

The game mechanics were simple from the start; rectangular bounding boxes for collision detection and a very simple physical simulation. You could say that it’s a trivial game engine, and you’d be right. I kept it simple so that I could concentrate on getting the entire project completed. While there is definitely room for expansion, with many tasks sitting in a TODO file, the basic engine is complete.

My favourite part of the completed project has always been the star field in the background. Many games with one simply scroll a static set of uniformly-sized stars at a set speed. I was never happy with that, and so I went for stars that varied in size, colour and speed. The result was a star field that gave a sense of depth and realism that just isn’t possible with a bunch of single-pixel stars all moving at the same speed. When I rewrote the engine to support Quartz, Apple’s Mac OS X 2D drawing API, the star field was able to take on an even better look.

I had originally written the code in Mac OS 9 using Carbon-compliant APIs. At the time I was using Metrowerks CodeWarrior, as it was the IDE I was most comfortable with. While the application worked natively under Mac OS X, there was no chance of porting it to x86 without a change of IDE and modifying the API used to draw the graphics and play sound.

The first hurdle I chose to jump was the XCode transition. This was pretty painless, since I had not used any Mac OS 9 specific APIs. The application would no longer be compatible with Mac OS 9, however, but this didn’t bother me at all. I was no longer using Mac OS 9, and many people were already making the move to Mac OS X.

The next step was to modernize the graphics. I had been using QuickDraw, Apple’s venerable drawing API. This was one of the APIs Apple was quick to drop in the move to x86, as it would have been quite difficult to port to a new architecture and didn’t support the modern features Quartz does. Given my simple rendering methods, it was almost trivial. I just had to flip the coordinate system and deal with the sprites as images files rather than icon resources. It also gave me the impetus to move from an integer based physics model to a floating point model. This allowed for smoother movement and smaller velocities than I had started with. The star field improved tremendously with that change alone.

The Quartz transition was good practice for me and gave me insight into Mac OS X’s graphics model. It’s a massive improvement over QuickDraw, which had still been based on a pixel-level resolution and didn’t support anti-aliasing.

One massive sticking point which has blocked me from making the complete x86 transition is my use of Apple’s Sound Manager. It too was dropped in the x86 Carbon transition, and I never took the time to find a fully suitable replacement. In any case, my sound engine had always been sub-par. When I do get around to making the change I’ll probably add 3D sound to give a more immersive experience.

The actual game is fun to play, but after the first level the levels repeat with no sense of real progress. There’s no high-score system, no real level structure and only one type of enemy. Definitely an area that’s seriously lacking panache. I’ve been lazy here, since my original goal had been reached ages ago. There’s certainly room for improvement, but I had never created graphics for new characters beyond what I already had when I started.

While the game itself is not all that fun to play, it does provide some entertainment value. It was certainly an excellent project for learning, and might be of use to someone out there to see how to make a simple game. I have left some of the QuickDraw code in the project, for comparison to the Quartz rendering methods. One good example is SRCgImageSprite versus SRIconSprite.

I can always hope someone will find the code useful, and perhaps the game a little fun. With luck, someone else will come along and fill in the gaps. I’m making the latest code available under the BSD license, so feel free to make modifications.


Friday, August 21, 2009

It seems comments weren't working, so I've fixed it. I think my template messes the embedded comment box.

The Sky

When you’re far away from the city lights, the clear night sky is a beautiful thing. The constellations shine brightly, the Milky Way stands out clearly, and the Moon can provide all the light you need to see by.

Living out here, I’ve had a chance to see wonderful things in the sky. Recently, the Perseid meteor shower provided my wife and I with a romantic bit of evening, with beautiful, astral accompaniment. We saw some spectacular meteors fall that night, and it was a welcome change from the cloudy night we had had previously.

In the winter, on a snow-covered night, with the full Moon out, the snow sparkles beautifully and you can see almost as well as during the day. The silence is stirring and inspirational, and you can stand there in your winter gear, relaxed and at peace, almost losing track of time completely.

To facilitate my Moon viewing, I wrote a small program called MoonPhase. You can find it where I keep many of my little projects at my main website. It shows the current phase of the Moon and lets you check out what the other phases look like.

One of my favourite pieces of astronomy software is Stellarium. Once you figure out the interface and set in your latitude and longitude you can see a view of the sky from your current location and time. Controls are provided to speed up the time of the display so that you can see what the sky will look like later on in the night. It helped me locate the Perseids this year and had me pointed in the right direction.

Cultures around the ages have looked to the stars and seen animals, people or tools in the patterns formed there. The names and exact shapes of these constellations vary, of course, but the human ability to make patterns lies at the centre of our creative ability to find a pattern and give it a life beyond its objective reality.

My father is an amateur astronomer and has a great telescope that he purchased with his retirement gifts. He’s a member of an amateur astronomy club (text in French, club meetings in French) in the Montérégie area of Quebec. The club has regular meetings where members give presentations on astronomical topics of interest. If you’re interested in joining one, there just might be one in your area listed here.

The night sky has many beautiful sights for the appreciative individual. When you next leave the city lights at night, look up and see if you can’t pick out a constellation or two. You can always make up your own; that’s how they first got their names!

KnitPicker - a knitting stitch counter programming project

Tuesday, August 18, 2009

The art of knitting lace is an intricate process; it takes great skill with knitting and the ability to keep track of complex knitting instructions. One day, my wife Sophie was knitting a particularly complex pattern, and she complained about not being able to keep track of how many stitches she should have for a particular row or how many should be left in the next row. Enter the programmer!

I’ve been throwing together little utilities for myself for ages. Sometimes I want to calculate some value that would take too long by hand; sometimes I want to sort a list in some particular way. Other times I have trouble deciding what to have for dinner, so I’ll write up a list of options and then pop in a random number to pick from it. I have one such script from ages ago that I used regularly when living in Montreal.

It was clear to me that Sophie needed software to handle her problem. With instructions spanning up to a hundred stitches, it’s the sort of thing that’s hard to keep track of in your head, and would take quite a bit of paper to work out by hand. Computers are great at keeping track of numbers and even better at doing arithmetic.

Knitting instructions use a very simple notation: k1 means “knit one stitch,” psso means “pass slipped stitch over,” and so on. These simple steps are listed in sequence to form a row of knitting, and this is the sort of thing a computer is great at processing. The kind of software that does this sort of processing is called a parser. A parser takes a string of characters and breaks it up into individual components called tokens.

I’m not a great parser writer, but I knew of a handy bit of software called Lex. It can analyze different pieces of each token and easily extract numerical information. This made it the right tool for the job, and its ease of use was an added bonus.

I wrote up a quick bit of Lex code, threw together a quick UI with Apple’s Interface Builder, and made the text field update its book-keeping every time the user typed in a new character. This made for a live-updating stitch counter that a lace knitter could use as they worked their way through a pattern. And so KnitPicker was born.

There are some limitations to the software at the moment, such as the lack of support for patterns that contain instructions on repeating a particular section. I had planned to eventually add such support, but never got around to it. Sophie had stopped knitting lace due to problems with carpal tunnel syndrome, no one else was using the software and I had other things to concentrate on.

Had there been other users demanding such a feature, no doubt it would have been added. I did take some time to research the problem, and I’m confident it would not be a big deal.

You can find KnitPicker at my main website, along with other things I’ve thrown together. All in all it was a good learning experience, and for a short while provided Sophie with a useful tool. It’s fun when you can meld your partner’s interests with your own and work out something productive.

Interactive Fiction - Finding the Mouse

Friday, August 14, 2009

For as long as I’ve been using computers I’ve known of text adventures. Using your imagination and the words on the screen, you construct a world in your mind and then interact with it through the computer by typing in commands. The goal is usually to solve different puzzles in order to come to some sort of winning scenario.

Nowadays text adventures have given way to interactive fiction, or IF. Much like text adventures, there is often a goal to reach. However, some can be entirely freeform and offer the reader a variety of scenery and possibilities to explore. They still stick to text as their means of communication and rely on the reader to imagine the scenery. There’s still usually some sort of puzzle to solve, and this can provide a lot of fun for some.

The interactive fiction community is still going strong. There are plenty of archives out there for the curious reader to explore; the most prominent being the IF Archive. There’s a newsgroup at (Google Groups link) that’s still quite active. New tools for building IF works have been developed recently that can interpret a designer’s plan in descriptions close to natural language.

I’ve experimented with writing these sorts of adventures for a long time. Early on in my programming experiences I tried to write one in BASIC. The limitations of the platform I was using slowed me down, and my relative green-ness and lack of community to rely on caused me to give it up.

A few years ago I heard about a 1-2K text adventure challenge. The idea was to write a text adventure and its interpreter in 1-2K of executable code and data. I never got around to submitting my entry, as I still had some issues in compressing the text into a small enough space to allow for some code to actually run the adventure. Recently I decided to resurrect that little adventure and develop it with Inform 7.

It took a bit of work to get the adventure to work just right using the features available in Inform. It’s certainly no longer anywhere near as small 2K, given the rich set of commands that Inform gives each and every IF work it produces. These commands allow for more leeway for the player to express their actions.

If you’d like to play my adventure, you can find a Java applet to play it here. If you have a z-code interpreter already, you can download the adventure itself. The basic premise is to find your computer’s mouse so that you can surf the web. The optimal solution can be done with six turns, so the adventure shouldn’t take you too long once you figure out what to do.

I’m going to be updating it from time to time to polish it up, so if you tried it and it was a bit rough, maybe give it another chance later on. The web page makes the story’s modification date available, so you can see when I last updated it.

The news group community has been really great in helping me out with it, and I’d like to thank them here for their support. Guys, thank you so much!

The world of interactive fiction has grown since the days of the earliest text adventures. A certain maturity has given newer titles more depth and flavour, and new possibilities with recent development tools have given writers more time to spend on the story, rather than on the mechanics of dealing with the interpreter. It’s an interesting field, and well worth looking into for anyone who enjoys reading.

Canadian Medicare and #welovethenhs

Health care, of all the services available, is almost certainly the most important one many of us will ever make use of. Without adequate health, our performance degrades at work, our enjoyment of life decreases and some of our routine responsibilities become uphill struggles. And yet, in some nations not everyone has affordable access to it.

In Canada, we have tax-funded, universally accessible health care under the label Medicare. Tommy Douglas, a former premier of Saskatchewan, fought hard with the Federal government of his time to develop Medicare. For his efforts Canadians voted him the Greatest Canadian in 2004 through a CBC-run television series.

Another prominent Canadian involved with supporting the creation of a system of socialized medicine was Norman Bethune. He went to China during the Japanese invasion in 1938 and acted as a battlefield surgeon, bringing anti-septic practices to Chinese medicine, a system of training doctors and nurses, and treated both Chinese and Japanese casualties.

As someone with an occasionally debilitating illness, I would be potentially homeless without Medicare. When I had to leave my job to recover from one severe bout, and left without any sort of income, I would have been bankrupt if I had had to pay for my medical treatment. It was only through Medicare, and Quebec’s tax-funded prescription drug insurance, that I was able to manage the recovery I did. In subsequent bouts, where I did have an income, it still came to my aid to keep me from losing my already reduced income.

With my mother currently battling cancer, I can only imagine the costs to our family if Medicare were not around. Her treatments happen regularly, her initial diagnosis took place in a timely fashion, and I’m satisfied that the oncologist and nurses are doing their best for her.

I think it’s clear that I am a big proponent of Medicare. There are other Canadians, however, who oppose it and believe it should be reduced in scope and replaced with private options. Chief among them is the Fraser Institute, who recently released an article pointing out weaknesses in Medicare.

While there are indeed weaknesses in Medicare, one has to consider the source of this griping. The Fraser Institute is a “free-”market think-tank, that is generally against government spending in favour of private options. That’s certainly a view point that has some, if dubious, merit. Generally those advocating such policies have the money to fund or use more expensive private alternatives to currently public services. In fact, the Fraser Institute’s contributors include a long list of wealthy individuals looking to dismantle Canada’s public services. Hardly freedom for those without the means to exploit the “free-”market.

So what does “free-”market economics bring us? The recent economic crisis, for one. It allows those with means to expand their portfolios, owing to the fact that no one is looking over their shoulders. It entails a transfer of wealth from those willing to spend theirs to those who tend to fund their own interests through organizations like the Fraser Institute and those corporate bodies that fund such organizations.

Generally, people living in countries with socialized medicine are quite attached to that service, and are willing to defend it vehemently. Graham Linehan, creator of the hit show IT Crowd, recently started a campaign on Twitter to allow fellow residents of the UK to speak out about how much they love the British, tax-funded health care system. By using the tag #welovethenhs, British Twitter members can post their views for the world to see. To give an example of its popularity, after loading the page for the tag I waited a couple of seconds. In that time, the tweets using the tag increased in number by 22. Another few seconds and a further 31 tweets appeared.

When interviewed by Channel 4 about the Twitter campaign, Graham Linehan spoke out against the current movement in the United States opposing socialized medicine. His aim is to “provide ammunition for those people who are fighting back against the scare stories in America.”

In fact, some Brits who have been featured in such scare tactics have spoken out against their stories being used out of context. They were asked to comment on their health-care experiences, being told it was for a documentary. The footage was then used in scare ads funded by opponents of President Obama’s health-care plan. While these women had some rough experiences with the NHS in the UK, both later said that they are fully supportive of their country’s socialized medicine. One felt as if she had had her naivety tested by this experience with American political media.

When I graduated from my government-subsidised university program I was quite well paid for a recent graduate. While I was contributing quite a bit to the government in the form of taxes, and I think they could have been lower by reducing government waste, this didn’t bother me all that much. Why? I want others to have the chance to benefit from affordable post-secondary education. I want others who are less fortunate than I was not to have to worry about whether they can afford health care if they get sick. Many university graduates do not get hired, and even those that do are often not paid well, in jobs that do not do their degrees justice. By reducing their burden, I free up their hard earned money to possibly find its way back to me in the form of software development contracts, or by supporting local businesses so that they can bring me goods and services at a lower cost.

Piet - an esoteric programming language

Tuesday, August 11, 2009

There’s a certain group of programmers out there that like to come up with programming languages just for the fun of it. Some of them have profanity as their names, and some are based on internet memes. Whatever the case may be, some individual out there enjoyed thinking up the language, and many of these languages are actually useable.

One esoteric language that stands out, for me, at least, is Piet, created by David Morgan-Mar. Based on the idea of making programs that look like abstract art, Piet allows the programmer to express their software in the form of coloured blocks. Numbers are represented by blocks of pixels containing a pixel count equal to the number itself. Operations are performed by changes in hue or darkness.

As an example, here is a Piet program I wrote to output the string “Hello World”. This image is in fact the entirety of the program, and can be run in any of the Piet interpreters out there. Other examples of Hello World programs are available on David’s site, as well as some other programs cooked up by Piet enthusiasts.

One property of a programming language is that it can be Turing-complete. What this means is: can the programming language be used to solve any arbitrary computing problem? In fact, extra kudos go to those esoteric programming language creators who create one that is Turing-complete.

It is believed that Piet is Turing-complete, but as of yet no one has stepped forward to implement a program to test this. However, given a stack of unlimited size, a reasonable interpreter for the language Brainf*ck could be implemented. Brainf*ck itself has been proven to be Turing-complete, and since Turing-completeness is transitive, a programming language that can interpret a Turing-complete language can be said to be Turing-complete as well.

Piet can be used to produce some functional, beautiful pieces of software, and it definitely piqued my curiosity when I first found out about it. Maybe you’ll find it interesting too, maybe you’ll write something in it, maybe you’ll join the discussion forum. Whatever the case may be, it’s one language that definitely has something special going for it.

Aldebaran Colony

Saturday, August 8, 2009

This is a quick little story I whipped together one day as a writing exercise. That's mainly the sort of stories I'll be putting up; 1000 word vignettes that I wrote during a day. Here it is:

Why they had thought they needed a podiatrist on the colonization team was something Harry Jones couldn’t figure out. He wasn’t even one of the best podiatrists, although he had his moments. It wasn’t as if he wasn’t happy to be along. He was, in fact, overjoyed when he was given the news. It had just come as a bit of a surprise to him that he had been selected to join the ten thousand other people on the colony ship bound for Aldebaran 5.

The ship had been equipped with a new Petrescu-drive engine, which would allow them to cross the distance between earth and the Aldebaran system in about 15 seconds. There had been some hushed conversations between the scientists setting up the engines, but Harry was confident that the colonists’ best interests were being kept in mind. After all, it was the first colonization trip outside of the solar system, and no one wanted a bad precedent set. Even when the scientists made sure to rush off the ship before the flight, Harry took no notice.

Loading up the ship hadn’t been much on Harry’s mind either. The loading had to take place in orbit, and the colonists would only be sent up once the entire ship had been packed. There was a special crew for loading all the belongings that had been sent up previously on an unmanned rocket. The colonists had each been allowed to bring along whatever personal effects they wanted. Given that the Petrescu engine operated on principles that weren’t affected by mass, it had been decided that restricting what the colonists could bring on board was simply more trouble than it was worth.

It wasn’t long after Harry had sent up his entire collection of 20th century science fiction novels that the call to fly up to the ship came. The colonists were being ferried up into lunar orbit by economy class earth-moon shuttles that had been repossessed by the bank that was funding the colonization trip. The shuttles were in bad repair, but Harry felt they did the job well, and that was all that counted. Sure, the trip out to the ship was a little bumpy, but the cabin never depressurized once, and so Harry was happy. It was actually Harry’s first trip into space, and he was excited enough that the bumps just reminded him of a roller coaster he had been on a few years earlier.

The colony ship itself was massive, and Harry was certain he was going to get lost. However, there were helpful terminals all around the ship that seemed quite happy to do Harry’s getting lost for him. Wherever they sent him, though, Harry found he always ended up somewhere he needed to be. The one place they seemed to get him to reliably was his quarters. An attached washroom was the only one he knew of on the ship, although he figured the other colonists had their own.

It wasn’t long after all non-colony personnel had scurried off the ship that the imminent Petrescu insertion was announced over the ship’s loud speakers. Harry had had to ask someone else to repeat the announcement, though, since the speakers seemed to emit a lot of noise that clearly wasn’t speech. However, the helpful terminals had the full text of the announcement, along with some useful facts about the Petrescu engine’s operation. Mentioned among the side-effects on humans was the fact that the insertion was rather unpleasantly like being drunk. Harry seemed to be the only one who caught the reference, and was certainly the only one who laughed at it.

When the designated time arrived, Harry was fully prepared to experience what a glass of water must feel like. Unfortunately, he was knocked the ground by a lurch as the engine engaged, and was knocked unconscious for the duration of the insertion. When he came to, he was disappointed to find that he had missed it. He was also surprised to find out that the pilots were incredibly surprised that they had made it through alive. When he asked one of them why they were so surprised, he was informed that the Petrescu engine had a 50-50 chance of killing everyone on board. The entire flight crew had been selected from criminals awaiting execution for thought crimes, and they had figured that at least, if the engines had killed them, it would have been a faster death than the ones they faced back on earth.

It took only a few hours after that to get into orbit around Aldebaran 5. The plan was for the ship to slowly lower itself through the atmosphere and then finally land on firm ground and proceed to fall apart. Harry was informed that this falling apart would be fine, that the colony ship was, in fact, simply going to become their new city. The ship had been in many pieces in the first place, so Harry wasn’t too concerned about it. Certainly the bank had taken every possible failure point into account.

The landing passed by rather uneventfully, and Harry was pleasantly surprised by how slow and relaxed the ship seemed to fall apart. He was in his own quarters at the time, and as the ship fell apart, he noticed that a new door had opened off his living room that led into what was obviously his new office. It seemed that someone had taken the time to move his equipment from his office on earth into this one. Even his over-sized, cartoon-style model of the human foot was there, and Harry was happy someone had actually remembered it, even though he had completely forgotten about those details himself.

As it turned out, a podiatrist was exactly the person who had needed to be included in the colony. In the first hour alone fifteen people had come to him complaining of foot injuries caused by the local terrain. A person could be walking along what seemed to be flat ground, when suddenly a short spike would shoot out of the ground through the person’s footwear. The spikes were apparently part of an underground plant that responded to vibrations from the surface. Luckily someone had thought to pack a lot of bandages into Harry’s equipment store.

However, it was with great disappointment that Harry discovered that someone had neglected to pack food for any extended period of time. A nutritionist who had also been recruited for the colony was teamed up with a botanist and a toxicologist to examine the local flora and fauna to see if there wasn’t anything native to eat. As it turned out, the underground plant was a perfect source of nutrition, and so the members of the colony proceeded to dig up as much of it as they could.

On the second week of their new colony, Harry began to feel rather ill. Using his diagnostic equipment, he planned to take a quick scan of his abdomen to see if there was anything visibly wrong in his gut. As he turned the scanner on, a short spike drove itself out his stomach and into the scanner’s receiver. It seemed that the plant was not, in fact, any good to eat.

The Buddhabrot

Friday, August 7, 2009

Ever since I got my first glimpse of computer-generated fractals, I was hooked. The Julia and Mandelbrot sets captured my imagination, and I knew I had to make my own generator. At the time all I felt comfortable programming was a TRS-80 Colour Computer 3, and I had a shaky knowledge of the complex numbers needed to calculate such fractals. My first attempts failed to properly render the Mandelbrot set, since I had not realized the need for an extra step.

When I finally got comfortable with C, I wrote another Mandelbrot generator. You can find it at the bottom of this page. It requires a pre-Mac OS X PowerPC Mac, but has some nifty optimizations I was quite proud of at the time. However, unlike some Mandelbrot generators of the time, the optimizations still just got pixels onto the screen faster, and eschewed any larger-scale optimizations. Other programmers had used techniques such as outlining boxes in the fractal, then filling them in with the colour of the border. This made calculating the fractal itself faster, but had some room for error.

When I discovered that someone had developed a new take on the Mandelbrot set, I got excited. Despite the religious connotations, I find the Buddhabrot quite aesthetically pleasing. It has a sort of ghostly appearance that appeals to my sometimes morbid bent.

How the Buddhabrot differs from the traditional Mandelbrot rendering method is that it tallies counts of how many times an iteration of the basic formula passes through a particular location. When scaled into a 256 grayscale image, the somewhat random looking points begin to take on a Mandelbrot-like image that some have likened to images of Buddha.

With a little work, the Buddhabrot can be extended into 4 dimensions. It creates what the original developer calls a Buddhabrot Hologram, or Buddhagram. You can rotate the image such that it appears to be a 3-dimensional object, and manipulating the 4th dimension allows for some further animation.

Always interested in programming my own fractal generators, I put together a version of a Buddhabrot program myself. It requires Mac OS X (not sure what minimum version, probably 10.4 or 10.5), and there are no optimizations whatsoever in it. The “Hog” control determines how much processor time the generating process will take. The settings drawer allows you to control the various parameters of the process, such as maximum iterations before each starting point’s iterations are cut off. You can also change which plane of the Buddhagram is calculated, and drag the image to other applications.

Have fun with it, I had fun making it. If you’re interested in the source code, just send me an email. If there’s enough demand, I’ll post it up here in an update.

The Idea Oubliette

A lot of thoughts pass through my mind in any given week. Some of them drive me to research a particular subject, others get me started on a project. But I have more ideas than I can use myself, and so some of them I'll take a look into and post them up here. Sometimes I just want to try something out, and I'll post my attempts up here.

Every month or so I'll also post a short story. These will be about 1000 words, and usually science fiction. I occasionally get a hankering to write horror, so maybe there'll be some of those as well.

The Idea Oubliette - Templates para novo blogger