The Shoulders of Giants: LensManagers

This is part 1 in a hopefully-ongoing series about videogame programming techniques I’ve acquired over the past several years. Broadly, it’s intended to help you solve common problems you encounter in your daily game development life. Yet rather than merely throwing a github or Asset Store link at you, my goal is to present a comprehensive programming style: how to think about the problem, why to think about it this way, and ultimately how to attack similar problems with valour and grace.

I once read a Gamasutra post describing something called ‘The Curtain Problem’. Here’s the basic idea: you must program a big Broadway-style stage curtain for the videogame you’re creating. You’ll use this curtain firstly as a loading screen: closing it whenever it’s time to unload the previous scene, then reopening it once the new scene has loaded. Yet your level designer is musing about reusing this curtain for dramatic effect at various points during the middle of gameplay. (Your antagonist, it turns out, is an underground R&B idol called ‘The Bleaknd’ who changes outfits often; it would be cool if each outfit swap caused the curtain to close and reopen around him.)

Had you brought this problem to an entry-level programming class, you’d inevitably find yourself staring at a projector slide with the following text on it:

The very first thing universities teach us about object-oriented programming is that this variety of public member access is, for some reason, sinful. Yet it’s difficult to explain to a novice programmer precisely why this is the case. In the land of C# and Unity3d, the first thing your professor would do is show you the ole’ getter & setter pattern:

It’s apparent to the student that this code snippet is functionally identical to the previous one, except that it’s many lines longer and, therefore, much harder to write correctly on the back of the handwritten exam Your professor is preparing to give you. They explain that this technique entitles you to a fresh and steamy mound of OOP shit™, which smells strongly of a thing called ‘encapsulation’ (best remember this one for your first job interview). The two of you soon arrive at something like:

This snippet, unlike the previous one, rises above complete pointlessness. It’s sort of neat that you can tell ‘Stage’ to open or close the curtain without needing to know what CurtainController is or what it’s doing. It’s sort of helpful that CurtainController is inaccessible from outside the Stage, and therefore has only one thing feeding it commands. You could probably reuse CurtainController somewhere else—perhaps as part of some other class—though you’ll probably never need to.

Inevitably, the very next problem you’ll encounter shall concern the sharing of control. What if your antagonist is frenemies with a local rap superstar (notorious, it turns out, for ‘runnin through the Styx with his ghosts’)? What if both characters need to open and close the curtain at arbitrary intervals? What if there were four characters, or six, or twenty?

Read more…

The Joy and Tragedy of Flash Programming

The phrase ‘Flash is dead!’ isn’t so much a declaration of fact as it is an expression of one’s political alignment. To discover the nature of this alignment we need only ask ourselves: if indeed Flash were dead—if, somehow, a medium for creative expression were capable of experiencing death—who would we say had killed it? Was it Steve Jobs in the hardware biz with the iPhone? Or was it the front-end web person in tech services, scheming to fix the broken relationship between HTML and CSS? Was it Google Chrome, whose commitment to ‘openness’ has predictably come to preclude any software its parent company can’t manipulate? Or was it JavaScript, that mangy nightmare of a programming language whose hunger will consume the world?

Should we rejoice in our ever-impending freedom from all of Flash’s dreadful security problems (to be replaced, one assumes, by every other platform’s dreadful security problems)? Or the tremendous memory management and performance benefits made possible by… uh… cross-compiling to JavaScript? Shall we shower ourselves in the splendour of CSS3 on Chrome, then shower ourselves in the splendour of CSS3 on Firefox, then shower ourselves in the splendour of CSS3 on IE 10.0 and up, then media query into a set of stylesheets that works on more than fifty percent of recent android phones?

As I said, it’s very much a question of politics.

What gets lost in the ideological shuffle, though, is how wonderful a programming language Flash’s ActionScript 3 is. It’s both powerful and flexible, which is nice; yet beyond that, AS3 is fun. Where Java is verbose, consistent and largely insufferable, AS3 gives you getters and setters to break up the monotony. Where C# gives you a giant kitchen sink in which to deploy any programming pattern ever conceived by humankind, AS3 lends itself to a more particular, off-beat style of code.

Most centrally, AS3 provides all “The Good Parts” of JavaScript while at every turn being worlds better than JavaScript. You of course get all the whacky closure-based nonsense you’d find in JS and any other function-y language; yet AS3 provides syntax for strongly-typed variables, permitting software devs to write honest-to-goodness APIs with coherent, half-readable method signatures! You get IDEs capable of auto-completion, tool-assisted-refactoring and reference lookups! You get the gift of sanity! Do you know what sort of creature writes software in Notepad++ with naught but some crummy syntax highlighting plugin? A WILD ANIMAL. Possibly a rabid one.

Then when it comes time to program some ambiguously-typed, data-structure-melting atrocity, it’s as simple as casting all your variables to * and hacking away the night. I must concede that kitchen-sink languages like C# present all sorts of interesting rope with which to hang yourself in these situations—generics, operator overrides, reflection, occult contracts and so on—yet I’m not certain a jungle of generics has ever proven much more comprehensible than a few AS3 dictionaries packed full of mystery meat. In neither case is anyone going to understand anything you just wrote two months from now.

Speaking of dictionaries: AS3’s dictionaries are obtuse and absurd and absolutely marvellous. For some reason you use ‘for(x in dict)’ loops to iterate through keys but ‘foreach(x in dict)’ loops to iterate through values. Anything can be a key, and anything can be a value; strict typing is not permitted, so the language almost begs you to do something cool/weird. Astonishingly, dictionaries can use weak-referenced keys! In fact, any AS3 event dispatcher can use weak-referenced callbacks! Not even C#, that notorious syntactic sugar thief, is able to do that!

There is a sublime quality to Flash’s outrageous RAM and CPU overhead that doesn’t quite come across until you’ve used it to program games. I once built a Flash game that streams hand-painted full-resolution environment art from the internet and loads all of it into memory at once:

I once programmed a dynamic 2d lighting engine that renders circular gradients into a bitmap every frame, blitting it back across the screen as an overlay:

I wrote all this using Flash’s excellent 2d graphics API, which treats me like a human being by asking for shapes, fills and gradients rather than vertices, triangle maps and my first-born’s blood. I never had to explain the foreign notion of a ‘line segment’ to some illiterate thousand-threaded polygon pump, futzing with triangle fans and clipper libraries and “programmable” shaders. The libraries I used were entirely CPU-based—which is to say slow as hell—and I still got away with murder.

To use my favourite Bogost-ism, I find certain a squalid grace in hogging 2 gigabytes of RAM and 3 gigahertz of computing power just to draw a 2d videogame. It speaks to a promise fulfilled: a world where we can make sprawling, beautiful, outrageous software without fear of over- or under-utilizing the hardware against which we labour. A world free of scarcity, in which computers serve programmers rather than the other way around. A world without limits.

Yet in the shadow of Flash’s ever-impending death—an era of innovation for its own sake, leaving everything behind amidst our fumble for the bleeding edge—that world cannot exist. The hardware will always be too slow; the software will always be half-broken and impliable. This is not cause for celebration; if anything, it’s cause for sorrow. There is value in the old and the venerable. There is culture. There is expressiveness. There is joy. We’d be wise to treat it with respect.

Elegant Editor-Only Script Execution in Unity3d

Lately I’ve been doing a lot of Unity programming. I love how easy it is to develop editor tools for my designers and how seamlessly these tools tend to integrate with the runtime environment. My favourite feature is the [ExecuteInEditMode] attribute because it lets me write all kinds of funky real-time level generation tools. (Like extruding 3D meshes from 2D primitives!) But what this attribute sorely lacks is the ability to have code execute ONLY in edit mode, where performance isn’t such a big deal. By default code placed in the Update() method will execute both when the scene changes in edit mode AND during every frame of play mode, making it unwieldy for expensive operations like realtime mesh generation (or even a large number of tiny operations, like setting a renderer’s sorting layer).

Step 1: Execute Only In Edit Mode

Various hacks around the internet purport to solve this problem. Some suggest using conditional compilation directives like #if UNITY_EDITOR. This is helpful for platform-specific builds, but unfortunately code placed within these directives will still execute in the editor’s play mode (which is, of course, where 98% of testing happens). Another approach involves checking a global variable like Application.isPlaying before doing anything editor-specific, but this is less than ideal should you have hundreds of active scripts in your scene (the performance cost of calling Update() on that many components, even if that function contains only one boolean comparison, can add up surprisingly fast). I’ve also found, although I haven’t verified it experimentally, that isPlaying becomes rather unreliable when it mixes with big scenes, custom inspectors and ExecuteInEditMode scripts.

I now use a solution that makes use of both conditional compile tags and a little-known global variable in the EditorApplication class:

Here’s how this works. In edit mode, isPlayingOrWillChangePlaymode will always return false; thus, the editor-only code located within that else statement will execute every time Update() is called (generally every time the scene changes). In play mode isPlayingOrWillChangePlaymode will always return true, causing the MonoBehaviour to disable itself on the very first Update() and cease hogging performance beyond the first frame. (This is especially helpful when you’re trying to use the profiler to isolate script bottlenecks.) In compiled versions of the game the Update() method won’t even exist, saving us the trouble of having to disable it. The result of all this is that you can run horrifyingly-expensive setup code in edit mode that costs virtually no performance during play, which arguably is the entire point of an IDE like Unity.

Now, I know what some of you are thinking: ‘Why not do away with all this ExecuteInEditMode voodoo and simply write a custom inspector? It will never run in play mode and you can use SerializedProperties and GUILayout and all that magic.’ Well, here’s the thing: Custom inspectors act only on currently-selected Unity object(s). Suppose you had a bunch of prefab instances, some of which had overridden properties, and you wanted every single one of them to regenerate their content each time you modified the parent prefab? What if some of your generator scripts modify other generator scripts, and you needed those ones to be responsible for their own regeneration even when not a single one of them is selected (and therefore their custom inspector code is completely unloaded)? What if those scripts used prefabs? ExecuteInEditMode provides an understandable, reliable, and relatively efficient way to let scripts respond to any change in state from anywhere in the IDE. Inspectors will never do that for you.

Read more…

Smacking Some Reason Into Your Akai MAX49

A Photograph of the Akai MAX49 MIDI Controller

I don’t care what the internet says; I think the red paint looks sexy.

I bought an Akai MAX49 MIDI controller recently. It’s an impressive device boasting a nice, stiff keybed, a reasonably-supple set of pads and, of course, its big killer feature: Four banks of eight responsive LED touch faders designed primarily to make your neighbours jealous. A musician, upon unboxing such an instrument, might set about playing music with it; I, however, am no musician.

The first thing I did with my MAX49 was dive into its configuration settings in an effort to set it up just so for use with Propellerhead’s excellent Reason software. Akai offers some presets that work with Reason’s ‘Remote API’, an interesting and mysterious Lua-based scripting system for binding the various physical knobs and dials on any MIDI device to the virtual ones inside Reason. These are pretty good for the most part, but I encountered one major annoyance almost immediately: The controller’s ‘responsive’ faders (which one would expect to work just like the motorized ones on a mixing board) were capable of sending data out to Reason but not of receiving it from Reason. Thus I could use my finger and the MAX49 to move a fader on one of Reason’s virtual line mixers, but if I then used my mouse pointer to tweak that fader in the application the change would not be represented on my physical controller. This was not acceptable.

Read more…

The Strawberry Game Jam

Screenshot of The Wheel

I did a game jam last weekend! You can look at the result right here.

This game is a parable about time and society. A person must journey all the way around the surface of the globe, following the footsteps of his doomed countrymen into hell and confronting the ancient thing that brought them there.

I developed this project alongside Dylan Bremner between the hours of 7:30pm on a Friday night and 4:00pm the following Sunday. We used Flash’s fancy newish Stage3D (via the somewhat-interesting StarlingPunk framework). The rings consist of rectangular textures bent over circle-shaped triangle fans using some clever UV mapping and programmable shaders. I am very happy with it. It was a productive and enlightening experience.

Special thanks to Phil and especially Emily for allowing us to stink up their suite for an entire weekend!

The Quest for Good Platformer Mechanics

What should a good platformer feel like? If you wanted to you could stop and think about it for a minute, but fortunately you don’t have to because I am here today to argue that it should feel mostly like this:

A screenshot of Super Mario Bros

Pictured: What good platformers should feel like

Super Mario Bros was not the first platform game ever released, but it is probably the most important. It is the bedrock on which the contemporary ‘platformer’ genre is founded; it is the thing that made Shigeru Miyamoto a household name, and the key component in Nintendo’s magical money-printing machine. But enough navel-gazing: What exactly is so special about Super Mario Bros? What makes it work?

You may be familiar with Tim Rogers. He is a game designer and possible crazy person who writes multi-thousand word essays on Kotaku as well as the excellent Action Button Dot Net. And, in one of his Kotaku pieces, he succinctly explains (which is rare for him) the secret to Mario’s success:

If you asked a space alien from the future to play Super Mario Bros., and then play any of the other side-scrolling platform games of that era, and then report back to you with one sentence on what he perceived as the major difference between the two, he would speak gibberish into his auto-translator, and it would output a little piece of ticker-tape with the words “STICKY FRICTION” printed on it. It is the inertia of Mario’s run that endeared him to us. It didn’t have anything to do with brand strength or graphic design. Those things were secondary. It was all about the inertia, the acceleration, the to-a-halt-screeching when you change direction. You can feel the weight of the character. People never put these feelings into words when talking about games, though they really, really are everything.

Friction, for our purposes, is more than a Newtonian coefficient or counter-force; it’s an aesthetic. It’s the way things move relative to one another and how players interpret that movement to construct their understanding of the game world. When Rogers speaks of inertia, he refers to the way virtual pixels on a screen can gain real mass, movement and livelihood through their dynamics (that is, the manner in which they change). Super Mario Bros does not need high-quality sound effects or 32-bit colour to convey itself to us. It does not need a rumble pack or a motion sensor. We grow to understand it with each of Mario’s steps, leaps and falls.

I thought a lot about this as I first started developing the platformer-ish aspect of my portfolio. Frankly, it scared me a little. I wasn’t quite sure how I wanted the movement to work, but I knew that if the friction didn’t feel right the whole thing would seem cheap and flimsy. And so I started coding. I gave myself a few simple parameters to tweak, then a few more complicated ones. I wondered what would happen if the character could jump or climb stairs and ramps; perhaps if my dude felt good to control in a real Mario level it would also feel good running side-to-side through a less elaborate virtual campus? I followed this rabbit hole down into collision detection systems, the Box2D API, and ultimately a rather complicated software solution. I’ve put it here for you to play around with and, if you like, download and use for your own purposes.

Read more…