Draw in the host: the wasm compositor sends draw ops, the host rasterises natively
CI / test (push) Failing after 29s

The wasm software renderer cost ~10-20 ns/pixel, so any changed frame took ~100+ ms at 1080p and
the desktop swung between idle and very slow. The compositor still builds the scene (windows,
decorations, panel, wallpaper) but a new moonplasma:host/raster interface turns it into pixels
in the host:
- host-wasm/src/raster.rs: a port of compositor/renderer (same blend arithmetic: fills, strokes,
  lines, circles, text, clips, shadows, surface blits), a wallpaper+desktop-card cache, and captured
  client surfaces (copied out of the shared memory once at commit, converted to RGBA, solid ones
  blit as row copies). 9 unit tests; a full frame matches the native software renderer except for
  text antialiasing (0.3% of pixels).
- compositor/raster sends a SceneGraph as ops; compositor.compose_scene() returns it only when
  something changed. The login session shows the host framebuffer directly (display.present-frame),
  the nested window gets it as a memfd (raster.export-memfd), --gfx-out reads it (read-frame).
- Client buffers never enter wasm: snapshot_shm_buffer captures in the host and keeps an id.
- Loop pacing sleeps the rest of the frame budget instead of a fixed 16/8 ms.
Full-screen terminal flooding output at 1080p: ~2 fps / 94% CPU -> ~57 fps; idle ~9%.
The native build keeps the software renderer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-25 04:39:40 -08:00
1 parent 66bf293085
commit c6e31b4a8f
38 files changed
+2141 -220

No files matched your search

+46 -14
View File
@@ -122,7 +122,6 @@ pub fn run(args : Array[String]) -> Int {
}
let gfx_surface = @gfx.Surface::new({ width: Some(width), height: Some(height) })
let gfx_ctx = @gfx.SurfaceFrameBufferContext::new(gfx_surface)
match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) {
None => {
@@ -138,8 +137,11 @@ pub fn run(args : Array[String]) -> Int {
comp.restore_state() // and the layout mode and recent apps from the last session
comp.shell.screen_w = width
if gfx_out.length() > 0 && !serve {
let pixmap = comp.present_to_gfx(gfx_ctx)
ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(pixmap)))
match comp.compose_scene() {
Some(sg) => @raster.submit(sg)
None => ()
}
ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height))))
comp.close()
@sys.log("frame written to " + gfx_out)
return 0
@@ -192,10 +194,19 @@ pub fn run(args : Array[String]) -> Int {
comp.step()
let f1 = @sys.monotonic_ms()
k.set_cursor_shape(comp.desired_cursor())
let px = comp.compose_frame()
need_present = need_present || comp.frame_changed
// The host draws; only a changed desktop is sent, and the frame is shown by the host
// straight from its framebuffer.
match comp.compose_scene() {
Some(sg) => {
let r0 = @sys.monotonic_ms()
@raster.submit(sg)
comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0)
need_present = true
}
None => ()
}
if need_present && k.frame_ready() {
k.present(px)
k.present_frame()
need_present = false
}
if profile {
@@ -213,7 +224,9 @@ pub fn run(args : Array[String]) -> Int {
comp.prof_raster_ms = 0UL
}
}
@sys.sleep_ms(8)
// Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work.
let spent = (@sys.monotonic_ms() - f0).to_int()
@sys.sleep_ms(if spent >= 8 { 1 } else { 8 - spent })
continue
}
None => ()
@@ -236,18 +249,35 @@ pub fn run(args : Array[String]) -> Int {
comp.handle_input(ev, now_ms)
}
n.set_cursor_shape(comp.desired_cursor())
let px = comp.compose_frame()
need_present = need_present || comp.frame_changed
match comp.compose_scene() {
Some(sg) => {
let r0 = @sys.monotonic_ms()
@raster.submit(sg)
comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0)
need_present = true
}
None => ()
}
if need_present && n.frame_ready() {
n.present(px)
n.present_frame(width, height)
need_present = false
}
}
None => {
comp.handle_gfx_events(gfx_surface)
let pixmap = comp.present_to_gfx(gfx_ctx)
if serve && gfx_out.length() > 0 && frames % 30 == 0 {
ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(pixmap)))
match comp.compose_scene() {
Some(sg) => {
let r0 = @sys.monotonic_ms()
@raster.submit(sg)
comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0)
need_present = true
}
None => ()
}
// No display: --serve keeps a PNG of the latest frame for looking at a live compositor.
if serve && gfx_out.length() > 0 && frames % 30 == 0 && need_present {
ignore(@sys.write_file_bytes(gfx_out, @renderer.encode_png(@raster.read_frame(width, height))))
need_present = false
}
}
}
@@ -266,7 +296,9 @@ pub fn run(args : Array[String]) -> Int {
comp.prof_raster_ms = 0UL
}
}
@sys.sleep_ms(16)
// About 60 frames a second: sleep what is left of 16 ms after the work.
let spent = (@sys.monotonic_ms() - f0).to_int()
@sys.sleep_ms(if spent >= 16 { 1 } else { 16 - spent })
}
match kms {
Some(k) => k.close()
+1
View File
@@ -7,6 +7,7 @@ import {
"moonplasma/desktop/compositor/host" @host,
"moonplasma/desktop/compositor/nested" @nested,
"moonplasma/desktop/compositor/kms" @kms,
"moonplasma/desktop/compositor/raster" @raster,
}
supported_targets = "+native+wasm"
+59 -11
View File
@@ -129,10 +129,21 @@ pub fn MoonPlasmaCompositor::new(
///|
pub fn MoonPlasmaCompositor::close(self : MoonPlasmaCompositor) -> Unit {
for _, win in self.windows {
release_snapshot(win.surface)
}
self.shell.shutdown()
self.server.close()
}
///| Let the host forget a client surface it captured (a no-op without the host rasteriser).
fn release_snapshot(s : @scene.ShmBufferSnapshot?) -> Unit {
match s {
Some(snap) => if snap.host_id != 0U { @sys.surface_release(snap.host_id) }
None => ()
}
}
///| What a frame was drawn from, compared with the next frame's to see whether it changed.
#derive(Eq)
pub(all) struct FrameSig {
@@ -284,6 +295,7 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit {
Some(win) => {
match snap {
Some(s) => {
release_snapshot(win.surface)
win.surface = Some(s)
self.damage.mark_rect(win.geometry)
}
@@ -300,7 +312,10 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit {
for p in self.popups {
if p.id == wid {
match snap {
Some(_) => p.surface = snap
Some(_) => {
release_snapshot(p.surface)
p.surface = snap
}
None => ()
}
self.damage.mark_full()
@@ -309,6 +324,10 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit {
@wayland.CompositorEvent::PopupClosed(wid) => self.close_popup(wid)
@wayland.CompositorEvent::ToplevelClosed(wid) => {
self.close_popup(wid)
match self.windows.get(wid) {
Some(win) => release_snapshot(win.surface)
None => ()
}
ignore(self.windows.remove(wid))
if self.ptr_win == Some(wid) {
self.ptr_win = None
@@ -379,9 +398,9 @@ pub fn MoonPlasmaCompositor::restore_state(self : MoonPlasmaCompositor) -> Unit
}
///|
pub fn MoonPlasmaCompositor::compose_frame(
fn MoonPlasmaCompositor::build_scene(
self : MoonPlasmaCompositor,
) -> @renderer.Pixmap {
) -> (@scene.SceneGraph, Bool) {
self.flush_configures()
let scene = @scene.SceneGraph::new(self.output_w, self.output_h)
let order = self.wm.stacking_order()
@@ -482,22 +501,46 @@ pub fn MoonPlasmaCompositor::compose_frame(
wins: scene.windows.map(w => (w.id, w.geometry, w.focused, w.fullscreen, w.deco_ops)),
popups: scene.popups.map(p => p.0),
}
// Nothing changed since the last frame (no client commit, same shell and decoration ops):
// hand back the previous pixels instead of rasterising 2 million pixels again.
match (self.last_frame, self.last_sig) {
(Some(prev), Some(ps)) =>
if !damaged && ps == sig {
// Unchanged since the last scene (no client commit, same shell and decoration ops)?
let unchanged = match self.last_sig {
Some(ps) => !damaged && ps == sig
None => false
}
if !unchanged {
self.last_sig = Some(sig)
}
self.prof_shell_ms = self.prof_shell_ms + (@sys.monotonic_ms() - t0)
(scene, !unchanged)
}
///| Compose the desktop for the host rasteriser (the wasm compositor): the scene to draw, or None
/// when nothing changed since the last one, so an idle desktop costs nothing to draw or present.
pub fn MoonPlasmaCompositor::compose_scene(
self : MoonPlasmaCompositor,
) -> @scene.SceneGraph? {
let (scene, changed) = self.build_scene()
self.frame_changed = changed
if changed { Some(scene) } else { None }
}
///| Compose the desktop and draw it with the software renderer (the native build and the tests).
/// An unchanged desktop hands back the previous pixels instead of rasterising them again.
pub fn MoonPlasmaCompositor::compose_frame(
self : MoonPlasmaCompositor,
) -> @renderer.Pixmap {
let (scene, changed) = self.build_scene()
match self.last_frame {
Some(prev) =>
if !changed {
self.frame_changed = false
return prev
}
_ => ()
None => ()
}
self.frame_changed = true
self.last_sig = Some(sig)
let t1 = @sys.monotonic_ms()
let px = @renderer.render_scene(scene)
self.last_frame = Some(px)
self.prof_shell_ms = self.prof_shell_ms + (t1 - t0)
self.prof_raster_ms = self.prof_raster_ms + (@sys.monotonic_ms() - t1)
px
}
@@ -638,6 +681,11 @@ fn MoonPlasmaCompositor::close_popup(self : MoonPlasmaCompositor, wid : UInt64)
return
}
let root = self.popup_root(wid)
for p in self.popups {
if p.id == wid {
release_snapshot(p.surface)
}
}
let keep = self.popups.filter(p => p.id != wid)
self.popups.clear()
for p in keep {
+32
View File
@@ -1030,3 +1030,35 @@ test "alt-tab switches to the previous window, tab again goes further back, esca
key(15U, true, 30U)
assert_false(comp.switcher_open())
}
///|
test "compose_scene hands the host a scene only when something changed" {
let socket_path = "/tmp/wayland-moon-scene-" + @sys.getpid().to_string() + ".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap()
// The first scene is always drawn; the wallpaper and the desktop card are split out of it.
match comp.compose_scene() {
Some(sg) => {
assert_true(sg.wallpaper_ops.length() > 0)
assert_true(sg.panel_ops.length() > 0)
}
None => abort("the first scene must be drawn")
}
// Nothing happened: nothing to draw.
assert_true(comp.compose_scene() is None)
assert_false(comp.frame_changed)
// A new window changes the scene, then it settles again.
ignore(open_and_configure_client(comp, socket_path, "A", "a"))
match comp.compose_scene() {
Some(sg) => assert_eq(sg.windows.length(), 1)
None => abort("a new window must change the scene")
}
assert_true(comp.compose_scene() is None)
// The switcher overlay is part of the scene too.
comp.handle_input(@nested.InputEvent::Key(56U, true), 1U)
ignore(open_and_configure_client(comp, socket_path, "B", "b"))
ignore(comp.compose_scene())
comp.handle_input(@nested.InputEvent::Key(15U, true), 2U)
assert_true(comp.switcher_open())
assert_true(comp.compose_scene() is Some(_))
}
+6
View File
@@ -118,3 +118,9 @@ pub fn Kms::take_input(_self : Kms) -> Array[@nested.InputEvent] {
pub fn Kms::close(_self : Kms) -> Unit {
c_close()
}
///| The native build draws with the software renderer and uses `present`; there is no host
/// framebuffer to show.
pub fn Kms::present_frame(_self : Kms) -> Unit {
abort("present_frame is only available to the wasm compositor")
}
+6
View File
@@ -41,6 +41,12 @@ pub fn Kms::present(_self : Kms, pixmap : @renderer.Pixmap) -> Unit {
)
}
///| Show the host framebuffer (what the host rasteriser drew) on the output: nothing is copied
/// through this program.
pub fn Kms::present_frame(_self : Kms) -> Unit {
@hostdisplay.present_frame()
}
///| Show the cursor for a wp_cursor_shape_v1 value.
pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit {
@hostdisplay.set_cursor_shape(shape)
+22 -2
View File
@@ -409,8 +409,7 @@ pub fn NestedWindow::present(self : NestedWindow, pixmap : @renderer.Pixmap) ->
}
let w = pixmap.width
let h = pixmap.height
let stride = w * 4
let len = stride * h
let len = w * 4 * h
// RGBA -> little-endian ARGB8888 (B, G, R, A).
let out : FixedArray[Byte] = FixedArray::make(len, b'\x00')
for i = 0; i < w * h; i = i + 1 {
@@ -425,6 +424,27 @@ pub fn NestedWindow::present(self : NestedWindow, pixmap : @renderer.Pixmap) ->
return
}
ignore(@sys.pwrite_bytes(memfd, Bytes::from_fixedarray(out), 0))
self.send_frame(memfd, w, h)
}
///| Show the host's framebuffer (drawn by the host rasteriser) in the window: the host fills a
/// memfd with it and this hands that to the host compositor, so no pixels pass through here.
pub fn NestedWindow::present_frame(self : NestedWindow, w : Int, h : Int) -> Unit {
if self.frame_pending || self.closed {
return
}
let memfd = @sys.frame_memfd()
if memfd < 0 {
return
}
self.send_frame(memfd, w, h)
}
///| Attach the ARGB8888 frame in `memfd` (w x h) to the window and ask for a frame callback.
/// Takes the descriptor: it is closed here once sent.
fn NestedWindow::send_frame(self : NestedWindow, memfd : Int, w : Int, h : Int) -> Unit {
let stride = w * 4
let len = stride * h
let pool = self.alloc()
let wp = @wayland.WireWriter::new()
wp.u32(pool)
+17
View File
@@ -0,0 +1,17 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/compositor/scene" @scene,
"moonplasma/desktop/compositor/renderer" @renderer,
"moonplasma/desktop/interface/moonplasma/host/raster" @hostraster,
}
supported_targets = "+native+wasm"
// The wasm compositor hands its scene to the host to draw (`moonplasma:host/raster`); the native
// build has the software renderer instead, so this package only stubs the calls there.
options(
targets: {
"raster_wasm.mbt": ["wasm"],
"raster_native.mbt": ["native"],
},
)
+12
View File
@@ -0,0 +1,12 @@
///| The native build draws with the software renderer (`@renderer.render_scene`); there is no host
/// to send a scene to.
///|
pub fn submit(_scene : @scene.SceneGraph) -> Unit {
abort("the host rasteriser is only available to the wasm compositor")
}
///|
pub fn read_frame(_width : Int, _height : Int) -> @renderer.Pixmap {
abort("the host rasteriser is only available to the wasm compositor")
}
+97
View File
@@ -0,0 +1,97 @@
///| Send a scene to the host to draw (`moonplasma:host/raster`).
///
/// The scene is the same one the software renderer takes (`@scene.SceneGraph`); here it is turned
/// into the interface's records and handed over. The host owns the framebuffer and does the pixel
/// work natively; client window buffers are already there (captured at commit, by id).
///|
fn conv_rect(r : @scene.Rect) -> @hostraster.Rect {
{ x: r.x, y: r.y, w: r.w, h: r.h }
}
///|
fn conv_color(c : @scene.Rgba) -> @hostraster.Color {
{ r: c.r, g: c.g, b: c.b, a: c.a }
}
///|
fn conv_align(a : @scene.TextAlign) -> Byte {
match a {
Left => b'\x00'
Center => b'\x01'
Right => b'\x02'
}
}
///|
fn conv_op(op : @scene.DrawOp) -> @hostraster.Op {
match op {
FillRect(r, c, radius) => FillRect({ area: conv_rect(r), color: conv_color(c), radius })
StrokeRect(r, c, width, radius) => StrokeRect({ area: conv_rect(r), color: conv_color(c), width, radius })
Line(x0, y0, x1, y1, c, width) => DrawLine({ x0, y0, x1, y1, color: conv_color(c), width })
Circle(cx, cy, radius, c, filled) => DrawCircle({ cx, cy, radius, color: conv_color(c), filled })
Text(x, y, text, size, c, align, bold) =>
DrawText({ x, y, text, size, color: conv_color(c), align: conv_align(align), bold, mono: false })
MonoText(x, y, text, size, c, align, bold) =>
DrawText({ x, y, text, size, color: conv_color(c), align: conv_align(align), bold, mono: true })
PushClip(r) => PushClip(conv_rect(r))
PopClip => PopClip
}
}
///|
fn conv_ops(ops : Array[@scene.DrawOp]) -> Array[@hostraster.Op] {
ops.map(conv_op)
}
///| The backdrop (wallpaper and the desktop card on it) the host last drew, and the size it was
/// drawn for. While neither changes the frame says "unchanged" and the host reuses its cached
/// pixels instead of being sent about two thousand ops again and drawing them.
let last_backdrop : Ref[Array[@scene.DrawOp]?] = { val: None }
///|
let last_size : Ref[(Int, Int)] = { val: (0, 0) }
///| Draw `scene` into the host framebuffer.
pub fn submit(scene : @scene.SceneGraph) -> Unit {
let backdrop = scene.wallpaper_ops + scene.background_ops
let same = match last_backdrop.val {
Some(prev) => prev == backdrop && last_size.val == (scene.output_w, scene.output_h)
None => false
}
if !same {
last_backdrop.val = Some(backdrop)
last_size.val = (scene.output_w, scene.output_h)
}
let windows : Array[@hostraster.Window] = scene.windows.map(w => {
let (top, right, bottom, left) = w.deco_insets
{
geometry: conv_rect(w.geometry),
inset_top: top,
inset_right: right,
inset_bottom: bottom,
inset_left: left,
deco: conv_ops(w.deco_ops),
fullscreen: w.fullscreen,
surface: match w.surface {
Some(s) => s.host_id
None => 0U
},
}
})
@hostraster.submit({
width: scene.output_w,
height: scene.output_h,
wallpaper: if same { None } else { Some(conv_ops(backdrop)) },
background: [],
windows,
panel: conv_ops(scene.panel_ops),
popups: scene.popups.map(p => { area: conv_rect(p.0), surface: p.1.host_id }),
})
}
///| The host framebuffer as a pixmap (screenshots and tests; the display path never needs it).
pub fn read_frame(width : Int, height : Int) -> @renderer.Pixmap {
let data = @hostraster.read_frame()
{ width, height, data }
}
+1 -1
View File
@@ -57,7 +57,7 @@ test "blitting a client buffer matches per-pixel blending, even partly off scree
let raw = Bytes::from_fixedarray(bytes)
for format in [0, 1] {
for pos in [(0, 0), (5, 4), (-7, -3), (50, 40), (60, 30)] {
let buf : @scene.ShmBufferSnapshot = { width: w, height: h, stride: w * 4, format, bytes: raw }
let buf : @scene.ShmBufferSnapshot = { width: w, height: h, stride: w * 4, format, bytes: raw, host_id: 0U }
let a = Pixmap::new(64, 48)
let b = Pixmap::new(64, 48)
for i = 0; i < a.data.length(); i = i + 1 {
+1
View File
@@ -44,6 +44,7 @@ test "software renderer alpha blending, rounded rect, shm blit, and png encoding
stride: 400,
format: 0,
bytes: Bytes::from_array(buf_bytes),
host_id: 0U,
}),
})
+3
View File
@@ -239,6 +239,9 @@ pub(all) struct ShmBufferSnapshot {
/// Wayland wl_shm format: 0 = ARGB8888, 1 = XRGB8888
format : Int
bytes : Bytes
/// With the host rasteriser (the wasm compositor) the pixels live in the host, not in `bytes`
/// (empty): this is the host's surface id, 0 when there is none.
host_id : UInt
}
///|
+1
View File
@@ -2,6 +2,7 @@ import {
"moonbitlang/core/builtin",
"moonbitlang/core/env" @env,
"moonplasma/desktop/interface/moonplasma/host/sys" @hostsys,
"moonplasma/desktop/interface/moonplasma/host/raster" @hostraster,
}
supported_targets = "+native+wasm"
+21
View File
@@ -269,3 +269,24 @@ pub fn monotonic_ms() -> UInt64 {
pub fn log(message : String) -> Unit {
println(message)
}
///| Whether the host draws the screen (the wasm compositor): then client buffers are captured in
/// the host and the pixels never enter this program. Never on the native build.
pub fn host_raster() -> Bool {
false
}
///| Copy a client buffer into a host surface; 0 (none) on the native build.
pub fn surface_capture(_fd : Int, _offset : Int, _stride : Int, _width : Int, _height : Int, _format : Int) -> UInt {
0U
}
///|
pub fn surface_release(_id : UInt) -> Unit {
()
}
///| A memfd with the host framebuffer as ARGB8888; -1 on the native build.
pub fn frame_memfd() -> Int {
-1
}
+22
View File
@@ -172,3 +172,25 @@ pub fn monotonic_ms() -> UInt64 {
pub fn log(message : String) -> Unit {
@hostsys.log(message)
}
///| The host draws the screen: client buffers are captured in the host (see `surface_capture`).
pub fn host_raster() -> Bool {
true
}
///| Copy `stride * height` bytes at `offset` of the file behind `fd` into a host surface (a native
/// copy; the pixels never enter this program). `format`: 0 ARGB8888, 1 XRGB8888. 0 on failure.
pub fn surface_capture(fd : Int, offset : Int, stride : Int, width : Int, height : Int, format : Int) -> UInt {
@hostraster.capture(fd, offset, stride, width, height, format)
}
///| Forget a captured surface.
pub fn surface_release(id : UInt) -> Unit {
@hostraster.release(id)
}
///| A new memfd holding the host framebuffer as little-endian ARGB8888, for a wl_shm pool. The
/// caller closes it. -1 on failure.
pub fn frame_memfd() -> Int {
@hostraster.export_memfd()
}
+18 -1
View File
@@ -385,8 +385,24 @@ fn snapshot_shm_buffer(
if needed <= 0 || buf.width <= 0 || buf.height <= 0 {
return None
}
// Only this buffer's bytes: a pool can be hundreds of MB while a buffer is a few.
let byte_len = buf.stride * buf.height
// With the host rasteriser the host copies the buffer itself and keeps the pixels: all this
// program holds is an id.
if @sys.host_raster() {
let id = @sys.surface_capture(pool.fd, buf.offset, buf.stride, buf.width, buf.height, buf.format)
if id == 0U {
return None
}
return Some({
width: buf.width,
height: buf.height,
stride: buf.stride,
format: buf.format,
bytes: Bytes::make(0, b'\x00'),
host_id: id,
})
}
// Only this buffer's bytes: a pool can be hundreds of MB while a buffer is a few.
let slice = @sys.mmap_read_at(pool.fd, buf.offset, byte_len)
if slice.length() < byte_len {
return None
@@ -397,6 +413,7 @@ fn snapshot_shm_buffer(
stride: buf.stride,
format: buf.format,
bytes: slice,
host_id: 0U,
})
}