          =======================================
          
              Violet Blue I - Developer Guide
          
          =======================================

Welcome to the Developer Guide of the Violet Blue I system. This document
describes how the system works and how to interract with it through
applications.

	Table of Contents

Chapter 1: System Overview & Architecture
	1.1 The Violet Blue Philosophy (Design Goals)
		Philosophy
		Why use it?
		What kind of applications is it meant for?
	1.2 Guest / Host Execution Model

Chapter 2: Theory of Operation & Pipeline
	2.1 Binary Stream Configuration
	2.2 Instruction Packet Formats (CMD0 - CMD5)
	2.3 Endianness & Memory Alignment
	2.4 The Coprocessor State Machine & Registers

Chapter 3: Subsystem Reference
	3.1 Graphics & Primitive Rasterizer
		Line Primitive (DRAWLINE)
		Rectangle Primitive (DRAWRECT)
		Ellipse Primitive (DRAWELLI)
		Text Rasterizer (DRAWTEXT)
	3.2 Bitmap Memory & Blitting
		Asset Management (BITMID / LOADBITM)
		Blitting (DRAWBITM)
	3.3 PSG Audio Synthesizer
		Sound Configuration (SETAUDIO)
		Volume Control (CHVOLUME)
		Master Mixer Control (SETVOL)

Chapter 4: Command Set Reference
	4.1 Command Set Table

Chapter 5: Developer's Cookbook
	5.1 Minimal C Application Blueprint
	5.2 Example 1: Drawing Primitives & Vector Graphics
	5.3 Example 2: Loading & Displaying Bitmaps
	5.4 Example 3: Generating Chiptune Sound Effects


	Chapter 1
	System Overview & Architecture
	
= 1.1 The Violet Blue I Philosophy (Design Goals) =

	- Philosophy -
	
The Violet Blue I acts like a virtual multimedia card that communicates
using the standard output file (stdout). It executes video and audio
commands sent by the host OS native applications.

	- Why use it? -

Violet Blue I gives that sense of control and the sense of working directly
on low-level hardware. The fact that it communicates using stdout means
that Violet Blue I is totally language-agnostic. Any program written in any
language can access video and audio without having to link with any external
libraries.

	- What kind of applications is it meant for? -

Violet Blue I is meant for writing prototypes for games and graphical tools.
Feel free to use Violet Blue for any of your project. It teaches writing
applications for hardware components with a friendlier and simpler architecture.

= 1.2 Guest / Host Execution Model =

Violet Blue I opens on a terminal that directly runs native applications in a
different process. The terminal serves just as an interface for the application.
Since the Host executes and runs at 60FPS, commands are sent asynchronously by
the Guest.

	+----------------+              +-------+
	| Host interface | <- stdout -- | Guest |
	|                | -- stdin --> |       |
	+----------------+              +-------+


	Chapter 2
	Theory of Operation & Pipeline

= 2.1 Binary Stream Configuration =

Because Violet Blue I reads binary commands over I/O pipes, the Guest process must
explicitly configure `stdout` to Binary mode. on Windows, stardard I/O is set to text
mode by default, which replaces LF (0x0A) characters to CRLF (0x0D0A). This can
corrupt some commands and bitmap payloads.

In C/C++, configure stdout before emitting any stream commands:

	_setmode(_fileno(stdout), _O_BINARY);

= 2.2 Instruction Packet Formats (CMD0 - CMD5) =

Commands sent over standard output consist of a 1-byte Opcode followed by a 
fixed-length or length-prefixed binary payload.

  Format   Layout                                               Size
  ─────────────────────────────────────
  CMD0     [8-bit opcode]                                       1 Byte
  CMD1     [8-bit opcode]+[32-bit arg]                          5 Bytes
  CMD2     [8-bit opcode]+[16-bit arg][16-bit arg]              5 Bytes
  CMD3     [8-bit opcode]+[ 8-bit arg][ 8-bit arg][16-bit arg]  5 Bytes
  CMD4     [8-bit opcode]+[ 8-bit arg][ 8-bit arg]              3 bytes
  CMD5     [8-bit opcode]+[16-bit arg][16-bit arg]+[8-bit data] 5 + N Bytes 

= 2.3 Endianness & Memory Alignment =

All multi-byte numeric fields (16-bit integers and 32-bit integers) inside
instruction packets are encoded in Little-Endian byte order (least significant
byte first). 

Packets do not require structural padding or memory alignment boundary constraints.
Data fields immediately follow the opcode byte. The Guest should write bytes sequentially
into buffers to prevent compiler-inserted struct alignment padding:

  +--------+--------+--------+--------+--------+
  | Opcode | Byte 0 | Byte 1 | Byte 2 | Byte 3 |  ... Payload
  +--------+--------+--------+--------+--------+
    [1B]     <----- 16-bit / 32-bit Data ----->

= 2.4 The Coprocessor State Machine & Registers =

When an application is ran, the systems defaults to the normal console mode, meaning
that commands are considered like text to draw normally. In order to enable Multimedia
Mode, the first character received from the Guest, in stdout, must be a `ENV` (0x01)
command. Which sends a Host windows handle and make sure anything commands are
interpreted like expected.

The architecture of the Violet Blue I system is stateful and register-driven. States
like color, cursor position and channels are modified seperately using dedicated commands
and influence how following commands like behave.

  Register        Size      Default Value    Description
  ───────────────────────────────────────
  WWIDTH, WHEIGHT uint16    Host size        Host environment size
  PX, PY          uint16    (0, 0)           Cursor raster coordinate
  COLOR           uint32    0xFFFFFFFF       32-bit ARGB draw color
  SCALE           uint32    1                Pixel scaling factor
  BITMID          uint32    0                Selected bitmap ID for load/blit
  MASTEVOL        uint16    100              Master audio output volume (0-100)
  MASTPITCH       uint16    0x0100           Master pitch modulation (Q8.8 fixed)

	Chapter 3
	Subsystem Reference

= 3.1 Graphics & Primitive Rasterizer =

Violet Blue I renders on a dynamic 32-bit ARGB8888 framebuffer. The graphics
registers `PX`, `PY` and `COLOR` modify how the Violet Blue I rasterizes
graphics.

	-- Line Primitive (DRAWLINE) --

The line primitive internally uses the bresenham algorithm with a pixel width
of 1. Starting from PX and PY to the end-points provided by the DRAWLINE command,
it draws a line using the color stored in the COLOR register.

	-- Rectangle Primitive (DRAWRECT) --

The rectangle primitive fills the region from PX and PY to (PX + Width) and
(PY + Height) with the color stored in the COLOR register. Width and Height
being 16-bit integers provided by the DRAWRECT command.

	-- Ellipse Primitive (DRAWELLI) --

The ellipse primitives rasterizes a filled ellipse with PX and PY as the
position of the center.
```
x^2 * RadY^2 + y^2 * RadX^2 <= RadX^2 * RadY^2
```

	-- Text Rasterizer (DRAWTEXT) --

The text rendering draws text using the default font using PX and PY as
the top-left point of the text. The background color of the text is black.
a NEWLINE character ('\n'), will move the cursor down for FONT_HEIGHT and
left to the starting PX position.

= 3.2 Bitmap Memory & Blitting =

Violet Blue I supports hardware-like bitmap caching. Bitmaps are transferred once
over the stdin pipe, bound to a numeric slot ID, and blitted instantly using 1-byte commands.

	-- Asset Management (BITMID & LOADBITM) --



	-- Blitting (DRAWBITM / 0x13) --

Executes a zero-copy blit of the currently active bitmap slot at screen coordinates (PX, PY).

= 3.3 PSG Audio Synthesizer =

Violet Blue I supports 4 audio channels with 5 sounds:
	0 = None (no audio)
	1 = Square (50% duty pulse)
	2 = Triangle
	3 = Sawtooth
	4 = White Noise

This allows to create melodies and sound effects for your applications and games.

	-- Sound Configuration (SETAUDIO) --

Configures and audio channel to play an sound depending on the Waveform and the Frequency.
The audio process uses fast functions to generate audio for effcient audio:

	SQUARE:    sample = (phase < 0.5) 1.0 else -1.0
	TRIANGLE:  sample = 4 * ABS(phase - 0.5) - 1.0f                 
	SAWTOOTH:  sample = 2 * phase - 1.0f
	NOISE:     sample = ((float)fast_rand() / 32767.0) * 2.0 - 1.0;

`fast_rand()` implements a PCG function for effeciency.

	-- Volume Control (CHVOLUME) --

Sets the volumes for an audio channel.
This command can be used anytime and the modification will happen in real-time.

	-- Master Mixer Control (SETVOL) --

Violet Blue I has commands to control the global mixer. `SETVOL` (0x0B) modifies the mixer volume
and the mixer pitch. This command can be used anytime and the modification will happen in real-time.
	
	
	Chapter 4
	Command Set Reference

= 4.1 Command Set Table =

	Name      Cmd   Layout                                                             Description
	─────────────────────────────────────────────────────────────────────────
	NOP       [0x00]                                                                   No-Operation
	ENV       [0x01]                                                                   Initializes the host binary parser & viewport environment
	SYNC      [0x02]                                                                   Sends a host frame sync marker
	RESET     [0x03]                                                                   Resets the coprocessor registers to default state
	BITMID    [0x04][Id:u32                             ]                              Sets BITMID
	LOADBITM  [0x05][Width:u16       ][Height:u16       ][Pixels:u32 * Width * Height] Uploads raw ARGB pixel memory into active bitmap slot
	CLEAR     [0x06]                                                                   Clears framebuffer with active COLOR
	SETWIN    [0x07][Width:u16       ][Height:u16       ]                              Sets WWIDTH and WHEIGHT
	SETSCALE  [0x08][Scale:u32                          ]                              Sets SCALE
	SETCOLOR  [0x09][Color:u32                          ]                              Sets COLOR
	SETPOS    [0x0A][X:u16           ][Y:u16            ]                              Sets PX, PY
	SETVOL    [0x0B][Volume:u16      ][Pitch:u16        ]                              Sets MASTEVOL (0-100) and Q8.8 MASTPITCH
	DRAWLINE  [0x10][EndX:u16        ][EndY:u16         ]                              Draws line from (PX, PY) to target (EndX, EndY)
	DRAWRECT  [0x11][Width:u16       ][Height:u16       ]                              Fills rectangle from (PX, PY) of dimensions (Width, Height)
	DRAWELLI  [0x12][RadX:u16        ][RadY:u16         ]                              Fills ellipse at center (PX, PY) with radii (RadX, RadY)
	DRAWBITM  [0x13]                                                                   Blits active bitmap in BITMID at (PX, PY)
	DRAWTEXT  [0x14][Unused:u16      ][Length:u16       ][Str:u8 * Length]             Renders Length bytes of string data at (PX, PY)
	SETAUDIO  [0x20][Chan:u8][Wave:u8][FreqHz:u16       ]                              Configures channel's waveform and frequency (in Hz).
	CHVOLUME  [0x21][Chan:u8][Vol:u8 ]                                                 Sets volume for channel [0-100]
	
	
	Chapter 5
	Developer's Cookbook

= 5.1 Minimal C Application Blueprint =

```c
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <windows.h>
#include <bluei.h>

int main(void) {
    _setmode(_fileno(stdout), _O_BINARY);
    unsigned char buf[256];
    unsigned char* p = buf;

    pCMD_ENV(p);
    pCMD_SETWIN(p, 320, 240);
    fwrite(buf, p - buf, 1, stdout);
    fflush(stdout);

    while (!(GetAsyncKeyState('Q') & 0x8000)) {
        p = buf;
        pCMD_SETCOLOR(p, 0x20, 0x20, 0x40, 0xFF);
        pCMD_CLEAR(p);
        
        fwrite(buf, p - buf, 1, stdout);
        fflush(stdout);
        Sleep(16);
    }
    return 0;
}
```

= 5.2 Example 1: Drawing Primitives & Vector Graphics =

```
// Draws a red rectangle
pCMD_SETCOLOR(p, 0xFF, 0x00, 0x00, 0xFF); // Red
pCMD_SETPOS(p, 50, 50);
pCMD_DRAWRECT(p, 100, 80);

// Draws a white ellipse
pCMD_SETCOLOR(p, 0xFF, 0xFF, 0xFF, 0xFF); // White
pCMD_SETPOS(p, 100, 90);
pCMD_DRAWELLI(p, 5, 5);
```

= 5.3 Example 2: Loading & Displaying Bitmaps =

```
// 1. Select Asset Slot 0 and upload a 2x2 sprite
uint32_t pixels[4] = { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFFFFFF };
pCMD_BITMID(p, 0);
pCMD_LOADBITM(p, 2, 2, pixels);

// 2. Draw the cached asset at position (120, 80)
pCMD_SETPOS(p, 120, 80);
pCMD_DRAWBITM(p);
```

= 5.4 Example 3: Generating Chiptune Sound Effects =

```
// Play a C-Major chord across channels 0, 1, and 2
pCMD_CHVOLUME(p, 0, 80);
pCMD_CHVOLUME(p, 1, 80);
pCMD_CHVOLUME(p, 2, 80);

pCMD_SETAUDIO(p, 0, 0, 262); // Square wave - C4
pCMD_SETAUDIO(p, 1, 0, 330); // Square wave - E4
pCMD_SETAUDIO(p, 2, 0, 392); // Square wave - G4

// Modulate global pitch up by 1.5x (Q8.8 format: 1.5 * 256 = 384 / 0x0180)
pCMD_SETVOL(p, 100, 0x0180);
```
