Official development blog

The Player is Always Right: An Existential Approach to Game AI

This post is not exactly as philosophical as the title might suggest, just a catchy way to paraphrase what I consider the best way to handle artificial intelligence in games.

In short, as long as there aren’t any glaring oddities in a mob’s behavior the player will tend to justify what’s going on by whatever logic makes sense to them. Thus we should all subscribe to the KISS principle when designing AI. Complex AI systems are not only difficult to create and maintain, they’re exponentially more likely to trip over themselves as the solution space expands outward. On the contrary, simple systems are capable of giving the illusion of intelligence, and half of that work can be done by players themselves!

An example from Cogmind:

  1. Player flees into a room with one other exit, turning to fight off pursuers before planning to escape if things get out of hand.
  2. Half-way through the battle a robot shows up at the other doorway, getting the player in a pincer.
  3. Player: “They’re moving to block my escape!?”
  4. AI: “No, my friend was blocking the other door so I found the only other entrance I could use to get to you.”

This is nothing more than everyday “go straight for the enemy” behavior at work.

Developers can rely on the fact that the player doesn’t know what’s going on behind the scenes. Implementing a realistic thought process isn’t necessary; all that matters is how the final behavior is interpreted by the player. The AI exists to challenge players, interact with them, thus for either tactical reasons or role-playing, players will attempt to rationalize any behavior that is not explicitly explained (i.e. anything a mob does without telling you why).

Of course for some types of games, notably those with many complex interactions, we’d need more capable AIs to deal with the variety of situations. At the tactical level roguelikes aren’t that complex since individual mobs only have a handful of possible actions, not to mention most roguelikes don’t even have any kind of AI for controlling the overall dungeon experience (a very unexplored design space--we’re going to change that with Cogmind). Any game that can should try to get away with the simplest AI possible and work up from there as necessary, just beyond whatever point at which the AI is apparently behaving stupidly.

Expert Systems

AI in games is often some kind of “expert system.” That is, it defines a set of specific behaviors based on the rules of the game, at the simplest level taking the form of if-then logic. At that level it’s pretty much all hard-coded and initially quick to put together, but difficult to maintain once it reaches a certain scope.

The most common type of expert system for games, albeit in an easier to maintain form, is a finite state machine (FSM). An AI essentially exists in a certain “state” and environmental factors can trigger it to switch to another state. While in a given state the AI engages in behavior associated with that state. Cogmind’s AI is sort of this, though most types of robots only have a few possible states.

For example, an unarmed worker bot is cleaning up debris (state: CLEANING) and gets attacked (trigger: ATTACKED), so it starts to run (state: FLEEING); after it hasn’t seen the attacker for a while (trigger: SAFE), it goes back to cleaning (state: CLEANING). The worker only has two states: while CLEANING it wanders around gathering any debris it finds, and while FLEEING it moves away from the attacker.

cogmind_ai_worker_fsm

Inside a worker bot’s brain. An FSM doesn’t get any simpler than this.

One of the most interesting types of game AI is goal-oriented action planning (GOAP), one form of goal-based planner that can calculate the optimal series of actions necessary to achieve a designated goal, and even change that plan on the fly as the situation changes. It’s great for games with numerous possible actions, and once the foundation is built it’s quite flexible. By chaining actions together this type of AI can do some really smart stuff, but it’s definitely overkill for most roguelikes, including Cogmind, in which each AI is only capable of a few actions anyway. I do hope to one day be able to use it in a project (maybe X@COM?).

Robot AI

For now Cogmind uses an FSM, one that was actually born several years ago before Cogmind even existed!

The year was 2011.

X@COM hadn’t been released yet but I was planning to put out a playable version for ARRP that year. The problem was before that point I had only been working on the interface and mechanics--the game still had no AI. So I spent half a day coding and integrating a simple state machine for the enemies. RUN and SHOOT. Very KISS.

In later versions I tacked on a few more states like FLEE, GUARD, and PATROL. Then 7DRL 2012 came around and it was time to write Cogmind, which reused most of the X@COM code, including the AI. The AI required just a few more states for unique robot behavior like CLEAN, RECYCLE, and BUILD, stuff other than fighting (for the non-combat robots). So yeah, the combat robots in Cogmind are still using the same AI as X-COM aliens ;)

After several years of accumulating states and triggers here and there, the Cogmind AI implementation has started to bother me. Imagine code conceived on one of those “I’ll just throw something together” days turning to spaghetti as the amount of behavior it has to account for balloons significantly, made scarier because it’s controlled purely via switch statements rather than an object-oriented solution (the latter would be more flexible). Triggers and states are threaded throughout a single method, and new states aren’t well supported without a sprinkle of special cases…

Okay, end of programming horror story in the making.

So I’m going to refactor it, yeah?

Nope. At least not now. For one, it works (though it’s only 80% complete now that there are new special robots it doesn’t have states for). Even player orders have already been integrated. It would be quite a bit of work to redesign, rewrite, and retest the whole system, so the current plan is to stick with what we have and continue tacking on missing pieces for a first release. In the future if it seems like the game would really benefit from a new AI then we’ll reconsider it.

Squads

In many roguelikes a large portion of enemies work as individuals, though you may end up fighting more than one at the same time due to their placement or poor maneuvering. In Cogmind almost all hostile robots work in groups.

As is these groups will not blow your mind with tactical genius--if they were really that intelligent they’d crush you due to their overwhelming numbers (required for gameplay balance). There’s something to be said for fighting off hordes of weaker enemies. That’s not to say they’re all weak (some you will definitely want to avoid if possible, in true roguelike fashion), nor are all groups composed of same-class robots as they were in the 7DRL. Special purpose squads might have a mixed composition of robots with abilities that complement each other. These are squads that may arrive on a map after you do, usually in response to your presence.

Yep, unlike many other roguelikes the number of enemies on the map is not static, and for that we need the Overmind.

Overmind

There’s nothing called the “Overmind” in game, it’s just a C++ class responsible for coordinating the general response to threats on maps where the primary robot faction has control. It has no direct control over individual AIs, only dispatching new squads as necessary.

This creates a more flexible enemy presence that makes different kinds of strategies equally viable yet hopefully equally challenging as well. Looking at both ends of the spectrum, as a stealthy hacker/assassin there won’t be too many threats to deal with but you’ll have to do so carefully--if you destroy more than necessary or are spotted too often you could eventually have no choice but to beef up your direct combat abilities; as a warmongering deathmobile you’ll be able to force your way through just about anywhere but attract a lot of attention (and therefore company) in the process--at some point it will no longer be worth the danger.

More on this topic in a future post.

 

Notice: Starting next week I’ll be out of town for a long family trip, so the next posts won’t come until the end of the month. When I get back there will be some great new content and a new website as we move towards launch! (No, it’s not quite that close, but the game is good enough to build a proper website around it. Prepare for a screenshot festival, or a gifalanche, or whatever you want to call it =p.)

Posted in Design | Tagged , | 3 Responses

From Prototype to Full Game

I often look back on the time it’s taken Cogmind to reach this stage and ask myself “why the #!@^# is it not done yet?!” (That’s actually me standing in a corridor between a Potion of Speed Coding and Trap of Feature Creep.) More recently I’ve also been wondering if the investment is worth it--think about it: I’ve already put in more than five times the amount of work that went into the 7DRL (including post-release updates) and the game still isn’t released. I’m perhaps not the best judge of my own work, but is the result really five times better? In any case, as a game the 7DRL was obviously a lot less than it could be. It lacked polish. And polish is what takes time.

While at some point the law of diminishing returns will inevitably kick in, Cogmind development still has yet to even cover all the core features, much less reach out into completely unnecessary territory. Since it’s about time for a general progress update anyway, here’s a quick look at Cogmind in the context of what it takes to turn a jam game into a polished product.

7DRL vs. Full Game

Seven-day roguelikes are great for prototyping, since the restrictive time limit ideally forces you to focus on a single core mechanic. Where commercial indie games are concerned, those most likely to be financially successful (defined as turning a profit…) will just stop there--polish a core mechanic and release.

For a (very) short time that was my intention, to simply polish up the Cogmind 7DRL and be done with it. That… would’ve been done by now ;)

But no.

Then I started thinking that a true roguelike also needs more. “This is already a fun, solid foundation to build on… what if we added X, Y, and Z?” More systems! More options! When properly combined in a procedural world these will multiply against each other to produce an exponentially deeper experience.

The thing about polish is that you obviously want the core game to have the highest quality possible, but that means every added feature or element must reach the same level of polish, otherwise a lack of consistency ruins the entire thing. Applying and maintaining consistent aesthetics and gameplay throughout a major project is a project in itself, manageable as a one-man independent operation only because roguelikes defer a good chunk of the experience to the player’s imagination (thereby reducing visual asset requirements).

Scope

So what exactly happened to explode the amount of work necessary to turn what was a pretty feature- and content-complete 7DRL into the expanded game described in the new design doc?

Let’s examine the new scope across three main areas:

World

The 7DRL was organized as a straight dungeon dive (although technically up, not down), passing through ten floors before completion. While the world retains that same central complex, there are now many alternate branching paths. You’ll still be able to go straight up to the surface, but that may not always be the best route depending on your situation.

cogmind_sample_world_map

A sample path through the world of Cogmind, highlighting the central area organized similarly to the 7DRL while also showing potential outlying branches. Each rectangle represents a separate map. (There are more areas generated in a given world than shown here--this is just one possible path, since taking one path means you lose access to others.)

Individual map size is also increased. Those which were mostly 100×100 in the 7DRL now range from 100×100 to 200×200.

cogmind_factory_evolution

A sample mid-level factory map layout--see how the size has quadrupled since the 7DRL, naturally along with significant algorithm improvements (still more to add).

We need lots of new content to fill this extra space, so in addition to unique themes and gameplay purposes for the new maps, they’re also occupied with new robots and even factions. (Really it’s the other way around--the added space was required to fit all the planned content.)

There will be a more in-depth discussion of the world later on “when it’s ready,” in traditional roguelikedev fashion ;)

Mechanics

At the prototype level Cogmind already came with a variety of items, that being instrumental to the core mechanic of building and rebuilding yourself throughout the game. However, the 7DRL is very obviously just shoot/avoid enemies -> attach parts -> rinse and repeat. Sure there are plenty of possibilities and considerations given the large number of parts to choose from, but it all boils down to combat (or fleeing from combat).

The prototype is the core mechanic, where it would be quite easy to add just a few more systems for a result that is greater than the sum of its parts. “Easy” taken in the design sense, not implementation (which takes forever, hence this post). Hacking was a logical choice, adding a whole new dimension to the game that integrates well with all its elements from combat to intelligence gathering and story. Even a range of new combat features found their way into the game, like melee weapons. Then of course there’s the collection of parts related to these new mechanics. And on top of that each part needs its own art and sound, neither of which existed in the 7DRL. Now that took a huge chunk of time.

NPCs and allies are another big addition, fleshing out the story and gameplay though requiring support for dialogue and orders.

Interface

In terms of visuals the 7DRL may seem relatively polished, which can be attributed to importing the existing X@COM code base (which had already been in development for nine months at that point).

Now that we’ve doubled the available width of text windows we have plenty more room to work with, as well as many more windows and UI components related to the new mechanics. These in turn need their own behavior logic and animation scripts consistent with the rest of the interface.

Improving accessibility is a big part of turning a prototype into a full game, thus the entire interface had to be updated or redesigned to make every interaction possible via both mouse and keyboard, sometimes even through a variety of different methods. Heck, there’s even drag and drop. The latest enhancements in particular have focused on visual action feedback, something largely missing from the prototype. I’ll be posted about those soon. (As a side note, one major/common accessibility feature not supported is key remapping. The input system isn’t set up for it, something I hope to resolve one day.)

Progress Update

Despite the significant increase in scope beyond the prototype, this is not me succumbing to feature creep ;). The added mechanics and content are things I think the game needs to satisfy the player’s desire for variety, depth and, more importantly for a roguelike, longevity.

So where are we now?

cogmind_progress_140930

Cogmind Development Snapshot: Sep. 30, 2014

Put simply, the three main components remaining are

  • Robot AI. There is an AI, but it’s pretty simple and doesn’t know how to handle any of the new robot types requiring special behavior.
  • Hacking. Machine hacking is complete as a system but there is no content yet, and robot hacking has yet to be added at all.
  • Maps. Parameters for the core maps are more or less done, but we’re still missing basic event scripting, prefabs, and then designs for other maps.

According to the roadmap, the above list combined with various odd items here and there will require 21 weeks of dev time.

The good news is that all features have been on target in terms of planned development time. The bad news is I only have about eight weeks of pure dev time left this year. Family reasons will be keeping me away from my dev machine the rest of the time. I’m partially making up for it by heavily prioritizing anything that must be in a first release while resisting urges to do anything non-essential (these features would be candidates for post-release updates). Unfortunately no amount of shifting priorities will get the game to a state where I can run a Kickstarter campaign that can finish before the end of the year (a requirement to work with my U.S. partner). Too bad since it would definitely help raise more funds to make Cogmind a better game. Skipping that phase isn’t without its advantages, so we’ll just make the best of it!

An Empirical Look

Besides listing features, we can also measure progress in numbers. It’s been a while since we last looked at lines of code:

cogmind_LOC_140930

Cogmind LOC: 55,632.

As of September 30th Cogmind has 55,632 lines of code, compared to 20k in the 7DRL (remember that much of the code was reused from previous projects) and 35k in February earlier this year. In addition to this there’s about 6,000 lines of scripts that define game objects, animations and sound effect behavior.

Time-wise progress has been pretty steady. Below you can see that aside from a few wider shelves where I was busy with something else, Cogmind is under regular development. In recent months you’ll see a lot of tiny ridges, created as I began concentrating development into weekdays and using weekends (the ridges) for other activities.

cogmind_cumulative_dev_hours

Cumulative development time from July 2013 to September 2014.

That’s certainly not all coding! There are many other aspects of development, all of which are included in the above graph: I divide my time records into Design, Code, Art, Audio, Content, Web, Community, and Business. We’ll wait until there’s more data to talk about that.

Instead, here’s Cogmind in numbers*:

  • 55,632 lines of code
  • 6,142 lines of script
  • 100 source files
  • 749 game files
  • 26 font bitmaps
  • 620 audio samples
  • 634 pieces of ASCII art
  • 636 items
  • 82 item special effects
  • 56 explosions
  • 116 robot definitions
  • 15 AI behavior modes
  • 10 NPCs
  • 23 map themes
  • 146 machines
  • 265 stats recorded for score/morgue file
  • 50 game options
  • 269 recognized input signatures
  • zero main menu (you’ve never seen one because Cogmind doesn’t have one)

*(set randomly chosen, numbers subject to change--the general trend being to revise them upward :D)

Posted in Uncategorized | Tagged , , , | 6 Responses

Cogmind Fonts

Cogmind currently comes with a whopping 26 bitmap fonts. This unusually large number is somewhat less impressive than it seems, as they are certainly not all completely unique styles, but it still took more than a week to draw, scale, and tweak them all to the point of polish sufficient for at least early releases.

Why does the game need so many fonts?

Target Resolutions

Cogmind’s GUI is designed for an 80×60 console, so to keep as close to that amount of content on screen as possible, the most appropriate font will be the one that can draw an 80×60 grid evenly onto a given screen resolution. To determine what font sizes we need, we turn to statistical data regarding the most commonly used resolutions:

cogmind_common_resolutions

The most common resolutions and their respective default font sizes in Cogmind.

Obviously if game is windowed then the whole range of font options is possible depending simply on how large a window (or what size text) the player prefers, but while running in fullscreen mode we want to minimize letterboxing (see Fonts in Roguelikes post for diagrams and discussion under header “Resolution”).

First we calculate the largest font compatible with a given resolution. Height will be the limiting factor because Cogmind uses a 4:3 aspect ratio while most screens are 16:9/10. Any remaining space is then filled by expanding the map view, which defaults to 50×50 cells but can show more if there’s room. Most fonts still result in a tiny bit of letterboxing in one dimension, but it’s a pretty insignificant amount since our grid cells are quite small, and well worth the pixel perfect appearance. Note that we could get closer to our target resolutions by using odd-dimension fonts (specifically a 15×15 font could perfectly match the common 1600×900 resolution’s height), but that would make it more difficult to keep different-sized fonts proportional to one another.

Thus from the list above we can see that the optimal font for a majority of players will be either 12×12 (25%), 14×14 (14%), 16×16 (13%), or 18×18 (33%). In addition to those, Cogmind adds another two sizes useful for special cases:

  • 10×10 “mini-fonts” for netbooks with tiny screens (minimum resolution: 800×600). Cells that small can be tough to accurately click on, but are not too small to see (if you’re already using a netbook…) and work just as well with keyboard-only play.
  • 20×20 “mega-fonts” for huge screens (like my own 1920×1200). These are required for recording videos, so useful for myself and LP’ers. YouTube compression is notoriously horrible for processing small pixel-perfect ASCII, so the key is to record at high resolution with thicker lines to retain as much information as possible. At least that’s the theory--I haven’t tested it yet. Cogmind’s animated gifs always look good down to the yummy pixel level, but for full immersion we need sound!

In total we have 6 different font sizes to support. Why do we want to draw fonts for all these resolutions instead of just scaling the window? Because scaling looks awful! (The other option discussed in the previous post is TrueType fonts, but they still don’t offer pixel-accurate control.)

Font Categories

For each font size, we need at least one separate bitmap for each of three different purposes.

cogmind_font_categories

A screenshot excerpt of the game running in 14×14 mode, showing all three font types in the same interface--the map, text, and art.

Map

The font used to display the map has a square aspect ratio to preserve uniform distribution of space for better tactical decision-making. In the future players will be able to optionally replace these fonts with (simple) sprites/tiles at the press of a button, but the sprites have not yet been added.

Text

Text fonts are half as wide as their respective map fonts, giving them a somewhat restrictive height-width ratio of 2:1 rather than more common ones like 8:14 or 10:16. This makes designing good fonts a bit more difficult, but the tile engine is optimized assuming font widths use multiples of a single value, so other ratios are out of the question.

Art

As discussed earlier (see here and here), Cogmind art is created purely from code page 437 glyphs. Unlike some other roguelikes, Cogmind map and text fonts do not need the entire 255 character range of CP437, instead sticking to standard alphanumerics and punctuation. This at least keeps the total number of required glyphs down from an otherwise ridiculously huge number, but we still need to draw the full character range for art font bitmaps, and need one CP437 art font for every supported font size.

Though map and text fonts use sans-serif styles, I decided to use mostly serifed fonts for CP437 to retain the traditional feel of individual glyphs. They have, however, been converted to a square format to make art creation a little easier and enable balanced symmetry in both dimensions.

Creating an art font is more time-consuming than a map or text font not only due to the greater number of glyphs, but because every different size must do its best to maintain the same proportions. This way pieces of art drawn at a given size (I draw at 12×12), will look more or less the same at all other sizes. (By comparison, map and text font styles should look similar at different sizes, but are not required to have the same proportions and can focus instead on readability, which is much more important in those cases.)

cogmind_art_scaling_phase_cannon

Scaling a Phase Cannon diagram using multiple bitmaps, 10×10 through 20×20.

Making sure this effect will work requires a lot of cross-comparison when drawing the fonts. Sometimes compromises are necessary due to space concerns, or whether there is an odd or even number of pixels available in a given area, etc. There’s still (always…) room for improvement, but enough time has been put into polish already.

At this point I’ve completed REXPaint‘s library of square-ratio CP437 fonts. That tool’s next release (1.0) will include everything from 8×8 to 20×20.

Player Choice

Another reason for the many fonts is that some styles have variants which may be more readable for some players. This applies only to text, for which readability is more of a concern (map and art fonts on the other hand only have a single option at each size). Each size usually has a couple variant styles to choose from.

cogmind_font_variants_16x16

Comparing two 8×16 variants: “cogmind” (top) and “wide” (bottom). This is a dialogue segment from Revision 17, a not-entirely-sane robot who gives you a tiny bit of background at the beginning.

With multiple fonts available it’s easy to change the style, and therefore appearance of much of the game overall, via the options menu:

cogmind_font_swapping_12x12

Swapping between two 6×12 fonts, the “crisp” style I’ve been using in all screenshots before now, and the newly-added “cogmind” style.

It’s also easy to add new fonts to the game--just draw a bitmap for one or more of the font categories and add it to the fonts/config.xt file:

cogmind_font_config

The current fonts/config.xt file listing all available font sets selectable in game.

Notes on Style

Keeping a thematic style is tough to do at small sizes, since every pixel becomes valuable in terms of readability, a property we can’t sacrifice in the name of style, at least not for a roguelike where reading text should be mostly effortless to avoid slowing down gameplay. I did recreate the cogmind style at 5×10, but it’s not very readable and won’t be included with the game:

cogmind_unused_font_5x10_styled

An unused cogmind-styled font at 5×10. It looks interesting, but the high pixel density hurts readability.

Instead there are two other 5×10 fonts that focus purely on readability:

cogmind_font_variants_5x10

Cogmind’s two smallest fonts: 5×10 all-caps, and 5×10 cased.

There were also symmetry issues designing mid-sized map fonts (16×16). For example, 12×12/14×14 fonts use 2-width ASCII lines, and the next size up should logically use 3-width lines, but you can’t center a value of 3 given an even dimension. As an experiment I tried to skip to 4-width lines to keep them centered in their cells, but the relative proportions are noticeably different, causing machines to appear not quite how they were intended. After some testing the best solution was to draw 3-width lines 1px off center (only a couple of fringe case machines look a bit off, as opposed to all machines).

cogmind_font_16x16_offcenter_lines

16×16 map font tests, demonstrating how thinner off-center lines (left) better reflect the original machine design than thicker centered lines (right).

Looking closely at the earlier 5×10 text fonts you’ll notice that both line glyphs as well as vertical strokes in certain letters are actually off-center as well. They have only 4 pixels of width for drawing (one is reserved for embedded spacing), and attempting to give them perfect symmetry by doubling the width/height of those lines stands out too much and unbalances the font’s overall appearance.

cogmind_font_5x10_unbalanced

Too much attention is drawn to the ‘I’s and ‘T’s etc. when trying to design for symmetry at this small a size, throwing off the balance.

Another stylistic consideration for roguelikes in particular is that certain characters can have disproportionately greater impact on the game’s appearance. Last time I talked about use of the period for empty spaces, and showed how a couple extra pixels on that one glyph can drastically change the appearance of the entire map. Similarly, the hash (‘#’) symbol is going to be pretty ubiquitous for any roguelike using it to depict walls, and thus deserves extra attention. Again as a transitional font size the 16×16 map font had to decide between a thin and thick version.

cogmind_font_16x16_hash_thickness

Comparison of hash symbols drawn with 1-pixel or 2-pixel lines (16×16 map font).

The 2-pixel version produces a much higher contrast between open and closed space, but also draws a lot of attention to walls as a character when we care much more about other characters representing interactive objects and entities. Later maps painted with brighter wall colors would suffer even more in this regard (no, we’re not setting different object brightness values for different sizes, thus colors that work at one size should ideally work at all sizes).

One aspect I like about thicker hashes is that they better mesh with wall-integrated machines:

cogmind_font_16x16_hash_thickness_machine

Thin vs. thick hashes as they work with wall-integrated machines.

However, this is less important overall so we’re going with the thin style (until at some future date I disagree with my current self).

Text Font Comparison

Below are all the text font options available for each cell size, all demonstrated using the same dialogue window. Feel free to share opinions on style, readability, or whatever. I’m interested in knowing what sizes and variants are preferred (or not preferred), as this can affect what fonts I tend to use for screenshots and gifs. The game’s default font(s) are also fairly important since many players will probably not immediately realize that switching fonts is so easy and that there are so many options (after all, customizable text is not very common outside of traditional roguelikes).

5×10

cogmind_fonts_5x10

Cogmind 5×10 Fonts: All-caps, Cased.

6×12

cogmind_fonts_6x12

Cogmind 6×12 Fonts: Cogmind, Crisp.

7×14

I’ve only drawn one font for 7×14 (this particular size was originally going to be left out, until a review of resolution stats showed it could be required by 1 out of 7 players!).

cogmind_fonts_7x14

Cogmind 7×14 Font.

8×16

cogmind_fonts_8x16

Cogmind 8×16 Fonts: Cogmind, Wide.

9×18

As we get larger, there is more room for variety in style.

cogmind_fonts_9x18

Cogmind 8×16 Fonts: Cogmind, Narrow, Wide.

10×20

Regardless of which sizes look better, I’ll definitely be using 20×20 to record videos since it should be best able to survive compression. Screenshots and gifs will use smaller fonts to fit more content at their native resolution and avoid shrinking.

cogmind_fonts_10x20

Cogmind 10×20 Fonts: Cogmind, Narrow, Tall.

More Options

Most of the text fonts are currently derived from a single style, attempting to take it in multiple directions and explore the potential for readability at different sizes. Depending on the results--the overall feel is certainly different when experienced in game interacting with the full UI--I may add more fonts with completely different styles that focus purely on readability. Already some good suggestions have come in from readers, including this.

This is the third in a three-part series on roguelike fonts:

Posted in Art, Dev Series: Fonts | Tagged , , , , | Leave a comment

Font Creation

Finding the perfect font can be difficult, even more so if you’re also hoping that font will offer a unique appearance associated with your game. You’ll often come across fonts that possess several of the right qualities but have other drawbacks, especially when taking into consideration the many factors covered in the previous post about roguelike fonts in particular. This is when you want to take those qualities as inspiration and break out the pixel brush. Roguelikes have so few visual assets that it’s worth investing some time developing your own font. I’ve been making and working with bitmap fonts for about ten years, so I’ll share some of my observations and workflow tips here.

Formats

There are two main options for dealing with fonts: 1) use a font engine to render a TrueType font (.ttf), or 2) use a bitmap.

TrueType has the advantage of being scalable to almost any size, making it the solution with ultimate flexibility. However, this flexibility comes at the cost of precise pixel control, thus TTFs won’t always look good at all sizes. In a game where text is secondary this drawback may not be a huge deal, but with terminal roguelikes (emulated or not), the text is the graphics, so it’s nice if we can control every pixel. Think of roguelike fonts as pixel art in that regard. Also note that creating a proper TFFs requires a good bit of technical knowledge, and specific tools.

Most roguelikes, and many 2D games, use bitmap fonts instead. The bitmap approach is great for that pixel-perfect WYSIWYG appearance. I’m guessing that most readers already know what a “bitmap font” is, but just in case:

rexpaint_cp437_10x10

A bitmap font image (REXPaint code page 437 in 10×10).

As in the above image, all the characters are pre-drawn in a grid, and at runtime the game copies individual characters from this image and puts them on the screen to form words.

The main drawbacks to bitmap fonts are the need for different bitmaps for every font size (if more than one), a lack of automatic kerning (which you get with TTFs), and narrow characters (like ‘i’) taking up much more horizontal space than they should. Bitmap fonts don’t have to be limited to monospaced output, but with a grid-based terminal display we don’t have the luxury of specifying character spacing.

Aside from that, bitmaps are more powerful than they appear. At runtime the engine can recolor them to any color necessary:

rexpaint_cp437_10x10_recolored

Each of these sentences was produced from the same bitmap shown above.

And “pixel-perfect” doesn’t have to mean sharp edges--bitmap fonts are even capable of alpha shading and anti-aliasing:

rexpaint_cp437_10x10_resized_alpha

To demonstrate, the 10×10 font bitmap was upscaled in Photoshop using a smoothing algorithm, producing anti-aliased characters that can be copied as well. (Naturally in actual use we’ll want to manually draw in the antialiasing--full pixel control FTW!)

As seen above, alpha-enabled fonts can be recolored all the same and preserve their alpha transparency.

Layout

With bitmap fonts the other consideration is what layout to use. Your game, or other programs, need to know where each letter is located, just as if this were any other sprite map. Since you can specify the coordinates, it’s really up to you.

One of the more common choices is US code page 437, the standard extended ASCII layout used by games like Dwarf Fortress--the same such layout you see in the first bitmap shown above. Some programs may orient it differently (column-wise rather than row-wise), but in general there is a benefit to making the bitmap directly correlate to ASCII values. There are lots of bitmap files already out there in the wild, and if you can read a more standard format like CP437 then you can potentially import any of them without trouble.

For Cogmind I’m not interested in reusing other bitmaps, nor am I using the entire code page 437 set, so seeing as we only have to map the character positions once in the source, might as well make editing the font easier by creating our own layout:

cogmind_7DRL_font

Bitmap layout for the Cogmind 7DRL/prototype default font. The layout will remain more or less the same, but the font will be retired (it’s a Deja Vu font--I didn’t make it).

This layout ignores the many ASCII characters we don’t need, and lines up lower and upper case letters immediately next to each other. Much cleaner to edit.

Tools & Basics

There are a ton of drawing programs out there, many free, though I always use Photoshop, even for pixel work (for which I don’t think it’s particularly suitable, but I’ve been using it regularly for about 15 years so it’s what I’m used to…). Examples will be shown in PS but translate to just about any decent program.

Layers

Below is the 9×18 text font design file.

cogmind_9x18_font_layers

One of Cogmind’s 9×18 fonts. Most of the (non-experimental) font files are layered like this.

All font files have a “guide” layer which shows the boundaries of each cell, useful when zoomed in drawing individual characters and for eyeballing pixel padding. I always use an overlay for guides in PS because using lines would occupy space and then you have to remember which cell the line belongs to and maybe even draw over it. (Area-based guides are also useful because you can ctrl-click the layer to select the entire guide area, though that doesn’t matter in this case and is a technique for other PS work.)

The 9×18 font currently includes three variants: “cogmind” (a highly-stylized sci-fi font), “wide” (8×10), and “narrow ” (7×10). Remember that when making a bitmap font for roguelikes in which a character will occupy an entire cell, we must embed horizontal character spacing and vertical line spacing in the actual font, so characters will rarely take up an entire cell in the bitmap itself. We can describe the variant by its letter size (I use the dimensions of ‘A’).

Common glyphs like lines are held in a separate layer since they don’t differ between variants.

Variants

When creating a font in multiple sizes and variant styles, to save time we’ll obviously be doing a lot of copying.

The 9×18 font actually began its life as a direct copy of the 16×16 square font, shifting lines/columns as necessary followed by tweaking features to bring it more in line with the other narrow text fonts and improve readability (in words). The 16×16 square font itself began as an upscaled 12×12:

cogmind_12x12_16upscale

The 16×16 font immediately after upscaling from 12×12--definitely needs lots of adjustments, but having most of the pixels there already will save plenty of time.

Note that when upscaling for this purpose, to avoid anti-aliasing/smoothing we have to change the resampling method to “Nearest Neighbor”:

photoshop_nearest_neighbor

Scaling pixel art images in Photoshop, because we’re going to fix them up manually.

Because larger fonts take much longer to draw, even if the intent isn’t to use a smaller font you can begin by drawing the general style at a size like 8×8 then upscale it. From there you can tweak the strokes, or even add anti-aliasing:

scaled_fonts_8x8_to_16x16

An example of scaling a smaller font for manual adjustment.

Typeface Anatomy

When you do have to draw from scratch, the first thing to do is decide on some basic parameters that will more or less remain consistent throughout the font. The relative positions of these three lines are especially important:

cogmind9x18_anatomy

The font baseline, mean line, and cap line.

Most characters sit on the baseline, the cap line defines the upper edge of capital letters, and the mean line is where we find the crossbars for capital letters and often the tops of lower case letters.

Remember that for roguelikes we must also embed both character and line spacing in the bitmap itself, and these can have a significant impact on the final result.

cogmind_9x18_narrow_vs_wide

The difference between leaving two (left, 7×10) or one (right, 8×10) pixel of horizontal space in the 9×18 font.

When scaling variants to multiple sizes, I’ll first sketch a quick reference diagram to ensure the ratio of space and glyph size remains fairly consistent to keep the style intact across each version.

cogmind_text_font_spacing

Spacing reference data for a text font at three different sizes.

Design

This post is geared towards the technical aspects of making bitmap fonts, but I can offer some simple guidelines and techniques for design.

Theme

It’s pretty obvious that fonts each have their own theme, essentially a set of defining characteristics that show the glyphs belong to the same group (font). Creating a consistent cohesive font is simply a matter of making a list of rules that define those characteristics, then sticking to it. Rules regarding how different letters treat the reference lines (base/mean/cap), uniform behavior of decenders (hanging lower case strokes), relative prominence of punctuation…

Again that last one is very important for roguelikes, since periods especially are so commonly used on maps. An extra pixel or two can make a huge difference in the overall appearance of a map. This and other thickness-related concerns are inseparable from the use of color, since they work together to determine how bright the interface will be overall (assuming the use of a traditional black background). Fine periods are compatible with bright colors, but thick periods would threaten to overwhelm the map unless presented only in dark colors.

cogmind_period_1v2px

Look at the huge difference a period makes: 1×1 vs. 2×2.

As you can see, even with a darker color the map is harder to read with a thicker period--looks like the 2×2 version would need to be even darker to work at that size. That’s a 12×12 map font, for which Cogmind is currently using the 1×1 centered dot (left).

In the end, a theme’s rules may need to be bent or broken for a few stubborn letters that aren’t too compatible with the chosen style, but do so sparingly.

Text vs. Map

In the previous post we outlined several properties that differentiate the ideal text font and map font, and we can actually treat them somewhat differently in our bitmap images. Herein lies another advantage of separating the two: For map fonts we can ignore character and line spacing for the purpose of text readability and instead put glyphs in the center of their own cell.

cogmind_centered_16x16_font

Glyphs from a 16×16 font demonstrating map font centering--they no longer share the same baseline.

This is another step away from the classic text-as-map roguelike appearance, but preserves the even distribution of space between objects as found in normal game maps. The advantage is most apparent with the period, which usually sits on the baseline but in this case can mark the center of an empty map position. Few if any roguelikes use this feature, but Cogmind certainly will:

cogmind_centered_16x16

An in-game comparison of non-centered vs. centered map fonts (16×16). Centering the glyphs results in better alignment between different map components.

While it’s true that in raising the baseline for lower case characters you might reduce the visual effect of “tall vs. short” when horizontally adjacent to their upper case counterparts, truly large creatures are best presented as multi-cell objects anyway (as they are in Cogmind), and upper case letters do still occupy more pixel space.

Perspective

When creating a bitmap font, it’s important to realize that while an individual character may look cool, its difficult to give a well-rounded appraisal while pixeling it because 1) you are usually zoomed in close, and 2) there is no question of how recognizable the character really is (you already know what you’re drawing!).

We must examine the font at its native resolution during the process. Most painting software comes with some kind of “preview” feature with which you can observe changes to the image itself while editing as if it were zoomed out. In Photoshop, selecting the “Window > Arrange > New Window for…” option creates a duplicate window for the current image, and both are updated simultaneously, so one can be set to the original image size to see changes as they are made while zoomed in at the pixel level.

But even keeping an eye on the font bitmap at its native resolution is not a complete solution. Remember that the readability of text fonts is partially defined by how characters interact with other neighboring characters. Seeing the font in action will suggest additional necessary tweaks, so intermittently dropping it into the game helps refine the design. For that purpose I keep a separate copy of REXPaint where I can quickly drop in fonts and see how well they work. (It helps that Cogmind’s GUI mockups are all stored in REXPaint .xp files.)

This is the second in a three-part series on roguelike fonts:

Posted in Design, Dev Series: Fonts | Tagged , | Leave a comment

Fonts in Roguelikes

The first aspect of a traditional roguelike viewers tend to notice is the color palette, but when it comes down to actually playing a game which requires interpreting large amounts of text, color takes a backseat to the importance of the font. Characters/glyphs form not only words and sentences, they even represent the map and every object contained within, blurring the distinction between font and sprites/tiles. Thus roguelike developers should not overlook the many considerations that go into creating or choosing the right font. This is the first post in a series that will explore those considerations, share font creation techniques, and look at examples from Cogmind itself. Note that although the topic is discussed in terms of roguelikes, some of the concepts and methods touched on apply to all kinds of games.

Readability

The number one consideration with a font that’s meant to be read a lot is, surprise, readability! This consideration is often at odds with the desire to stylize a font to give it a unique look reflecting the theme of the game. So while roguelikes are often set in a fantasy world, they don’t use the styled fantasy fonts you might see in a lot of graphical CRPGs (especially older ones). There are many reasons for this, and a number of factors that affect readability.

Single Font

By necessity, traditional roguelikes use a single font for everything displayed, be it text or map information. There’s already an inherent dilemma here: The idea of “readability” takes on a different meaning when referring to either text or a map. The ideal readable text font produces easily recognizable words and sentences, while a map font should produce “tactically readable” maps. With the latter, glyphs should be drawn with an eye towards easy individual recognition rather than as a component of a larger word. This is different from regular font design which places heavy emphasis on how letters interact, knowing that we recognize words as a collection of letters and not for the individual letters of which they’re composed. Thus individual letters in fantasy text fonts can be fairly stylized, but would take an extra moment to recognize or distinguish when used in isolation on a map. Certainly it’s possible for a player to adapt to even the strangest fonts used in this way, as they are simply representative symbols, but letters often carry addition information to aid recognition, like using categorical abbreviations such as ‘c’ for canine, ‘h’ for humanoid, ‘z’ for undead, etc. Less readable fonts also create yet another barrier to adoption when players already have to face learning a new set of input, mechanics, and glyph meanings, systems which themselves may already be complex (though are not required to be). Even long-time roguelike players tend to have a low adoption rate for different roguelikes, not even trying them unless there is an extremely compelling reason to do so, or they need a break from their favorite RL ;)

Another characteristic of tactically readable maps is a square aspect ratio, where horizontal and vertical distances are equivalent in terms of both screen space and game space. Having to translate between the two is something long-time players will be familiar with.

DCSS_aspect_ratio

Dungeon Crawl Stone Soup in ASCII mode, with all cells within range 7 encircled. Here Sigmund is 7 steps away, but could feel a lot more menacing if he approached from the left or right. As if Sigmund wasn’t intimidating enough…

This relic of old console roguelikes is best avoided since it unnecessarily* distorts space and causes a disconnect between what we see and the actual situation. (*Unless we count nostalgia among those necessary qualities.)

The reason this convention is so prevalent is that we have the “single font” factor (and that font gives preference to text readability due to a high ratio of text content) combined with another roguelike characteristic: the grid-based display.

Grid-Based Display

Unlike most other games, as a traditionally terminal-based genre roguelikes originated in a grid environment. Though technically no longer restricted in the same way, even many newer roguelikes are played in emulated terminals that maintain the same convention to preserve that traditional look and feel (being simpler to code is another factor).

Given our single-font, grid-based display, what happens if we favor a square aspect ratio to aid tactical decision-making? This:

cogmind_7DRL_wide_text

The Cogmind 7DRL/prototype used a square font to make the map easier to interpret, but the effect on the text… not so readable.

The issue is even more acute with large blocks of text, which become a chore to read as your eyes have to move 50% faster to decipher each line of text. Libtcod seems to be a major force influencing the trend in this direction, because it uses square fonts by default and is one of the primary tools for new developers. Many libtcod games use square fonts, and their text readability suffers as a result.

Words and sentences are more difficult to clearly lay out in a strict grid because some letters are naturally narrower than others. Interfaces without a grid can specify a static one or more pixels between characters, or even apply kerning (adjusting the distance between letters based on their neighbors), to resolve spacing issues.

Serifs

We can’t discuss fonts without mentioning the two major classifications: serif and non-serif. Serifs are short lines protruding from the ends strokes/lines that form a glyph.

sans_vs_serif

Sans-serif vs. serif letters.

In roguelikes, serifs can serve to distinguish ’1′, ‘l’, and ‘I’, which is especially important in cases where all of these are used to represent map objects as they don’t belong to a word which can be used as a reference when interpreting them. This same consideration comes into play when selecting a monospace programming font, where you also want to make sure that ‘O’ (the letter) and ’0′ (zero) are easy to distinguish.

In addition to their functional impact, serifs are also meaningful stylistically. Serifed fonts tend to evoke a fantasy aesthetic, though that’s not to say you can’t use serif fonts in sci-fi games. For roguelikes at least serif fonts do have the most traditional appeal, no doubt for nostalgic reasons since the IBM PC/MS-DOS console font was mostly serifed.

cp437_ibm_pc

IBM PC code page 437.

 

caves_of_qud

Caves of Qud: A sci-fi roguelike displayed with a good old serifed non-square font.

Fonts can say a lot about a game, though.

font_sword_of_the_stars

This font says “I am probably not a fantasy game.”

In general sans-serif fonts tend to suggest more sci-fi qualities: crisp, clean, streamlined. I’ll be sticking to that theme for Cogmind’s fonts, so no serifs.

Solutions

There are many solutions for addressing the readability issues discussed above.

Size

If you want a square aspect ratio but don’t want to sacrifice too much readability and don’t mind being forced into a certain style, sufficiently small wide fonts are fairly readable. Like this 8×8:

incursion_8x8

Incursion: Halls of the Goblin King, shown in a small 8×8 font (click for original size). Characters are small, but then so is the relative space between them.

Using small fonts also enables you to pack a lot of content/information into the UI, though this isn’t advisable for mouse-enabled interfaces where cell size suddenly matters for click accuracy. Fortunately roguelikes are heavy on keyboard use. Despite its many features, Cogmind is entirely playable via keyboard and/or mouse. However, if you’re on a netbook and running one of the 10×10 mini-fonts, I’d recommend sticking to the keyboard unless you don’t mind occasionally clicking the wrong target ;)

Choices

While properties that make a roguelike “readable” can be defined objectively, players’ own preferences won’t always align with that definition. More importantly, each player’s situation may differ somewhat due to factors including eyesight, available light, monitor size and quality, etc.

Roguelikes are often pretty good about offering ways to customize the experience to meet these different needs, and with such a low overhead to providing alternative game appearances (just a bitmap), it makes sense to do give players many options in that regard.

cogmind_font_swapping_10x10

Using the options menu to swap between the two 10×10 mini-fonts I’ve been working on for Cogmind (what you see here is the text version, which is 5×10). With these, the smallest resolution/window supported by the game is 800×600.

Font switching is fairly common in terminal roguelikes, but developers can’t rely on the player to decide on the best one right away. A game’s default font ends up being quite important since a majority of players just go with the default, which becomes the font associated with the game in general (screenshots/LPs). There’s also the first impression to consider, since a font that doesn’t click with a given player can contribute to them not liking the game early on (in which case they may not get deep enough into it to want to swap in another font).

Mixed Fonts

To get the best of both worlds, a square aspect map font and narrower font for text, we have to take the radical step unavailable to standard terminal roguelikes: use multiple fonts. As mentioned in the intro, roguelike usage of fonts traditionally blurs the distinction between font and sprites/tiles. However, even if we don’t go as far as using actual sprites, by separating the two we can at least choose an ideal font for each.

Now that many roguelikes with a grid-based interface use an emulated terminal, instructing them to store font information for each cell and pull characters from one of two separate font bitmaps at render time is easy. My own engine uses the simplest implementation, which has the narrow text font take up exactly half the width of the current square font.

cogmind_narrow_text

A Cogmind parts list like that seen in the earlier 7DRL/prototype image, converted from 12×12 to 6×12 half-width font. Whew.

Half-width text fonts technically double the number of horizontal cells in the interface, but allow layered UI elements to stack nicely while partially obscured lower layers can still be displayed properly. This is more compatible with the cell-stacking system of my own engine which simplifies culling, retains the traditional grid-based look, and is simple to manage since UI offsets are still handled in cells rather than pixels.

mixed_font_visualization

A random UI layout mockup showing how 6×12 (green) and 12×12 (red) cells stack on each other.

The primary drawback to this approach is the heavier CPU load from all the extra cells for the same amount of screen space. Cogmind’s display requires more processing power than the 7DRL, but it’s been two years since then, plus the cell stacking system was later optimized somewhat.

Resolution

The original roguelikes never had to worry about the player’s monitor resolution, expecting instead an 80×25 console window--fullscreen support wasn’t an issue, nor were the implications of different monitors.

Today many players like to fully utilize their screen space rather than keep a game windowed like some application. To accomplish this, unlike tile-based or 3D games that scale geometry, textures, sprites, fonts, and interface elements, roguelikes have an alternative option (or the only option before/without the use of non-console engines): swap out font bitmaps to change the resolution of the entire game to match the target resolution as closely as possible.

For most games it would be costly and time-consuming to manually recreate assets for multiple resolutions, but not so for roguelikes. All we have to do is redraw the font map, a single image, at a different size. This enables us to keep a crisp-looking pixel-perfect appearance at any resolution for which there is a font.

An example of why we don’t want to just stretch the interface:

caves_of_qud_opengl

Caves of Qud in OpenGL mode.

The OpenGL version of Caves of Qud scales the entire interface rather than using an actual font renderer (compare to the earlier CoQ terminal image, which is pure awesome). While rendering fonts would be a better option, even those don’t always look good at every resolution. Working with pixels we know exactly what the result will look like, and seeing as it’s fairly easy to provide fonts for multiple resolutions, I think we should make that effort.

Once we decide against automated scaling, the next important question is how many resolutions do we have to realistically support? Wikipedia has aggregated some interesting and useful data on that topic:

common_display_resolutions_2014

Most common display resolutions that games should support, because that’s what players are using.

Ranking display resolution usage by percentage of Steam users, we see that more than half are using one of either 1920×1080 or 1366×768.

Because a given resolution will not necessarily be evenly divisible by any font, in making these additional fonts we’ll need to consider some other solutions.

The simplest is to add black strips around the interface to fill extra space (a.k.a. letterboxing), though it’s best to minimize usage of this method as some will complain it’s not “true fullscreen” (however, it is important to remember in gamedev that technically someone will complain regardless of what you do…).

gui_layout_1366x768_letterbox

An 80×60 console GUI rendered using a 12×12 square font, the largest that will fit the entire interface within a 1366×768 resolution. This happens to be Cogmind’s UI layout, and what it would look like letterboxed at this resolution.

Ideally one or more interface elements will have adjustable dimensions, so that we can increase the amount of actual visible content as opposed to leaving portions of the screen space unused. For games where the maps are large (like Cogmind), we can increase the amount of visible map area.

gui_layout_1366x768_expanded

Taking the same GUI elements from above and expanding their content (no stretching) results in a 66% increase in map/log width (+33 cells), and ~8% increase in map/HUD height (+4 cells). Because the 12×12 font is not perfectly divisible into 1366, there will be 5-pixel vertical bars along each side, a small price to pay for a pixel-perfect interface.

The third font post, in which I’ll cover Cogmind fonts in more detail, will also discuss the selection of font sizes and target resolutions.

A second observation to take away from the display data: Wide screens are now the norm, thus new games should develop their GUIs accordingly. Cogmind happens to have been designed for a 4:3 aspect ratio, which are growing increasingly rare as far as fullscreen resolutions go. Of course, there are a few advantages as well: 1) takes up less space when windowed, 2) keeps information more evenly distributed, 3) requires less computing power. That said, after reviewing the state of resolutions here, on rebooting development of my other game X@COM I now plan to redesign the UI to take full advantage of wide screen support.

This is the first in a three-part series on roguelike fonts:

Posted in Design, Dev Series: Fonts | Tagged , , , , | 8 Responses