Drawing¶
malibx has three ways to put pixels on screen:
| Method | Best for | Speed |
|---|---|---|
pixel_put |
A few dots, lines, debugging | one call per pixel |
string_put |
Labels, scores, HUDs | one call per string |
| Images | Backgrounds, sprites, anything big | one call per image |
All three draw into the window's pixel buffer. It appears on screen at the next frame of the loop.
Colors¶
Colors are plain integers in the form 0xRRGGBB: one byte each for red,
green and blue, from 00 to FF.
Writing a helper to build colors from components is common:
def rgb(r: int, g: int, b: int) -> int:
"""0-255 components -> 0xRRGGBB."""
return (r << 16) | (g << 8) | b
rgb(255, 128, 0) == 0xFF8000 # True
And going the other way:
pixel_put and string_put ignore anything above the lowest 24 bits, so
0xFF000000 | RED draws plain red. The top byte only matters in
images.
Single pixels¶
Sets one pixel. (0, 0) is the top-left corner. Coordinates outside the window
are ignored, so you can draw shapes that go off the edge without clipping
them yourself.
A few shapes built from pixel_put:
for x in range(640):
shade = x * 255 // 639
for y in range(480):
malibx.pixel_put(mlx, win, x, y, rgb(shade, 0, 255 - shade))
This is 307,200 calls, which is slow if you redraw it every frame. Draw it once into an image instead.
Clearing¶
Fills the whole window with black. Windows keep whatever you drew until you draw over it, so clear (or redraw a full-window background) at the start of each frame when things move.
Text¶
Draws a string with malibx's built-in 8×8 bitmap font.
(x, y)is the left end of the baseline, as in X11 and MiniLibX. With the default size, letters extend 7 pixels aboveyand 1 pixel below it. To put text at the very top of a window, usey = 7or more, noty = 0.- Only the letter pixels are drawn. The background stays as it was, so text works on top of images.
- Each character is 8 pixels wide. A string of
ncharacters is8 * npixels wide. - ASCII and Latin-1 characters (
é,ü,ñ,©, …) are supported. Other characters are left blank, but still take up a character's width.
┌────────┐
│ ████ │ ┐
│ ██ ██ │ │
│ ██ ██ │ │ 7 px above the baseline
│ ██████ │ │
│ ██ ██ │ │
│ ██ ██ │ ┘
(x, y) ● ├────────┤ ← baseline
│ │ 1 px below
└────────┘
8 px
Bigger text with set_font¶
set_font sets the text size for that window, and it stays in effect
until you change it. malibx has one font, so the name chooses a size: "8x8"
(default), "16x16", "24x24", "32x32", "40x40", "48x48", "56x56",
or "64x64". Each step scales the 8×8 font up in whole pixels, so it stays
sharp. Any other name raises ValueError.
Everything scales together. At "16x16", characters are 16 px wide and rise
14 px above the baseline.
Centering text
Images¶
An image is a block of pixels in memory that you fill however you like, then draw to a window in a single call. Use images for anything big or anything you draw every frame.
img = malibx.new_image(mlx, width, height) # black
buf, bpp, size_line, endian = malibx.get_data_addr(img)
# ... write pixels into buf ...
malibx.put_image_to_window(mlx, win, img, x, y) # (x, y) = top-left
The pixel buffer¶
get_data_addr returns four values, the same as MiniLibX:
| Value | What it is | In malibx |
|---|---|---|
buf |
A writable memoryview of the image's bytes |
len(buf) == size_line * height |
bpp |
Bits per pixel | always 32 |
size_line |
Bytes per row | always width * 4 |
endian |
Byte order | always 0 (little endian) |
Each pixel is 4 bytes in the order B, G, R, A. Pixel (x, y) starts at:
pixel (0,0) pixel (1,0) pixel (2,0)
buf: ┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬────┬─ ─
│ B │ G │ R │ A │ B │ G │ R │ A │ B │ G │ R │ A │ …
└────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴────┴─ ─
i=0 i=4 i=8
row y starts at i = y * size_line
That's the byte order of 0xAARRGGBB stored little endian, so the easy way
to write a pixel is:
And the easy way to read one back:
Filling an image fast¶
Python loops are slow, but slice assignment on a memoryview runs at C
speed. Build the bytes for a whole row (or the whole image) and assign them
at once:
W, H = 640, 480
img = malibx.new_image(mlx, W, H)
buf, _, size_line, _ = malibx.get_data_addr(img)
row = b"".join(rgb(x * 255 // (W - 1), 0, 255 - x * 255 // (W - 1))
.to_bytes(4, "little") for x in range(W))
for y in range(H):
buf[y * size_line:(y + 1) * size_line] = row
The 307,200 pixel_put calls from before become 480 slice assignments.
Keep the image, redraw the image
Build images once, outside the loop, and only call
put_image_to_window each frame. Drawing a full-window image each frame is
cheap. Rebuilding it pixel by pixel each frame isn't.
Transparency¶
When an image is drawn, a pixel whose alpha byte is 0xFF isn't drawn,
so the window shows through. Any other alpha is drawn fully opaque. There's
no blending. This matches MiniLibX.
CLEAR = (0xFF000000).to_bytes(4, "little") # alpha 0xFF = transparent
sprite = malibx.new_image(mlx, 32, 32)
buf, _, size_line, _ = malibx.get_data_addr(sprite)
buf[:] = CLEAR * (32 * 32) # start fully transparent
fill_rect(buf, size_line, 8, 8, 16, 16, 0xFFD700) # opaque yellow square
Opaque by default
color.to_bytes(4, "little") for a normal 0xRRGGBB color leaves alpha
at 0x00, which means opaque. That's usually what you want. It's the
reverse of most graphics libraries, where 0 alpha means invisible.
Images from XPM files¶
XPM is the text-based image format MiniLibX uses. malibx can load it:
img, width, height = malibx.xpm_file_to_image(mlx, "assets/skull.xpm")
malibx.put_image_to_window(mlx, win, img, 100, 50)
filenamecan be astror apathlib.Path.- XPM pixels with the color
Nonebecome transparent. - Colors can be
#RGB,#RRGGBB,#RRRRGGGGBBBBor an X11 color name likewhiteorlight blue. Unknown names become black. - A missing file raises
FileNotFoundError, and a malformed one raisesValueError.
If the XPM data is already in your program, pass its strings as a list:
SMILEY = [
"8 8 3 1", # width height colors chars-per-pixel
". c None",
"y c #FFD700",
"k c #000000",
"..yyyy..",
".yyyyyy.",
"yykyykyy",
"yyyyyyyy",
"ykyyyyky",
"yykkkkyy",
".yyyyyy.",
"..yyyy..",
]
img, w, h = malibx.xpm_to_image(mlx, SMILEY)
The image you get is an ordinary malibx image, so you can also edit it
through get_data_addr.
Freeing images¶
This releases the image's memory straight away. Using the image afterwards
raises RuntimeError: image is destroyed. Python also frees images automatically when nothing refers
to them anymore, so you only need destroy_image to free a large image at a
specific moment, or for MiniLibX-style code.
Putting it together¶
A starfield: a background image built once, a text overlay, and a transparent sprite that moves with the frame counter.
Next: Keyboard and mouse