Skip to content

About

Retro game developing

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

ColourClashNet - Work in progress

CI

A .NET 10 toolkit to convert modern images into pictures displayable by retro computers and consoles, using color quantization, palette reduction, hardware specific video mode emulation and dithering.

Alt text

Purposes

These tools can be used to create displayable images for old computer video modes, using various color reduction algorithms, color quantization, and dithering. They can also extract sprites and tiles (blobs) from sprite sheets.

Reduction recipe

To reduce colors on source images for old systems' video mode we need to know:

  • The output computer color space, aka the number of bits the system uses to represent a color. Source image usually has 3 color channels (red, green, and blue) with 8-bit per channel, for a total of 16 million selectable colors. Old systems usually have 3 channels with 3 or 4-bit for color, for a total of 512 or 4096 selectable colors, or even a fixed color palette.
  • The maximum number of colors displayable on video modes. Most computers can display only 16 colors on screen.
  • The hardware limitations. Most computers use tricks to minimize ram consumption, like using tiles (attribute cells), doubling pixels or changing the palette on every scanline.

Solution structure

Project Target Content
ColourClashLib net10.0 Core library: packed colors, color spaces (RGB, HSV, LAB, GRAY), palettes, histograms, quantization, color transformations, dithering, tiles, image load/save (SkiaSharp), indexed BMP and Amiga bitplane export
ColourClashProcessing net10.0 Image processing: global color threshold, run length extraction, blob (connected component) detection and sprite export
ColourClashSupport net10.0 Logging facade (LogMan) over NLog, Trace and a UI event
ColourClashDrawings net10.0-windows WinForms components: zoomable bitmap renderer, coordinate and mouse managers, processing pipeline manager, ColorAnalyzer control, GDI+ conversions
ColourClashNet net10.0-windows Main WinForms application (one ColorAnalyzer per tab)
ModuleTester net10.0-windows Manual test bench for every transformation
ColourClash net10.0 Command line tool ColourClashNetCli: runs, validates and creates JSON pipelines
XUnitTester net10.0-windows xUnit v3 tests

How to

Create a color transformation, configure it with its options record, feed it with an input image and get the transformed image.

using ColourClashNet.Color;
using ColourClashNet.Color.Dithering;
using ColourClashNet.Color.Transformation;
using ColourClashNet.Imaging;

var source = ImageTools.LoadImage("input.png");

var transform = new ColorTransformClustering
{
    Options = new ClusteringOptions
    {
        MaxColors = 16,
        TrainingLoops = 10,
        Selection = ColorSelectionMode.EvaluateColorMean,
        DistanceMode = ColorDistanceEvaluationMode.RGB,
        Dithering = new DitherOptions { DitheringType = ColorDithering.FloydSteinberg },
    },
};

var result = transform.Process(source);            // or await transform.ProcessAsync(source)
if (result.IsSuccess)
{
    ImageTools.SaveImage(result.DataOut, "output.png", ImageSaveFormat.Png);
    Console.WriteLine($"{result.TransformationError:g4} in {result.ProcessingTimeMilliseconds:f0} ms");
}
else
{
    Console.WriteLine(result.Message);   // "Class.Method : what failed : nested cause"
}

Process(source, reference, token) is the single entry point (ProcessAsync runs it on a worker thread): it loads the images, validates the options, transforms, dithers and evaluates the error. Errors and cancellation are returned in the result, never thrown. The options record also selects the algorithm: ColorTransformBase.CreateTransform(options) creates the matching IColorTransform (CreateTransform(ColorTransformType) uses the default options).

Events of a run, in order:

Event When Typical use
StartProcessing first, before anything is done change the options with SetOptions, or cancel the run
Creating, Created around the loading of the images reserved for future use
Processing options valid, transformation starting show a progress window
Progress any number of times, also from nested transformations and tiles progress percentage and intermediate images
Dithering before the final dithering (only when it is applied) inspect the undithered image
Completed always last, also on error or cancellation final result

Destroying and Destroyed are raised by Dispose() (reserved for future use). Every event carries a CancellationTokenSource linked to the run: cancelling it stops the processing.

A transformation instance is not thread safe: it processes one image at a time. Run concurrent work on separate instances (the UI pipeline, the tiles and the nested steps always create their own).

Options

Every transformation is configured by an immutable record derived from TransformOptions:

  • Common settings (TransformOptions): DistanceMode, Dithering (DitherOptions) and UserPalette (colors chosen by the user: kept by the fast and clustering reductions, used as target palette by the fixed palette mappings).
  • Specific settings, one record per transformation: ClusteringOptions, MedianCutOptions, FastOptions, QuantizationOptions, HsvOptions, ScanlineOptions, CgaOptions, VgaOptions, C64Options, AmigaOptions, CpcOptions, ZxOptions, ...
  • Nested steps are options too: e.g. ScanlineOptions.ChunkReduction, VgaOptions.Reduction and AmigaOptions.BasePaletteReduction accept any ColorReductionOptions (fast, median cut or clustering).
  • Hardware palettes (CGA, EGA, CPC, C64, ZX ...) belong to the transformation and are never stored in the options.

Change a value with a with expression; the same instance can be shared freely:

transform.Options = transform.Options with { MaxColors = 8 };

Options are validated when processing starts (Validate()): invalid values produce an error result instead of an exception. Presets can be saved and loaded as JSON with TransformOptionsSerializer:

TransformOptionsSerializer.Save(transform.Options, "c64-multicolor.json");
var preset = TransformOptionsSerializer.Load("c64-multicolor.json");
var transform2 = ColorTransformBase.CreateColorTransformInterface(preset);

The UI pipeline (background removal, quantization, transformation) is described by PipelineOptions.

Processing

graph TD;
    Source_Image-->Background_Removal;
    Background_Removal-->Color_Quantization;
    Color_Quantization-->Transformation_Map;
    Transformation_Map-->Color_Reduction_Algorithm;
    Color_Reduction_Algorithm-->Dithering;
    Dithering-->Dither_FX;
    Dither_FX-->Output_Image;
Loading

Each ColorTransformBase runs the same pipeline in Process:

  1. load the source and reference images;
  2. validate the options (invalid options give an error result listing every problem);
  3. ExecuteTransform: the single hook of the derived classes, produces the reduced image;
  4. dithering against the reference image, when enabled and the result has at most 256 colors;
  5. evaluation of the mean color error (TransformationError, also in the result with the processing time).

Transformations based on a color map (fast, median cut, clustering, quantization, palette mappings, background removal) derive from ColorTransformMapBase<TOptions> and only implement CreateTransformationMap. Type always comes from the options (TransformOptions.TransformType).

A transformation can skip step 4 by setting BypassDithering inside ExecuteTransform (the flag is reset at every run), when it dithers by itself or when dithering does not apply in its current mode: for example the wide pixel modes (CPC modes 0/3, C64 multicolor, CGA composite) dither at half horizontal resolution, before doubling the pixels back.

Color representation

Colors are stored as packed int values: the lower 24 bits hold the RGB888 color (0xRRGGBB), the upper 8 bits hold a ColorInfo flag (mask, tile, transparent, invalid). Every value that is not a real color is negative, so value < 0 filters it out quickly.

Limitations

Processing algorithms don't support alpha channels: the alpha channel is discarded when an image is loaded, and odd widths are padded to an even number of columns.

To do

A lot of stuff, like sprite masking, raw data export for every system and assembly code generation.

Support

Quantization

Quantization reduces the number of bits for colors channel. The lower value, the less shadow of colors.

Quantization Level Red Shades Green Shades Blue Shades Total selectable colors Notes
8-8-8 256 256 256 16,777,216 24 bit images, SVGA, Amiga AGA
6-6-6 64 64 64 262,144 Amiga HAM8, VGA
5-6-5 32 64 32 65536 16 Bit Hi Color
5-5-5 32 32 32 32768 15 Bit Hi Color, SNES
4-4-4 16 16 16 4096 Amiga OCS/ECS/HAM6, Atari STE, NeoGeo
3-3-3 8 8 8 512 Atari ST, Sega Genesis, PC Engine
2-2-2 4 4 4 64 EGA
1-1-1 2 2 2 8 Basic Color Schemes

To generate an image for Sega Genesis, the proper 3-3-3 color quantization should be selected before processing image. Quantized channels replicate their high bits into the low bits, so the full intensity range is preserved (e.g. 4 bit 0xF becomes 0xFF).

Original Image (22000 colors) 5-6-5 Quantization 4-4-4 Quantization 3-3-3 Quantization 1-1-1 Quantization
Alt text Alt text Alt text Alt text Alt text

Color distance

The metric used to find the nearest palette color is selectable (ColorDistanceEvaluationMode): RGB (squared Euclidean), RGBalt (RGB with cross-channel terms that penalize hue shifts), HSV (circular hue distance), LAB (CIE76 ΔE) and GRAY.

Dithering

Dithering spreads the color reduction approximation errors over the entire image. After the color reduction process, dither tries to simulate the missing color using the remaining color information. Dithering strength can be adjusted to obtain better results.

Family Algorithms
Ordered (Bayer) 2x2, 4x4, 6x6, 8x8
Error diffusion Floyd-Steinberg, Atkinson, Burkes, Jarvis-Judice-Ninke, Sierra, Stucki, ScanLine (current line only)

A post-dithering effect (ColorDitheringFx) can restore every other row or column from the undithered image, producing a scanline-like blend between the dithered and the plain result.

16 Color Image Without Dithering 2x2 Ordered Dithering 4x4 Ordered Dithering Floyd Steinberg Dithering Jarvis, Judice and Ninke Dithering
Alt text Alt text Alt text Alt text Alt text

Color Reduction

There are lots of classic color reduction algorithms. The majority simply reduce the number of colors, while others try also to adapt the source image according to the system screen mode limitations.

Transformation Class Description
Quantization ColorTransformQuantization Channel bit-depth reduction
Fast ColorTransformFast Keeps the most frequent colors
Median cut ColorTransformMedianCut Recursive split along the widest channel
Clustering ColorTransformClustering K-means with reseeding of empty clusters; fixed reference colors never move
Fixed palette ColorTransformFixedPalette Nearest color of a user palette
Enhanced palette ColorTransformFixedPaletteEnhanced Fixed palette plus the mean of every color pair (simulated 50% dither)
Scanline ColorTransformScanLine Palette per group of lines (Amiga copper style), independent or shared palette
HSV adjust ColorTransformLumSat Hue rotation (any value, wrapped on the color wheel), saturation and brightness multipliers; non-color pixels are kept
Background removal ColorTransformBkgRemover Replaces selected background colors
IBM PC ColorTransformHercules, ColorTransformCGA, ColorTransformEGA, ColorTransformVGA Hercules, CGA modes 4/5/6 and composite artifact colors, EGA 16 colors, VGA 256 colors (RGB666)
Commodore 64 ColorTransformCbm64 Hires, Multicolor, FLI, Hires FLI, base and enhanced palette; PETSCII text modes (TextPetsciiUpper, TextPetsciiLower) and multicolor text modes (TextPetsciiUpperMulticolor, TextPetsciiLowerMulticolor); reference palettes
Commodore Amiga ColorTransformCbmAmiga HAM6, HAM8 (each pixel choice scored on the next HamLookahead pixels to reduce fringes), Extra Half-Brite
Amstrad CPC ColorTransformAmstradCPC Modes 0, 1, 2 and 3 on the 27 color palette
ZX Spectrum ColorTransformZxSpectrum 8x8 attribute cells, normal/bright palettes, automatic seed tuning
Text art ColorTransformAsciiArt Every cell becomes the character and the two colors that approximate it best (ASCII, CP437, PETSCII, ATASCII, ZX81, BBC, block mosaics, braille, custom sets)

Tile based modes (C64, ZX Spectrum, scanline) use TileManager, which splits the image into cells and color-reduces each one independently.

Notes on some modes:

  • CGA composite (Composite_0, Composite_1): every pair of adjacent pixels of mode 4 is seen on an NTSC monitor as one of 16 artifact colors. The image is halved horizontally, mapped and dithered, then doubled back. With CgaOptions.OutputMode = RawImage each artifact color is replaced by the two mode 4 pixels that generate it (left pixel in the high bits, high intensity palettes); the palette modes output the processed image unchanged. The true 16 color RGBI palette is available as DebugPalette.
  • Amiga HAM: each pixel is a base palette color or the previous pixel with one channel modified. Choosing by the error of the current pixel only produces color fringes, so every choice is scored on the current pixel plus the next AmigaOptions.HamLookahead pixels (default 2, range 0-4; 0 = previous greedy behavior).
  • Wide pixel modes keep odd image widths: the doubled image is cropped back to the source width.
  • C64 reference palettes (C64Options.ReferencePalette, file ColorTransformCbm64_Palettes.cs): Default (the palette used so far), Pepto, Colodore, Vice, C64S, Ccs64, Frodo, or Custom (16 colors in UserPalette, in C64 color code order). The base and the enhanced palettes, the text modes and the exports are rebuilt from it. The VIC-II colors are analog: an image made with an emulator matches best with the palette of that emulator (e.g. two PETSCII screens made with VICE: error 270 instead of 1213 with Default). The palette values are the commonly published ones and should be checked against the original files of the emulators.
  • C64 multicolor text: a cell is a normal character or a multicolor one (pixel pairs: background, two shared colors $D022 / $D023, cell color). The color RAM bit 3 selects multicolor, so every cell color, also of the normal characters, is 0-7: an image drawn in hires text with colors 8-15 gets worse in this mode.
Original Image (22000 colors)
Alt text
SVGA 256 Colors VGA 256 Colors EGA 16 Colors
Alt text Alt text Alt text
AMIGA HAM8 Mode AMIGA HAM6 Mode AMIGA OCS 16 Colors with Copper
Alt text Alt text Alt text
ATARI STE 16 Colors ATARI ST 16 Colors
Alt text Alt text
Commodore 64 HiRes Mode Commodore 64 LoRes Mode
Alt text Alt text
Zx Spectrum Zx Spectrum Alternative
Alt text Alt text
Amstrad CPC Mode0 Amstrad CPC Mode1 Amstrad CPC Mode2
Alt text Alt text Alt text

Text art

ColorTransformAsciiArt (options AsciiArtOptions, $type AsciiArt) splits the image into cells of the glyph size and gives every cell the character of a character set, and the two palette colors, with the smallest error. The foreground and background errors are independent, so the search is exact and fast (a 40x25 PETSCII screen with 256 characters and 16 colors in well under a second); TextArtConverter does the work and returns a TextScreen.

Setting Values
CharacterSet Ascii, Cp437, PetsciiUpper, PetsciiLower, PetUpper, PetLower (PET / VIC-20), Atascii, BbcMicro, Zx81, Quadrants (2x2), Sextants (2x3, teletext style), Braille (2x4 dots, 8x16 cells)
CharacterSetFile custom set: a .charset.json descriptor with its tile sheet image, or a raw 8x8 ROM file (e.g. your own C64 chargen)
Palette Cga16, C64, Digital8, Mono, Atari, Custom (= UserPalette)
ColorMode Free (two colors per cell, PC text), FixedColors (ForegroundColor / BackgroundColor), SharedBackground (one background for the screen, chosen automatically with AutoBackground, as on the C64)
ErrorMetric Pixel (exact colors), Luminance, Blurred (compares blurred shapes: the typical text art look)
ForegroundColorCount foreground limited to the first N palette colors (8 for the VIC-20)
AllowReverse, ExcludedCodes character filters
ErrorDiffusion 0-1, the error of every cell is spread to the next cells (Floyd-Steinberg weights)
  • The image is not resized: resize it first to columns x rows cells (320x200 for 40x25 8x8 cells, 640x200 for 80x25). The output keeps the source size; the last row and column of cells may be partial.
  • Codes are the ones of the screen memory: Commodore screen codes, Atari internal codes, PC and ASCII codes.
  • The C64 text modes run the conversion with the PETSCII set, the C64 palette and one shared background (C64Options.TextMetric, C64Options.TextErrorDiffusion).
  • Application: the IBM tab has an ASCII group for 8 bit ASCII (code page 437): palette Mono (white on black) or CGA 16 colors (two per character), algorithm (Pixel, Luminance, Blurred), error diffusion and Process; the Text tab shows every option of the transformation (any character set).
  • Export (TextScreen.Save, pipeline step ExportText, button Save text... in the Text tab of the application): .txt UTF-8 text, .ans ANSI art (16 colors, code page 437 bytes for the CP437 set, UTF-8 otherwise), .bin C64 screen data (1000 screen codes, 1000 color RAM values, background color).
  • Custom sets: ColourClashNetCli charset PetsciiUpper --output petscii.png writes any set as an editable tile sheet plus its petscii.charset.json descriptor (glyph size, columns, first code, threshold, reverse codes, Unicode text).
  • The 8x8 sets are generated from the Unscii font sources (public domain / CC0), which reproduce the classic system fonts; the block and braille sets are generated by code. The original ROMs are not distributed: a ROM you own can be loaded with CharacterSetFile.
C64 PETSCII text mode, 40x25 PC CP437, 16 colors, blurred metric, 40x25 ASCII, white on black, blurred metric
C64 PETSCII PC ANSI ASCII

Blob extraction

ColourClashProcessing.Blob.Blob extracts sprites from a sprite sheet:

  1. a global threshold separates foreground from the selected background colors (with tolerance and optional inversion);
  2. foreground pixels are converted into horizontal run lengths;
  3. runs are grouped into blobs by run based connected component labeling (union-find, 4 or 8 connectivity);
  4. blobs are filtered by size.

Each blob can be cut from the source image with a cookie-cut mask, exported as a separate image (BlobTools.ExportImages) or stacked into a single image (BlobTools.ReshapeVertical).

The detector is configured, like the transformations, with immutable records:

var blob = new Blob
{
    Options = new BlobOptions
    {
        Threshold = new ThresholdOptions { BackgroundColors = new[] { 0xFF00FF }, Tolerance = 0 },
        ConnectionMode = BlobConnectionModes.EightConnected,
        MinArea = 10,          // size limits set to 0 are disabled
    },
};
var result = blob.Process(spriteSheet);
blob.Options = blob.Options with { MinArea = 20 };

Pipelines

A pipeline is a JSON file with an ordered list of steps; each step works on the image produced by the previous one.

Step ($type) Settings Action
Load File loads an image (PNG, BMP, JPG ...)
Crop X, Y, Width, Height keeps an area of the image
Resize Width, Height (0 keeps the aspect ratio), Mode (Nearest, Average) resizes the image
Roi Shape (Rectangle, Ellipse, Polygon), X, Y, Width, Height or Points, OutsideColor keeps a region of interest; outside pixels take OutsideColor (a rectangle keeps every pixel)
Transform Options: any transformation options record ($type = Clustering, C64, ZxSpectrum, Amiga ...) runs a transformation
Blob Options (background colors, tolerance, connectivity, size filters), Padding, ExportFolder, ExportPrefix extracts the sprites: the image becomes the sprites stacked, optionally each one saved as PNG
Save File, Format (Auto, Png, Bmp, Jpg, IndexedBmp), Quality saves the current image
ExportText File, Format (Auto, Text, Ansi, C64Screen) writes the text screen of the last text transformation (AsciiArt, C64 text modes)
Export Format (see formats), File, Options writes the result in a machine or source code format (see Export)
Viewer Format (see formats), File, Options (DataFile, Name, Border) writes the program that shows the exported data (see Viewers)

Every step accepts an optional Label. Relative paths are relative to the folder of the pipeline file.

{
  "Version": 1,
  "Name": "ZX Spectrum, autotune",
  "Steps": [
    { "$type": "Load", "File": "photo.png" },
    { "$type": "Resize", "Width": 256, "Height": 192, "Mode": "Average" },
    { "$type": "Transform", "Options": { "$type": "ZxSpectrum", "Autotune": "Fast" } },
    { "$type": "Save", "File": "output/photo-zx.png" }
  ]
}
  • Version: files record the format version (PipelineDefinition.CurrentVersion); a file written by a newer program is refused with a clear message, a file without Version is read as version 1.
  • Hand written files may contain comments and trailing commas, use any letter case and put $type anywhere.
  • Colors are written as "#RRGGBB" (numbers are still read, for older files).
  • Only settings are written: computed values such as TransformType are left out.
  • In code: PipelineSerializer.Load/Save, PipelineDefinition.Validate(), new PipelineRunner().Run(pipeline, image) (step events, progress of the transformations, cancellation; errors are returned in the result).

Ready to run examples are in ColourClash/PipelineExamples, copied next to the executables at every build: common transformations, blob processing, regions of interest and combos (e.g. one photo for four platforms, sprites to the Game Boy palette).

Command line (ColourClash project, executable ColourClashNetCli):

ColourClashNetCli run PipelineExamples/Transformations/zx-autotune.json --input photo.png --output photo-zx.png
ColourClashNetCli validate PipelineExamples
ColourClashNetCli template ZxSpectrum --input photo.png --output out.png > my-pipeline.json
ColourClashNetCli list
ColourClashNetCli charset Cp437 --output cp437.png
ColourClashNetCli formats

run and validate accept several files and folders (every *.json inside, except the *.charset.json character set descriptors). charset without a name lists the built-in character sets; formats lists the export formats. With a single pipeline, --input replaces the first load step and --output the last save step (they are added when missing), --verbose prints the log. Exit codes: 0 success, 1 pipeline failed or invalid, 2 wrong command line or unreadable file.

User interface (menu Pipeline):

  • Save current settings as pipeline: resize (when a resolution is set), background removal (when background colors are picked), quantization (when not RGB888) and the last transformation run; no load and save steps, so the file works on any image (--input, --output on the command line);
  • Run pipeline on current image: runs a pipeline file on the image of the tab, the result is the processed image;
  • Run pipeline in a new tab: for pipelines that load their own image.

Image views and regions of interest

The source and processed images are shown by BitmapRender views:

Mouse Action
Left drag scroll the image; while a shape tool is active: draw the ROI
Middle drag scroll the image
Wheel zoom (25% per notch in manual zoom)
Left double click reset the image position (also "Reset position" in the context menu)
Right click context menu: zoom, reset position, shape tools, grid, color picking

A region of interest (ROI) is drawn with the left button, after choosing a tool in the toolbar (Freehand, Rectangle, Ellipse, Polygon; the button names are in the tooltips) or in the context menu:

  • Freehand, Rectangle, Ellipse: drag to draw;
  • Polygon: click to add vertices, double click, click the first vertex or "Close polygon" in the context menu to close it;
  • once the ROI is drawn the tool turns off and the left button scrolls the image again;
  • drag a handle (box corners and edge midpoints, polygon vertices) to resize or reshape, at any time;
  • drag the round center handle to move the whole ROI.

Grid: the toolbar grid button (or Grid > Show grid in the context menu) draws a pixel grid over the image, with one line style per level: 8 pixels dotted, 16 dash dot dot, 64 dash dot, 128 solid. Levels too dense for the current zoom are hidden. Snap to grid (toolbar button, the arrow chooses 8, 16, 64 or 128) aligns the ROI corners, polygon vertices, moved handles and the moved ROI to the grid; freehand paths are not aligned. The grid settings are shared by the source and processed views.

The ROI is kept in image coordinates (ColourClashNet.Imaging.Shapes.RoiShape), so it follows zoom and scroll, and it is shared by the source and processed views. Rectangles and ellipses snap to whole pixels. While a ROI is drawn or edited its size in image pixels is shown next to it, and the status bar always shows it.

Extract Shape opens the ROI in a new tab, with the size shown. A rectangle keeps every pixel of its box; for the other shapes the pixels outside the shape take the background replacement color, so the background removal can drop them.

Export

Images:

  • PNG, BMP and JPG through SkiaSharp (ImageTools.SaveImage);
  • 8 bit indexed BMP with optional width alignment (ImageTools.SaveImageAsIndexedBitmap);
  • text screens as text, ANSI art and C64 screen data (see Text art).

Machine and source code formats (namespace ColourClashNet.Export, pipeline step Export, menu Export of the application). An export writes data only; the programs that show the data are the viewers.

Id Files
Code.C, Code.Cpp, Code.CSharp, Code.Python palette (0xRRGGBB) and pixels: indexes (optionally packed to 1/2/4 bits), RGB888 or RGB565; flat or one row per array; Python list, tuple or bytes
Text.Hex, Text.Csv, Text.Json, Text.Ppm, Text.Xpm hex dump, CSV of indexes, JSON, plain PPM, XPM
Amiga.Bpl, Amiga.Ibpl sequential / interleaved bitplanes, .pal palette (24 bit or 12 bit)
Amiga.Palette palette only
Amiga.Ilbm IFF ILBM: BMHD, CMAP, CAMG (HAM, EHB, hires, lace), BODY (ByteRun1 optional)
Amiga.AsmOne AsmOne / AsmPro / Devpac data: EQUs, bitplanes in chip RAM aligned with CNOP for the fetch mode (1x / 2x / 4x), palette as 12 bit words or AGA high / low nibbles, line palettes
AtariSt.Degas, AtariSt.DegasElite, AtariSt.Neo Degas (.pi1 / .pi2 / .pi3, 32034 bytes), Degas Elite compressed (.pc1 ...), NEOchrome (.neo, 32128 bytes)
AtariSt.Raw, AtariSt.Devpac 32000 byte screen and 16 word palette; Devpac / vasm data source
C64.Koala Koala Painter (multicolor, 10003 bytes)
C64.Raw .bitmap, .screen, .color
C64.Prg binary loaded at $5C00 (screen, bitmap at $6000, color RAM, background) for the BASIC viewer
C64.Acme ACME !byte source
C64Text.Prg, C64Text.Acme PETSCII text screen: binary at $C000 for the BASIC viewer (codes, colors, background, the two multicolor colors), ACME source
Zx.Scr, Zx.Tap, Zx.Sjasm 6912 byte .scr; tape with the screen as a CODE block (LOAD "name" SCREEN$); sjasmplus source
Cpc.Scr, Cpc.Raw, Cpc.Sjasm 16 KB screen with AMSDOS header, raw screen, sjasmplus source
  • Machine data: every format works on a model of the machine data (IndexedImage, AmigaPlanarImage, AtariStScreen, C64Bitmap, ZxScreen, CpcScreen, TextScreen). The transformations keep what the image cannot tell (IMachineDataSource: the HAM base palette of the Amiga transformation, the text screens); the rest is encoded from the image (image.ToC64Bitmap(...), image.ToAmigaPlanar(...), image.ToAtariStScreen(), image.ToZxScreen(), image.ToCpcScreen(mode)), with the settings of the transformation. The encoders check the limits of the platform: an image that breaks them is still exported with the nearest allowed colors, and the problems are listed as warnings.
  • Typed API: extension methods on the models, e.g. c64.ToKoala(), planar.ToIlbm(true), st.ToDegasElite(false), zx.ToTap("photo"), indexed.ToSourceCode(CodeLanguage.C, options, "logo"); ExportRegistry adds the runtime match (ForData lists the formats available for a result) used by pipelines, the command line and the UI.
  • Descriptions: every raw file gets a .txt file with the same name (photo.bpl.txt): source, transformation, platform, size, depth, bytes per row, layout, palette, warnings. Sources carry the same text as comments.
  • Atari ST: low (320x200, 16 colors), medium (640x200, 4) and high (640x400, 2) resolution, chosen from the image size; palette words for the ST (3 bits per channel) or, with AtariSte, the STE (4 bits).

Viewers

A viewer is a program that shows the exported data. Viewers are kept apart from the exports (namespace ColourClashNet.Export.Viewers, ViewerRegistry, pipeline step Viewer, menu Export > Viewers): each one names the export format of the data it reads, and the viewer step writes only the program. Assembly viewers for every platform, BASIC viewers for the 8 bit machines.

Id Language Data (export) What it does
Amiga.AsmOne AsmOne Amiga.AsmOne includes the data; copper list with palette and line palettes; OCS/ECS lores (32 colors, EHB, HAM6)
AtariSt.Devpac Devpac / vasm AtariSt.Devpac includes the data; GEMDOS program: resolution, palette, copy to the screen, a key quits and restores
C64.Acme ACME C64.Acme includes the data at $2000, BASIC stub (RUN)
C64.Basic BASIC V2 C64.Prg LOAD "NAME",8,1, VIC bank 1, color RAM copy (tokenized .prg and .bas)
C64Text.Acme ACME C64Text.Acme copies screen codes and colors, selects the character set
C64Text.Basic BASIC V2 C64Text.Prg loads the binary at $C000 and copies it
C64Text.BasicData BASIC V2 (included) the screen in DATA lines: small data, no data file
Zx.Sjasm sjasmplus Zx.Sjasm includes the data, copies it to $4000, writes a .sna
Zx.Basic Sinclair BASIC Zx.Tap tape with LOAD "name" SCREEN$ (autostart); put it before the screen tape (copy /b loader.tap + photo.tap all.tap)
Cpc.Sjasm sjasmplus Cpc.Sjasm includes the data; firmware calls for mode, inks and border; SAVEBIN for &4000
Cpc.Basic Locomotive BASIC Cpc.Scr MODE, INK, BORDER, LOAD "NAME.SCR",&C000
  • DataFile names the data file (default: the viewer file name without -viewer, with the extension of the data format); Name the labels of the data source (default: the data file name, as the export does).
  • Assembled by the tests (TestAssemblers): the AsmOne viewers (HAM6, EHB interleaved, scanline with copper palettes), the AGA data (4x fetch) and the Atari ST viewer with vasm (vasmm68k_mot, -Fhunkexe / -Ftos -devpac), the C64 viewers with ACME; every program is checked to hold the exported data (bitplanes, screen, palette). The tests find the assemblers through VASM_M68K / ACME or the PATH and are skipped without them; the CI builds both from source. Not checked: the sjasmplus sources, and no viewer has been run on a real machine or an emulator.

Logging

LogMan (project ColourClashSupport) writes every message to System.Diagnostics.Trace, to a rolling NLog file (./Logs/Log.txt, archived above 4 MB in ./Logs/LogsArchive) and to the LogMan.OnLogMessage event, used by the UI. Each line reports time, level and Class.Method:

2026-11-21 22:30:24.218 | Debug | ColorTransformBase.Process : ColorReductionClustering : processing completed in 243 ms : 16 colors, error 7504
Level Content
Fatal, Exception, Error Failures, with the nested cause and the exception dump
Warning Handled conditions, e.g. cancelled operations
Message Main UI operations: transformation started/completed, blobs found
Debug Start of every heavy step with its parameters, completion with time, colors and error, file load/save
Trace Sub-steps: full options, clustering loops, ZX autotune steps, tile summaries

LogMan.MinLogLevel selects the minimum level and can be changed at any time (the applications start at Message). Use LogMan.IsDebugEnabled/IsTraceEnabled to skip building expensive messages. Transformations log nothing inside pixel loops, and the transformations of the tiles do not log their steps (ColorTransformBase.LogProcessingSteps): errors and exceptions are always logged.

Build and test

dotnet build ColourClashNetSolution.sln

The WinForms projects target Windows; on other systems the solution builds with -p:EnableWindowsTargeting=true, but the UI and the XUnitTester project run on Windows only. The tests are a self-hosted xUnit v3 executable:

dotnet run --project XUnitTester/XUnitTester.csproj

The assembler tests (TestAssemblers) need vasm and ACME; without them they are skipped:

VASM_M68K=/path/to/vasmm68k_mot ACME=/path/to/acme dotnet run --project XUnitTester/XUnitTester.csproj

vasm: make CPU=m68k SYNTAX=mot in the sources from http://sun.hasenbraten.de/vasm; ACME: https://github.com/meonwax/acme.

Continuous integration: .github/workflows/ci.yml builds the solution, builds vasm and ACME (MSYS2 / MinGW), runs the tests (the assembler tests included), then validates and runs every example pipeline with the command line tool, on every push and pull request (Windows runner, .NET 10). The images produced by the examples can be downloaded from the run page (artifact sample-pipeline-results).

The tests do not need external files. Reference pictures made on the real systems, useful to compare the results, are in Images/References/TestImages (Amstrad CPC modes 0/1/2, CGA, C64 hires/multicolor/FLI/PETSCII, Amiga EHB/HAM6/HAM8, ZX Spectrum).

Coding conventions

  • Local variables, parameters and fields are camelCase and carry only the name, without type prefixes (val, not sVal).
  • Properties are PascalCase.
  • Every class keeps sC/sClass (from nameof(Class)) and every method sM/sMethod (from nameof(Method)) for logging with LogMan.
  • Log messages are in English and start with the transformation type when available ({Type} : ...); no logs inside pixel loops.
  • Code, comments and documentation are in English; public types and members are documented with XML comments.

License

MIT, see LICENSE.txt.

The built-in 8x8 character sets (ColourClashLib/Imaging/Text/CharacterSetData.cs) are generated from the Unscii font sources by viznut, released as public domain / CC0.

About

Retro game developing

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages