Skip to content

SDL graphics: add an SDL3 backend for 2D and 3D - #693

Open
Jafaral wants to merge 36 commits into
uniconproject:masterfrom
Jafaral:sdl3-graphics
Open

Jafaral wants to merge 36 commits into
uniconproject:masterfrom
Jafaral:sdl3-graphics

Conversation

@Jafaral

@Jafaral Jafaral commented Nov 1, 2026

Copy link
Copy Markdown
Member

No description provided.

@greptile-apps

greptile-apps Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge, with two non-blocking fixes needed in the Windows FreeType setup.

Findings

  1. P2 Disabled FreeType gets enabled ▶
  2. P2 Windows instructions miss required DLLs ▶
Fix with agent prompt
### Issue 1
configure.ac:863
The new Windows retry ignores `--without-freetype`. `CHECK_FREETYPE()` skips its check when that option is set, but this branch still tries the import library and enables FreeType if it succeeds. Users can get a dependency they explicitly disabled. Check `with_freetype` here too, so configure reports the missing required library instead of overriding their choice.

### Issue 2
configure.ac:878
The new `libfreetype.dll.a` fallback adds a FreeType DLL dependency, but the Windows instructions still tell users to copy only `SDL3.dll`. Users who follow that advice to run outside MSYS2 get a missing-DLL error before the program starts. Update the instructions to include FreeType and its required DLLs, or tell users to keep the UCRT64 `bin` directory on `PATH`.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds an SDL3 graphics backend with a software canvas for 2D drawing and OpenGL for 3D.

  • Unicon’s SDL3 windows draw and show graphics through software canvases.
  • SDL3 3D windows show OpenGL frames through the same canvas as 2D graphics.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Unicon graphics calls] --> B[SDL runtime backend]
  B --> C[Software canvas]
  B --> D[OpenGL framebuffer]
  D --> C
  C --> E[SDL3 window]
  E --> F[Unicon input events]
Loading

Reviews (6) · Last reviewed commit: "SDL graphics: find FreeType under the MS..." · Reviewed by Greptile

Comment thread ipl/gincl/keysyms.icn Resolved
Comment thread src/common/ucanvas.c Resolved
Comment thread src/runtime/rsdlwin.ri Resolved
Comment thread src/runtime/rsdlwin.ri Resolved
Comment thread src/common/ucanvas.c Resolved
Comment thread src/runtime/rsdlwin.ri Resolved
Comment thread src/runtime/rsdlwin.ri Resolved
Comment thread configure.ac
CHECK_FREETYPE()
# Windows links with --static, which does not pick up the DLL
# import library. Name it, as for SDL3.
if test "x$cv_libfreetype" != "xyes" -a "ms$unicon_os" = "mswindows" ; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Disabled FreeType gets enabled

The new Windows retry ignores --without-freetype. CHECK_FREETYPE() skips its check when that option is set, but this branch still tries the import library and enables FreeType if it succeeds. Users can get a dependency they explicitly disabled. Check with_freetype here too, so configure reports the missing required library instead of overriding their choice.

Prompt To Fix With AI
This is a comment left during a code review.
Path: configure.ac
Line: 863

Comment:
**Disabled FreeType gets enabled**

The new Windows retry ignores `--without-freetype`. `CHECK_FREETYPE()` skips its check when that option is set, but this branch still tries the import library and enables FreeType if it succeeds. Users can get a dependency they explicitly disabled. Check `with_freetype` here too, so configure reports the missing required library instead of overriding their choice.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread configure.ac
fi
CPPFLAGS="$CPPFLAGS $ft_cflags"
LDFLAGS="$LDFLAGS $ft_lflags"
LIBS="-l:libfreetype.dll.a $LIBS"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Windows instructions miss required DLLs

The new libfreetype.dll.a fallback adds a FreeType DLL dependency, but the Windows instructions still tell users to copy only SDL3.dll. Users who follow that advice to run outside MSYS2 get a missing-DLL error before the program starts. Update the instructions to include FreeType and its required DLLs, or tell users to keep the UCRT64 bin directory on PATH.

Prompt To Fix With AI
This is a comment left during a code review.
Path: configure.ac
Line: 878

Comment:
**Windows instructions miss required DLLs**

The new `libfreetype.dll.a` fallback adds a FreeType DLL dependency, but the Windows instructions still tell users to copy only `SDL3.dll`. Users who follow that advice to run outside MSYS2 get a missing-DLL error before the program starts. Update the instructions to include FreeType and its required DLLs, or tell users to keep the UCRT64 `bin` directory on `PATH`.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

ucanvas is a 32-bit pixel buffer with a rasterizer for everything the
2D graphics facilities draw: points, thin and wide lines with dashes,
rectangles, polygons, arcs and pie slices, and text through FreeType.
Drawing honours the Unicon graphics context: drawing operation (all
sixteen, plus the reverse mode the caller expresses as xor), line width
and style, fill style with stipple patterns, and the clip rectangle.

The geometry follows X11 so programs render the same way: thin lines
include both end points, filled shapes include the pixels whose centres
lie inside, and an outlined w x h figure covers (w+1) x (h+1) pixels.
Wide lines are rasterized into a coverage mask first, so xor and the
other non-idempotent operations touch each pixel once at the joins.

Fonts are found with fontconfig when it is available, and otherwise in
the usual font directories (including the macOS system fonts). The
portable families mono, typewriter, sans and serif map to the closest
installed faces; a font file can also be named directly.  Bold and
italic are synthesized when a family lacks them.

The canvas is plain C with no window-system dependency.  It is compiled
only for the SDL graphics backend, which follows.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
usdlwin is the window-system half of the SDL graphics backend.  It
creates native windows (Cocoa on macOS, X11 or Wayland on Linux, Win32
on Windows), shows a canvas in one by uploading only the part that
changed, and translates SDL input into the events the runtime expects:

- keys that produce text arrive as Latin-1 characters through SDL text
  input, so keyboard layouts and dead keys work;
- Ctrl and Alt/Cmd combinations, Return, Tab, BackSpace, Escape and
  Delete produce the same characters XLookupString does;
- outboard keys (arrows, function keys, Home, ...) produce their X11
  keysyms, which is what keysyms.icn and the GUI library use;
- mouse buttons 1-3, motion with the held buttons, wheel steps (with
  fractional trackpad motion accumulated), resize, move, close
  requests and expose/state changes.

Pointer, cursor shape and clipboard (converted between Latin-1 and
UTF-8) are here too.  SDL is told not to quit when the last window
closes and not to install signal handlers; the runtime owns both.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
rsdlwin.ri is a third window-system backend next to rxwin.ri and
rmswin.ri, selected by SDLGraphics.  Each canvas is a software canvas
(ucanvas) that plays the role of the X backend's backing pixmap; an
on-screen canvas also has an SDL window (usdlwin) that displays it.
Hidden canvases, CopyArea, Pixel, WriteImage and the drawing
operations therefore behave the same way on every platform.

The code follows rxwin.ri closely so programs see the same behaviour:
the same event codes and modifier bits, X11 keysyms for outboard keys,
cooked-mode text output and echo, the text cursor, resize events,
WindowClosureMask handling, canvas states, X cursor names (mapped to
the closest system cursors), patterns, the X11 color names, and a
default gamma equal to the one the X backend computes, so colors come
out the same.  Image formats are the generic ones (GIF, BMP, PNG,
JPEG).  The selection is the system clipboard.

Output reaches the screen when the program waits for an event, calls
WFlush()/WSync(), or (at most every 30ms) when the interpreter polls.

Not supported yet: 3D graphics, mutable colors (NewColor() fails),
window icons, and lowering a window.  SDL must be driven from the
main thread, so graphics from Unicon threads other than the main one
are not supported on macOS.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
On macOS, configure now builds the SDL3 graphics backend when SDL3 and
FreeType are installed, so Unicon graphics no longer need XQuartz.  If
SDL3 is missing it falls back to X11 as before, and
--disable-sdl-graphics asks for X11 explicitly.  Elsewhere X11 stays
the default and --enable-sdl-graphics selects SDL3 (an error if SDL3
or FreeType cannot be found).  The SDL backend is 2D only, so 3D
graphics are turned off when it is selected.

SDL3, FreeType and the optional fontconfig are located through
pkg-config when no --with-PACKAGE=DIR is given, which finds Homebrew
installs on both Intel and Apple silicon Macs.  Xft and libXpm are not
checked for an SDL build, and the summary shows +SDL3 in place of
+X11.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Predefine _SDL_GRAPHICS for the "SDL graphics" feature, as is done for
_X_WINDOW_SYSTEM.  The SDL backend reports outboard keys with their X11
key symbols, so keysyms.icn now defines _X_KEYSYMS for either window
system and gives both the X11 values; vtext and tgrmap test that symbol
instead of _X_WINDOW_SYSTEM.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
macOS builds need SDL3 and FreeType (from Homebrew, for example) for
graphics instead of XQuartz; Linux builds can opt in with
--enable-sdl-graphics.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Without fontconfig (the usual case on macOS), a family name other than
the portable ones only matched a file named exactly after it.  Now the
font directories are also scanned for files whose names start with the
family, ignoring case, spaces and punctuation, so "Courier New" finds
Courier New.ttf and "DejaVu Sans" finds DejaVuSans.ttf.

A font given as a file ("/path/to/face.ttf,16") was cut short by
parsefont()'s 40-character limit on the family word.  Take the file
name as written and parse only the rest of the spec.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Coordinates come from programs as arbitrary integers.  A thin line to
a point millions of pixels away walked every one of them; a dashed
wide line generated every dash; and a few int conversions could
overflow.  Found by fuzzing the canvas under ASan and UBSan with
random primitives, states and coordinates up to +/-2e9.

Very long thin lines and dashed wide lines are now cut down to the
part near the clip region first, carrying the dash phase over, so the
pixels drawn on the canvas do not change.  Rectangle fills clip in
long arithmetic, and double-to-int conversions saturate.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Closing a window from the window manager (without "c" in the input
mask) freed the window binding while Event() was still waiting on it,
which crashed with a memory violation.  Like the X11 backend, the
window now just goes away: the closed event is queued, Event() delivers
it and stops further I/O on the window (error 142 afterwards), and the
binding and canvas live until the program closes the window.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
After WAttrib() maximizes, iconifies, moves or resizes a window, handle
the window system's replies before returning, so that the attributes
read next ("size", "canvas", ...) already show the result, as they do
under X11.  The interpreter's rate-limited event poll could skip them.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
An X server shows what was drawn and services the windows on its own;
with SDL that is the program's job.  Before reading a line from a
terminal, flush all canvases to the screen, as the X11 backend flushes
its requests.  During delay(), keep handling window events (repaints,
moves, input, which is queued) for the whole delay instead of
sleeping, so the windows stay responsive; on macOS a program that
stops handling events gets the spinning beach ball.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
On macOS 14 and later SDL no longer activates the application at
startup, so a program run from a terminal opened its windows behind
the terminal.  Raise each new window when it is shown, as a window
manager does for a new X11 window.

AppKit, and so SDL's Cocoa code, may only be used from the main
thread.  On macOS, opening a window from another Unicon thread now
fails instead of crashing, and event handling and presents requested
by other threads are left to the main thread's next poll; drawing
from other threads still goes to the canvas.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
On a high-density (Retina) display the canvas was drawn at one pixel
per point and the system scaled it up, so text came out blurry, as it
does under XQuartz.  Canvases now hold scale x scale device pixels per
Unicon pixel, where scale is the display's pixel density (2 on Retina),
and windows are created at that density so the canvas maps one to one
onto the screen.

Unicon geometry does not change: shapes are still rasterized in Unicon
pixels (each one a solid scale x scale block), Pixel(), WriteImage()
and CopyArea() still work in Unicon pixels, and font metrics and text
widths are computed from unhinted advances so layouts match a
standard-density display.  Only glyphs are rendered at the full device
resolution.  UNICON_SCALE=n overrides the detected scale (1 to 4),
which is also a way to try the 2x path on an ordinary display.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Under X11, ReadImage(), WriteImage() and image= also handle XBM and
XPM files, through Xlib and libXpm.  The SDL backend handed them to the
generic code, which does not know them, so they failed.

Parse and write both formats directly:

 - XBM in the X11 and X10 layouts; 1 bits are drawn in the foreground
   color and 0 bits in the background, as XCopyPlane() does.  Written
   files mark dark pixels as 1 bits.
 - XPM3 and XPM2, any number of colors and characters per pixel, with
   #rgb values read as XParseColor() does, X11 color names (spaces and
   case ignored), and None pixels left transparent.
 - image= with either format starts the window as the image, at its size.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
iconimage= was recorded for WAttrib() but otherwise ignored.  Load the
named file, in any format ReadImage() reads (including XBM and XPM), or
copy the window given, and hand it to SDL as the window's icon.  On
macOS SDL makes it the application's Dock icon.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Pixel() turned each display value back into a linear color, so a pixel
drawn with Fg(w, "50,100,200") read back as 41,88,199: 8 bits per
channel cannot hold the low end of a gamma curve.  Under X11, Pixel()
finds the pixel in the display's color table and reports the color
that was allocated for it, very nearly the one asked for.

Remember, per display, the color asked for at each display value that
colors are converted to, and report it when the pixel has that value.
Other pixels (from images, for example) are converted back as before.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
The graphics tests are programs to run and look at.  Add a graphics
suite that checks pixels instead, so make Test can run it:

 - gfxbasic: shapes, drawing ops, clipping, copying, patterns, image
   strings, colors and the event queue, counted pixel by pixel;
 - imgrw: window contents written as GIF, BMP, PNG, JPEG, XPM and XBM
   and read back, pixel for pixel (JPEG: size only).

SDL graphics runs them on SDL's offscreen video driver; X11 runs them
when there is a display.  Both give the same results.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Install SDL3, FreeType, libjpeg and libpng on macOS, where configure
then picks the SDL backend, and add a Debian 13 build configured with
--enable-sdl-graphics.  The new graphics test suite runs in both.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
mkfont() in rxwin.ri only chooses the FTGL font file for a 3D window's
font, and nothing in it depends on X11.  Move it to ropengl.ri as
mkfont3d(), so other window systems can use it too.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
A subwindow made with Clone(w, "g", ...) became a borderless top-level
window of its own, and its canvas was made before its size was known,
so it stayed 1x1 pixels and showed nothing.

As under X11, show subwindows inside their parent: the canvas is made
when the subwindow is mapped, and the top-level window shows its canvas
with its subwindows drawn over it (later ones on top, each clipped to
its parent), 2D ones with a one-pixel border in their foreground color.
Mouse and keyboard input goes to the subwindow under the pointer, with
coordinates relative to it; pos=, size= and canvas=hidden move, resize
and hide a subwindow within its parent.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
The SDL backend was 2D only; configure turned 3D off with it.  Give
each 3D window an OpenGL context, made through SDL, that renders into a
framebuffer object the size of the window.  When ropengl.ri finishes a
frame (where X11 swaps buffers), the frame is read back into the
window's canvas and shown like 2D drawing.  So the existing 3D code runs
unchanged, and:

 - 3D windows, hidden 3D windows and 3D subwindows all work, and render
   the same pictures as under X11;
 - Pixel(), WriteImage(), CopyArea() and Texture() see what was drawn;
 - resizing renders the scene again at the new size;
 - picking (pick=on) works as under X11.

The contexts share their textures and are compatibility (on macOS,
legacy) contexts, for the fixed-function pipeline ropengl.ri uses.
SDL's renderer may use OpenGL itself, so the 3D context is kept current
across its calls.  On macOS configure uses the OpenGL framework.
Window textures copy the canvas's colors as shown.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Add gl3d to the graphics suite: primitives, a texture from an image
string and one from another window, a 3D subwindow, and resizing, each
checked by the color at a point inside it (lighting shades surfaces, so
only the hue is compared).  It runs on SDL's offscreen driver where that
has OpenGL (EGL), as on Linux; the Debian SDL build in CI installs EGL
and Mesa for it.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
On a high-density (Retina) display, 3D windows were rendered at one
pixel per Unicon pixel and then enlarged, so they looked blurred next to
the 2D drawing and text, which the canvas renders at the display's
resolution.

Size each 3D framebuffer at the canvas's resolution and copy frames into
the canvas pixel for pixel.  ropengl.ri keeps working in Unicon pixels:
its viewport, line widths, point size, pixel reads and picking region
are scaled to the framebuffer (GLSCALE is 1 for the other window
systems).

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Unicon threads that each opened and drew in a window failed under SDL
("window system error") or hung, where X11 (with XInitThreads) copes:
SDL and the window layer's own state were used by several threads at
once.

Give the window layer's entry points one recursive lock.  Waiting for an
event releases it, so other threads can draw meanwhile.  (On macOS only
the main thread may use AppKit, as before.)

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
readGIF(), readJPEG() and readPNG() opened their files with "rb" only
when MSWindows was defined.  A Windows build without the native
backend (SDL graphics) opened them in text mode, and stopped reading a
GIF at the first byte that looks like end-of-file.  Binary mode is the
right mode everywhere.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Let configure --enable-sdl-graphics replace the native (GDI) backend on
MS Windows too, 2D and 3D:

 - configure: Windows builds link with --static, so link SDL3 through
   its DLL import library by name.
 - config.h: the Makefiles define MSWindows for the Windows runtime;
   with SDL graphics it is undefined again and SDLWindows defined, the
   GUI build (wiconx) keeps its console window (now an SDL window), and
   the tools are not given console replacements for stdio.
 - main() and WinMain() call iconx() (rwinsys.r); the GUI translator
   (wicont) gets iconx() as with the native backend.
 - system() and idelay() keep their Windows versions.
 - fonts are found in the Windows font folders (arial, consola, cour,
   times, ... with their bd/i/bi/z variants); config.h makes "index" a
   macro on Windows, so the font code no longer uses it as a name.

Cross-built with MinGW and run under Wine, iconx, wiconx, icont and
wicont work, the graphics tests pass, and 3D renders as on Linux.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Add a Windows job configured with --enable-sdl-graphics, with SDL3 and
FreeType from MSYS2.  The graphics test suite runs there on SDL's
offscreen driver (2D; 3D needs EGL).

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Texture(w, w3) with a 3D window w3 as the source recorded the texture
under w3's current texture rather than w's, which Texture() had just
chosen, writing before the texture table when w3 had none (found by
AddressSanitizer).  Use w's context, as texwindow2D() does.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
X11's default font, "fixed", is a 6x13 bitmap font, and window and
dialog layouts are sized for it: ivib places labels and fields by its
metrics, and the gui package keeps it as the window font.  Under SDL an
unsized "fixed" was the mono face at 13 pixels, 8x17 with DejaVu Sans
Mono or Menlo, so text ran a third wider and overflowed its space in
ivib and ui dialogs and menus.

Open an unsized "fixed" at the largest size whose cells fit in 6x13
(size 10 with those faces, exactly 6x13), and keep that size for later
windows.  A "fixed" with a size, and every other family, is unchanged.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
drawop=reverse swaps fg and bg, which X11 does by xoring with fg ^ bg.
The gui package draws a selected TextList line, a pressed button and a
progress bar that way, over text drawn earlier.  X11's core fonts are
not smoothed, so only fg and bg pixels are there; SDL's text has edge
pixels that blend the two, and xor turned those into unrelated colors,
so selected lines showed dark text with red and yellow fringes instead
of light text.

Add a canvas operation that sets each 8-bit channel to fg + bg - dst
(mod 256).  It swaps fg and bg exactly as the xor did, swaps the blends
between them too, and restores every pixel when done twice.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
SDL3 can be enabled on Linux, macOS, and Windows. Keep the top-level
build notes short and put the package lists, the macOS disk image, and
the Windows DLL in doc/sdl-graphics.md.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Glyphs were rendered with light hinting, which snaps them only
vertically.  At the default font's 6-pixel cell that blurs the stems
of narrow glyphs together: the m of "fixed" came out as a grey block,
and " and ' were hard to tell apart.

Below 16 device pixels, hint with the autohinter at full strength, so
stems land on whole pixels, also in faces that carry no hints of their
own (Menlo, say).  Advances still come from the unhinted outline, so
text is as wide as before.  Larger text, and text on high-density
displays, is unchanged.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
UCRT64 installs the headers in $MSYSTEM_PREFIX/include/freetype2, which
the compiler does not search, so the Windows SDL configure failed with
an empty FreeType prefix. Use that prefix when pkg-config has not named
one, and link libfreetype.dll.a when --static skips the import library.
Install pkgconf in the Windows CI job so pkg-config can find it too.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
--static makes -lfreetype select libfreetype.a. A probe of FT_Open_Face
succeeds, but iconx then pulls the archive's WOFF, autofit, and bzip
objects, which need brotli, harfbuzz, and bzip2. Use the DLL import
library, as for SDL3.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Windows already links with --static so OpenSSL and libssh are inside
the executable. SDL and FreeType were still import libraries, because
libfreetype.a needs harfbuzz, brotli, and bzip2 and a one-symbol probe
never asks for them. Default to the static closure from pkg-config on
Windows, and keep --with-graphics-libs=shared for the DLLs.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant