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

From a Transforming Ship to a Transforming Engine

Voltron assembles from five lions. The Valkyrie in Macross folds from a fighter jet into a battle-ready mecha. The Autobots have been telling us for forty years that there’s “more than meets the eye.” Transformation is one of gaming and animation’s oldest tricks — take something familiar, and reveal it was always capable of becoming something bigger.

That’s also, more or less, the plot of Caravellius.

The ship that started it all

Back in 2021, I set out to build a shoot-’em-up called Caravellius — the Caravela, an old-world sailing ship, transforms into a spaceship to defend Earth from a Venusian invasion. Here’s the first footage of it taking shape:

Caravellius — early build

I made one deliberate, slightly stubborn decision going in: I wasn’t going to reach for an existing engine. I wanted to actually understand how games get built — cameras, collision, sprites, tile maps, all of it — by writing the plumbing myself.

Two candidates stood out for the actual graphics primitives: raylib and SDL. Rather than pick one and hard-wire the whole game to it, I built a boundary between “my game logic” and “whatever draws the pixels” from day one. If I ever wanted to swap the backend later, I shouldn’t have to rewrite the game to do it.

That boundary is what eventually became sunlight.

The engine transforms

About three months in, sunlight had grown enough of its own identity — map rendering, collision, sprites, sound, a scripting layer — that it stopped feeling like “part of Caravellius” and started feeling like its own thing. So I split it out into its own repository.

That’s the Voltron moment, if you squint: the pieces that had been quietly doing their job inside Caravellius assembled into something that could stand on its own.

Here’s a later look at Caravellius, running on top of that separated engine, with updated art and music:

Caravellius — updated build

Since the split, sunlight has kept leveling up on its own track — a real CI pipeline building it on Linux, macOS, and Windows on every change; a proper unit test suite; five sample projects showing off map rendering, animated sprites, collision, gamepad input, and a scripted “stage intro” cutscene; generated API docs; and, as of this week, its first tagged release, v0.1.0 — with prebuilt packages for all three platforms attached automatically the moment the tag goes up.

The next form

Here’s where the transformation keeps going. sunlight isn’t just Caravellius’s engine anymore — it’s now the rendering backend for Scarab, a new game engine I’m building that adds Lua scripting on top. Where sunlight handles the “how do pixels get on screen and what happens when two things collide,” Scarab is meant to let game logic live in Lua instead of C++.

It’s the same shape as the Caravela becoming a spaceship: the thing underneath didn’t get thrown away when it transformed. It got carried forward into something that could do more.

sunlight is open source under the zlib license — the repo, docs, and the v0.1.0 release are all up on GitHub if you want to see how a ship-turned-spaceship’s engine turned out:

github.com/popolony2k/sunlight

More forms to come.

Enjoy

[]’s

PopolonY2k

MSX LoRa – First contact

Finalmente após algum período longe do desenvolvimento de software para MSX, decidi voltar ao game unindo o útil mundo do IoT ao agradável universo de retrocomputing através do nosso querido e amado MSX.

Como se trata de um tema atual, rico de informações e possibilidades, decidi escrever dois artigos sendo esse aqui o primeiro que é mais introdutório e o segundo será mais prático, descrevendo o passo-a-passo de como usar toda a tecnologia envolvida nesse pequeno projeto.

Não é a primeira vez que me aventuro na área de comunicação no MSX, pois há 10 anos atrás (passou o tempo e nem percebi) escrevi sobre Networking no MSX através de 2 artigos intitulados MSX Networking e MSX Networking – Developers, developers, developers, developers, … respectivamente e que na época tiveram boa receptividade na comunidade MSX.

Nesses posts apresentei tecnologias como a interface de rede para MSX denominada ObsoNET e a interface que estava sendo desenvolvida na comunidade MSX na época e que não tinha nome e que eu intitulei como OptoNET e desde então é reconhecida como OptoNET, inclusive teve uma versão Wi-Fi da mesma e que usa ESP8266.

No ultimo artigo inclusive liberei a implementação de uma abstração de Network Socket para uso em aplicações escritas em Turbo Pascal 3 no MSX, bem como a implementação de um driver para OptoNET sendo assim possível a sua programação em Pascal usando essa abstração.

Nesse interim adquiri quase tudo o que pude referente a comunicação, desde as diversas placas de rede existentes para MSX como a excelente Gr8Net de Eugeny Brychkov (from Russia with love), DenYoNet da Sunrise, até interfaces RS-232 como a Fast Harukaze e a CT-80NET da Gradiente.

Comecei a desenvolver muita coisa para RS-232 utilizando a BIOS padronizada pelo consorcio MSX mas infelizmente paralisei seu desenvolvimento em um estágio bem avançado, o mesmo tendo acontecido com o desenvolvimento das rotinas para uso da ObsoNET que também está quase no mesmo estágio de conclusão das rotinas de RS-232 e que esse ano, ambas as implementações certamente serão concluídas e assim teremos mais uma importante feature na PopolonY2k Framework Library.

Pois bem, há quase 10 anos tenho essas duas interfaces RS-232, Fast Harukaze e a Gradiente CT-80NET e arrisco a dizer que a possibilidade de programar softwares de comunicação para MSX foi o que me fez a voltar a ser bastante atuante na comunidade (isso lá no início dos anos 2000) e que principalmente foi um tópico que me fez a querer ter um MSX real (agora também os sintetizados via FPGA) para colocar meus planos em prática.

RS-232 – O inicio de tudo

O RS-232, também conhecido como RS-232C, é um protocolo padrão de mercado criado no final dos anos 60, mais especificamente em 1969 e que teve seu uso amplamente difundido para o público técnico e de uso geral principalmente nos anos 80 com o advento da computação pessoal difundida pelos mais diversos PC`’s de 8, 16 e 32 Bits da época, atravessando o tempo e chegando aos dispositivos IoT dos dias atuais, como Arduino e Raspberry Pi.

LoRa – Um protocolo serial via wireless

A comunicação avançou muito nos últimos anos e com todo esse avanço tivemos diversas tecnologias criadas que vão desde comunicação via Ethernet cabeada, até WiFi, o que chamamos de comunicação Wireless ou sem fio.

Apesar do bom e velho RS-232C e suas variantes como a RS-485 terem sido desenvolvidos principalmente para operar utilizando cabos, não é recente a sua utilização via wireless através de dispositivos especialmente projetados para lidar com as caraterísticas especiais de uma comunicação sem fio.

Nesse universo e principalmente devido ao grande avanço das tecnologias de Internet Of Things (IoT), muita coisa nova tem sido desenvolvida, principalmente através da união de grandes players de tecnologia, que por sua vez tem ajudado a criar padrões para utilização no universo IoT.

É nesse cenário nasce a Lora Alliance, que é uma organização sem fins lucrativos responsável pela criação, especificação de tecnologias baseadas em LoRa.

Mas que raios é esse LoRa afinal ?

LoRa é um protocolo de comunicação via rádio que significa Long Range (Longo alcance), ou seja, é um protocolo para envio de informações a longas distâncias, onde se tem relatos de comunicação entre 2 pontos a uma distância de até 15Km.

É lógico que depende de vários fatores, como visada (Line of Sight) dentre outros que podem interferir no alcance, porém só o fato de existir essa possibilidade de comunicação a longas distâncias já torna LoRa muito interessante para uso em diversas aplicações como já vem sendo utilizado pelo agronegócio para monitoria de equipamentos em fazendas que na maioria dos casos é um ambiente propício para esse tipo de aplicação

Apesar da grande distância que um dispositivo LoRa pode proporcionar, nem tudo são flores sendo a principal desvantagem a baixa velocidade pois a comunicação entre dispositivos LoRa é extremamente lenta, impossibilitando o seu uso em transmissões com grande volume de dados como áudio e vídeo por exemplo.

Esse é um dos principais motivos pelos quais as informações trafegadas entre dispositivos LoRa, estar restrita a envio de dados de telemetria ou aplicações onde baixa latência não é o principal requisito.

LoRa possui duas topologias de operação, sendo elas Point-to-Point e Network, essa última de fato é uma espécie de Broadcasting, além de variantes como a LoRaWan capaz de colocar um dispositivo LoRa na internet, o que foge um pouco do escopo desse post portanto vamos explorá-la em um post futuro.

Dispositivos LoRa na prática

Na prática temos uma infinidade de dispositivos LoRa desenvolvidos por diversos fabricantes e embora exista uma certa padronização no nível de sinal, frequência de rádio e afins, não há uma padronização na interface de software com LoRa, com isso cada fabricante de dispositivos LoRa está criando sua própria abstração de comunicação com seus dispositivos.

A fabricante REYAX, é a que melhor se adaptou e está usando comandos AT, padrão da Hayes criado para comunicação via modem que se tornou padrão de facto sendo amplamente utilizado pela industria desde os anos 80 bem como pela própria REYAX em seu RYLR998, o que torna esse dispositivo um dos mais “padronizados” em nível de software no mercado.

Dentre os diversos fabricantes, um dos mais “famosos” é a chinesa EBYTE, que possui diversos modelos de módulos LoRa, todos bem parecidos visualmente e operacionalmente entre si, apenas mudando especificações técnicas talvez relacionadas a potência e consumo por exemplo.
O módulo que utilizo nos experimentos com MSX e IoT é exatamente esse da imagem, o E220-900T22D.

Tanto o módulo LoRa da REYAX, quanto o da EBYTE, tem sua interface física de comunicação baseada em UART TTL serial e no caso dos módulos da EBYTE eles tem um protocolo binário bem simples para setup do módulo LoRa e que está disponível quando o módulo está operando em modo de setup/configuração.

A documentação do módulo LoRa da EBYTE pode ser encontrada nesse link aqui, ou em nosso repositório local aqui.

Infelizmente a documentação do módulo da EBYTE não é muito clara e gera algumas duvidas que nos induz a pensar que a documentação está errada ou o módulo não funciona, entretanto após pesquisar outros sites e vídeos sobre esses módulos da EBYTE percebi mesmo que essa documentação é só mau escrita mesmo e que o módulo funciona corretamente e de fato ele é mais simples do que eu imaginava, não necessitando conhecer algum protocolo específico para sua operação (exceto quando você está em modo de setup/configuração do módulo).

Bom, acredito que após essa longa introdução sobre comunicação, dispositivos seriais e LoRa, podemos começar a colocar a mão na massa e ver como usar os dispositivos LoRa e principalmente como utilizá-los através de um computador MSX.

Como eu já citei inicialmente, esse é o primeiro artigo introdutório e no próximo descreveremos tecnicamente os detalhes e possibilidades de integração de dispositivos LoRa no MSX ou em outras tecnologias como Arduino, Raspberry Pi, etc.

Enjoy

[]’s
PopolonY2k

PopolonY2k Framework Memory Mapper support

Após alguns meses do lançamento da última versão do PopolonY2k Framework, venho trabalhando em alguns programas de exemplo para reforçar os conceitos implementados no framework bem como na difusão de conhecimento de tudo o que tem nele desenvolvido.

A comunidade nacional tem utilizado muitas partes do framework e principalmente a comunidade internacional tem reportado alguns problemas encontrados, principalmente no Pop!Art, o que me levou a verificar que de fato os problemas estão relacionados a algumas peças do framework e que brevemente serão ajustadas ainda esse ano.

No grupo de WhatsApp “MSX Pascal, C, ASM e etc” temos discutido muito sobre assuntos relacionados a desenvolvimento para retro-machines, principalmente para o MSX e em algumas dessas discussões surgiram alguns questionamentos sobre o uso das rotinas de uso da mapper do PopolonY2k Framework.

Por esse motivo, preparei um sample com um código bem elucidativo sobre o uso das principais rotinas de alocação e paginação da mapper que fazem uso das rotinas do MSXDOS2 disponíveis no framework, conforme análise e explicação pode ser vista no vídeo abaixo.

MSXDOS2 Mapper PopolonY2k Framework routines

O framework também contempla uso da mapper através do acesso direto a portas de I/O, o que torna o seu uso mais rápido, entretanto essas rotinas são as chamadas “mal comportadas” e devem ser utilizadas com muita cautela principalmente quando se tem completa certeza de que não há conflitos com áreas pré-alocadas pelo próprio MSXDOS2 via suas rotinas padrão.

O Pop!Art faz isso com extrema segurança, onde o mesmo aloca e preenche os dados da música VGM usando as rotinas de mapper padrão do MSXDOS2 e usa as de acesso direto, apenas no momento em que está tocando quando está apenas fazendo paginação dos segmentos da mapper pré-alocados pelas rotinas do MSXDOS2.

Os exemplos estão sendo adicionados diretamente no repositório do projeto na OldSkoolTech no SourceForge.net e podem ser consultados nesse link aqui.

O sample de uso da mapper (maprtest.pas) está completamente comentado sendo bem auto-explicativo, além de ter uma análise bem completa no vídeo acima, podendo seu código ser conferido abaixo:

(*<maprtest.pas>
 * Memory mapper routines test.
 *
 * - Routines tested:
 * - InitMapper;
 * - GetMapperPageByAddress;
 * - PutMapperPageByAddress;
 * - AllocMapperSegment;
 * - FreeMapperSegment;
 *
 * CopyLeft (c) since 1995 by PopolonY2k.
 *)

(**
  *
  * $Id$
  * $Author$
  * $Date$
  * $Revision$
  * $HeadURL$
  *)

{-----------------------------------------------------------------------------}
{                      PopolonY2k Framework dependencies                      }
{-----------------------------------------------------------------------------}

{$i types.pas}
{$i helpchar.pas}
{$i msxbios.pas}
{$i extbio.pas}
{$i maprbase.pas}
{$i maprallc.pas}
{$i maprpage.pas}

{-----------------------------------------------------------------------------}
{                             Module definitions                              }
{-----------------------------------------------------------------------------}

Type TMappedBuffer = Array[0..ctMaxMapperPageSize] Of Char; { Mapped 16K bufr }


{-----------------------------------------------------------------------------}
{                              Helper functions                               }
{-----------------------------------------------------------------------------}

(**
  * Print part of a buffer content passed as reference.
  * @param aBuffer Reference to buffer to be printed;
  *)
Procedure PrintBuffer( Var aBuffer : TMappedBuffer );
Const
       __ctMaxCol   : Byte = 10;

Var
       x, y  : Byte;

Begin
  For y := 0 To __ctMaxCol Do
    For x := 0 To __ctMaxCol Do
    Begin
      GotoXY( ( x + 1 ), ( y + 1 ) );
      Write( aBuffer[( x + y ) * __ctMaxCol] );
    End;

  WriteLn;
  WriteLn( 'Press <enter> to continue' );
  ReadLn;
  ClrScr;
End;

{-----------------------------------------------------------------------------}
{                    Main program variables and constants                     }
{-----------------------------------------------------------------------------}

Const
           ctDefaultPage  = $8000;     { Default page for data - Page 2 }

Var
      maprHandle       : TMapperHandle;
      chKey            : Char;
      nActiveSegmentId : Byte;
      aSegments        : Array[0..1] Of Byte;
      aDataBuffer      : TMappedBuffer Absolute ctDefaultPage;


{-----------------------------------------------------------------------------}
{                          Main program entry point                           }
{-----------------------------------------------------------------------------}

Begin    { Main program entry }
  ClrScr;

  { Initialize mapper system }
  If( Not InitMapper( maprHandle ) )  Then
  Begin
    WriteLn( 'Error to initialize Mapper' );
    Exit;
  End;

  WriteLn( 'Mapper succesfully initialized' );

  { Get the current segment used by data buffer on stack }
  aSegments[0] := GetMapperPageByAddress( maprHandle, Addr( aDataBuffer ) );

  WriteLn( 'Main Segment -> ', aSegments[0], ' on page 2' );
  WriteLn( 'Press <enter> to see it''s content' );
  ReadLn;
  ClrScr;

  { Fill page 2 on Main Segment, fully with X character }
  FillChar( aDataBuffer, SizeOf( aDataBuffer ), 'X' );
  PrintBuffer( aDataBuffer );

  { Alloc new segment to put data (MSXDOS2 BIOS) }
  If( Not AllocMapperSegment( maprHandle,
                              maprHandle.nPriMapperSlot,
                              UserSegment, aSegments[1] ) )  Then
  Begin
    WriteLn( 'Mapper segment allocation failed' );
    Exit;
  End;

  WriteLn( 'New Segment -> ', aSegments[1], ' successfully allocated' );
  WriteLn( 'Type <enter> to see it''s content' );
  ReadLn;
  ClrScr;

  { Activate page 2 content to the New Segment allocated }
  PutMapperPageByAddress( maprHandle, aSegments[1], Addr( aDataBuffer ) );

  { Fill page 2 on New Segment fully with Y character }
  FillChar( aDataBuffer, SizeOf( aDataBuffer ), 'Y' );

  PrintBuffer( aDataBuffer );

  nActiveSegmentId := aSegments[1];

  { Handle user switch segment contents }
  Repeat
    GotoXY( 1, 19 );
    WriteLn( 'Active Segment -> ', nActiveSegmentId );
    WriteLn;
    WriteLn( '0 - Switch to Main Segment ', aSegments[0] );
    WriteLn( '1 - Switch to New Segment  ', aSegments[1] );
    WriteLn( 'ESC - exit' );
    chKey := ReadKey;

    If( chKey In ['0', '1'] ) Then
    Begin
      nActiveSegmentId := aSegments[Byte( chKey ) - Byte( '0' )];

      { Activate page 2 content to segment chosen by user }
      PutMapperPageByAddress( maprHandle,
                              nActiveSegmentId,
                              Addr( aDataBuffer ) );

      { Show segment content }
      PrintBuffer( aDataBuffer );
    End;
  Until( chKey = #27 );

  WriteLn;

  { Release all segments allocated by the application }
  If( Not FreeMapperSegment( maprHandle,
                             maprHandle.nPriMapperSlot,
                             aSegments[1] ) ) Then
  Begin
    WriteLn( 'SegmentId -> ', aSegments[1], ' deallocation failed' );
    Exit;
  End;

  WriteLn( 'All segments successfully deallocated' );
End.

Em tempo, Ricardo Jurczyk Pinheiro desenvolveu um excelente e mais completo exemplo que faz uso das rotinas de mapper do framework de maneira mais completa, explorando inclusive outras funções de suporte a mapper do framework.

Seu exemplo pode ser visto no link abaixo:

https://github.com/ricardojpinheiro/test/blob/master/mappdemo.pas

Enjoy coding 🙂

Referências

Pop!Art VGM Player for MSX

Is known by the brazilian MSX community about the development of Pop!Art VGM player that I’m working on since middle 2014.

Some practical results about Pop!Art were reported in 2014 by one of the most important retrocomputing blogs in Brazil, the Retrocomputaria+ blog and by the biggest brazilian MSX community on FaceBook, the MSX Brasil Oficial.

Pop!Art VGM player already supports all existing chips on the MSX platform, like Konami SCC (K051649), PSG (AY8910), FM (YM2413), SFG01/05(YM2151), OPL3/OPL4 and the Philips Music Module (Y8950).

Note: Some months after I presented some Pop!Art results, another excellent VGM Player (VGMPLAY by Grauw) was released.

My first motivation to start this development was only for fun and also to start learning about how sound chips works. The second motivation was to start a big project in chiptune’s scene.

In fact to get information about these old chips was the biggest challenge because some of them just can be found on manufacturer’s data-sheet that sometimes are poorly written and with a small percentage of useful information.

In most cases these datasheet information are confused so the best alternative to these poor data-sheets are the Linux sound cards drivers source code.
After reading these drivers source code, I got some specific details about how several of these chips really work.

Custom chips like Konami SCC don’t have any data-sheets but fortunately are well documented by the international MSX community and sources like BiFi’s website were my main information source.

Another big source of information for MSX developers in general is the MSX Assembly Pages (brought by the same author of VGMPLAY, Grauw) that in my opinion is the best source of information for developers who want to make useful and cool things for MSX computers.

Presenting Pop!Art

Pop!Art is an original software made using Turbo Pascal 3, almost 97% of it’s code is written in Pascal, with some parts written in Z80 ASM. If you want to compile it’s source code and modify it, feel free because the source code was released under GPLv3 and can be reached at OldSkoolTech SVN’s repositories on SourceForge.net.

It is compatible with Borland Turbo Pascal 3.0 (CP/M80-MSXDOS), Turbo Pascal 3.3f from MSX Club Enschede, (MSXDOS 1 & 2), and it also can be ported to others newer Pascal compilers, like FreePascal (Lazarus) and maybe newer versions of Delphi compiler.

The source code is fully commented and several parts of Pop!Art software were incorporated to the framework that I’m developing since I had started the development of the MSXDUMP in 1995 (best known as PopolonY2k Framework).

This framework can deal with several technologies present on MSX architecture, like IDE device handling, MSXDOS and MSXBIOS function calls and direct console handling.

Pop!Art introduces some important features in the framework, like support to Z80 interrupts, all MSX sound chips handling (K051649 aka SCC, YM2413 aka FM, YM2151 aka SFG01/05, OPL3/OPL4, Y8950 aka Philips Music Module, AY8910 aka PSG) and a better and accurate “wait” routines that can deal with resolutions below 50Hz or 60Hz, fixing time errors caused by songs with “tempo” below these resolutions (50Hz or 60Hz), that minimizes any standard deviation.

The current Pop!Art engine also supports all existing chips for the MSX platform and in future, newer chips supported by the VGM format similar to any existing on MSX platform will be added to the Pop!Art engine.

The VGM file format

VGM, aka Video Game Music, is a logging format based on GYM format which is another video game format used specifically to store Sega Mega Drive (Genesis) songs, but contrary to GYM, the VGM format can be used with several other chips different to Mega Drive sound chip. The first version of VGM was released in 2005 and after this release, six new format specifications were released until the current 1.70.

Another curiosity about VGM is that the format was very popular with Winamp users because this music player was the first player capable of playing VGM songs through a plugin specially created for it.

GD3 tag format

The VGM format has a GD3 metadata present in file header specification. The GD3 format is the same format used by MP3 files to store several tracks information, like author, song name and so on.

Pop!Art VGM Support

Pop!Art supports all VGM version’s format, since 1.0 to 1.70 and the GD3 tag format is partially implemented in Pop!Art engine but will be finished in future releases.

The VGM format contains all data samples sent to the sound chips using a speed rate of 41,000 samples per second, so your library must be very fast and precise to deal with VGM files in an accurate way and basically just assembly codes can reach this performance using all of the chip’s power….right ???

Hummm…..maybe not.

Turbo Pascal

I’m really thinking to start writing code to MSX using modern compilers, like SDCC C compiler, which is known to be one of the most powerful and optimized compilers for small devices, but I have written a lot of code to the old Turbo Pascal 3 for CP-M80/MSX for years and my framework has increased a lot its capabilities to handle several standard devices present in MSX world.

Turbo Pascal

In fact I’m using this good, but not so optimized compiler, to learn about new optimization techniques and about the Turbo Pascal internals. And also how to avoid not optimized coding style when you’re programming for machines with low resources. Maybe in the future I can write a new, modern and optimized Pascal compiler (maybe a cross-compiler) for MSX machines, but this is another dream.

When I started writing this article in 2015, FreePascal compiler was not an alternative because it lacked Z80 binary generation support, but since beginning 2020 FreePascal started supporting Z80 platform.

https://wiki.freepascal.org/Z80

Borland Turbo Pascal 3.0 is an impressive compiler because it is a very fast compiler but unfortunately there are several things that were created to be generic and problem solving in a generic way are known to be slower than a more specialized code generation.

I’m dedicated to improve my framework to be so generic as possible but sometimes I’ll need to be more specific to resolve big performance problems using Turbo Pascal code instead using assembly code.

The small list below can help programmers who are thinking start coding in Turbo Pascal, C and another language different of ASM.

1) In Pascal avoid nested functions – This kind of structured feature is not optimized in Turbo Pascal 3;

2) In any high level language with floating point builtin data types support, like Pascal and C, try to avoid real time processing using these floating point types (float/double in C and Real in Pascal).
These data types can deal with an “excellent” precision but is known that when you have, or want, an “excellent” precision, the processor will pay the price for this precision, so avoid floating point real time operations if is possible. Sometimes this can be done performing some data pre-processing or using fixed point, instead floating point;

3) Use integer instead floating point data and byte instead of Integer data, depending on numeric range, for the same reason of previous item;

4) Try “think” your application in JUMP TABLES, instead nested IF’s or even switch-case (case-of for Pascal programmers);

5) Read this article before coding http://www.popolony2k.com.br/?p=2402

NOTE ABOUT THE 5th ITEM: I’m using GOTO in small pieces of code, because old compilers like Turbo Pascal 3 are very antique, so features like “break” and “continue”, widely used in loop iterations, can be “simulated” by using GOTO.

PopolonY2k framework

As I wrote at the beginning of this text that I’m working on a framework fully written in Turbo Pascal, with some parts in ASM, since I released the MSX DUMP (part of MSX Disk Doctor suite). I thought that this framework was optimized but I was completely wrong, because there’s no framework or any other piece of code which the performance can be measured when discs and slow devices are used by these codes.

So when I tested this framework using my MSX Turbo R machine, everything seemed to be 100% ok and fast, but when I tested the same code on a MSX, running a slower Z80 processor, some problems started to be more visible, then fixing these problems and keep everything working fast using a Z80 in the same way like a R800 processor is a hard work.

This framework was started 20 years ago, when I was leaving the university and in those days I just wrote code for old devices like, disk drives and some generic code code to access the MSXBIOS and MSXDOS (1).
When I restarted coding this framework in 2011, I quickly improved it by adding features to access new devices, like Sunrise IDE devices, Network socket API, UNAPI and RS232 support are still WIP (Work in Progress).

Bellow is the list of all features present on this framework

1) FOUNDATION MODULES – New modules to make Turbo Pascal “more compatible” with new Turbo Pascal releases. New features like Big Integer handling;

2) MSX INTERNALS MODULES – MSX related functions and information (e.g. MSX System Variables);

3) BIOS MODULES – MSX BIOS functions by category;

4) MSXDOS (1 & 2) MODULES – MSX DOS functions;

5) SLOT MANAGEMENT – Functions related to slot manipulation;

6) INTERRUPT HANDLING – Functions to enable interrupt vector function handling using Turbo Pascal;

7) COMMUNICATION – Functions related to communication (RS232 (Work in progress), Sockets);

8) COMMUNICATION DRIVERS – Drivers written to support the Sockets implementation above. Support to OPTONET cards;

9) UNAPI FRAMEWORK – Support to UNAPI framework in Turbo Pascal (Work in progress);

10) SOUND CHIP DRIVERS – Drivers for all sound chips found on MSX standard;

11) VGM PLAYER FRAMEWORK – Functions to play songs in VGM format;

12) IDE SUNRISE-LIKE FRAMEWORK – Functions to handle Sunrise-like IDE devices;

13) USER INTERFACE AND OPTIMIZED CONSOLE MODULES – New functions to increase the speed of console applications and to handle user interface;

14) UNIT TEST FRAMEWORK – PopolonY2k TEST SUITE (PTEST) – Functions providing UNIT tests capabilities for Turbo Pascal 3 projects (widely used in the Big Integer implementation);

An updated framework features list can be reached here.

Pop!Art features list

  1. VGM file support (1.0 up to 1.70 – some commands are still disabled. eg. non MSX existing chip commands);
  2. Memory Mapper support (VGM files longer than 64Kb can be loaded and played);
  3. MSXDOS2 only support (sub-directories access). Maybe MSXDOS1 will be supported in future releases;
  4. AY8910 support;
  5. YM2413 support;
  6. YM2151 (SFG 01/05) support;
  7. Y8950 (Philips Music Module) support;
  8. YMF278 (OPL4) support;
  9. K051649 (SCC) support;

Known Pop!Art missing features in this release (0.0).

  1. VGZ file support (in fact is VGM inside a .tar.gz file);
  2. MSXDOS1 support;

Pop!Art memory layout

The application memory layout is described below:

  1. $0000-$3FFF – MSXDOS CP/M-80 + Turbo Pascal runtime workspace;
  2. $4000-$7FFF – Application object code;
  3. $8000-$BFFF – VGM Song data (16Kb memory mapped paged system);
  4. $C000-$FFFF – Unused;

Pop!Art in action

After writing a long story and mainly a lot of technical stuff, it is time to play some song using Pop!Art finally after 5 years 🙂

Check the video below where I explain technical details about how Pop!Art works internally.

Pop!Art in action (portuguese video only)

Downloading Pop!Art

Pop!Art binaries can be downloaded here, https://sourceforge.net/projects/oldskooltech/files/MSX/Pop%21Art/

Enter the version directory you want (e.g v0.0, etc) and download a preferred compressed file (pop_art_v_?_?.zip or pop_art_v_?_?.lhz).

After downloading and decompressing the chosen file, popvgm.com and popplay.chn files will be extracted, put them together in the same directory and then execute popvgm.com.

These files are the two main modules of Pop!Art described below.

  • popvgm.com is the VGM loader;
  • popplay.chn is the VGM player itself.

Hidden gems

Unfortunately all Turbo Pascal 3.x for MSX, both Borland and MSX Club Enschede, are too old products and are both an one pass compiler, so generated binaries are not so optimized as newer compilers like Free Pascal compiler.

Borland did an excellent work when decided create a powerful runtime not just placing the biggest part of standard library there but all comparison test routines are placed there too.

Using this model, the amount of binary code generated by the compiler was decreased considerably but on the other hand they sacrificed performance with this strategy.

I realized that all If’s in the main Pop!Art streaming routine was jumping to the respectives runtime routines and this behavior was decreasing performance a lot, so after a long time think about this problem finally I decided to change the Borland Turbo Pascal 3.0 binary by adding an extra pre-processing compiler directive to generate inline code for all comparison routines and consider Integer (-32768 .. 32767) like Word/Unsigned int (0 .. 65535).

But changing this behavior could turn specific code written to this specific Turbo Pascal version, incompatible with both Borland and MSX Club Enschede, so instead using the standard compiler directive {$ }, I created an extended compiler directive {% } that is considered by Borland and MSX Club Enschede Turbo Pascal as a regular comment but for my modified Turbo Pascal version is an extended compiler directive.

The first extended directive is {%W} and is a scoped directive, so to activate the starting scope the programmer must start with {%W+} and finish the scope with {%W-}.

This will inform the compiler to treat comparison routines as unsigned integer and generating inline code from starting point {%W+} to ending point {%W-}.

Below a small piece of Pop!Art code using this technique:

Procedure __MoveMapper16BitData{( __pSndChipArrayParms : Pointer )};
  Begin
    {%W+}
    If( nCurrentStreamPos < __ctMapperBufferEndAddr ) Then
    {%W-}
    Begin
      __pSndChipArrayParms := Ptr( nCurrentStreamPos );
      nCurrentStreamPos := nCurrentStreamPos + 2;

      (* Direct jump to command processing routine *)
      Inline( $2A/nFnJmpAddr   { LD HL,(nFnJmpAddr) }
              /$E9             { JP (HL)            } );
    End
    Else
    Begin
      __pSndChipArrayParms := Ptr( Addr( aSndBuffer ) );
      aSndBuffer[0] := Mem[nCurrentStreamPos];
      __ExecMapperPaging;
      aSndBuffer[1] := Mem[nCurrentStreamPos];
      nCurrentStreamPos := Succ( nCurrentStreamPos );

      (* Direct jump to command processing routine *)
      Inline( $2A/nFnJmpAddr   { LD HL,(nFnJmpAddr) }
              /$E9             { JP (HL)            } );
    End;
  End;

All comparison structures below are covered by this extended directive:

  • While .. Do
  • Repeat .. Until
  • If… Then … Else

Conclusion

Pop!Art can still be considered a work in progress and soon some extra and useful features will be added to it’s core engine, like:

  • Add support to VGZ (compressed VGM) file format;
  • Chip sound drivers improvement, adding chip specific extra features still not implemented;
  • Core engine speed optimization (improving Turbo Pascal performance);
  • Add full support to VGM 1.70;

So, I hope you enjoy Pop!Art and thanks for reading.

[]’s
PopolonY2k