Smoother animations without a GPU: faster rasteriser, frame pacing, software/hardware mode
CI / test (push) Failing after 3m2s

Measured headless at 1920x1080 with CHANDRA_FRAME_TRACE (new: one log line per drawn frame):
- Overview open: 46 -> 62 fps, worst frame gap 69 -> 36 ms, raster 14 -> 5 ms a frame.
- Live Starfield: 19 -> 30 fps (its target), raster 49 -> 13 ms, CPU 97% -> 46%.

Rasteriser (MoonBit host; circles and previews also in the Rust host):
- Blending works on two channels at a time in 16-bit lanes with an exact /255: same pixels,
  about 3x quicker on big translucent fills (the overview's dim, the starfield's nebulae).
- Filled circles are drawn as row spans, rings skip their empty middle (a sqrt per pixel of the
  bounding box before). Same pixels; a Rust test checks it against the old loop.
- Window previews gliding in the overview are sampled straight from the preview at each frame's
  size instead of filtered and cached at a size used once; the MoonBit host also gets the
  one-large-size cache and 4096 px draw limit the Rust host had (it kept every size and didn't
  draw previews past 1024 px).
- Image scaling sums each output row's columns once, with 32-bit sums and division.

Frame pacing: frames are drawn only when the output can take them (no page flip in flight on
KMS; the previous frame shown nested and on X11), with a frame every 250 ms for an output that
never gets ready. The KMS loop runs at 125 Hz, so animations used to rasterise frames that were
never shown.

Software or hardware mode (compositor/shell/render_mode.mbt, docs/rendering.md): detected from
the DRM render nodes' drivers (and NVIDIA's proprietary driver, LIBGL_ALWAYS_SOFTWARE),
overridden by CHANDRA_RENDER=software|hardware or Settings > Session "Lighter animations"
(state.edn :render, saved only when it differs from what was detected). Software mode remakes
changing previews every 200 ms instead of 100 ms and caps desktop modules at ~30 fps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hkTQp5uN5FtwpzrXUA
This commit is contained in:
Claude committed 2026-11-26 01:55:50 +00:00
1 parent 1aabccba5d
commit 71f0b858d6
16 files changed
+719 -97

No files matched your search

+4
View File
@@ -92,6 +92,10 @@ session), `--x11` (on Xorg; `--fullscreen` under a window manager, `--login-sess
desktop session), `--theme PATH`, `--no-restore`, `--profile`, `--size WxH` and `--gfx-out frame.png`
(render to a PNG, headless; add `--serve` to keep refreshing it). `WASMHOST_PROFILE=1` prints the
time spent in each host function every 5 seconds; `WASMHOST_TRACE=1` logs every host call.
No GPU? Chandra detects it and asks less of the CPU; `CHANDRA_RENDER=software|hardware` or
Settings > Session > Lighter animations overrides it, and `CHANDRA_FRAME_TRACE=1` logs frame times
([docs/rendering.md](docs/rendering.md)).
`CHANDRA_DEBUG_CONFIGURE=1` (any host) logs each window's configures, acks and committed buffer
sizes, for an app that draws at the wrong size.
+58 -36
View File
@@ -179,7 +179,11 @@ pub fn run(args : Array[String]) -> Int {
let login = drm || login
comp.sync_system_theme = login // the login session sets apps' dark/light preference
comp.login_session = login // and power actions (suspend, power off) act on the machine
// GPU or not (CHANDRA_RENDER overrides): without one the desktop asks less of the CPU.
let (rmode, rwhy) = @shell.detect_render_mode()
comp.shell.set_render_detected(rmode, rwhy)
comp.restore_state() // and the layout mode and recent apps from the last session
@sys.log(comp.shell.render_summary())
comp.shell.screen_w = width
// Screenshots and recordings read the host's framebuffer (it draws the desktop).
comp.frame_source = Some(fn() { Some(@raster.read_frame(comp.output_w, comp.output_h)) })
@@ -239,6 +243,10 @@ pub fn run(args : Array[String]) -> Int {
}
let mut frames = 0
let idle = IdleClock::new()
// CHANDRA_FRAME_TRACE=1: one log line per drawn frame (when, and how long composing and
// rasterising took), for measuring how smooth animations are.
let trace = @sys.getenv("CHANDRA_FRAME_TRACE").length() > 0
let pacer = Pacer::{ last_ms: 0UL }
// A changed frame waits here until the display can take it (no page flip in flight).
let mut need_present = true
// --profile: every 3 s print how long each frame part took on average.
@@ -274,15 +282,15 @@ pub fn run(args : Array[String]) -> Int {
k.set_cursor_shape(comp.desired_cursor())
// The host draws; only a changed desktop is sent, and the frame is shown by the host
// straight from its framebuffer.
let 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
true
}
None => false
// Draw only when the display can take the frame (no page flip in flight): a frame
// drawn meanwhile would never be seen, and drawing it costs a whole frame's CPU.
let changed = if k.frame_ready() || comp.screen_off || pacer.overdue() {
draw_frame(comp, trace, pacer)
} else {
false
}
if changed {
need_present = true
}
if need_present && k.frame_ready() {
k.present_frame()
@@ -361,15 +369,10 @@ pub fn run(args : Array[String]) -> Int {
comp.handle_input(ev, now_ms)
}
n.set_cursor_shape(comp.desired_cursor())
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
busy = true
}
None => ()
// As on a display: draw when the host compositor can take the frame.
if (n.frame_ready() || pacer.overdue()) && draw_frame(comp, trace, pacer) {
need_present = true
busy = true
}
if need_present && n.frame_ready() {
n.present_frame(width, height)
@@ -407,15 +410,9 @@ pub fn run(args : Array[String]) -> Int {
comp.handle_input(ev, now_ms)
}
x.set_cursor_shape(comp.desired_cursor())
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
busy = true
}
None => ()
if (x.frame_ready() || pacer.overdue()) && draw_frame(comp, trace, pacer) {
need_present = true
busy = true
}
if need_present && x.frame_ready() {
x.present_frame(width, height)
@@ -426,15 +423,9 @@ pub fn run(args : Array[String]) -> Int {
}
None => {
comp.handle_gfx_events(gfx_surface)
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 = serve && gfx_out.length() > 0
busy = true
}
None => ()
if draw_frame(comp, trace, pacer) {
need_present = serve && gfx_out.length() > 0
busy = true
}
// 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 {
@@ -479,6 +470,37 @@ pub fn run(args : Array[String]) -> Int {
}
}
///| When the last frame was drawn: an output that never says it is ready again (a hidden nested
/// window gets no frame callbacks) still gets a frame now and then, so screenshots, recordings
/// and clients waiting on frame callbacks carry on.
struct Pacer {
mut last_ms : UInt64
}
///|
fn Pacer::overdue(self : Pacer) -> Bool {
@sys.monotonic_ms() - self.last_ms >= 250UL
}
///| Compose the desktop and hand a changed frame to the host to draw. True when it changed.
fn draw_frame(comp : @host.ChandraCompositor, trace : Bool, pacer : Pacer) -> Bool {
let c0 = @sys.monotonic_ms()
pacer.last_ms = c0
match comp.compose_scene() {
Some(sg) => {
let r0 = @sys.monotonic_ms()
@raster.submit(sg)
let r1 = @sys.monotonic_ms()
comp.prof_raster_ms = comp.prof_raster_ms + (r1 - r0)
if trace {
@sys.log("frame " + r1.to_string() + " compose " + (r0 - c0).to_string() + " raster " + (r1 - r0).to_string())
}
true
}
None => false
}
}
///| How long an idle main loop may sleep. Nothing on screen changes without a client, the seat or
/// the display waking the loop, except what follows the wall clock (clocks, the desktop card,
/// system stats, notices), which changes on whole seconds. So an idle loop sleeps until just
+1
View File
@@ -5,6 +5,7 @@ import {
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/gfx" @gfx,
"chandra/desktop/compositor/host" @host,
"chandra/desktop/compositor/shell" @shell,
"chandra/desktop/compositor/nested" @nested,
"chandra/desktop/compositor/x11" @x11,
"chandra/desktop/compositor/kms" @kms,
+5 -2
View File
@@ -1694,8 +1694,11 @@ test "open_settings opens the settings module on the tab asked for" {
assert_eq(pr.h, 40 + (1 + 4 + 6) * 28 + 6)
assert_true(comp.shell.open_settings(Session))
ignore(comp.compose_frame())
// The four settings, then Face unlock (a heading; chandra-face isn't installed in tests).
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 6 * 28 + 6)
// The five settings, then Face unlock (a heading; chandra-face isn't installed in tests).
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 7 * 28 + 6)
assert_true(
comp.shell.slot_popup_texts(slot).iter().any(t => t.0.has_prefix("Lighter animations (")),
)
}
///|
+1 -1
View File
@@ -15,7 +15,7 @@
/// those whose title or app id don't match fade out.
///
/// The previews are the Alt+Tab switcher's (switcher.mbt: `switcher_thumb`), made only while
/// the overview is up and remade at most every `THUMB_REFRESH_MS` for windows that keep drawing.
/// the overview is up and remade at most every `preview_refresh_ms` for windows that keep drawing.
/// Nothing is redrawn for the overview once it settles unless a window draws or the pointer
/// moves onto another window.
+49
View File
@@ -0,0 +1,49 @@
///|
test "a real GPU's render node means hardware; display-only drivers and none mean software" {
assert_eq(@shell.classify_render(["i915"], false, false).0, @shell.RenderMode::Hardware)
assert_eq(@shell.classify_render(["simpledrm", "amdgpu"], false, false).0, @shell.RenderMode::Hardware)
assert_eq(@shell.classify_render(["virtio_gpu"], false, false).0, @shell.RenderMode::Software)
assert_eq(@shell.classify_render(["vkms"], false, false).1, "no GPU (only vkms)")
assert_eq(@shell.classify_render([], false, false), (@shell.RenderMode::Software, "no GPU found"))
// NVIDIA's proprietary driver without nvidia-drm loaded has no render node, but it is a GPU.
assert_eq(@shell.classify_render([], true, false).0, @shell.RenderMode::Hardware)
// LIBGL_ALWAYS_SOFTWARE: apps draw in software whatever the hardware.
assert_eq(@shell.classify_render(["i915"], true, true).0, @shell.RenderMode::Software)
assert_eq(@shell.uevent_driver("MAJOR=226\nDRIVER=amdgpu\nPCI_ID=1002:73BF\n"), "amdgpu")
assert_eq(@shell.uevent_driver("MAJOR=226\n"), "")
assert_eq(@shell.RenderMode::parse(" Software\n"), Some(@shell.RenderMode::Software))
assert_eq(@shell.RenderMode::parse("gpu"), Some(@shell.RenderMode::Hardware))
assert_eq(@shell.RenderMode::parse("fast"), None)
}
///|
test "the Lighter animations switch overrides detection and is saved only when it differs" {
let comp = new_comp("rendermode")
comp.shell.persist = true
write_state_edn("{}\n")
comp.shell.set_render_detected(@shell.RenderMode::Hardware, "GPU: i915")
comp.restore_state()
assert_false(comp.shell.software_render())
assert_eq(comp.shell.preview_refresh_ms(), 100UL)
assert_eq(comp.shell.desktop_min_frame_ms(), 16)
// On: software, remembered.
comp.shell.set_session_setting(4, true)
assert_true(comp.shell.software_render())
assert_eq(comp.shell.preview_refresh_ms(), 200UL)
assert_eq(comp.shell.desktop_min_frame_ms(), 33)
assert_true(read_state_edn().contains(":render :software"))
assert_true(comp.shell.render_summary().contains("chosen in Settings"))
// Back to what was detected: nothing saved.
comp.shell.set_session_setting(4, false)
assert_false(comp.shell.software_render())
assert_false(read_state_edn().contains(":render"))
// A saved choice is read back; on a machine where it matches detection it is dropped.
write_state_edn("{:render :software}\n")
comp.restore_state()
assert_true(comp.shell.software_render())
comp.shell.set_render_detected(@shell.RenderMode::Software, "no GPU found")
comp.restore_state()
assert_true(comp.shell.software_render())
assert_eq(comp.shell.render_choice, None)
comp.close()
}
+2 -2
View File
@@ -154,7 +154,7 @@ pub(all) struct SwitcherThumb {
///| How often a preview of a window that keeps redrawing (a video) is made again: scaling a
/// full-screen buffer down takes a couple of ms, too much for every frame of every window.
const THUMB_REFRESH_MS : UInt64 = 100UL
/// Every 100 ms, or 200 ms with software rendering (`DesktopShell::preview_refresh_ms`).
///| True while the switcher is up and a preview waits for its next refresh (the main loop
/// keeps its frame pace for it).
@@ -219,7 +219,7 @@ fn ChandraCompositor::switcher_thumb(self : ChandraCompositor, id : UInt64, box_
let now = @sys.monotonic_ms()
match old {
Some(t) if t.w == tw && t.h == th && t.handle != 0U &&
(!t.stale || now - t.made_ms < THUMB_REFRESH_MS) => return (t.handle, tw, th)
(!t.stale || now - t.made_ms < self.shell.preview_refresh_ms()) => return (t.handle, tw, th)
_ => ()
}
let reuse = match old {
+3
View File
@@ -323,6 +323,9 @@ fn DesktopShell::desktop_tick(self : DesktopShell, now : UInt64) -> Unit {
let ms = (now - self.desk_t0).to_int()
let r = d.pl.desktop_tick(ms)
let r = if r > max_frame_delay { max_frame_delay } else { r }
// Software rendering: at most ~30 frames a second, however often the module asks.
let min = self.desktop_min_frame_ms()
let r = if r > 0 && r < min { min } else { r }
self.desk_next = if r > 0 { now + r.to_uint64() } else { 0 }
}
}
+188
View File
@@ -0,0 +1,188 @@
///| Software or hardware rendering: whether this machine has a GPU that apps can draw with.
///
/// Chandra itself always draws the desktop on the CPU (the host's rasteriser), so the GPU never
/// makes the compositor's own frames cheaper. What it changes is how much CPU is left over: with
/// a GPU, apps (browsers, video, games) draw there; without one they draw with llvmpipe or their
/// own software paths on the same cores as Chandra. So in software mode the desktop asks for
/// less: window previews are remade less often while they are on screen, and a desktop module
/// (Live Starfield) gets at most 30 frames a second.
///
/// Detected at start (`detect_render_mode`): a DRM render node whose driver drives a real GPU
/// (i915, xe, amdgpu, radeon, nouveau, nvidia, Arm and other SoC GPUs) means hardware; none, or
/// only virtual/display-only ones (simpledrm, vkms, virtio_gpu, qxl, bochs, vmwgfx, ...), or
/// LIBGL_ALWAYS_SOFTWARE=1 mean software. Overrides, strongest first: the CHANDRA_RENDER
/// environment variable (`software` or `hardware`), then Settings > Session "Lighter
/// animations", saved in state.edn as `:render :software` or `:render :hardware` only when it
/// differs from what was detected.
///|
pub(all) enum RenderMode {
Software
Hardware
} derive(Eq, Show, Debug)
///| The name state.edn and CHANDRA_RENDER use.
pub fn RenderMode::name(self : RenderMode) -> String {
match self {
Software => "software"
Hardware => "hardware"
}
}
///| "software" / "hardware" (any case, also "sw" / "hw", "gpu" / "cpu").
pub fn RenderMode::parse(s : String) -> RenderMode? {
match s.trim(chars=" \n\t").to_lower().to_string() {
"software" | "sw" | "cpu" => Some(Software)
"hardware" | "hw" | "gpu" => Some(Hardware)
_ => None
}
}
///| DRM drivers that only scan out or emulate a display: a render node from one of these is no
/// GPU to draw with.
let software_drm_drivers : Array[String] = [
"simpledrm", "simple-framebuffer", "efifb", "vesafb", "vkms", "vgem", "virtio_gpu", "virtio-gpu",
"qxl", "bochs", "bochs-drm", "cirrus", "cirrus-qemu", "vboxvideo", "vmwgfx", "hyperv_drm", "udl",
"gud", "ast", "mgag200", "xen-front",
]
///| The driver named by a sysfs `uevent` file's DRIVER= line ("" when it has none).
pub fn uevent_driver(text : String) -> String {
for line in text.split("\n") {
let l = line.to_string()
if l.has_prefix("DRIVER=") {
return l[7:].to_string()
}
}
""
}
///| Hardware or software from the DRM render nodes' drivers (render node drivers as found, in
/// order), the NVIDIA proprietary driver being loaded, and LIBGL_ALWAYS_SOFTWARE. Also why, for
/// the log and Settings.
pub fn classify_render(
drivers : Array[String],
nvidia : Bool,
libgl_software : Bool,
) -> (RenderMode, String) {
if libgl_software {
return (Software, "LIBGL_ALWAYS_SOFTWARE is set")
}
for d in drivers {
if d.length() > 0 && !software_drm_drivers.contains(d) {
return (Hardware, "GPU: " + d)
}
}
if nvidia {
return (Hardware, "GPU: nvidia")
}
match drivers.iter().find_first(d => d.length() > 0) {
Some(d) => (Software, "no GPU (only " + d + ")")
None => (Software, "no GPU found")
}
}
///| Look at this machine: see `classify_render`.
pub fn detect_render_mode() -> (RenderMode, String) {
let drivers : Array[String] = []
for n = 128; n < 136; n = n + 1 {
let b = @sys.read_proc_bytes("/sys/class/drm/renderD" + n.to_string() + "/device/uevent")
if b.length() > 0 {
drivers.push(uevent_driver(bytes_text(b)))
}
}
let nvidia = @sys.read_proc_bytes("/proc/driver/nvidia/version").length() > 0
let libgl = @sys.getenv("LIBGL_ALWAYS_SOFTWARE")
classify_render(drivers, nvidia, libgl.length() > 0 && libgl != "0" && libgl != "false")
}
///|
fn bytes_text(b : Bytes) -> String {
let sb = StringBuilder()
for c in b {
sb.write_char(Int::unsafe_to_char(c.to_int()))
}
sb.to_string()
}
///| Set the detected mode (and why) at start; CHANDRA_RENDER, when set, replaces it.
pub fn DesktopShell::set_render_detected(self : DesktopShell, mode : RenderMode, why : String) -> Unit {
match RenderMode::parse(@sys.getenv("CHANDRA_RENDER")) {
Some(m) => {
self.render_detected = m
self.render_why = "CHANDRA_RENDER=" + m.name()
self.render_forced = true
}
None => {
self.render_detected = mode
self.render_why = why
self.render_forced = false
}
}
}
///| The mode in effect: CHANDRA_RENDER, else the Settings choice, else what was detected.
pub fn DesktopShell::render_mode(self : DesktopShell) -> RenderMode {
if self.render_forced {
return self.render_detected
}
match self.render_choice {
Some(m) => m
None => self.render_detected
}
}
///| True when the desktop should ask less of the CPU (no GPU).
pub fn DesktopShell::software_render(self : DesktopShell) -> Bool {
self.render_mode() == Software
}
///| One line for the log: the mode and where it came from.
pub fn DesktopShell::render_summary(self : DesktopShell) -> String {
let from = if self.render_forced {
self.render_why
} else if self.render_choice is Some(_) {
"chosen in Settings; detected " + self.render_detected.name() + ", " + self.render_why
} else {
self.render_why
}
"rendering: " + self.render_mode().name() + " (" + from + ")"
}
///| Choose software (true) or hardware rendering in Settings: remembered only when it differs
/// from what was detected.
pub fn DesktopShell::choose_software_render(self : DesktopShell, on : Bool) -> Unit {
let m = if on { Software } else { Hardware }
self.render_choice = if m == self.render_detected { None } else { Some(m) }
}
///| The Settings switch's label: what it does and what was found.
fn DesktopShell::render_setting_label(self : DesktopShell) -> String {
let found = if self.render_forced {
self.render_why
} else {
match self.render_detected {
Software => "no GPU found"
Hardware => "GPU found"
}
}
"Lighter animations (" + found + ")"
}
///| How often (ms) a window preview that keeps changing is remade while it is on screen.
pub fn DesktopShell::preview_refresh_ms(self : DesktopShell) -> UInt64 {
if self.software_render() {
200UL
} else {
100UL
}
}
///| The shortest time (ms) between a desktop module's frames.
pub fn DesktopShell::desktop_min_frame_ms(self : DesktopShell) -> Int {
if self.software_render() {
33
} else {
16
}
}
+11
View File
@@ -280,6 +280,13 @@ pub(all) struct DesktopShell {
/// Chandra's own password dialog answers polkit (run0, pkexec, ...); off: the system's polkit
/// agent does. Saved as state.edn `:auth-agent :system` when off.
mut native_auth_agent : Bool
/// Software or hardware rendering (render_mode.mbt): what was detected at start (or
/// CHANDRA_RENDER, then `render_forced`), why, and the Settings choice when it differs
/// (state.edn `:render`).
mut render_detected : RenderMode
mut render_why : String
mut render_forced : Bool
mut render_choice : RenderMode?
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
mut dark_mode : Bool
/// Power: minutes without input before the login session turns the screen off / suspends
@@ -445,6 +452,10 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
net: None,
remember_windows: true,
native_auth_agent: true,
render_detected: Hardware,
render_why: "not detected",
render_forced: false,
render_choice: None,
dark_mode: true,
screen_off_min: default_screen_off_min,
suspend_min: default_suspend_min,
+16 -1
View File
@@ -51,6 +51,8 @@ pub(all) struct SavedState {
terminal : String?
/// From `:auth-agent`: true for :chandra, false for :system.
native_auth_agent : Bool?
/// From `:render`: :software or :hardware chosen in Settings (absent: as detected).
render : RenderMode?
}
///|
@@ -64,7 +66,7 @@ let layout_names : Array[String] = ["tiling", "monocle", "floating"]
///| The keys this build owns; everything else in the file is kept as it is.
let owned_keys : Array[String] = [
"layout", "recent", "desktop-card", "windows", "wallpaper", "restore-session", "remember-windows",
"theme", "power", "shortcuts", "terminal", "auth-agent",
"theme", "power", "shortcuts", "terminal", "auth-agent", "render",
]
///| How state.edn names each wallpaper, in `@libshell.wallpaper_names` order.
@@ -113,6 +115,7 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState {
shortcuts: [],
terminal: None,
native_auth_agent: None,
render: None,
}
}
let entries = read_state_file()
@@ -228,6 +231,10 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState {
Some(Text(t)) if t.length() > 0 => Some(t)
_ => None
},
render: match lookup_key(entries, "render") {
Some(Keyword(k)) | Some(Text(k)) => RenderMode::parse(k)
_ => None
},
native_auth_agent: match lookup_key(entries, "auth-agent") {
Some(Keyword("system")) => Some(false)
Some(Keyword("chandra")) => Some(true)
@@ -288,6 +295,10 @@ pub fn DesktopShell::apply_state(self : DesktopShell, st : SavedState) -> Unit {
Some(b) => self.native_auth_agent = b
None => ()
}
self.render_choice = match st.render {
Some(m) if m != self.render_detected => Some(m)
_ => None
}
match st.terminal {
Some(t) => {
self.terminal = t
@@ -388,6 +399,10 @@ pub fn DesktopShell::save_state(self : DesktopShell) -> Unit {
if !self.native_auth_agent {
entries.insert(2, (@edn.Value::Keyword("auth-agent"), @edn.Value::Keyword("system")))
}
match self.render_choice {
Some(m) => entries.insert(2, (@edn.Value::Keyword("render"), @edn.Value::Keyword(m.name())))
None => ()
}
if !self.dark_mode {
entries.insert(2, (@edn.Value::Keyword("theme"), @edn.Value::Keyword("light")))
}
+13 -2
View File
@@ -684,7 +684,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
}
if self.any_cap("session-settings") {
let st = @wasm.Table::new()
for n in session_setting_names {
for n in self.session_setting_labels() {
st.str(n)
st.end_row()
}
@@ -759,14 +759,24 @@ pub fn DesktopShell::set_wallpaper(self : DesktopShell, i : Int) -> Unit {
///| The session settings the session settings module lists, in index order.
let session_setting_names : Array[String] = [
"Reopen windows at login", "Remember window positions", "Dark mode", "Chandra password dialog",
render_setting_name,
]
///| The rendering switch (its label is made by `render_setting_label`).
let render_setting_name : String = "Lighter animations"
///| The session settings' labels as listed (the rendering one says what was detected).
fn DesktopShell::session_setting_labels(self : DesktopShell) -> Array[String] {
session_setting_names.map(n => if n == render_setting_name { self.render_setting_label() } else { n })
}
///| Which session settings are on: bit i for `session_setting_names[i]`.
fn DesktopShell::session_settings_bits(self : DesktopShell) -> Int {
(if self.restore_session { 1 } else { 0 }) |
(if self.remember_windows { 2 } else { 0 }) |
(if self.dark_mode { 4 } else { 0 }) |
(if self.native_auth_agent { 8 } else { 0 })
(if self.native_auth_agent { 8 } else { 0 }) |
(if self.software_render() { 16 } else { 0 })
}
///| Turn session setting `i` on or off (ignored when out of range) and remember it in state.edn.
@@ -784,6 +794,7 @@ pub fn DesktopShell::set_session_setting(self : DesktopShell, i : Int, on : Bool
self.native_auth_agent = on
self.actions.push(AuthAgentChanged)
}
4 => self.choose_software_render(on)
_ => return
}
@wasm.publish_session_settings(self.session_settings_bits())
+58
View File
@@ -0,0 +1,58 @@
# Rendering, animations and machines without a GPU
Chandra draws the desktop on the CPU on every machine: the host (build/wasmhost, or the Rust
host) rasterises each frame into its own framebuffer and hands it to the display (KMS, X11, a
nested Wayland window). A GPU never makes Chandra's own frames cheaper. What it changes is how
much CPU is left: with a GPU, apps (browsers, video, games) draw there; without one they draw
with llvmpipe or their own software paths on the same cores as Chandra.
## Software or hardware mode
At start Chandra looks for a GPU and logs what it decided:
rendering: software (no GPU found)
rendering: hardware (GPU: amdgpu)
- A DRM render node (`/sys/class/drm/renderD*`) whose driver drives a real GPU (i915, xe,
amdgpu, radeon, nouveau, nvidia, SoC GPUs), or NVIDIA's proprietary driver
(`/proc/driver/nvidia/version`), means **hardware**.
- No render node, or only display-only / virtual ones (simpledrm, vkms, virtio_gpu, qxl, bochs,
vmwgfx, ast, ...), or `LIBGL_ALWAYS_SOFTWARE=1`, means **software**.
Overrides, strongest first:
- `CHANDRA_RENDER=software` or `CHANDRA_RENDER=hardware` in the environment.
- Settings > Session > **Lighter animations (no GPU found / GPU found)**: on is software mode.
Saved in state.edn as `:render :software` or `:render :hardware`, only when it differs from
what was detected (so the same state.edn follows you between machines).
What software mode changes: window previews that keep changing (a video in the overview or
Alt+Tab) are remade every 200 ms instead of 100 ms, and a desktop module (Live Starfield) gets at
most ~30 frames a second however often it asks.
## What makes animations smooth everywhere
- Frames are drawn only when the output can take them: on KMS when no page flip is in flight,
nested and on X11 when the previous frame was shown. A frame drawn while one is still on its way
would never be seen (the KMS loop runs at 125 Hz), and it costs a whole frame of CPU. An output
that never says it is ready (a hidden nested window) still gets a frame every 250 ms.
- Animations are timed by the clock, so a slow frame makes the next one jump ahead instead of
slowing the animation down.
- The rasteriser blends two colour channels at a time (16-bit lanes, exact division by 255),
draws filled circles as row spans (big translucent discs cost a square root per pixel before),
and scales images with 32-bit sums.
- Window previews gliding in the overview are sampled straight from the preview at each frame's
size (nearest pixel), not filtered and cached at a size used once; once the overview settles
they are drawn at the size they were made at. On the MoonBit host other large images drawn
at a new size every frame are treated the same way from their second frame on.
## Measuring
`CHANDRA_FRAME_TRACE=1` logs one line per drawn frame:
frame 1795657160219 compose 1 raster 3
(the clock in ms, then how long composing the scene and rasterising it took). The benchmark in
the project files (`smooth-anim/anim-bench.sh`) runs a headless 1920x1080 session with four
windows, opens and closes the overview six times and runs Live Starfield, and prints frame
rates, frame gaps and raster times from that trace.
+143 -9
View File
@@ -185,13 +185,19 @@ fn blend_span(c: &mut Canvas, y: i32, xa: i32, xb: i32, r: i32, g: i32, b: i32,
}
return;
}
let inv = 255 - a;
let (ra, ga, ba) = (r * a + 127, g * a + 127, b * a + 127);
// Two channels at a time in 16-bit lanes with an exact floor(v / 255): the same pixels as
// c' = (c * a + d * (255 - a) + 127) / 255 per channel, and alpha a + (d * (255 - a) + 127) / 255
// (the alpha lane adds a * 255 before dividing, which is the same).
let inv = (255 - a) as u32;
let rbadd = (((b * a + 127) as u32) << 16) | (r * a + 127) as u32;
let agadd = (((255 * a + 127) as u32) << 16) | (g * a + 127) as u32;
for p in row.chunks_exact_mut(4) {
p[0] = ((ra + p[0] as i32 * inv) / 255) as u8;
p[1] = ((ga + p[1] as i32 * inv) / 255) as u8;
p[2] = ((ba + p[2] as i32 * inv) / 255) as u8;
p[3] = clamp_u8(a + (p[3] as i32 * inv + 127) / 255);
let px = u32::from_le_bytes([p[0], p[1], p[2], p[3]]);
let mut rb = (px & 0x00FF_00FF) * inv + rbadd;
let mut ag = ((px >> 8) & 0x00FF_00FF) * inv + agadd;
rb = ((rb + ((rb >> 8) & 0x00FF_00FF) + 0x0001_0001) >> 8) & 0x00FF_00FF;
ag = (ag + ((ag >> 8) & 0x00FF_00FF) + 0x0001_0001) & 0xFF00_FF00;
p.copy_from_slice(&(rb | ag).to_le_bytes());
}
}
@@ -353,8 +359,46 @@ fn draw_circle(c: &mut Canvas, d: &wt::Disc, ox: i32, oy: i32, clip: Clip) {
let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64);
let rad = d.radius as f64;
let (cx, cy) = (d.cx + ox, d.cy + oy);
// Row by row: the antialiased edge pixel by pixel, a filled disc's solid middle (dist <= rad
// - 0.5, full coverage) as one span and a ring's empty middle (dist <= rad - 2) skipped. The
// same pixels as testing every pixel of the bounding box.
let solid = if d.filled {
(rad - 0.5) * (rad - 0.5)
} else if rad >= 2.0 {
(rad - 2.0) * (rad - 2.0)
} else {
-1.0
};
for dy in (-d.radius - 1)..=(d.radius + 1) {
for dx in (-d.radius - 1)..=(d.radius + 1) {
let y = cy + dy;
if y < 0 || y >= c.h || clip.is_some_and(|k| y < k.y || y >= k.y + k.h) {
continue;
}
let left = solid - (dy * dy) as f64;
let mut m: i32 = -1;
if left >= 0.0 {
m = left.sqrt() as i32;
while ((m + 1) * (m + 1)) as f64 <= left {
m += 1;
}
while m >= 0 && (m * m) as f64 > left {
m -= 1;
}
}
let mut dx = -d.radius - 1;
while dx <= d.radius + 1 {
if m >= 0 && dx == -m {
if d.filled {
let (mut xa, mut xb) = ((cx - m).max(0), (cx + m + 1).min(c.w));
if let Some(k) = clip {
xa = xa.max(k.x);
xb = xb.min(k.x + k.w);
}
blend_span(c, y, xa, xb, cr, cg, cb, ca as i32);
}
dx = m + 1;
continue;
}
let dist = ((dx * dx + dy * dy) as f64).sqrt();
let outer = rad + 0.5 - dist;
let mut cov = if outer > 1.0 { 1.0 } else { outer };
@@ -366,8 +410,9 @@ fn draw_circle(c: &mut Canvas, d: &wt::Disc, ox: i32, oy: i32, clip: Clip) {
}
}
if cov > 0.02 {
blend_pixel(c, cx + dx, cy + dy, cr, cg, cb, (ca * cov).round() as i32, clip);
blend_pixel(c, cx + dx, y, cr, cg, cb, (ca * cov).round() as i32, clip);
}
dx += 1;
}
}
}
@@ -433,6 +478,10 @@ pub struct Images {
srcs: Vec<ImageSrc>,
by_path: HashMap<String, u32>,
sized: RefCell<HashMap<(u32, i32, i32), Rc<Vec<u8>>>>,
/// Window previews (`Raster::thumbnail`): made at the size they settle at, so at any other
/// size (gliding in the overview) they are sampled straight from their pixels, not scaled
/// and kept.
previews: std::collections::HashSet<u32>,
}
/// Biggest image side accepted from a file, and drawn.
@@ -563,12 +612,24 @@ impl Images {
if reuse > 0 && (reuse as usize) <= self.srcs.len() && !self.by_path.values().any(|&v| v == reuse) {
self.srcs[reuse as usize - 1] = src;
self.sized.borrow_mut().retain(|k, _| k.0 != reuse);
self.previews.remove(&reuse);
return reuse;
}
self.srcs.push(src);
self.srcs.len() as u32
}
/// The pixels of preview `handle` when it is one and isn't `w` x `h`: (its w, h, pixels).
fn preview_at_other_size(&self, handle: u32, w: i32, h: i32) -> Option<(i32, i32, &[u8])> {
if !self.previews.contains(&handle) {
return None;
}
match self.srcs.get((handle as usize).checked_sub(1)?)? {
ImageSrc::Pixels { w: sw, h: sh, rgba } if (*sw, *sh) != (w, h) => Some((*sw, *sh, rgba)),
_ => None,
}
}
/// Image `handle` at `w` x `h` (cached), or None for an unknown handle or a silly size.
fn sized(&self, handle: u32, w: i32, h: i32) -> Option<Rc<Vec<u8>>> {
if w <= 0 || h <= 0 || w > MAX_DRAW || h > MAX_DRAW {
@@ -596,6 +657,21 @@ impl Images {
fn draw_image(c: &mut Canvas, imgs: &Images, p: &wt::Picture, ox: i32, oy: i32, clip: Clip) {
let (w, h) = (p.area.w, p.area.h);
if w > 0 && h > 0 && w <= MAX_DRAW && h <= MAX_DRAW {
if let Some((sw, sh, src)) = imgs.preview_at_other_size(p.image, w, h) {
// A moving preview: each pixel from the nearest source pixel, nothing kept.
let (x0, y0) = (p.area.x + ox, p.area.y + oy);
let sx: Vec<usize> = (0..w).map(|x| ((x as i64 * 2 + 1) * sw as i64 / (2 * w as i64)) as usize).collect();
for y in 0..h {
let row = ((y as i64 * 2 + 1) * sh as i64 / (2 * h as i64)) as usize * sw as usize;
for (x, &cx) in sx.iter().enumerate() {
let o = (row + cx) * 4;
blend_pixel(c, x0 + x as i32, y0 + y, src[o] as i32, src[o + 1] as i32, src[o + 2] as i32, src[o + 3] as i32, clip);
}
}
return;
}
}
let Some(px) = imgs.sized(p.image, w, h) else { return };
let (x0, y0) = (p.area.x + ox, p.area.y + oy);
for y in 0..h {
@@ -831,7 +907,9 @@ impl Raster {
}
let Some(s) = self.surfaces.get(&id) else { return 0 };
let px = scale_rgba(&s.rgba, s.w, s.h, w, h);
self.images.put_pixels(reuse, w, h, px)
let handle = self.images.put_pixels(reuse, w, h, px);
self.images.previews.insert(handle);
handle
}
pub fn surface_count(&self) -> usize {
@@ -1226,6 +1304,62 @@ mod tests {
assert_eq!(px(&r, 0, 0), [0, 0, 255, 255]);
}
/// The old way: every pixel of the bounding box.
fn circle_reference(c: &mut Canvas, d: &wt::Disc, clip: Clip) {
let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64);
let rad = d.radius as f64;
for dy in (-d.radius - 1)..=(d.radius + 1) {
for dx in (-d.radius - 1)..=(d.radius + 1) {
let dist = ((dx * dx + dy * dy) as f64).sqrt();
let outer = rad + 0.5 - dist;
let mut cov = if outer > 1.0 { 1.0 } else { outer };
if !d.filled {
let inner = dist - (rad - 1.0 - 0.5);
let ic = if inner > 1.0 { 1.0 } else { inner };
if ic < cov {
cov = ic;
}
}
if cov > 0.02 {
blend_pixel(c, d.cx + dx, d.cy + dy, cr, cg, cb, (ca * cov).round() as i32, clip);
}
}
}
}
#[test]
fn circles_drawn_by_rows_match_the_per_pixel_reference() {
let clips = [None, Some(R { x: 13, y: 40, w: 50, h: 31 })];
for radius in [1, 2, 3, 5, 17, 40, 70] {
for filled in [true, false] {
for alpha in [255u8, 200, 6] {
for (ci, clip) in clips.iter().enumerate() {
let d = wt::Disc { cx: 45, cy: 52, radius, color: color(250, 120, 30, alpha), filled };
let mut a: Vec<u8> = (0..100 * 90 * 4).map(|i| (i * 7 % 251) as u8).collect();
let mut b = a.clone();
draw_circle(&mut Canvas { w: 100, h: 90, data: &mut a }, &d, 0, 0, *clip);
circle_reference(&mut Canvas { w: 100, h: 90, data: &mut b }, &d, *clip);
assert!(a == b, "radius {radius} filled {filled} alpha {alpha} clip {ci}");
}
}
}
}
}
#[test]
fn a_preview_glides_sampled_and_keeps_no_scaled_copy() {
let mut r = Raster::default();
let src = [199u8, 99, 9, 255].repeat(16); // BGRA
let s = r.add_surface(Surface::from_bgra(&src, 16, 4, 4, true).unwrap());
let t = r.thumbnail(s, 2, 2, 0);
assert_ne!(t, 0);
r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 200, 150), image: t })], ..frame(300, 300) }, &mut Fonts::default());
assert_eq!(px(&r, 0, 0), [9, 99, 199, 255]);
assert_eq!(px(&r, 199, 149), [9, 99, 199, 255]);
assert_eq!(px(&r, 200, 150), [0, 0, 0, 0]);
assert!(r.images.sized.borrow().is_empty());
}
#[test]
fn a_large_image_is_cached_at_one_large_size_only() {
let mut imgs = Images::default();
+4
View File
@@ -175,6 +175,9 @@ fn changed_images(panel : @wt.Val) -> R {
d
}
///|
extern "C" fn rs_frame_begin() = "rs_frame_begin"
///|
extern "C" fn rs_damage(x : Int, y : Int, w : Int, h : Int) = "rs_damage"
@@ -658,6 +661,7 @@ fn submit(v : @wt.Val) -> Unit {
}
let w = f.width
let h = f.height
rs_frame_begin()
let resized = rs_resize(w, h) != 0
// The frame starts from the cached backdrop (which covers every pixel), so the buffer is only
// cleared when there is none.
+163 -44
View File
@@ -63,36 +63,48 @@ void rs_set_clip(int32_t on, int32_t x, int32_t y, int32_t w, int32_t h) {
clip_x = x; clip_y = y; clip_w = w; clip_h = h;
}
/* Colour (r, g, b) at alpha a over the RGBA8888 pixel at p: two channels at a time in 16-bit
* lanes, with an exact floor(v / 255). The same pixels as, per channel,
* c' = (c_src * a + c * (255 - a) + 127) / 255 and alpha' = a + (alpha * (255 - a) + 127) / 255
* (the alpha lane adds a * 255 before the division, which is the same thing). */
static inline uint32_t blend32(uint32_t px, uint32_t inv, uint32_t rbadd, uint32_t agadd) {
uint32_t rb = (px & 0x00FF00FFu) * inv + rbadd;
uint32_t ag = ((px >> 8) & 0x00FF00FFu) * inv + agadd;
rb = ((rb + ((rb >> 8) & 0x00FF00FFu) + 0x00010001u) >> 8) & 0x00FF00FFu;
ag = (ag + ((ag >> 8) & 0x00FF00FFu) + 0x00010001u) & 0xFF00FF00u;
return rb | ag;
}
/* The lane constants for colour (r, g, b) at alpha a. */
#define BLEND_ADDS(r, g, b, a) \
uint32_t rbadd = ((uint32_t)((b) * (a) + 127) << 16) | (uint32_t)((r) * (a) + 127); \
uint32_t agadd = ((uint32_t)(255 * (a) + 127) << 16) | (uint32_t)((g) * (a) + 127)
static inline uint32_t opaque32(int r, int g, int b) {
return 0xFF000000u | ((uint32_t)b << 16) | ((uint32_t)g << 8) | (uint32_t)r;
}
static inline void blend_pixel(int x, int y, int r, int g, int b, int a) {
if (x < 0 || y < 0 || x >= fb_w || y >= fb_h || a <= 0) return;
if (clip_on && (x < clip_x || y < clip_y || x >= clip_x + clip_w || y >= clip_y + clip_h)) return;
uint8_t *d = fb + ((size_t)y * fb_w + x) * 4;
if (a >= 255) {
d[0] = (uint8_t)r; d[1] = (uint8_t)g; d[2] = (uint8_t)b; d[3] = 0xff;
return;
}
int inv = 255 - a;
d[0] = (uint8_t)((r * a + d[0] * inv + 127) / 255);
d[1] = (uint8_t)((g * a + d[1] * inv + 127) / 255);
d[2] = (uint8_t)((b * a + d[2] * inv + 127) / 255);
d[3] = (uint8_t)clamp_u8(a + (d[3] * inv + 127) / 255);
uint32_t *d = (uint32_t *)fb + (size_t)y * fb_w + x;
if (a >= 255) { *d = opaque32(r, g, b); return; }
BLEND_ADDS(r, g, b, a);
*d = blend32(*d, 255u - (uint32_t)a, rbadd, agadd);
}
/* Blend a colour over pixels [xa, xb) of row y; the span is already clipped. */
static void blend_span(int y, int xa, int xb, int r, int g, int b, int a) {
if (xa >= xb || a <= 0) return;
uint8_t *p = fb + ((size_t)y * fb_w + xa) * 4, *end = fb + ((size_t)y * fb_w + xb) * 4;
uint32_t *p = (uint32_t *)fb + (size_t)y * fb_w + xa, *end = (uint32_t *)fb + (size_t)y * fb_w + xb;
if (a >= 255) {
for (; p < end; p += 4) { p[0] = (uint8_t)r; p[1] = (uint8_t)g; p[2] = (uint8_t)b; p[3] = 0xff; }
uint32_t c = opaque32(r, g, b);
for (; p < end; p++) *p = c;
return;
}
int inv = 255 - a, ra = r * a + 127, ga = g * a + 127, ba = b * a + 127;
for (; p < end; p += 4) {
p[0] = (uint8_t)((ra + p[0] * inv) / 255);
p[1] = (uint8_t)((ga + p[1] * inv) / 255);
p[2] = (uint8_t)((ba + p[2] * inv) / 255);
p[3] = (uint8_t)clamp_u8(a + (p[3] * inv + 127) / 255);
}
uint32_t inv = 255u - (uint32_t)a;
BLEND_ADDS(r, g, b, a);
for (; p < end; p++) *p = blend32(*p, inv, rbadd, agadd);
}
static int in_rounded_rect(int px, int py, int rx, int ry, int rw, int rh, int rad) {
@@ -193,21 +205,51 @@ void rs_line(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t cr, int32_t
}
}
/* Coverage of pixel (dx, dy) of a circle of radius `rad` (filled, or a 1 px ring). */
static inline double circle_cov(int dx, int dy, double rad, int filled) {
double dist = sqrt((double)(dx * dx + dy * dy));
double outer = rad + 0.5 - dist;
double cov = outer > 1.0 ? 1.0 : outer;
if (!filled) {
double inner = dist - (rad - 1.0 - 0.5);
double ic = inner > 1.0 ? 1.0 : inner;
if (ic < cov) cov = ic;
}
return cov;
}
/* Row by row: the antialiased edge pixel by pixel, a filled circle's solid middle as one span and
* a ring's empty middle skipped (big translucent discs, like the starfield's nebulae, cost a
* sqrt per pixel otherwise). The same pixels as testing every pixel of the bounding box. */
void rs_circle(int32_t cx, int32_t cy, int32_t radius, int32_t cr, int32_t cg, int32_t cb, int32_t ca,
int32_t filled) {
if (!fb || radius <= 0) return;
double rad = radius;
/* Fully covered (filled) when dist <= rad - 0.5; certainly empty (ring) when dist <= rad - 2. */
double solid = filled ? (rad - 0.5) * (rad - 0.5) : (rad >= 2 ? (rad - 2.0) * (rad - 2.0) : -1.0);
for (int dy = -radius - 1; dy <= radius + 1; dy++) {
int y = cy + dy;
if (y < 0 || y >= fb_h || (clip_on && (y < clip_y || y >= clip_y + clip_h))) continue;
/* The middle run |dx| <= m is solid (or empty); m = -1 when there is none. */
int m = -1;
double left = solid - (double)dy * dy;
if (left >= 0) {
m = (int)sqrt(left);
while ((double)(m + 1) * (m + 1) <= left) m++;
while (m >= 0 && (double)m * m > left) m--;
}
for (int dx = -radius - 1; dx <= radius + 1; dx++) {
double dist = sqrt((double)(dx * dx + dy * dy));
double outer = rad + 0.5 - dist;
double cov = outer > 1.0 ? 1.0 : outer;
if (!filled) {
double inner = dist - (rad - 1.0 - 0.5);
double ic = inner > 1.0 ? 1.0 : inner;
if (ic < cov) cov = ic;
if (m >= 0 && dx == -m) {
if (filled) {
int xa = imax(cx - m, 0), xb = imin(cx + m + 1, fb_w);
if (clip_on) { xa = imax(xa, clip_x); xb = imin(xb, clip_x + clip_w); }
blend_span(y, xa, xb, cr, cg, cb, ca);
}
dx = m;
continue;
}
if (cov > 0.02) blend_pixel(cx + dx, cy + dy, cr, cg, cb, (int)round(ca * cov));
double cov = circle_cov(dx, dy, rad, filled);
if (cov > 0.02) blend_pixel(cx + dx, y, cr, cg, cb, (int)round(ca * cov));
}
}
}
@@ -312,33 +354,55 @@ typedef struct {
NSVGimage *svg;
Sized *sized; /* the image at the sizes it was drawn at */
int changed; /* new pixels under an old handle since the last frame (a preview) */
uint32_t resized_at; /* the frame it was last drawn at a new large size */
int preview; /* a window preview (rs_thumbnail): drawn sampled at any other size */
} Image;
static Image *images;
static int32_t n_images, cap_images;
/* Scale RGBA src (sw x sh) to w x h: average of the covered source pixels (alpha weighted), the
* nearest one when enlarging. Same as the software renderer. */
* nearest one when enlarging. Same as the software renderer. Each output row sums its source
* rows per column first (32-bit sums; a column of up to 4096 rows of 255 * 255 fits), then each
* output pixel sums its columns: one pass over the source, row by row. */
static uint8_t *scale_rgba(const uint8_t *src, int sw, int sh, int w, int h) {
uint8_t *out = calloc((size_t)w * h, 4);
uint32_t *col = malloc(sizeof(uint32_t) * 5 * (size_t)sw); /* r*a, g*a, b*a, a, n per column */
for (int y = 0; y < h; y++) {
int y0 = y * sh / h, y1 = imax((y + 1) * sh / h, y0 + 1);
int x_hi = 0; /* columns summed so far for this row (they are needed left to right) */
for (int x = 0; x < w; x++) {
int x0 = x * sw / w, x1 = imax((x + 1) * sw / w, x0 + 1);
int64_t r = 0, g = 0, b = 0, a = 0, n = 0;
for (int sy = y0; sy < y1; sy++) {
for (int sx = x0; sx < x1; sx++) {
const uint8_t *p = src + ((size_t)sy * sw + sx) * 4;
int64_t pa = p[3];
r += p[0] * pa; g += p[1] * pa; b += p[2] * pa; a += pa; n++;
for (; x_hi < x1; x_hi++) {
uint32_t r = 0, g = 0, b = 0, a = 0;
const uint8_t *p = src + ((size_t)y0 * sw + x_hi) * 4;
for (int sy = y0; sy < y1; sy++, p += (size_t)sw * 4) {
uint32_t pa = p[3];
r += p[0] * pa; g += p[1] * pa; b += p[2] * pa; a += pa;
}
uint32_t *c = col + (size_t)x_hi * 5;
c[0] = r; c[1] = g; c[2] = b; c[3] = a; c[4] = (uint32_t)(y1 - y0);
}
if (a > 0) {
uint8_t *o = out + ((size_t)y * w + x) * 4;
o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n);
uint8_t *o = out + ((size_t)y * w + x) * 4;
if ((int64_t)(x1 - x0) * (y1 - y0) <= 66000) {
/* The sums fit 32 bits (255 * 255 per pixel), and 32-bit division is much quicker. */
uint32_t r = 0, g = 0, b = 0, a = 0, n = 0;
for (int sx = x0; sx < x1; sx++) {
const uint32_t *c = col + (size_t)sx * 5;
r += c[0]; g += c[1]; b += c[2]; a += c[3]; n += c[4];
}
if (a > 0) { o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n); }
continue;
}
int64_t r = 0, g = 0, b = 0, a = 0, n = 0;
for (int sx = x0; sx < x1; sx++) {
const uint32_t *c = col + (size_t)sx * 5;
r += c[0]; g += c[1]; b += c[2]; a += c[3]; n += c[4];
}
if (a > 0) { o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n); }
}
}
free(col);
return out;
}
@@ -487,30 +551,84 @@ static uint8_t *render_svg(NSVGimage *svg, int w, int h) {
return out;
}
/* The largest size an image is drawn at (a window preview gliding to its window's size). */
#define MAX_DRAW 4096
/* Sizes past which only one scaled copy of an image is kept (icons are drawn at a few small
* sizes; previews at one large one, or a new one each frame while they move). */
static int big_size(int w, int h) { return w * h > 128 * 128; }
/* Frames submitted so far (rs_frame_begin): tells a moving image from one drawn at a new size once. */
static uint32_t frame_seq = 1;
void rs_frame_begin(void) { frame_seq++; }
/* Image `handle` at w x h, cached. NULL for an unknown handle or a silly size, and for a window
* preview at another size or a large image that was drawn at another new size in the frame
* before: it is moving (the overview's gliding previews), so rs_draw_image samples it instead of
* filtering it and keeping a copy at a size used once. */
static const uint8_t *image_sized(int32_t handle, int w, int h) {
if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return NULL;
if (w <= 0 || h <= 0 || w > MAX_DRAW || h > MAX_DRAW) return NULL;
if (handle <= 0 || handle > n_images || !images[handle - 1].used) return NULL;
Image *im = &images[handle - 1];
if (im->rgba && im->w == w && im->h == h) return im->rgba;
for (Sized *s = im->sized; s; s = s->next)
if (s->w == w && s->h == h) return s->rgba;
int big = big_size(w, h);
if (im->preview) return NULL; /* made at the size it settles at; stretched only while moving */
if (big && im->rgba) {
int moving = im->resized_at + 1 >= frame_seq;
im->resized_at = frame_seq;
if (moving) return NULL;
}
uint8_t *px = im->svg ? render_svg(im->svg, w, h) : im->rgba ? scale_rgba(im->rgba, im->w, im->h, w, h) : NULL;
if (!px) return NULL;
if (big) {
/* Keep one large size: drop the other large copies. */
for (Sized **pp = &im->sized; *pp;) {
Sized *s = *pp;
if (big_size(s->w, s->h)) { *pp = s->next; free(s->rgba); free(s); }
else pp = &s->next;
}
}
Sized *s = malloc(sizeof *s);
s->w = w; s->h = h; s->rgba = px; s->next = im->sized;
im->sized = s;
return px;
}
/* Blend straight-RGBA pixels `px` (w x h, row `stride` pixels) at (x0, y0), clipped. When `sx` /
* `sy` are given, destination column x / row y takes source column sx[x] / row sy[y] (sampling). */
static void blend_image(const uint8_t *px, int stride, int x0, int y0, int w, int h, const int *sx, const int *sy) {
int xa, ya, xb, yb;
if (!visible(x0, y0, w, h, &xa, &ya, &xb, &yb)) return;
for (int y = ya; y < yb; y++) {
int row = sy ? sy[y - y0] : y - y0;
const uint8_t *src = px + (size_t)row * stride * 4;
uint8_t *d = fb + ((size_t)y * fb_w + xa) * 4;
for (int x = xa; x < xb; x++, d += 4) {
const uint8_t *p = src + (size_t)(sx ? sx[x - x0] : x - x0) * 4;
int a = p[3];
if (a <= 0) continue;
if (a >= 255) { *(uint32_t *)d = opaque32(p[0], p[1], p[2]); continue; }
BLEND_ADDS(p[0], p[1], p[2], a);
*(uint32_t *)d = blend32(*(uint32_t *)d, 255u - (uint32_t)a, rbadd, agadd);
}
}
}
void rs_draw_image(int32_t handle, int32_t x0, int32_t y0, int32_t w, int32_t h) {
if (!fb) return;
const uint8_t *px = image_sized(handle, w, h);
if (!px) return;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
const uint8_t *p = px + ((size_t)y * w + x) * 4;
blend_pixel(x0 + x, y0 + y, p[0], p[1], p[2], p[3]);
}
if (px) { blend_image(px, w, x0, y0, w, h, NULL, NULL); return; }
/* A moving large image: each pixel from the nearest source pixel, nothing kept. */
if (w <= 0 || h <= 0 || w > MAX_DRAW || h > MAX_DRAW || handle <= 0 || handle > n_images) return;
Image *im = &images[handle - 1];
if (!im->used || !im->rgba) return;
int *sx = malloc(sizeof(int) * (size_t)(w + h)), *sy = sx + w;
for (int x = 0; x < w; x++) sx[x] = (int)(((int64_t)x * 2 + 1) * im->w / (2 * w));
for (int y = 0; y < h; y++) sy[y] = (int)(((int64_t)y * 2 + 1) * im->h / (2 * h));
blend_image(im->rgba, im->w, x0, y0, w, h, sx, sy);
free(sx);
}
/* ------------------------------------------------------------------ surfaces */
@@ -691,6 +809,7 @@ int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) {
int32_t img = image_slot(reuse);
images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px;
images[img - 1].changed = img == reuse;
images[img - 1].preview = 1;
return img;
}