RMGui 0.15.0
C11 retained-mode UI library: layout kernel, style schema, widget painters, fonts, software framebuffer
Loading...
Searching...
No Matches
Rendering and images

Charts

Need Headers under <rmgui/…>
Store samples chart_series.h — caller-owned ring
Plot with axes chart_plot.h, chart_axis.h — per-column downsampling
Other views chart_bars.h, chart_flame.h, chart_heat.h, chart_candles.h, chart_spark.h

Painters allocate nothing and draw only in clip ∩ rect. Start with the illustrated chart.

Rounded geometry and shadows

Give a face and its casting shadow the same device-pixel radii.

Blue face with four different corner radii
rmgui_corner_radii_t radii = {12, 4, 16, 0};
if (rmgui_draw_fill_rounded_corners(fb, clip, rect, radii, color,
return -1;
@ RMGUI_DRAW_MODE_OVER
Definition draw.h:164
int rmgui_draw_fill_rounded_corners(rmgui_fb_t *fb, rmgui_rect_t clip, rmgui_rect_t rect, rmgui_corner_radii_t radii, rmgui_color_t color, rmgui_draw_mode_t mode)
Paint independent circular corners.
Corner radii in device pixels, clockwise from the top left.
Definition rounded.h:27
Attribute Rule
Order Top left, top right, bottom right, bottom left.
Limits For a casting shadow, set shadow.radii = radii. Nonnegative values clamp to half the shorter edge, rounded down. Use the same face and shadow extent.
Motion Call rmgui_element_motion_visual(m, rs, radii, t, shadow). Device-pixel radii are not scaled again.
Uniform faces Use rmgui_corner_radii_uniform(rs.corner_radius) for resolved controls. Progress has an authored radius; radio indicators use half their width; checkboxes are square.
Sampling rmgui_draw_fill_rounded uses binary scanlines. _rounded_corners antialiases; asymmetric shadows follow that coverage. Uniform shadows retain their legacy silhouette.
Shadow initializer {offset_x, offset_y, {tl, tr, br, bl}, blur_px, color, mode}

Rounded geometry contract

Paths, fills and coverage

CPU linear gradients use exact quotient/remainder stepping for ordinary axes, with the wide-integer path retained for extreme coordinates. Vertical gradients evaluate colour once per row; equal-alpha segments use exact 32-bit reciprocal interpolation. Fractionally translated layers reuse invariant filter fractions and omit identity horizontal interpolation. These paths allocate no storage and preserve the existing integer rounding and premultiplied painter order byte for byte.

paths/path.h builds Move/Line/Quad/Cubic/endpoint-Arc/Close commands into caller-provided command and point arrays. Fill handles nonconvex and self-intersecting contours with nonzero or even-odd winding; stroke supports butt, round and square caps, miter/round/bevel joins, and signed-offset dash arrays. Callers provide flattened-vertex, stroke-geometry and scanline-crossing scratch. Crossing storage needs one rmgui_draw_crossing_t per vertex, including its Y schedule and persistent crossing-order workspace; size it with sizeof, not a fixed byte stride. Exhaustion refuses before pixels change. Curves use deterministic integer subdivision and the same Q8 rounding and 16×16 sample grid as draw_aa; the path contract specifies the flattening tolerance and Q16 range. Target variants snapshot flattened geometry; submit scratch holds the largest command's crossing array plus alignment padding. Native GPU submission explicitly refuses these new operations rather than silently substituting a different rasterizer.

Gradients accept any positive int stop count, including conic gradients with clockwise Q16-turn rotation. Filtered tile and nine-patch painters interpolate premultiplied RGBA before tinting, wrapping tiled axes and clamping stretched axes. rounded.h provides AA independent-corner fills, checked per-side rectangle insets and single-composite side borders. The Paths showcase page exposes curve dragging, dash/cap/join and winding controls alongside these fills. All these CPU painters are integer-only, allocation-free and replay byte-identically through their target variants.

core/mask.h owns 8-bit coverage masks and provides rounded-rectangle, ellipse, convex-polygon and framebuffer-alpha generators. A layout node's optional shape intersects its rounded-rect and clip hit region; rejected pixels fall through to earlier siblings or the enclosing input scope. Masks are stretched by nearest-pixel mapping and hit at coverage 128 or above. The kernel borrows the mask without copying: keep it allocated and unmodified until every snapshot generation using it is no longer queried.

rmgui_input_shape filters pointer and wheel events before any element input call; use a rect enclosing all input regions for grouped elements. Sprite-sheet image buttons (elements/image_button.h) reuse button state and input, select REST/HOVER/PRESSED/DISABLED frames, composite filtered straight-alpha images, and derive a node's hit mask from the REST frame. They paint no label.

Image formats

core/image.h decodes PNG bytes into allocated straight-alpha RGBA8. rmgui_image_codecs_t borrows a caller-sized array of decoder descriptor pointers; initialize it with rmgui_image_codecs_init, explicitly register codecs with rmgui_image_codecs_add, and dispatch by magic using rmgui_image_decode. The first matching codec owns the decode attempt; failure does not fall through to another codec. There is no global registry. PNG's descriptor belongs to image; image_jpeg and image_webp are separate optional modules, linked only when their descriptors or direct decoders are used. Decode success transfers ownership to the caller (rmgui_fb_free); refusal leaves the output unchanged. Pass rmgui_image_limits_t on each decode to set dimension and pixel-count safety bounds, or NULL for the RMGUI_IMAGE_LIMITS_DEFAULT policy (16,384 pixels per side, 16,777,216 pixels). These defaults may be raised; positive int dimensions, representable byte counts and format-specific integer limits still apply. The limits do not bound intermediate allocations or CPU work of crafted compressed streams. The Image formats showcase registers PNG, JPEG and WebP in one local registry. JPEG supports baseline/progressive scans and applies EXIF orientations 1–8; alpha is 255. Malformed EXIF and color profiles are ignored. Its encoded length and decoded RGBA byte count must fit stb's signed int representation. WebP supports still VP8L and VP8 with optional ALPH. VP8L and alpha are exact; lossy RGB uses centered bilinear chroma and integer BT.601, within 3 per channel of libwebp's default fancy-upsampled output. Different YUV-to-RGB upsamplers (including ffmpeg's default conversion) need not meet that RGB bound. Animation is refused; ICC/EXIF/XMP do not modify pixels. rmgui_image_paint composites that framebuffer using an IMAGE snapshot's artwork placement and clips, with nearest-neighbour INTEGER_SCALE and filtered other fits, tint, and the intersection of rounded corners with an optional coverage shape. The showcase's IMAGES page displays embedded procedural PNGs, all four fits, soft alpha and cut-outs, and transactional decode refusals. BUTTON's IMAGE view demonstrates the interactive four-frame image button whose transparent corners are not clickable.

Meshes

<rmgui/mesh.h> loads GLB scenes with 16-bit geometry indices. <rmgui/mesh_large.h> adds 32-bit indices and uses per-primitive UV offsets instead of per-vertex UVs. Both measure the storage needed for the model and its independently mutable poses. The two paint APIs rasterize cel bands and device-pixel outlines with caller-owned supersampling scratch; the large path also supports repeating UVs and sRGB-correct base-level bilinear PNG sampling. GPU meshes consume the same poses as CPU paint.

Each GLB can supply any number of rigid node animation clips within the load budgets. Choose a clip ID from model->clips, or look up a unique name once with rmgui_mesh_large_clip_find. Sample before painting:

int clip = rmgui_mesh_large_clip_find(model, "Inspect");
if (clip < 0)
return RMGUI_MESH_ARGUMENT; /* Explicit binding failed. */
return rmgui_mesh_large_sample_clip(pose, clip, phase_seconds, 1);
@ RMGUI_MESH_ARGUMENT
NULL, nonfinite or otherwise invalid caller argument.
Definition mesh.h:65
int rmgui_mesh_large_clip_find(const rmgui_mesh_large_model_t *model, const char *name)
As rmgui_mesh_clip_find: return a unique exact name match or -1.
rmgui_mesh_result_t rmgui_mesh_large_sample_clip(rmgui_mesh_large_instance_t *instance, int clip, float seconds, int loop)
As rmgui_mesh_sample_clip: sample a clip ID or RMGUI_MESH_REST at a caller-supplied finite time.

The host owns time, input routing and bindings. It can keep a loop's phase while changing its speed, sample a one-shot with loop = 0, or set the authored rest pose with RMGUI_MESH_REST. Sampling preserves node visibility and notification badge changes. It does not start a timer or schedule paints. The desktop showcase binds its bundled icons' Hover clips explicitly and caches the globe's idle image. The bundled GLBs are not installed with the library.

ABI 13 replaces the implicit *_sample functions and model-wide duration with explicit clip selection and per-clip durations. Rebuild consumers against the matching headers and archive. To retain legacy frame-zero behavior, resolve Hover in the host and sample that clip at time zero; RMGUI_MESH_REST may produce a different pose. See the mesh contracts for the supported GLB subset and limits.

CPU and recording targets

gpu/draw_target.h provides explicit CPU and bounded record destinations. The caller supplies command, payload and resource storage before painting; each command is 64 bytes. Prepare every text/size combination with rmgui_font_prepare_to before the first recorded command; preparation may allocate in the CPU font cache, but recording and replay do not allocate. Keep pinned image/mask headers and pixels immutable and alive through submit/discard. Captured glyph coverage and value payloads belong to the stream; sealed child streams and their storage remain alive and immutable through parent submit/discard.

Retained image and mask owners can declare an explicit nonzero identity and generation before the first _to painter uses each source in a stream: rmgui_target_source_stamped(&target, &image, &stamp) or rmgui_target_mask_stamped(&target, &mask, &stamp), where stamp is a caller-owned rmgui_source_stamp_t. Every existing image, composite, blit and mask painter reuses that pin. Keep the stamp alive through submit/discard and increment its generation before recording changed bytes; never reuse a pair for different contents. Native storage retains stamps in its bounded image/mask slots, so eviction explicitly causes a later rehash/upload, not stale output. No new storage allocation or implicit registry is introduced.

RMGUI_VERIFY_PINNED_SOURCES defaults to 1 without NDEBUG, retaining full per-frame mutation checks, and to 0 with NDEBUG. With verification disabled, native stamped sources hash pixels only on a residency miss or generation change, and compare stamps and headers otherwise. Mutation without a generation bump is a caller contract violation and is deliberately undetected. Compatibility pins retain their existing behavior. The package workflow does not define NDEBUG, so public pins (including stamped pins) keep full verification. Optimized packages set RMGUI_OWNED_SOURCE_FAST_PATH=1 only for internally registered, immutable showcase assets such as skin sheets and desktop/backdrop art. Their owners retire outstanding recordings before changing bytes and advance the stamp on each replacement. Headers and stamp generations are still checked at prepare and consume. Default local builds and the native-san package audit these owned assets too. A clean build can still explicitly opt out of public pixel verification using make NATIVE_CC='cc -DRMGUI_VERIFY_PINNED_SOURCES=0' native (use the corresponding compiler variable for other targets), or by adding -DRMGUI_VERIFY_PINNED_SOURCES=0 to RMGUI_CFLAGS in rmgui.mk. Rebuild the library, not just the consumer. make check-source-generation exercises default, explicit NDEBUG and optimized package configurations on software GL.

rmgui_target_finish seals the stream and reports its first failure. rmgui_target_submit validates the whole stream before writing pixels, replays once into a CPU framebuffer and consumes the stream. Supply separate caller-owned replay scratch for simultaneously active layer surfaces; it must not overlap the destination, stream storage or pinned sources. No failed prefix is drawn. Discard resets storage and releases resource references for an explicit retry. Existing framebuffer APIs retain their ABI and pixel semantics; _to painters add explicit destinations. Recording does not implement raw hosted GL rendering or manage a host's graphics context, passes or presentation.

GPU presenters

gpu/native_gpu.h rasterizes sealed draw streams with the native float GPU renderer and fixed create-time capacities, including image/layer pool extents. Pass frame dimensions and optional damage through the prepare descriptor. The host owns its sokol_gfx implementation, setup/shutdown, passes and commits; call native APIs on that host's graphics thread and release before shutdown. Create, prepare and cancel outside passes; consume once inside a host RGBA8, no-depth, single-sample pass. Keep the stream and its borrowed sources alive and immutable until consume or cancel, commit before preparing again after uploads or offscreen draws, and reapply the host's pipeline, bindings, uniforms, viewport and scissor after consume. A failed prepare submits no consuming draw prefix and leaves committed counters unchanged. Destination-snapshot streams require a borrowed same-extent RGBA8 image/view or an explicit transparent initial state; they prepare an offscreen root and replace damaged host pixels at consume. CPU-visible captures require the host's synchronizing readback callback; an explicit framebuffer-identity table opts individual captures into GPU-only output. Native layer shadows and glows support only uniform corner radii. Asymmetric radii are explicitly refused through the native renderer's existing fallback contract; CPU rendering fully supports them.

One native frame, in the order the contract requires (sizes and error handling are the host's):

/* Once, outside any pass, after sg_setup. Every capacity must be positive:
storage.{instances,resources,upload_bytes,atlas_width,atlas_height,glyphs,
resource_width,resource_height} and vertices, indices, parameters, runs,
passes, dependencies. Pools and the rest default to zero. */
rmgui_native_desc_t desc = { /* capacities */ };
rmgui_native_t *native = NULL;
if (rmgui_native_create(&native, &desc) != RMGUI_NATIVE_OK) { /* refused */ }
/* Each frame: record with the usual painters, then seal. */
rmgui_draw_stream_t stream = { /* caller-owned command, payload, resource storage */ };
rmgui_target_t target = rmgui_target_record(&stream, width, height);
/* ... paint into &target ... */
if (rmgui_target_finish(&stream) != RMGUI_TARGET_OK) { /* inspect stream.status */ }
/* Outside any pass: validates everything, then uploads and renders offscreen
work itself. transparent_initial permits a stream that never reads the
destination to omit the initial image. */
.width = width, .height = height, .transparent_initial = 1 };
if (rmgui_native_prepare(native, &stream, &frame) != RMGUI_NATIVE_OK) {
/* rmgui_native_status(native) names the opcode and the exhausted capacity */
}
/* Inside the host's RGBA8, single-sample, no-depth pass: draws only. */
sg_begin_pass(&host_pass);
sg_end_pass();
sg_commit(); /* before the next prepare */
/* Before sg_shutdown, outside any pass. */
rmgui_target_t rmgui_target_record(rmgui_draw_stream_t *stream, int width, int height)
Bind empty caller-owned bounded storage to an extent.
@ RMGUI_TARGET_OK
Definition draw_target.h:32
rmgui_target_status_t rmgui_target_finish(rmgui_draw_stream_t *stream)
Seal once and report the first failure; error releases resources.
struct rmgui_native rmgui_native_t
Independent float GPU renderer.
Definition native_gpu.h:131
rmgui_native_result_t rmgui_native_consume(rmgui_native_t *native)
Consume once inside a host single-sample RGBA8/no-depth pass.
rmgui_native_result_t rmgui_native_create(rmgui_native_t **out, const rmgui_native_desc_t *desc)
Allocate fixed CPU storage and backend handles outside passes.
void rmgui_native_release(rmgui_native_t *native)
Release owned handles/storage outside passes; NULL is a no-op.
rmgui_native_result_t
Failures submit no consuming draws; prepare validates the complete stream before uploads or offscreen...
Definition native_gpu.h:23
@ RMGUI_NATIVE_OK
Definition native_gpu.h:24
rmgui_native_result_t rmgui_native_prepare(rmgui_native_t *native, rmgui_draw_stream_t *stream, const rmgui_native_prepare_desc_t *desc)
Validate the complete sealed tree and all native capabilities before GPU work.
Caller supplies all storage before painting.
Definition draw_target.h:146
GPU payload reservation (no driver alignment, metadata, handle pools, host targets,...
Definition native_gpu.h:186
Device-pixel frame inputs, borrowed through consume/cancel.
Definition native_gpu.h:199
Tagged destination: a record target has no framebuffer or pixel pointer.
Definition draw_target.h:163

gpu/gpu_sokol.h composites into a host-owned sokol_gfx render pass; it is a compositor, not a GPU rasterizer. Painters still rasterize on the CPU into an rmgui_fb_t; the backend uploads dirty rectangles of that framebuffer into a retained GPU image and draws it, and any host-supplied texture view (for example a premultiplied RGBA8 atlas rendered earlier in the frame), inside the host's pass. The host owns its one sokol_gfx implementation, backend macro, sg_setup/sg_shutdown, devices, contexts, swapchains, passes and sg_commit; the library only references sg_* symbols (it never defines them, never calls sg_setup, sg_begin_pass, sg_end_pass or sg_commit, and reads nothing back), so a link that pulls the backend needs the host's one sokol_gfx implementation, built from the pin recorded in rmgui.target. Uploads run outside a pass, drawing runs between rmgui_gpu_begin and rmgui_gpu_end inside one, and the host reapplies its own pipeline, bindings, uniforms, viewport and scissor afterwards. Shaders are generated from one source (gpu/gpu_sokol.glsl) by tools/sokol-shaders.sh into a glsl430+300es variant (default) and a glsl410+300es variant (macos-arm64 default). Both also carry HLSL5/D3D11 and Metal macOS source payloads; the host's sokol backend compiles them at runtime. Admission requires a generated descriptor for the runtime backend and the required format capabilities. GPU output matches the CPU composite within 1 LSB, not bit-exactly, so the pixel-exact gates cover only the CPU path. Verified on software GL 4.5 core, GLES 3.2 and WebGL2 (llvmpipe, SwiftShader). The native path's gpu_bench has also been verified on hardware GLES 3.2: Intel UHD P630 (Mesa iris) passes all scenes, and AMD Radeon RX 7800 XT (Mesa radeonsi 26.1.8) passes all except an intermittent single-pixel DCC artifact in retained-damage cases with tiny overlapping opaque fills (AMD_DEBUG=nodcc eliminates it). GL 4.1 has not been tested directly.

Native D3D11/Metal rendering and runtime shader compilation have not been executed in CI. Projection Y follows sokol's +Y-up clip space independently of framebuffer/texture origin; borrowed textures retain the explicit v_up storage-row contract. Cross-build checks link Windows PE images and compile Metal objects (Metal linking requires Darwin compiler-rt on a macOS host).

gpu/gpu_mesh.h draws loaded 3D mesh models inline inside 2D UI layouts under the same host-owned pass contract (for example, rotating 3D buttons, globes, or icons that composite directly with flat controls). Create once per immutable model outside a pass, then begin/draw/end inside a pass; model and instance storage remain caller-owned. The host must provide a depth attachment and reapply its render state afterwards. Cel lighting uses the CPU style's linear bands. An sRGB attachment provides linear-light blending; RGBA8 encodes shader output before fixed-function blending, so translucent overlaps differ from the CPU oracle. GPU antialiasing follows the host attachment sample count, not the CPU style's supersample field. Inverted-hull outlines expand the silhouette in device pixels; they do not reproduce CPU screen-space internal depth/material edges. The optional ABI 5 radial emerald style remains available independently of the globe. tools/sokol-shaders.sh regenerates and --check verifies all compositor, mesh and cloud headers with the same pinned compiler/language set.

rmgui_gpu_mesh_raster_* in the same header renders one large pose into a retained RGBA8 texture that matches rmgui_mesh_large_paint onto transparent black (encoded-space premultiplied, y-down rows, v_up 0), including supersample resolve and the CPU's depth-edge outline. It is for poses that change every frame: after creation a pose uploads nothing, only uniforms and draws. Call rmgui_gpu_mesh_raster_query first; on OpenGL core, ES 3 and WebGL2 devices with renderable RGBA32F it reports zero missing capabilities, and otherwise names the missing one so the caller can keep its CPU path. Draw the returned tile with your own compositor; destination blending, tint and obscuration stay with the caller. The scene pass repeats the CPU's per-sample arithmetic instead of using rasteriser interpolation, so the tile is byte-identical to the CPU result on llvmpipe (OpenGL core and ES 3) in every measured case; other devices can differ at isolated decision-boundary samples by their float behaviour, which the consumer should measure on its own hardware. make check-gpu-mesh reports every case.

gpu/gpu_cloud_orb.h remains an exported ABI 5 texture-free volume renderer; the showcase start button does not use it. Its continuous motion has 2 s acceleration and 0.5 s deceleration. Its 128-byte params hold eight aligned vec4 values, with linear palette RGB and model-local orthonormal camera axes. The host creates/destroys outside passes and draws inside begin/end, after opaque content and before a transparent shell. Output is straight linear RGBA; use an sRGB attachment or a linear intermediate and perform output transfer once after compositing. No CPU cloud oracle exists. make check-gpu-cloud-orb, -gles3, and -webgl2 exercise the shader; the matching check-gpu-mesh targets compare cel rendering with the CPU oracle.