A 2D drawing framework for BlitzMax NG, with familiar functions such as
DrawImage, DrawText, DrawRect and Flip across OpenGL, Direct3D and SDL3
backends.
Use it for sprites and animation, cameras, render-to-texture, scalable text, texture atlases and tile-based games. The shared drawing API handles batching, drawing state, virtual resolution and input-coordinate conversion, so you can choose a backend without rewriting your scene code.
- Get started
- Choose a backend
- What you can build
- Effects and group masks
- Optional modules
- Moving from BRL.Max2D
- Capabilities and limitations
- Examples and documentation
Use a bcc2-based BlitzMax NG SDK with up-to-date BRL, Pub, Text and Math
modules. In particular, the core uses BRL.PixelFormat, BRL.TextureData,
Text.Boundaries, Text.Bidi and Math.Polygon. The native Unicode providers
are optional; see text and fonts.
From the SDK directory, install this repository as mod/max2d.mod:
git clone https://github.com/bmx-ng/max2d.mod.git mod/max2d.modFor either SDL3 backend, also install
SDL3 as mod/sdl3.mod and follow its platform
setup instructions. SDL3 is built from bundled sources; no separate SDL library
is required. Linux SDL3 builds need BMK2 4.04 or newer.
Save this as hello.bmx in your SDK directory:
SuperStrict
Framework Max2D.GLMax2D
Graphics 800, 450
SetClsColor 24, 28, 38
While Not KeyDown(KEY_ESCAPE) And Not AppTerminate()
Cls
SetColor 55, 170, 240
DrawRect 40, 40, 160, 100
SetColor 255, 255, 255
DrawText "Hello from Max2D!", 40, 170
Flip
Wend
EndGraphicsBuild and run it in your IDE, or build it from the SDK directory:
./bin/bmk makeapp -r -t gui hello.bmxOn Windows:
.\bin\bmk.exe makeapp -r -t gui hello.bmxRun the executable or application bundle generated beside the source file.
Press Escape or close the window to quit. The built-in font needs no asset files.
Import an image or font loader when you start loading your own assets—for example,
BRL.PNGLoader for PNG images or BRL.FreeTypeFont for ordinary outline fonts.
Select one backend with the application's Framework line. Each imports
Max2D.Core, which provides the common drawing API.
| Framework | Use it for |
|---|---|
Max2D.GLMax2D |
Desktop OpenGL through BRL.GLGraphics on macOS, Windows and Linux/X11. Requires OpenGL 2.1, GLSL 1.20 and framebuffer-object support. |
Max2D.SDL3RenderMax2D |
SDL's renderer API on macOS, Windows and Linux, with SDL choosing an available rendering driver. |
Max2D.SDL3GPUMax2D |
Direct use of SDL's GPU API through Metal, Vulkan or Direct3D 12, subject to platform and device support. |
Max2D.D3D9Max2D |
Native Direct3D9 rendering on Windows. |
Max2D.D3D11Max2D |
Native Direct3D11 rendering on Windows. |
The two SDL3 backends are separate implementations. Selecting a renderer called
gpu within SDL_Renderer still uses Max2D.SDL3RenderMax2D; it does not switch to
the direct GPU backend. See the SDL GPU guide for choosing between
them and checking device availability.
Backend guides: OpenGL, D3D9, D3D11, SDL GPU.
- Draw shapes, images, animation frames and text with ordered batching.
- Pan, zoom and rotate with
TCamera2D; convert window, virtual and world coordinates for mouse picking. - Use
SetVirtualResolution(320, 180, VIRTUAL_LETTERBOX)for a fixed canvas with aspect-preserving bars, orVIRTUAL_INTEGERfor whole-number scaling when it fits. - Draw native-resolution overlays independently of a virtual scene.
- Save and restore drawing state manually with
PushMax2DState/PopMax2DState, or automatically withScopedMax2DState()in aUsingblock. - Switch between windowed, borderless and exclusive fullscreen where supported.
Virtual resolution changes drawing coordinates. To render a deliberately low-resolution scene, draw into a small render image and scale it up. Camera and mouse conversions account for display scaling and letterbox bars.
See cameras, drawing state, window modes and virtual resolution and input.
Load images from existing pixmap loaders, draw into render images, update dynamic images, and share texture storage between sprite views. Alpha-mask collisions support animation, atlas regions and transformed images.
Build atlases at runtime or with the included atlas builder. Trim transparent borders while retaining sprite size and drawing position; save PNG/JSON atlas packages with names, handles, animation frames and timing.
For explicit GPU storage, use BRL.TextureData to supply mip levels, single-channel
coverage, floating-point pixels or BC1/BC3 compressed data on supported backends.
Import Image.DDS to load supported DDS files without expanding their compressed
blocks into pixmaps. Ordinary TPixmap image loading remains available.
See images and atlases, atlas packages, collisions, texture data, mipmaps and compressed textures.
Use SetBlend(SUBTRACTBLEND) to darken the destination by the source colour
multiplied by its alpha. Use CreateBlendMode(...) for custom colour and alpha
factors and operations; its return value works with the ordinary SetBlend,
GetBlend and drawing-state functions. Check Max2DSupportsBlend after opening
graphics, because available combinations depend on the backend and device.
See Blending: recipes and backend support, the blend gallery and blending into a transparent image.
Use DrawText for simple labels, or prepare reusable paragraph layouts with
wrapping, alignment, font/colour spans and backgrounds. Optional interaction
geometry supports caret placement, hit testing and selection in scrollable text.
A selection controller handles character, word and line selection, including drag.
Import Max2D.RichText to prepare inline tags such as [b]bold[/b],
[color=#FFD060]gold[/color] and [style=heading]Title[/style]. Parse content once,
resolve it using registered fonts and styles, and reuse the ordinary text layout
cache. See inline rich text and the
interactive example.
Import Max2D.ScalableFont for FreeType/HarfBuzz text that selects an appropriate
glyph raster size for the current display scale and drawing transform. Load the
actual font faces you need; automatic font fallback is not provided.
International text features are added by import:
Text.Unibreaksupplies Unicode line, word and grapheme boundaries.Text.SheenBidisupplies bidirectional analysis for mixed-direction text.
Without those providers, the core retains its basic layout behaviour and does not link their native libraries. Fonts are supplied by your application.
See text layout and interaction and font loading and caches.
Start with Applying effects: provider selection, a complete runnable example, and guidance on when to draw directly, build a layer chain, or cache a result. The API uses ordinary Max2D images, transforms, colour, alpha and blending.
- Direct effects: saturation, colourize, colour matrices, distortion, displacement, dissolve and texture masks.
- Layer effects: ordered chains, blur, outlines, alpha masks and cutouts.
- Cached helpers: reusable buffers, bloom, soft shadows and inner shadows.
- Colour and output: linear artwork conversion, floating-point composition, tone mapping and optional SDL GPU HDR display output.
Shader providers are available for SDL GPU, OpenGL, native D3D9 and native D3D11. Import the provider matching your framework and query its capabilities.
Continue with effects and masking, shader packages, or HDR output. Explore the two-page gallery for visual comparisons. Flux Pinball and Afterlight show effects in playable applications.
Create editable maps in code without an external editor, or load Tiled and LDtk projects through optional modules. The native tilemap API includes orthogonal, isometric, staggered isometric and pointy/flat hex layouts.
Use camera-aware picking, visible-area rendering, animated tiles, properties, region queries and ground-depth sorting. Hex helpers provide coordinate conversion, neighbours, distances, ranges and rings.
Start with the tilemap guide or the asset-free hex-board example. Editor guides: Tiled and LDtk.
Import these when your application needs them. Their dependencies are separate from the basic drawing API.
| Module | Adds |
|---|---|
Max2D.Scene |
Optional node trees, transforms, rendering, interaction, culling and inspection. |
Max2D.SceneTileMap |
Scene adapter for shared tilemaps, explicit animation clocks and capture invalidation; see adapters. |
Max2D.SceneParticles |
Fixed-capacity scene particle batches with automatic local bounds and lifetime fading. |
Max2D.SceneAnimation |
Optional retained transform/opacity timelines; see scene animation. |
Max2D.SceneEffects |
Scene composites, automatic caches, storage budgets and retained effect stages. |
Max2D.Lighting |
Image lighting, receiver materials, occluders and capability-based grouped rendering. |
Max2D.SceneLighting |
Scene light/occluder nodes, lit sprites and retained custom canvases; uses Max2D.Lighting. |
Max2D.Profiling |
Optional asynchronous elapsed-GPU timing contract. |
Max2D.GLProfiling |
OpenGL timer-query provider; see GPU profiling. |
Max2D.D3DProfiling |
Optional Direct3D 9/11 timestamp-query provider, including unreliable-sample accounting. |
Max2D.Effects |
Shared effect descriptions, layer operations, buffer owners, bloom and shadows; no shader provider. |
Max2D.SDL3GPUEffects / Max2D.GLEffects |
Built-in and packaged effects for SDL GPU / OpenGL. |
Max2D.D3D11Effects / Max2D.D3D9Effects |
Built-in and packaged image effects for the native Windows renderers; D3D9 effects require shader 3.0. |
Max2D.ShaderEffects |
Shared shader-package assets, parameters and factories. Imported by all four effects providers; use a matching provider to draw. |
Max2D.Atlas |
Batch atlas construction using BRL.RectPacker. Runtime atlas allocation is already in Core. |
Max2D.AtlasIO |
PNG/JSON atlas packages; uses Image.PNG and Text.JSON. |
Max2D.RichText |
Optional inline markup, named styles and registered font variants over the paragraph API. |
Max2D.ScalableFont |
Scalable, shaped text using Text.HBFreeTypeFont. |
Max2D.VirtualJoystick |
Safe-area-aware floating or fixed onscreen stick and action buttons for touch games. |
Max2D.TileMap |
Native editable tilemaps, rendering, picking and geometry queries. |
Max2D.Tiled |
Tiled XML/JSON maps, tilesets and templates; uses Text.XML, Text.JSON and Archive.ZLib. |
Max2D.TiledZstd |
Optional zstd decoding for Tiled maps; uses Archive.Zstd. |
Max2D.LDTK |
LDtk projects, levels, tiles, IntGrid, entities and backgrounds; uses Text.JSON. |
The virtual joystick renders at native window resolution, independently of the game's virtual scene, and can use otherwise empty presentation bars. See the virtual joystick guide and example.
On macOS, Windows and Linux/X11, Max2D.SDL3RenderMax2D and Max2D.SDL3GPUMax2D support drawing into MaxGUI canvases when you
also import SDL3.SDL3MaxGUI. MaxGUI keeps its native controls, input and event
loop. See the SDL3 canvas guide
and sdl3.mod/sdl3maxgui.mod/examples/canvas.bmx in your SDK. This requires
BRL.System 1.31. On Linux, launch with GDK_BACKEND=x11; XWayland is supported,
while native Wayland canvas attachment remains future work.
The familiar drawing functions are retained, but Max2D.Core has its own image,
font, context and driver types. Use one Max2D namespace in an application: do
not import BRL.Max2D alongside it, including indirectly through helper modules.
Start by changing the framework import, then check any code that accesses
low-level image frames, implements a custom driver or assumes a particular
relationship between window coordinates and drawable pixels. Existing image
loaders can still provide TPixmap data.
See the API compatibility guide for supported calls and intentional differences. The ported SDK samples show practical migration examples, including Oldskool2, viewport clipping, snowfall and background image loading.
Query the active context before relying on optional features:
Max2DSupportsBlend, Max2DSupportsImageFlags, Max2DTextureDataSupport,
Max2DSupportsFullscreen and Max2DSupportsBorderlessFullscreen.
Use Max2DStats to inspect rendering counters and diagnose batching, upload and
readback costs. See capabilities and statistics.
Some choices affect which backend or asset workflow you need:
- SDL3 Renderer does not support mipmaps. Its
MASKBLENDsupport depends on the selected renderer and the available masking path; see SDL3 masking. - Packed atlases do not support mipmaps or rotated packing.
- Scalable fonts do not provide automatic fallback, colour glyphs or vertical layout.
- Native widget attachment is available for SDL3 MaxGUI canvases; see MaxGUI canvases. Other backend/widget combinations are not supported.
Max2D.D3D7Max2Dremains disabled pending hardware validation; D3D9 is the supported Direct3D minimum.
Rendering belongs on the main rendering thread. Draw order is preserved, but queued work may be flushed by target changes, uploads or readbacks. Images loaded from CPU data can be used across contexts; render images belong to the context that created them. Do not sample a render image while it is the active target. See resource and rendering rules.
The backend capability matrix and validation notes describe tested configurations and platform-specific limits.
For a complete playable project, try Afterlight, a three-room greenhouse puzzle combining tilemaps, touch controls, text, masked layers, cached bloom and shadows. More complete applications live in demos.
Build examples from your SDK directory, for example:
./bin/bmk makeapp -r -t gui mod/max2d.mod/examples/camera.bmx| Example | Explore |
|---|---|
| composition_helpers.bmx | Padded capture, resolution scaling and retained effect chains; see the guide. |
| effects_quickstart.bmx | Direct effects, a retained chain and a cached shadow without assets. |
| gl_hello.bmx | OpenGL drawing with virtual and native coordinates. |
| sdl_gpu_hello.bmx | The direct SDL GPU backend. |
| scene_alpha_masks.bmx | Soft local alpha masks, inverted cutouts, transformed clipping and optional CPU alpha picking. |
| scene_clipping.bmx | Local rectangular clipping, rotated and nested panels, matching pointer picking and cached captures. |
| scene_composite.bmx | Cached subtree composition, flattened opacity, animated bloom, shared memory budgets, bounds overlays and live processing counters. |
| scene_shadows.bmx | Cached outer and inner shadows with animated logical offsets. |
| scene_lit_canvas.bmx | Retained text, mesh and shape artwork with shared scene lighting and materials. |
| scene_stages.bmx | Explicit scene capture and retained effect stages. |
| scene_culling.bmx | Culling and render statistics across 2,500 grouped tiles. |
| scene_controls.bmx | Hover, keyboard focus, key routing and dragging. |
| scene_drag.bmx | Dragging through pointer event routing and capture. |
| scene_picking.bmx | Pointer picking through transformed, overlapping cards. |
| scene_bounds_order.bmx | Cached subtree bounds and stable sibling draw ordering. |
| scene_material_maps.bmx | Separate emission/specular artwork on lit sprites and deforming meshes, with interactive toggles. |
| scene_lit_mesh.bmx | Animated textured geometry with normal/specular materials and a movable point light. |
| scene_textured_mesh.bmx | Retained textured grid with animated vertices and shared artwork. |
| scene_gallery.bmx | Retained scene sprites, text, meshes, custom drawing and layer views. |
| scene_tree.bmx | Scene ownership, explicit updates and affine coordinates (console). |
| camera.bmx | A moving, rotating view and minimap. |
| drawing_state.bmx | Nested transforms, clips and state restoration. |
| presentation.bmx | Letterboxing, integer scaling and mouse mapping. |
| paragraph.bmx | Retained text layout. |
| paragraph_bidi.bmx | Mixed-direction text, scrolling and selection. |
| atlas_animation.bmx | Trimming and timed animation. |
| hex_board.bmx | An interactive hex grid without external assets. |
| rendering_diagnostics.bmx | Capabilities and rendering statistics. |
Some examples require a font path, an asset directory or SDL3; see their source headers and linked guides. Additional map viewers are provided in tiled.mod/examples and ldtk.mod/examples.
For more detail, read the drawing guide, browse topic guides, or use the module's bbdoc API documentation. Maintainers can find regression commands in stabilisation and performance measurements in benchmarks.
Max2D.Scene now provides reusable object trees, lifecycle callbacks, explicit
updates and affine transforms without requiring a graphics context. Its optional
render traversal draws sprites, text, meshes and custom geometry on the current
Max2D target. Start with the foundation guide and
rendering guide, followed by bounds and ordering,
coordinates and picking, and
pointer routing and capture and
hover and keyboard focus, then
culling and render diagnostics. The optional
effect-stage module provides layouts and retained chains,
with composite nodes and automatic caches, local
rectangular clips and alpha masks with optional picking.
See the design and behavioural specification,
API outline and worked examples.
The development sequence separates
remaining work from implemented capabilities.
The November capability review
summarises scenes, effects and lighting, their current capabilities and measured limits.
For a complete scene-framework application, see the Reactor Workshop, including a reusable component, interactive controls and capture/resource checks. The Touch Playground adds simultaneous dragging, native SDL3 input conversion and cancellation experiments. Camera World completes the set with camera-aware picking, a fixed HUD and ordinary drawing alongside the scene. See also the scene performance measurements for reproducible warmed allocation and rendering benchmarks, and platform validation for correctness checks and known toolchain limitations.
The lighting guide covers ambient, coloured point and directional lights, scene light nodes, textured point lights, selective receivers, normal-mapped and specular materials (including per-pixel gloss), light height, unlit HUDs, and optional cached composition. Light Lab is a complete interactive example. Convex and concave occluders add hard or filtered point and directional shadows with independent caster masks, finite caster heights and receiver control. Reusable lighting diagnostics and a stress benchmark expose pass counts, shadow reuse and retained storage. Optional grouped lighting combines up to sixteen lights per pass, including normal/specular materials, projected patterns and shadow maps up to 512×512. The first eligible group also composes ambient, saving one draw per eligible receiver, including single-light receivers. Emission maps can join that group alongside shadows and patterns where the four-texture material shader is supported. Separate specular maps use a fifth sampler where supported, avoiding CPU normal-alpha packing while retaining the packed fallback. Native D3D9 retains eight-light groups; other backends fall back when the larger shader is unavailable. Batching also combines non-overlapping deformed meshes into one draw per light group, preserving per-triangle normal mapping and ordered fallback for unsupported cases. See mesh lighting. Backend authors can use the optional lighting renderer contract to supply grouped lighting independently of image-effect texture and parameter limits. Distance-dependent penumbras remain a planned extension.
Max2D uses the zlib/libpng licence. See NOTICE.md for third-party code and example asset credits.