The Beetle That Carried the Light

I. The Light Before the Word

Before the first pyramid, before the first word was carved into stone, there was only Ra’s light — endless, indifferent, spilling over sand and river alike, asking nothing and giving no direction. Light without a path is just light. Someone, something, had to move it.

Thoth kept the words. Every incantation ever spoken, every spell ever written in the sacred script, lived in his keeping — and no two were ever quite the same. A farmer’s charm for rain was not a priest’s rite for the dead, was not a king’s decree carved to outlast his own bones. Thoth cared nothing for which words a person chose to speak. He only kept them, infinite and unjudging, waiting for a voice.

And between the two — between the light that meant nothing until it moved, and the words that meant nothing until they were carried — there was Khepri.

He was small. He owned no light of his own, and spoke no incantation that was his. He simply rolled — a plain, dark shell against a rising sun, pushing forward whatever the morning gave him to push, asking no tribute, keeping no secrets, caring not at all whether what he carried belonged to a king or a farmer. Each dawn was the same to him: something arrived that needed carrying, and he carried it.

II. What a Beetle Is For

That’s also, more or less, what a game engine is for.

A little while back I wrote about the ship that became sunlight — the engine underneath, the part that actually knows how pixels get on screen, what happens when two things collide, what a tile map even is. I said then that sunlight wasn’t the end of it, that it had already become the rendering backend for something else I was building on top, and that I’d leave what that something else turned out to be for later. This is later.

Scarab turned out to be almost nothing, on purpose.

Not nothing in the sense of unfinished — nothing in the sense that it doesn’t own a single line of game logic anywhere inside it. It’s a thin C++17 shell around sunlight: it opens the window, loads whatever Lua you hand it, and calls straight into a handful of functions that script defines — an on_update called every frame, an on_load_stage when a stage begins, and so on. Everything that makes one game different from another — the ship, the aliens, how a level unfolds, what happens when you die — lives entirely in that Lua, calling back into a few hundred small verbs Scarab exposes: acquire a sprite, load a map, play a sound, start a timer. You could point it at a vertical shooter one day and a puzzle game the next, and it would never know the difference, because it isn’t supposed to.

The smallest possible game Scarab will actually run looks like this, in full:

-- main.lua — the entire "game"

function on_load_stage(stageId)
    return true -- Scarab has no opinion on what a stage means; Lua claims it
end

function on_update(dt)
    draw_text("Hello, Khepri", 10, 10, 20)
end

sp_wait(1) -- queue at least one command, or the beetle refuses to roll at all

That’s it. No class to subclass, no engine object to instantiate, no build step of its own — one file, two callbacks C++ will call back into, and a scatter of verbs like draw_text standing in for the whole rest of the engine underneath. A whole game, script and every asset it needs, can travel as a single sealed .zip — Scarab reads out of one exactly the way it reads out of a loose folder on disk, no difference at all from the inside. One incantation, whole, ready to be handed to anything that knows how to carry it.

That’s Khepri’s whole trick, really. He never asked what he was rolling. He just rolled it.

III. Not a God’s Throne Room

Every pantheon has a jealous god somewhere — one who guards his own light behind ritual and tribute, who’ll carry your incantation only if it’s written in his own priesthood’s tongue, and who charges for the privilege of being carried at all. He’s not evil, exactly. He’s just decided that what he offers is worth owning, and that ownership means someone else has to ask permission.

Scarab doesn’t ask permission for anything, and it doesn’t sell what it doesn’t have to sell. It’s released under the zlib license — about as close to “take it, use it, sell your own game built on it, just don’t pretend you wrote the engine yourself” as a license gets. There’s no tier where the real features live behind a paywall, because there’s nothing in here worth locking away in the first place: no game logic, no assets, nothing proprietary. What you get is a beetle, not a god’s throne room.

The clearest place this actually shows up is the newest thing I’ve built into it: a way to encrypt a game’s own files, so a Lua script and its assets can be bundled up tight enough that a casual look won’t just hand them over.

The whole workflow is three commands, from a source tree to a sealed, encrypted archive only your own build can open:

# 1. Generate a key of your own (32 random bytes, hex-encoded) and
#    build scarab with it baked in
python3 -c "import secrets; print(secrets.token_hex(32))"
cmake -B build -S . -DSCARAB_CONTENT_KEY=<the 64 hex characters just generated>
cmake --build build -j 4

# 2. Point --pack at a game's own source directory
echo '{ "source_dir": "/path/to/my_game_source", "output": "/path/to/my_game.zip" }' > pack-config.json
./build/scarab --pack pack-config.json

# 3. Run it back - only this exact build, with this exact key, can open it
./build/scarab /path/to/my_game.zip

Nothing exotic underneath: a 256-bit key handed to CMake at build time, a small JSON file telling the packer which folder to seal and where to write the result, and the same executable used both to seal it and to open it again. Anyone who builds their own private copy this way — with a key of their own choosing, kept somewhere only they can see it — gets a bundle nobody else’s build can read.

The tempting version of this feature — the one a jealous god would build — bakes in one secret key for everybody, ships it quietly in every public download, and lets you assume you’re protected. Scarab does the opposite on purpose: the key every public download actually ships with is worked out fresh for each release, from a private formula, different every time — and still, every one of those downloads prints out loud, every single time you run it, that this particular key was never meant to be private, and that anyone willing to spend five minutes with a disassembler can pull it straight out of the binary. If you want the real thing, you build your own copy with your own key, kept where only you can see it. Nothing hidden, nothing implied. The idol lies by omission; Khepri just tells you what he is.

IV. Two Priesthoods

None of this works if Scarab tries to own everything itself, which is why it doesn’t even try. sunlight is its own project now, with its own repository, its own releases, its own author’s-worth-of-decisions that Scarab has no say in — and that separation isn’t a limitation, it’s the whole point. When something breaks at the seam between them, neither side can just reach over and fix the other’s code. What actually happens is closer to two priesthoods comparing notes: a precise account of exactly what’s wrong, checked line by line against the real source before a word of it is sent, handed across, and answered with a real fix and a real test — not a favor, an actual collaboration between two things that owe each other nothing.

A multi-file bitmap font — the kind that’s a text file plus a separate image, rather than one neat file — refused to load through Scarab at all, and for a long time nobody could say why beyond “it just doesn’t.” Every resource Scarab loads — a texture, a sound, a script, that same font — is meant to go through one shared reading point sunlight maintains, precisely so a loose folder of files and a single sealed .zip get treated exactly the same way underneath. The whole project is just a folder with one small manifest at its root:

// project.json
{ "main_script": "src/main.lua" }
# Run it straight from the loose folder...
./scarab project.json

# ...or seal the exact same folder into one file and run that instead
./scarab --pack pack-config.json
./scarab my_game.zip

main_script resolves relative to project.json‘s own location, not wherever scarab happens to be run from — so the folder above works untouched whether it’s sitting loose on disk or packed whole into my_game.zip. Neither main_script nor a single line of the game’s own Lua needs to know or care which of the two it’s actually running from; that’s the shared reading point’s whole job, not something each resource load has to handle for itself.

Tracing the bug all the way down showed the image half of the font quietly slipping past that shared point instead of through it — asked for by a path that had grown a stray ./ in front of it, which the reader underneath rejected without a word. No error, no warning, just a fallback font appearing where the right one should have been, and nothing in the logs to say a substitution had even happened. That got fixed, verified, shipped.

And then it broke again, in a way the first fix couldn’t have caught: the font’s own text half — the part that isn’t an image at all — turned out to have never been wired into that shared reading point in the first place. It had simply never been asked to matter, because on every machine anyone had tested it on, the real file happened to be sitting right there on disk regardless, quietly answering a question nobody knew they were still asking wrong. It only broke once a game shipped as one sealed bundle with nothing loose left lying around to rescue it — which is, not coincidentally, exactly the situation Scarab exists to make normal. Fixed the same way as the first: found for real, described precisely, handed across, verified independently by both sides before anyone called it done.

Twice, the failure was the same shape — something silently standing in for what should have been there, saying nothing about it. Khepri doesn’t do that. When he can’t carry something, he stops, and he says why.

V. Another Dawn

Ra didn’t stop making light because Khepri rolled it once. Tomorrow, there’ll be another dawn, another stretch of sand needing exactly the same small labor as today’s — and Khepri will be there again, not because the work was left unfinished, but because that’s simply what the work is. It was never going to be a monument. It was always going to be a practice.

Scarab’s first real version shipped with just enough to actually run a game — a window, a way to load Lua, the bare minimum a story needs before it can move at all. Every feature since has been added because some actual game needed it, never because a roadmap said so. As of v0.1.13, that list looks like this:

  • Sprites — texture-backed, animated, pooled by handle
  • Collision — shape-based detection between sprites
  • Tile maps — Tiled (.tmx) map loading and per-layer rendering
  • Camera — scrolling/following a target across a map
  • Sound — one-shot effects and streamed background songs
  • Timers — background-thread scheduled callbacks back into Lua
  • Input — keyboard, mouse, and multiple gamepads
  • Text — TrueType and multi-file bitmap fonts
  • JSON — reading arbitrary config/data files from Lua
  • A scripting/sequencing layer — queuing stage transitions and scripted waits without hand-rolled state machines
  • Content encryption — sealing a whole game’s Lua and assets into one encrypted .zip, openable only by the build it was sealed for
  • A packaging tool (--pack) — turning a loose source folder into that sealed .zip with one command

None of that was there on day one, and none of it is the last of it either.

Sometime back, I ended a story about a transforming ship by saying more forms were coming, without saying what they’d be. This was one of them. It won’t be the last.

Enjoy.

[]’s
PopolonY2k


Scarab GitHub project link

https://github.com/popolony2k/scarab

Projeto Parallax – Engine de jogos 2D escrita em Java

Na ultima semana recebi por email a notificação do Cosmic Effect, onde sou inscrito, divulgando um post do desenvolvedor Michel Montenegro, descrevendo sobre o seu projeto de uma engine 2D escrita em Java, denominada Projeto Parallax.

Ao ler o post e assistir ao vídeo de apresentação da engine logo percebi que se trata de um dos projetos mais legais, inovadores e internacionais feitos por um brasileiro nos ultimos anos. Usei justamente o termo internacional pelo fato de eu já ter trabalhado em projetos internacionais, como o simulador de vôo Open Source FlightGear, adquirindo uma certa experiência que me possibilitou perceber o cuidado do autor em fazer um trabalho expansível e aberto, do mesmo nível de outros projetos internacionais.

Não posso deixar de citar que uma das maiores empolgações que tive de imediato ao assistir o vídeo, foi perceber que a engine trabalha nos moldes de muitos dos RPG‘s conhecidos pelos usuários e entusiastas da comunidade MSX, como Gouvellius, XAK, Fray, Shalom (Knightmare 3)  e com pitadas de SD-Snatcher.

Xak – The art of visual stage

De imediato tratei de entrar em contato com o autor do Projeto Parallax que me respondeu prontamente e atenciosamente de tal forma que trocamos endereços de email, GTalk e por fim nos falamos por mais de uma hora através do Skype. Foi um bate papo descontraído e  bastante proveitoso até porque conversamos sobre diversos assuntos relacionados a engine do Parallax, onde também citei o desenvolvimento do jogo pela comunidade MSX Brasil, divulgado meses atrás, nesse link aqui, sendo que o game da comunidade é no estilo Click-and-Point, próximo a RPG, porém em menor escala de complexidade.

Após muita conversa técnica, onde o autor me mostrou a estrutura da engine incluindo partes do código fonte em Java, percebi diversas coisas, algumas das quais compartilho abaixo:

  • O autor tem profundo conhecimento pois estudou a fundo o processo de desenolvimento de jogos, particularmente os RPG’s;
  • O projeto é altamente estruturado, não devendo nada aos projetos internacionais;
  • O código fonte (escrito em Java) é de excelente qualidade, muito claro e com excelente orientação a objetos e principalmente implementando com clareza os conceitos propostos pela engine;
  • O autor é muito, mas muito gente fina :);

Pedi então que o Michel fizesse um post explicando os detalhes do projeto Parallax e em pouco tempo ele me enviou um texto por email que reproduzo, na íntegra, abaixo.

Divirtam-se 🙂

Projeto Parallax – Uma engine de jogos 2D escrita em Java
por Michel Montenegro

Tudo bom pessoal, vim falar a vocês sobre o projeto Parallax, o projeto é um motor de criação de jogos 2D, ele funciona basicamente como um RPGMaker, para a criação de jogos ao estilo Dofus, Tibia e outros. Um dos focos do projeto é que o criador não programe uma única linha de código Java, somente altere valores em um “database” parecido com o do RPGMaker e edite suas imagens para o seu gosto e necessidade. Outro foco importante para o projeto é que ele vai dar suporte a jogos On-Line (MMOG). Imagine criar um jogo já com a possibilidade de ter um servidor em uma maquina e acessá-lo?.
Sou um fã de jogos em 2D e 3D, porém os jogos em 2D possuem uma mágica que atualmente vem sendo reconquistada no ambiente On-Line, tenho me deliciado com jogos online atuais que seguem aquele estilo visual, como o “épico e cômico” Dofus, o conhecido Tibia e mais recentemente o Club Penguin — este, um MMO em flash sob o selo de qualidade Disney, portanto, imaginem a qualidade da arte 2D.

Games

Uma engine em Java para RPGs em 2D
Não existem engines em Java para jogos 2D, para 3D existe o JMonkeyEngine, existem muitas bibliotecas para o apoio no desenvolvimento 2D, mas nada que ultrapasse esta barreira, não existe no Brasil um projeto similar e que esteja funcional e com este grau de amadurecimento.
Fazer jogos em Java é completamente viável por vários motivos, e algumas dessas razões me motivaram a escolher Java como linguagem, vou citar as vantagens desta engine:

  • Projeto open source – O usuário da engine poderá se assim desejar, fazer alterações personalizadas.
  • Compatibilidade – Possibilidade de rodar em qualquer sistema operacional que tenha uma JVM (Máquina Virtual Java) desde que atenda os padrões mínimos de hardware.
  • Sem programação – Não ter a necessidade de conhecer nenhuma linguagem de programação, apenas conceitos básicos de operação em qualquer sistema operacional.
  • Expansivo – Inicialmente, oferecer a capacidade de gerar jogos no mesmo estilo do RPG Maker para então expandir para outros modos. O Projeto Parallax é totalmente modular.
  • Off-line e on-line – Oferecer suporte online, possibilitando criar um MMOG ou MMORPG. Importante lembrar que o JMMORPG, protótipo do Parallax, obteve sucesso neste aspecto e suas estruturas estão sendo aproveitadas.
  • Custo zero – O Projeto Parallax somente faz uso de tecnologias 100% livres e de código aberto em sua construção.
  • Padronização no código e na criação final do produto – Utilização de técnicas modernas durante o desenvolvimento, garantindo compatibilidade com conceitos e tecnologias atuais.
  • Porta aberta para todos – Para quem deseja entrar na área de desenvolvimento de jogos, principalmente em Java, nosso projeto pode ser uma excelente escola.
  • Qualidade e simplicidade – Se for para qualquer um poder criar, não pode ser complexo. Procuro manter o código-fonte o mais objetivo, enxuto e padronizado possível.
O projeto parallax

Um relato rápido: no início, alguns profissionais da área de TI/desenvolvimento de jogos até me desmotivaram com relação a esta ideia, por conta da existência do XNA (framework de jogos para PC/X360 e Windows Phone), o GameMaker e até mesmo o próprio HTML5. Dei uma espiada nelas e pude concluir que, para o meu objetivo, Java continuou como a opção mais interessante, por quê?

  1. Existe JVM para Windows, Linux Mac, Symbian, Android, ambiente web (Applet) e outros que possuam uma JVM (aumentando a possibilidade de expansão ou adaptação do projeto, até para outra vertente, no que se refere à plataforma).
  2. Existem bibliotecas que agilizam muito o desenvolvimento em Java (Apesar do Graphic User Interface ser seu ponto fraco no quesito, ser trabalhoso e até complexo em relação a outras linguagens ou ferramentas mais especificas como o Flex, o resultado e controle que a linguagem dá por trás compensa estes detalhes).
  3. Uma rica quantidade de documentação a respeito da linguagem e de suas bibliotecas, dando suporte para um aprendizado mais veloz, além de poder usar qualquer outro conceito da área de desenvolvimento de jogos, sem o menor problema.
  4. Não ter que pegar nenhum tipo de licença, todas as tecnologias usadas são 100% gratuitas e de código aberto (Possibilitando mudanças personalizadas), dando total autonomia para o criador.
Engine em ação
Engine em ação

O Projeto Parallax já incentivou outros a pensar em fazer engines para Android e Symbian, uma outra vertente que gostaria de ver nossa engine se expandindo no futuro. Espero que gostem do trabalho e acreditem: foram dois anos e “uns quebrados” de muito estudo e pretendo levar a frente.
Peço que divulguem este artigo o máximo que puderem para seus amigos nas redes sociais e onde mais acharem relevante, quanto mais divulgação, maior a chance de ter colaboradores que ajudem o projeto a crescer mais rápido, lembrem-se “em solo fértil, um povo unido não passa fome” . Pois bem, respirei Projeto Parallax nos últimos dois anos e no site http://www.einformacao.com.br/parallax/ você pode encontrar em que pé a engine está neste momento. Sempre que possível vamos estar atualizando aqui o estado atual da engine ( ^^ ) um abraço a todos e obrigado!

Engine funcionando, com o jogo “As Crônicas Do Aventureiro”
Parallax Project – Video 2
Parallax Project – Video 3

Referência na internet

Site oficial do projeto Parallax
http://www.einformacao.com.br/parallax/

CosmicEffect – Video games ontem e hoje
http://cosmiceffect.com.br/

Project Parallax (CosmicEffect)
http://cosmiceffect.com.br/2012/02/16/projeto-parallax-engine-em-java-para-jogos-2d/

FlightGear – Open source Flight simulator
http://www.flightgear.org/

Java Home
http://www.java.com/en/

MSX, games e produções indepemntes (PopolonY2k Rulezz)
http://www.popolony2k.com.br/?p=967

MSX Brasil (Orkut)
http://www.orkut.com.br/Main#Community?cmm=98375914

RPG (Wikipedia)
http://en.wikipedia.org/wiki/Role-playing_video_game

Click-and-point adventure games (Wikipedia)
http://en.wikipedia.org/wiki/Adventure_game

Gouvellius (Wikipedia)
http://en.wikipedia.org/wiki/Golvellius

Xak (Wikipedia)
http://en.wikipedia.org/wiki/Xak

Fray (Wikipedia)
http://en.wikipedia.org/wiki/Fray_in_Magical_Adventure

SD-Snatcher (Wikipedia)
http://en.wikipedia.org/wiki/SD_Snatcher

Knightmare 3 – Shalom
http://knightmaresaga.msxblue.com/shalom/index.htm