Higher-Order Fun

Game Design & Game Programming

On how Diablo III fails to live up to the Diablo legacy

Diablo III just got released this week, to a spectacularly catastrophic launch day in which almost nobody could play. But once the server loads normalized and the initial hype died out, a surge of furious comments started to take over Twitter and Metacritic (where it has the wonderful User Score of 3.6). What went wrong? In my opinion, Blizzard has slowly been taking away everything that made Diablo excellent, and re-worked it into a far more generic (and perhaps marketable, they expect) experience.

It got to the point where I was almost quitting the game in disgust several times, but I tried to endure – until I saw King Leoric – a character who, in the original game, would greet you with “The warmth of life has entered my tomb. Prepare yourself, mortal, to serve my master for eternity” – brought back as a pathetic parody of its former self, in a ridiculous context, spitting out boring lines, and I just couldn’t take it anymore. I will probably go back to it, and maybe eventually beat it, but it will never be anything near the first two Diablo games.

For a game that actually has a reasonably solid gameplay, it’s peculiar that such things would bother me so much. But they did, and I think that understanding why is important, so here’s my best attempt at expressing what I felt. This might resonate with your own experiences, or you might have had completely different feelings. If so, please share in the comments.

Let’s recap.

Mood

Diablo (and by that I mean Diablo I) was a dark, moody, atmospheric game. I don’t feel that it’d be a major stretch to call it a horror game. The soundtrack was unique, powerful, memorable, and very, very creepy. The sound effects were of excellent quality – possibly better than in Diablo II and III, even. The scenarios were dark, and you couldn’t see much. Your character was initially very weak, and through most of the game, a bad mistake would cost your life (which was a far worse punishment – you’d drop all equipment to the floor, leaving it vulnerable to be stolen, and making it harder to kill whatever killed you). The game intro set the perfect tone for the game:

Then along came Diablo II. Instead of being confined to maze-like dark dungeons, you were thrown into open, bright worlds full of creatures that posed less of a real challenge. The music was unremarkable, and failed to add to the atmosphere. Worst of all, you felt POWERFUL. This was no longer about a mad heroic journey – this was just hack and slashing. This is the same reason why Amnesia is genuinely scary, while Doom 3 and Dead Space are nowhere near as much – you just have too much power in those games, compared to the defenseless protagonist of Amnesia. But Diablo II still tried to be dark and horror-ish, and in many senses, it succeeded. The cinematics certainly preserve the feel of the original game. Let’s look at the intro:

And then comes Diablo III. It took the same changes Diablo II had done, and amplified them. I see no hint of horror in this game. All I see is generic adventuring. This feels like D&D. This feels like Torchlight. This feels like WoW. It feels like many things… unfortunately, Diablo is not one of them. Here’s the intro:

The progressive change of mood in those intro videos is fairly telling of what’s going on with the series, I’m afraid.

Story

This is where the game really stroke a nerve. I’ve been under the impression that all of Blizzard’s writers were either fired or driven to incompetence after the release of the original StarCraft. From Brood War onwards, the quality of the text and storylines has decreased significantly, and Diablo III is the most telling example.

Diablo I had little in-game plot. You just returned to Tristram, which has been overran by a mysterious dark force coming from the depths of the local church. As you slowly descended through its dungeons, you got a few more hints of what was going on, until you finally came face-to-face with the Lord of Terror himself, Diablo. But that’s not to say that it was bad – first of all, it strengthened the atmosphere of mystery in the game. Second, what little was told was superbly well written. Third, the manual itself had excellent backstory, explaining the events preceding the fall of Tristram in a compelling and believable way. Here’s a sample of in-game dialogue:


It’s said that Tolkien was once asked why didn’t he wrote about all those distant mountains he would talk about on his books. His reply was supposedly “I could talk about them, but then I would need even farther mountains”. Part of making the world believable is to have a lot more to it than just what’s immediately visible to the player. The team behind Diablo I understood that well… but in Diablo II, they made a terrible mistake. They systematically went through the backstory in the Diablo manual and, as if holding a checklist, made sure that everything they encountered there would be directly relevant to the story of Diablo II. Andariel, Duriel, Mephisto and Baal. Archangel Tyrael. Tal Rasha. Even Izual and the Hellforge. Very little was added to make up for the losses, and what little it was was of far inferior quality. The game world had completely lost all its depth. A world in which you can see for yourself EVERYTHING ever mentioned in any form of Lore might be suitable for a massive MMO where you can actually travel the whole world – but just makes everything seem very shallow when you stride across a handful of small towns and just happen to run into every legend there ever was. Dialogues were plentyful, but very bland. In every way, they had managed to lose the magic of the game’s story. In a way, it felt like a fan game – eagerly consuming any elements it could find from canon, while making very predictable and boring additions.

When I thought that it couldn’t get any worse, Diablo III managed it. Do you remember how, in Diablo, your character (now called “Aidan”) was the elder son of King Leoric? No? Well, neither do I, but it has been retconned to be that way by Diablo III. Very peculiar that nobody in Diablo recognized him as such, and that he would say “Rest well, Leoric, I will find your son!” after slaying his undead body. The installer presents an avalanche of slightly tweaked events, written with pompous adjectives and going as far as pausing mid-sentence to name Tyrael’s sword – as if that had ever been relevant. Do you remember Adria’s daughter, Leah? You know, Deckard Cain’s niece? No? Also, people sure do like Tristram, going ahead and building a “New Tristram” right next to where one of the three Prime Evils came back not so many years ago (I assume so, anyway, as Cain was already old in the first game and has managed not to kick the bucket yet). Speaking of Tristram, can we decide whether the whole incident took place in its church (D1), monastery (D2) or cathedral (D3)? But now I’m stepping into nitpicking territory – although this sort of inconsistency only shows how little they care about making it coherent.

Gameplay

I would normally argue that gameplay is the most important thing in a game, but Diablo III makes me wonder to what degree is that true. There’s nothing really WRONG with the gameplay – it has been simplified from Diablo I and II, certainly, as it is now much more forgiving and “casual-friendly”, but that doesn’t bother me too much. I prefer more complex RPGs, but this is hardly what’s stopping me from playing.

It does have to be said that the new system does make me feel like a versatile, powerful character, which, as I mentioned before, is the exact opposite of what a Diablo character should ideally feel like. But I suppose that role-playing a cool and powerful character that spits pseudo-witty lines to coward mayors is very popular with most players, and setting be damned.

There is one thing, however, which is unforgivable. In an attempt to stop cheating and piracy, Blizzard has forced everyone to ALWAYS be playing online, through their servers. If their servers are down, or if your connection is unstable, or if you’re in an airplane – you can’t play. It doesn’t matter if you just want to have some solo fun – you’re STILL playing multiplayer, for every technical purpose. This is the worst form of DRM, and the only reason why anyone is willing to put up with it is because of Blizzard’s history of excellent games. Unfortunately, as of late, I can’t even say that they still make excellent games. Speaking of Blizzard’s history of DRM, do you remember how Diablo I would let you install a semi-demo copy (“Spawned version”) on a friend’s computer, so he could play with somebody who had the full version, subject to only a few limitations? And how the game didn’t even have a CD-key? From that to THIS? How long you’ve come, Blizzard.

I might not buy another Blizzard game, but this hardly matters – I’m sure their profits will continue to escalate. By making “popular art”, they sacrifice the exquisite quality that their games always had, but profit even more. Jonathan Blow said that you shouldn’t try to do what the audience wants – instead, you should make something great, and the audience (or, at least, some of it) will want that even more than what they originally thought they wanted – and I agree with that sentiment. I don’t think that many others do, however.

A shame, too. I WANTED to love this game.

“Fourteen years were not enough” / “14 anos não foram o suficiente”

A while ago, there was a discussion in a mail group composed of members of the Brazilian videogame industry, regarding its perceived lack of progress when compared to many other countries – the case in point was that even Iran was showing more impressive results than us. I sent the following email, and since people have since come to tell me that they really enjoyed the text and wanted to publish or spread it, I’ve decided to make it available here on the blog, both the original in Portuguese and an English translation.

English Translation

Here follows my opinion. I don’t presume to assert it as fact, but to me it seems like a realistic picture of the situation.

There might be a lack of governmental incentive, but that, in my opinion, is no excuse. We have examples of games which had literally millions of Reais spent on them, and at the end had a catastrophic or disappointing result. There are many examples of games with less exorbitant budgets – merely adequate – that have failed anyway. And some with a low budget that worked (and a few others that failed). I believe that examples of all categories will come to your minds.

Clearly, the financial matter is not the only obstacle. From what I can see, there’s a serious problem of arrogance in the Brazilian industry. It’s NOT generalized, and there ARE exceptions, but it seems far too common for a team without the least experience in developing games to try to bite more than they can chew. There’s nothing wrong in having a little ambition, but one should be fully aware of the enormous difficulties involved in the game development process. This most common case is of the person who has never developed a game, but has read two blogs and a book (sometimes, not even that) and considers himself a professional game designer. Like every other art form, game design is a skill that needs practice and is refined after many years. This kind of belief (where one considers himself an expert in a topic in which he’s a beginner) is a known psychological effect: http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect

What do I propose? I believe that the best solution is for teams to think small, and make simple games, at least at first. This is important for a number of reasons:
- To get experience;
- To be able to experiment, without the fear of sinking a big project;
- To have Brazilian games on the market, which is useful not only to inspire the remainder of the community, but also to start the flow of money and show them what we can do;
- Understand that it’s always harder than it looks.

And it truly is harder than it looks. Look at the “top” indie games. Note that all of them have a simple concept, and yet took a very long time to get there. Now imagine how much harder it would have been, were they complex ideas. Braid, for example, can be roughly described as a “puzzle game with simple physics and a basic platform movement, where you can go back in time”. Sounds easy, no? It took three years to be developed, and cost around 180 thousand dollars, paid by Jonathan Blow himself. It’s worth remembering that he had 16 years of programming experience, and wrote for game magazines, among other qualifications. Similar cases are seen in World of Goo, Super Meat Boy, Aquaria, etc. If your idea is to “make an MMO” or “make an FPS” or something even more complicated, stop and think about it. It’s not impossible, of course, but I consider it naïve to pick this path without a team that has obtained a lot of experience in successful games. Especially the Game Designer.

Currently, the situation is a bit sad. There are a few Brazilian games ranging from OK to Good available commercially (e.g. Eversion, Freekscape). I can’t think of any that I consider to be truly excellent. Outlive was mentioned on this thread, and indeed it had much potential, but its execution was underwhelming.

However, the future does not seem so bleak. With each passing day, I see people starting less greedy projects, doing it more for the love for the craft, truly studying – not merely trying to be famous like an “awesome guy from the industry”. iPhone’s rise might have helped, making it more “acceptable” to develop small and fun games. I hope that, through this path, our industry can learn what makes a good game tick (in the same way that Japan and the United States learned decades ago, at the time of the old consoles) and then use that knowledge to make true brazilian masterpieces.

I have some fear about this “cultural” concern in our games. I believe that the best games transcend the culture of the country that originated them, and speak directly to human nature, without the need to appeal to national identification. I’m no fan of Taikodom, but one thing that it did right was to deal with that tactfully – instead of throwing Brazilian culture in your face, there are mere subtle references, e.g. “Santos Dummont Station”. Other games take a less subtle path, and try to create a “culturally rich” experience… which ends being almost ridiculous. Remember that Demon’s Souls is Japanese, Heavy Rain is French, Minecraft is Swedish, The Path is Belgian (and I don’t imply that I like The Path), Darwinia is British, Crysis is German, Eve Online is Icelandic, Limbo is Danish…. and none of those felt the need to have a distinctive element of their countries visible. Why is there this need in Brazil? (Perhaps I am mistaken, but it DOES seem like a recurring theme.)

My advice? Make Flash games. Make iPhone games. Make cell phone games. Join the Global Game Jam (we had lots of fun Brazilian games last year – not bad, considering the mere 48 hours to develop them). Don’t take those things as “inferior work”, a mere obstacle on your path to glory; Face them as opportunities to experiment with gameplay, to learn WHAT is a real game, and later, YEARS later, bring your ambitious dreams into reality. Read books. Join forums. Exchange ideas. Your gameplay ideas are NOT as genius as you think they are: don’t make secrets out of them. If you’re a programmer, implement games and engines. If you’re a game designer, learn to use Game Maker or Construct and get to work.

I wrote my first game in 1997, in Klik & Play (probably the first Game Maker-like tool). Years later, I learned C, and then C++, but ever since that first game, I never stopped playing with implementing games. I’ve released several on different events, but the great majority lies unfinished – they ended up being mere experiments. Today I work on the field, and develop games professionally, for the casual market. Fourteen years developing games were not enough for me to consider myself an expert on the field – and another fourteen won’t be, either. Yet, I want to be able to keep practicing and studying, both because I want to improve, and because I love it. This is the least I expect of myself, and the least I expect of you. Dedicate yourselves and you shall have success. Just don’t expect to achieve it without much sweating.

Good luck and sorry for the long rant!

Original (Português)

Segue minha opinião. Não tenho a presunção de afirmar que é fato, mas me parece ser um quadro realista da situação.

Pode até haver uma falta de incentivo governamental, mas isso, na minha opinião, não serve de desculpa. Nós temos exemplos de jogos que tiveram literalmente milhões de reais gastos neles, e no final ou tiveram um resultado catastrófico ou decepcionante. Há vários outros exemplos de jogos com verbas menos exorbitantes – meramente adequadas - e que ainda assim fracassaram. E alguns com verba baixa ou zero que deram certo (e mais outros que deram errado). Acredito que exemplos de todos os casos surgirão na mente de vocês.

Claramente, a questão financeira não é o único empecilho. Pelo que eu observo, existe um problema sério de arrogância na indústria brasileira. NÃO é generalizado, e EXISTEM exceções, mas me parece ser muito comum que uma equipe sem a mínima experiência em desenvolvimento de jogos tente abocanhar mais do que conseguem. Não existe nada de errado em ter um pouco de ambição, mas deve-se ter plena consciência das enormes dificuldades envolvidas no processo de se desenvolver um jogo. O caso mais comum é o da pessoa que nunca desenvolveu um jogo, mas leu dois blogs e um livro (as vezes, nem isso) e se considera o game designer profissional. Como toda forma de arte, game design é uma habilidade que se pratica e se refina ao longo de muitos anos. Esse tipo de crença (onde a pessoa se considera ótima em um tópico na qual ela é iniciante) é um efeito psicológico bem conhecido: http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect

O que eu proponho? Acredito que a melhor solução é para as equipes pensarem pequeno, e fazer jogos simples, pelo menos a princípio. Isso é importante por vários motivos:
- Ganhar experiência;
- Poder experimentar, sem medo de errar em um projeto gigantesco;
- Ter jogos Brasileiros no mercado, o que serve não apenas para inspirar o resto da comunidade, como também para começar um fluxo de caixa e mostrar que podemos fazê-lo;
- Entender como é sempre mais difícil do que parece.

E realmente é mais difícil do que parece. Observe os Indie “top”. Note que todos têm um conceito bastante simples, e ainda assim levaram um tempo enorme para chegar lá. Agora imagine o quão mais difícil seria se fossem idéias complexas. Braid, por exemplo, pode ser descrito (grosseiramente) como “um jogo de Puzzle com física simples e movimento básico de plataforma, onde você pode voltar no tempo”. Parece fácil, não? Levou 3 anos para ser desenvolvido, e custou cerca de 180 mil dólares, pagos do bolso do próprio Jonathan Blow. Vale lembrar que ele tinha 16 anos de experiência com programação, e escrevia para revistas de jogos, dentre outras qualificações. Casos similares são vistos em World of Goo, Super Meat Boy, Aquaria, etc. Se a sua idéia é “fazer um MMO” ou “um FPS” ou algo ainda mais complexo, pare e reflita sobre isso. Não é impossível, claro, mas eu acho ingênuo escolher esse caminho sem uma equipe que tenha obtido bastante experiência em vários jogos que já tiveram sucesso. ESPECIALMENTE o Game Designer.

Atualmente a situação é um pouco triste. Existem alguns jogos Brasileiros de qualidade OK a Boa disponíveis comercialmente (e.g. Eversion, Freekscape). Não consigo pensar em nenhum que seja realmente excelente. O Outlive foi citado nesta thread, e realmente é um jogo que tinha muito potencial, mas a execução deixou muito a desejar.

Entretanto, o futuro não parece tão ruim. Cada vez mais, eu vejo pessoas começando projetos menos gananciosos, fazendo aquilo pelo amor à arte, estudando de verdade - não apenas querendo aparecer como um ”cara foda da indústria”. A ascensão do iPhone talvez tenha ajudado, tornando-se mais “aceitável” desenvolver jogos pequenos e divertidos. Espero que através desse caminho, nossa indústria possa aprender o que faz um jogo ser bom, (da mesma forma como o Japão e os Estados Unidos aprenderam décadas atrás, na época dos consoles antigos) e depois usar esse conhecimento para fazer verdadeiras obras primas Made in Brazil.

Tenho um certo receio quanto a essa preocupação ”cultural” nos nossos jogos. Acredito que os melhores jogos transcendem a cultura do país de onde originaram, e falam diretamente com a natureza humana, sem precisar apelar à identificação nacional. Não sou fan do Taikodom, mas uma coisa que ele fez bem foi usar isso com tato – ao invés de ser uma coisa brasileira jogada na sua cara, há meras referências sutis, e.g. ”Estação Santos Dummont”. Outros jogos pegam um caminho menos sutil, e tentam criar uma experiência “culturalmente rica”… que acaba sendo quase ridículo. Lembre-se que Demon’s Souls é Japonês, Heavy Rain é Francês, Minecraft é Sueco, The Path é Belga (e não implico que eu goste de The Path), Darwinia é Britânico, Crysis é Alemão, Eve Online é Islandês, Limbo é Dinamarquês… e nenhum desses sentiu a necessidade de ter um elemento distintivo de seu país evidente. Por que então há essa necessidade aqui no Brasil? (Talvez eu esteja enganado, mas me parece um tema recorrente.)

Meu conselho? Faça jogos em Flash. Faça jogos para o iPhone. Faça jogos para celular. Participe do Global Game Jam (tivemos vários jogos Brasileiros bastante divertidos ano passado – nada mal, considerando-se as meras 48 horas para desenvolvê-los). Não encare essas coisas como “trabalho inferior”, um mero obstáculo no caminho da sua glória; Encare essas coisas como oportunidades de experimentar com gameplay, de aprender O QUE é um jogo de verdade, e depois, ANOS depois, bote seus sonhos ambiciosos na prática. Leia livros. Participe
de fóruns. Troque idéias. Suas idéias de gameplay NÃO são tão geniais quanto você acha que elas são: não guarde-as como segredo. Se você é programador, implemente jogos e engines. Se você é game designer, aprenda a usar Game Maker ou Construct e bote a mão na massa.

Eu implementei meu primeiro jogo em 1997, no Klik & Play (provavelmente o primeiro programa estilo Game Maker). Anos depois, aprendi C e depois C++, mas desde aquele primeiro, eu nunca parei de brincar de implementar jogos. Lancei vários em diversos eventos, mas a maioria esmagadora nunca foi terminada – acabaram sendo apenas experimentos. Hoje trabalho com isso, e desenvolvo jogos profissionalmente, para um público casual. 14 anos desenvolvendo jogos não foram o suficiente para que eu me considere um expert na área – e mais 14 não serão. Ainda assim quero poder continuar estudando e praticando, tanto para continuar a me aperfeiçoar, mas também porque eu amo fazê-lo. Esse é o mínimo que eu espero de mim mesmo, e é o mínimo que espero de vocês. Dediquem-se e vocês terão sucesso. Só não esperem alcançar o sucesso sem muito suor.

Boa sorte e desculpem o rant prolongado!

SPJam 2011 – Down Goes the Phoenix

Last weekend, I was in São Paulo with my friends at Studio Miniboss to join the first edition of SPJam. The event was lots of fun and a success, with almost a hundred entrants and over 20 digital or board games. Our entry, made in the 48 hours of the event, is “Down Goes the Phoenix”:

It’s a horizontal scrolling shoot ‘em up on which you play with a Phoenix. As the game progresses, your phoenix grows older as the bar on the bottom fills. Shooting or getting hit lowers the bar. When the bar is full, you’re a mature phoenix and you can reincarnate – doing so resets your power-ups, but increases your score multiplier and kills all enemies, as well as removing the fog that slowly descends upon the screen, obstructing your view. As an arcade game, the objective is to obtain a high score, and knowing the right time to reincarnate is a critical point.

The game is written in C++11 in my own engine. I was the programmer and Amora, Santo, bitmOO and Marina Val were the visual artists. The music was composed by Rafa Miranda, and we had some game design help in the first day from Iko. Thanks to everyone involved!

The SPJam version of the game can be downloaded here: http://higherorderfun.com/stuff/DownGoesThePhoenix.zip (Win32 binary). This is the exact version made in those 48 hours, save for minor bug fixes.

Best of Game Development Videos and Presentations

Here’s a list of my favourite videos and presentations on several subjects related to game development. I strongly recommend every single video listed below, at least those that match your area of expertise.

If you can think of any good videos that I missed, please leave a link on the comments. I will update the post with any videos that I enjoy.

Game Design

Programming & Technical

C++

(Most of the following are highly technical and specific, but I recommend the first presentation, “Why C++?”, to every programmer.)

Religion in MMOs: Proposal of an Experiment

Here’s an experiment idea:

It’s common in RPGs to have some sort of religion system, generally with a multitude of deities which are more-or-less at peace with one another, and whose followers typically do not try to murder each other at the first opportunity. Sometimes, you can offer donations to churches to get some bonuses, to karma or luck or whichever is applicable. Knowing the right time to pray is even a key gameplay element in Nethack.

This sort of behavior is, of course, also observed in the real world – people will often pray and make donations seeking to get something in exchange. The difference is that, in the game world, they actually get something out of it. But they don’t have to.

Consider an MMORPG with a religion system (whether it’s monotheistic or polytheistic is not important), and a series of temples spread around the world. Players can visit those temples, and consult a list of services that the temple can perform, along with their costs. Perhaps a player can get a 5% extra to-hit bonus for a donation of 100 gold. For 500 gold, he will get a +5% bonus chance to find rare items… Or so the temple claims. The player spends his hard-earned coin, and the game says something along the lines of “you feel lucky”. And nothing changes.

How many people would believe that? Would anyone conduct a systematic, scientific in-game research to evaluate how much of a difference said donations would provide? Even if some “skeptic” told other players that it’s a hoax, would they believe it? Perhaps they’ve donated once, and found a very rare item afterwards. Their minds would be making connections. What if this “truth” is spread in forums, FAQs and wikis… perhaps in the game manual itself? After months investing money in those things, wouldn’t the player feel even more compelled to believe that he wasn’t being cheated all along?

The idea could be developed further and let players take on the role of priests, although a mechanic would have to be designed to allow them to mess with the system without easily exposing its truth. For example, perhaps there’s a holy book defining how those bonuses work, in a cryptic (and possibly self-contradicting way) and leave it to the priests to interpret it and write the list of services. Temples that offered so much that it was visible that it didn’t work would lost trust, and temples that offered too little wouldn’t be able to compete. Some form of selection would eventually choose the best religion.

To my knowledge, no game has ever implemented such a system (if you know of one, please mention it on the comments). If it works as intended, analysis of player’s reactions to the system (and to the discovery that it was all their imaginations, if the developers ever decided to Word of God (pun unintended) it) could be very enlightening. Would that change how they perceive religion in the real world? Would such a study have any impact on understanding the psychology of belief? Perhaps not. But, if nothing else, it would be an interesting topic to bring up in a religion discussion.

Multi-thread OpenGL texture loading

Those who have used OpenGL are probably aware that you can only invoke OpenGL procedures for a given context on the thread that currently owns it – usually, the main thread. This leads many programmers to assume that OpenGL is strictly single-threaded, and that no loading can be done on the background, inside some loader thread. This is not the actual case, and it’s actually fairly simple to work around this.

The key to multi-threaded OpenGL is in creating multiple contexts that share data between them. On Windows, it is done with the wglShareLists() procedure. On X and Apple APIs, it can be done during context creation (glXCreateContext() and aglCreateContext(), respectively). It boils down to creating a second context for the loader thread, and setting it to share data with the main context. This way, all data loaded on the second context will be available on the main one – you can just create a texture normally on the loader thread, and then glBindTexture() it on the main thread, for example.

On Windows/C++0x, the code looks like this:

void startLoader(HWND hwnd)
{
	// Assuming that this is the main thread
	HDC hdc = GetDC(hwnd);
	HGLRC mainContext = wglGetCurrentContext();
	HGLRC loaderContext = wglCreateContext(hdc);
	wglShareLists(loaderContext, mainContext); // Order matters

	boost::thread([=] () {
		wglMakeCurrent(hdc, loaderContext);
		runLoader();	// Your method for loading textures
		wglMakeCurrent(nullptr, nullptr);
		wglDeleteContext(loaderContext);
	});
}

Most APIs (such as Allegro, SDL, wxWidgets, etc) will provide you with a simple method of retrieving the window handle, which is all that you require to call the above procedure.

Note that you could create the context and share the lists inside the loader thread, but wglShareLists() must be called BEFORE anything is done on the main context, so the safest way is to do it on the main thread (otherwise, the new thread could take a while to run and be too late to do it).

IMPORTANT! I have observed that, on some cases (Windows 7 64, NVIDIA 320M), attempting to use a texture after it has been created (via glGenTextures()) but before its data finished uploaded (in this case, via glTexSubImage2D()) resulted in the texture being corrupted, and remaining corrupted even after it was uploaded. This will happen even if you wait for glTexSubImage2D() to return before using it on the main thread, since OpenGL is asynchronous. To avoid this problem, make sure that you glFinish() the loader thread before you attempt to use any textures initialized there.

Programming is Art

Programming is a subject most often lumped in with engineering or science, and there are countless books dedicated to writing better code, but is this a good approach? To me, it seems much more reasonable to understand it as a form of art.

Does it matter? Yes, I think it does. I believe that this distinction is important, and I believe that many other programmers agree with it. I also think that it affects how we view and hire programmers, and, ultimately, it greatly influences the productivity of software development in many companies.

Read the full article »

If programming languages were religions…

I originally wrote this article in December 15, 2008, and posted it on the Aegisub blog. I’m re-posting it here for archival purposes.

“If programming languages were religions”

(Inspired by “If programming languages were cars“)

C would be Judaism - it’s old and restrictive, but most of the world is familiar with its laws and respects them. The catch is, you can’t convert into it – you’re either into it from the start, or you will think that it’s insanity. Also, when things go wrong, many people are willing to blame the problems of the world on it.

Read the full article »

Global Game Jam 2011 – Planetary Plan C

Last weekend, the Global Game Jam 2011 was held all over the world, attracting some 6500 people into a challenge to develop a game with the theme of “extinction” in a mere 48 hours.

I was joined by six incredibly talented people (and a few other friends who were supporting us) to make Planetary Plan C, our entry for the event. I was the only programmer, there was one musician, and, for the other five, each took on a mix of the roles of illustration, animation, design, concept art, and story.

Planetary Plan C

For our efforts, we were rewarded with the title of being one of the 10 winners of the GGJ11 according to Gamesauce. It was an incredibly rewarding event, and I highly recommend every aspiring game developer to join such competitions at least once.

The game was written using C++ on an engine that was custom-written by myself, based on SDL and OpenGL. All of the art, music and code (except for the engine) was produced during those 48 hours.

The team:

Pedro, Amora, Irene and Rafa from Studio Miniboss;
Karen from Vortex Studios;
Henrique from Sulistas;
and myself.

A huge “thank you” to everyone involved!

Understanding the Game Main Loop

Video games are simply ordinary software – there’s nothing intrinsically special about them. However, they SEEM to behave in a very different way from your ordinary everyday applications – so much that many experienced programmers are at a complete loss when faced with the task of developing a game from scratch. This difference is mostly caused by game’s close ties to their main loop. In this article, we’ll examine what is the main loop, how it works, and why it’s important.

A simple model

How simply could we model a computer game? Let’s start by separating the game in two parts: the data inside the computer, and everything outside the computer. This might seem like a strange thing to say, but remember that games are, first and foremost, interactive software. So, outside the computer, we have (at the very least) the player. Inside the computer we have all sorts of data, but the most important is what we call the game state: it contains all the dynamic information of the game: the position of the player, monsters and camera; the current time; the score – in essence, everything that changes with time.

A computer game can then be understood as a system in which those two entities – player and game state – interact with each other according to a specific pattern of rules. The player inputs data into the system, and the system uses the game state to generate output to display to the player. This is not very different from ordinary applications, in which e.g. a click (input) might cause a dialog to show up (output). The difference is how that behaves in respect with time.

The Game Loop

Most applications are developed in a reactive way – your program just sits around waiting for the user to click something, and then it does something in response. There is a main loop behind your application as well, but it’s not important – it’s abstracted away. With games, your code is constantly being invoked, even in the absence of user input.

The pseudo-code for a video game will often look like this:

void GameClass::main() {
    init();
    runMainLoop();
    deInit();
}

The main loop looks something like this:

while (running) {
    processInput();
    updateGameState();
    drawScreen();
}

First, it reads input from the user and stores it somewhere. Here, it will check the keyboard, gamepad, plastic guitar and network message queues – basically, it will collect all information from the outside world.

After that, it will use that information to update the game state – depending on what conditions we have, they will have different results. For example, on the menu screen, detecting that the “down” arrow got pressed might increment the “currently selected menu item” variable, but the same input while on the game might instead trigger the “set player as moving down” flag. Note that the world update is invoked even if the user didn’t perform any input. This is a very important property of most video games.

Lastly, it will collect the current game state data to generate the output – it will figure out where the player and camera and everything else are, and generate an image to display on the screen. A more complicated game will also have to deal with other forms of output – audio and network, for example.

A More Sophisticated Main Loop

The loop pseudo-code above suffers from a major flaw: it will run at unpredictable speeds – on fast machines it might run thousands of times per second (which would be a waste), and on slow machines it might run on unacceptably slow speeds – perhaps only five updates per second or so. Besides the obvious issues, this makes the game much harder to program – it’s much easier to write your game logic when you know that you’ll have a fixed number of steps per second.

Consider this: the player presses the right arrow, and you store a flag containing that information. Now, on every step, regardless of any player action, you’ll move the player to the right by 1 unit in the game state (which, let’s say, corresponds to 1 pixel on the screen). If the game runs at 5 Hz (that is, 5 updates per second), the player will move VERY slowly. If it runs at 5000 Hz, he’ll be out of the screen before you can even see it!

A possible solution to this is to calculate the real time elapsed between two steps and use this information during the step. In practice, however, this makes the game development much harder and error prone. It will also make networking a true nightmare, and will essentially make reliable behavior (e.g. replays) impossible.

A much better solution is to fix the rate at which your game performs its updates. Most modern games use an internal clock of 60 Hz or 30 Hz. Let’s assume 60 Hz for our example. This means that, 60 times per second, your game will check the input from the player, update the game state, and try to display something on the screen. But how do we control that?

First, let’s consider the case of a very fast computer. In this case, before each iteration of the main loop, we’ll check if it’s time for the update. If it isn’t, we’ll simply wait (preferably yielding the time slice back to the operating system), without doing any processing.

In the case of a slower computer, things are trickier – we can’t skip on updating the game state, or the game will run in slow motion, so we must sacrifice the output – the screen rendering. On most games, screen rendering is the slowest part of the pipeline, meaning that most games WILL be able to run at 60 Hz given enough sacrifice on graphics. If not, then the game will be way too slow, and we have no choice but ask the player to get a better computer.

In pseudo-code, our new algorithm now looks somewhat like this:

while (running) {
    if (isTimeToUpdate()) {
        processInput();
        updateGameState();
        if (hasTimeToDraw()) drawScreen();
    } else {
        waitUntilItsTime();
    }
}

It’s simple, but it’s very similar to real game loops found in real games.

The Foundation

At this point, it should be clear that the vast majority of the game code will run inside the main loop – in a simple game, everything except for initialization and deinitialization. Also, that code is now separated in three functions: processing input, updating the game state, and rendering the screen. Since all three of them are controlled by the loop, it’s the foundation block of every game.

Having this foundation, your task of implementing a game has been reduced into three simpler and relatively independent tasks. The input you collect will be used on the state updating stage, and the state created by that step will be used to generate the output to the user, but they are each their own logically distinct operations, and how they interact with each other is now clear.

If you understand the topic discussed in this article, then all you have to figure out in order to make a (very) simple game is “how to read user input?”, “how to draw stuff on the screen?” and “how to keep track of my state and update it?”. None of those are, at a basic level, difficult, but they might be different from what programmers are used to coding.

On the next article, we’ll try to figure those things out and write an extremely simple real-time game using those concepts.