Add opt-in shared slide zoom with fast buffered crop rendering

This commit is contained in:
Dandaedre 2026-11-20 08:17:31 +01:00
parent 00d69dafed
commit edfae03ff4
46 changed files with 7512 additions and 25 deletions

50
Cargo.lock generated
View File

@ -577,6 +577,25 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
@ -816,14 +835,19 @@ dependencies = [
[[package]]
name = "egui_software_backend"
version = "0.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8ca3a47168e93a5cca79b7cb830817acaf07ebc1f8756aa368a6b2d6250f6ae"
dependencies = [
"constify",
"egui",
"rayon",
"strength_reduce",
]
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "emath"
version = "0.34.3"
@ -2221,7 +2245,7 @@ dependencies = [
[[package]]
name = "pdf-presenter"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"bytemuck",
"chrono",
@ -2531,6 +2555,26 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
[[package]]
name = "rayon"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "read-fonts"
version = "0.37.0"

View File

@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"]
resolver = "3"
[workspace.package]
version = "0.1.53"
version = "0.1.54"
edition = "2024"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter"
@ -17,3 +17,6 @@ strip = true
[profile.dev.package."*"]
opt-level = 2
[patch.crates-io]
egui_software_backend = { path = "vendor/egui_software_backend" }

View File

@ -56,7 +56,9 @@ pointer near an edge or right-click to recover them.
Prepared slides are cached for reuse. The presenter shows loading progress, RAM use
and an ETA when available; decks larger than the RAM budget use a rolling buffer.
Notes can come from the PDF or picture-folder sidecars. Themes and English/French
controls are available in Menu.
controls are available in Menu. Optional shared slide zoom is available under
**Menu → Preferences → Enable page zoom**; scroll to zoom, drag to pan, double-click
to reset on the current preview or presentation screen.
## Import your notes

View File

@ -14,7 +14,7 @@ font8x8 = "=0.3.1"
egui = { version = "=0.34.1", features = ["default_fonts"] }
egui-winit = { version = "=0.34.1", default-features = false, features = ["x11", "wayland"] }
egui_software_backend = { version = "=0.0.3", default-features = false, features = ["std"] }
egui_software_backend = { version = "=0.0.3", default-features = false, features = ["std", "rayon"] }
bytemuck = "1.25"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

View File

@ -90,3 +90,5 @@ pub mod timer;
/// Editable presentation notes sidecars.
pub mod notes;
pub mod zoom;

View File

@ -39,6 +39,24 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str {
return text;
}
match text {
"Enable page zoom" => "Activer le zoom des diapositives",
"Page zoom" => "Zoom de la diapositive",
"Reset zoom" => "Réinitialiser le zoom",
"Disable zoom" => "Désactiver le zoom",
"Keep zoom enabled" => "Garder le zoom activé",
"Zoom performance" => "Performances du zoom",
"Scroll to zoom · drag to pan · double-click to reset" => {
"Molette pour zoomer · glisser pour déplacer · double-clic pour réinitialiser"
}
"Use the current slide preview or a presentation screen. Changing slides resets zoom." => {
"Utilisez l’aperçu actuel ou un écran de présentation. Changer de diapositive réinitialise le zoom."
}
"Zoom reuses buffered images: no extra PDF rendering or image memory. Enlarged slides may look softer. Software drawing can slow down on large or multiple displays." => {
"Le zoom réutilise les images en mémoire, sans rendu PDF ni mémoire d’image supplémentaires. Les diapositives agrandies peuvent être moins nettes. Le dessin logiciel peut ralentir sur des écrans grands ou multiples."
}
"Zoomed frames are taking over 33 ms to draw. Panning may feel slow on this display. Reset or disable zoom to return to normal viewing." => {
"Les images zoomées prennent plus de 33 ms à dessiner. Le déplacement peut sembler lent sur cet écran. Réinitialisez ou désactivez le zoom pour revenir à l’affichage normal."
}
"Cancel" => "Annuler",
"Preview (first 3 slides)" => "Aperçu (3 premières diapositives)",
"Import notes…" => "Importer des notes…",

View File

@ -46,6 +46,9 @@ struct NativeWindow {
transition: Option<(Instant, bool)>,
frames: usize,
display_action: Option<DisplayAction>,
zoom_change: Option<crate::zoom::View>,
zoom_watch: crate::zoom::PerformanceWatch,
zoom_slow: bool,
#[cfg(target_os = "linux")]
browser_parent: Option<WindowId>,
}
@ -98,6 +101,9 @@ impl NativeWindow {
transition: None,
frames: 0,
display_action: None,
zoom_change: None,
zoom_watch: Default::default(),
zoom_slow: false,
#[cfg(target_os = "linux")]
browser_parent: None,
})
@ -166,6 +172,7 @@ impl NativeWindow {
blank: bool,
setup: Option<&HostState>,
) -> Result<(), Failure> {
let render_started = Instant::now();
let size = self.window.inner_size();
if size.width == 0 || size.height == 0 {
return Ok(());
@ -182,6 +189,7 @@ impl NativeWindow {
let ui_state = &mut self.ui;
let ctx = self.ctx.clone();
let display_action = &mut self.display_action;
let zoom_change = &mut self.zoom_change;
let output = ctx.run_ui(input, |ui| match role {
Role::Presenter => {
presenter_ui::presenter(ui, studio.as_deref_mut().unwrap(), ui_state)
@ -193,7 +201,7 @@ impl NativeWindow {
if let Some(setup) = setup {
*display_action = presenter_ui::output_display_recovery(
ui,
setup.setup_controls,
setup.setup_controls && !setup.zoom.enabled,
setup.route_trial.is_some(),
);
}
@ -216,12 +224,43 @@ impl NativeWindow {
egui::TextureOptions::LINEAR,
)
});
presenter_ui::paint_slide(
let mut view = setup.map(|s| s.zoom.view).unwrap_or_default();
if let Some(setup) = setup
&& setup.zoom.enabled
&& setup.route_trial.is_none()
&& setup
.frame
.as_ref()
.is_some_and(|f| f.path == frame.info.path)
{
let target = presenter_ui::fitted_slide(
ui.max_rect(),
[frame.info.width, frame.info.height],
);
let (next, response) = presenter_ui::zoom_gestures(ui, target, view);
if setup.setup_controls {
response.context_menu(|ui| {
if ui
.button("Swap presenter and presentation displays…")
.clicked()
{
*display_action = Some(DisplayAction::Swap);
ui.close();
}
});
}
if next != view {
*zoom_change = Some(next);
view = next;
}
}
presenter_ui::paint_slide_zoomed(
ui.painter(),
ui.max_rect(),
tex.id(),
[frame.info.width, frame.info.height],
setup.map(|s| s.slide_colors).unwrap_or_default(),
view,
);
}
}
@ -248,6 +287,19 @@ impl NativeWindow {
self.window.pre_present_notify();
buffer.present()?;
self.frames += 1;
let zoomed = if role == Role::Presenter {
studio
.as_ref()
.is_some_and(|s| s.zoom.enabled && s.zoom.view.scale > 1.)
} else {
!blank && setup.is_some_and(|s| s.zoom.enabled && s.zoom.view.scale > 1.)
};
if self.zoom_watch.observe(zoomed, render_started.elapsed()) {
self.zoom_slow = true;
if let Some(s) = studio {
s.zoom_warning = true;
}
}
Ok(())
}
}
@ -347,6 +399,9 @@ struct Host {
presented: HashSet<WindowId>,
failed_reads: HashSet<std::path::PathBuf>,
preload_cursor: usize,
zoom_pending: bool,
zoom_slow: bool,
next_zoom_ack: Instant,
}
// The last visible frame may outlive its cache entry during a working-set change.
// Count that allocation and pin it until the requested replacement is available.
@ -656,6 +711,7 @@ impl App {
fn poll(&mut self, el: &ActiveEventLoop) {
let mut repaint = false;
if let Some(s) = &mut self.studio {
repaint |= s.new_zoom;
let before = (
s.generation,
s.frames.len(),
@ -719,6 +775,20 @@ impl App {
}
if let Some(output) = &self.output {
while let Ok(ack) = output.rx.try_recv() {
if let Some(zoom) = ack.zoom {
if ack.generation == s.buffer_generation() && ack.page == Some(s.requested)
{
if s.zoom.accept_output(zoom) {
repaint = true;
}
if zoom.epoch == s.zoom.epoch {
s.zoom_warning |= ack.zoom_slow;
s.new_zoom = true; // Echo newest serial so output can stop retrying.
repaint |= ack.zoom_slow;
}
}
continue;
}
if let Some(action) = ack.display_action {
s.display_control(action, ack.route_trial);
}
@ -750,6 +820,7 @@ impl App {
if s.new_output {
s.output_sequence += 1;
let state = HostState {
zoom: s.zoom,
setup_controls: !s.presentation_started,
route_trial: s.route_trial.as_ref().map(|t| t.id),
sequence: s.output_sequence,
@ -778,11 +849,27 @@ impl App {
};
if output.tx.try_send(state).is_ok() {
s.new_output = false;
s.new_zoom = false;
} else {
s.output_sequence -= 1;
}
}
}
if s.new_zoom
&& !s.new_output
&& let Some(output) = &self.output
{
let state = HostState {
zoom_only: true,
zoom: s.zoom,
generation: s.buffer_generation(),
page: s.requested,
..Default::default()
};
if output.tx.try_send(state).is_ok() {
s.new_zoom = false;
}
}
if s.close_requested {
el.exit();
}
@ -799,7 +886,7 @@ impl App {
}
if let Some(host) = &mut self.host {
loop {
let state = match host.commands.try_recv() {
let mut state = match host.commands.try_recv() {
Ok(state) => state,
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
@ -809,6 +896,18 @@ impl App {
break;
}
};
if state.zoom_only {
if state.generation == host.state.generation && state.page == host.state.page {
let before = host.state.zoom;
host.state.zoom.accept_presenter(state.zoom);
host.zoom_pending = host.state.zoom != state.zoom.normalized();
repaint |= before != host.state.zoom;
}
continue;
}
host.state.zoom.accept_presenter(state.zoom);
host.zoom_pending = host.state.zoom != state.zoom.normalized();
state.zoom = host.state.zoom;
if !state.blanked {
host.close_requested = false;
}
@ -847,6 +946,16 @@ impl App {
}
host.state = state;
}
if host.zoom_pending && host.parent_connected && Instant::now() >= host.next_zoom_ack {
let _ = host.acks.try_send(Ack {
zoom: Some(host.state.zoom),
zoom_slow: host.zoom_slow,
generation: host.state.generation,
page: Some(host.state.page),
..Default::default()
});
host.next_zoom_ack = Instant::now() + Duration::from_millis(33);
}
if !host.parent_connected && (host.close_requested || self.windows.is_empty()) {
el.exit();
return;
@ -1049,6 +1158,17 @@ impl ApplicationHandler for App {
blank,
self.host.as_ref().map(|h| &h.state),
);
if let Some(host) = &mut self.host {
if let Some(view) = self.windows[index].zoom_change.take() {
host.state.zoom.gesture(view);
host.zoom_pending = true;
self.windows.iter().for_each(|w| w.window.request_redraw());
}
if self.windows[index].zoom_slow && !host.zoom_slow {
host.zoom_slow = true;
host.zoom_pending = true;
}
}
if let Some(action) = self.windows[index].display_action.take()
&& let Some(host) = &self.host
{
@ -1227,6 +1347,9 @@ pub fn run_output() -> Result<(), Failure> {
presented: HashSet::new(),
failed_reads: HashSet::new(),
preload_cursor: 0,
zoom_pending: false,
zoom_slow: false,
next_zoom_ack: now,
}),
output: None,
lease: Some(SleepLease::new()),

View File

@ -23,6 +23,10 @@ pub enum DisplayAction {
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct HostState {
#[serde(default)]
pub zoom: crate::zoom::Sync,
#[serde(default)]
pub zoom_only: bool,
#[serde(default)]
pub slide_colors: crate::settings::SlideColors,
#[serde(default)]
@ -44,6 +48,10 @@ pub struct HostState {
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct Ack {
#[serde(default)]
pub zoom: Option<crate::zoom::Sync>,
#[serde(default)]
pub zoom_slow: bool,
/// Explicit operator blanking, separate from diagnostic status messages.
#[serde(default)]
pub request_blank: bool,
@ -60,6 +68,18 @@ pub struct Ack {
#[serde(default)]
pub buffered: usize,
}
/// A lightweight crop update must never discard queued frame/routing state.
pub fn coalesce(latest: &mut Option<HostState>, command: HostState) {
if command.zoom_only
&& let Some(previous) = latest
{
if previous.generation == command.generation && previous.page == command.page {
previous.zoom.accept_presenter(command.zoom);
}
} else {
*latest = Some(command);
}
}
pub struct OutputLink {
pub tx: SyncSender<HostState>,
pub rx: Receiver<Ack>,
@ -130,7 +150,7 @@ impl OutputLink {
}
let mut latest = None;
while let Ok(command) = commands.try_recv() {
latest = Some(command);
coalesce(&mut latest, command);
}
if let Some(command) = latest {
if write_json(&mut stdin, &command).is_err() {

View File

@ -18,19 +18,102 @@ pub fn paint_slide(
dimensions: [u32; 2],
colors: crate::settings::SlideColors,
) {
let [width, height] = dimensions.map(|v| v as f32);
paint_slide_zoomed(
painter,
rect,
texture,
dimensions,
colors,
Default::default(),
);
}
pub fn fitted_slide(rect: Rect, dimensions: [u32; 2]) -> Rect {
let [width, height] = dimensions.map(|v| v.max(1) as f32);
let scale = (rect.width() / width).min(rect.height() / height);
let target = Rect::from_center_size(rect.center(), Vec2::new(width * scale, height * scale));
Rect::from_center_size(rect.center(), Vec2::new(width * scale, height * scale))
}
/// Crop UVs, never enlarge geometry or allocate another image for zoom.
pub fn paint_slide_zoomed(
painter: &egui::Painter,
rect: Rect,
texture: egui::TextureId,
dimensions: [u32; 2],
colors: crate::settings::SlideColors,
view: crate::zoom::View,
) {
let target = fitted_slide(rect, dimensions);
let [r, g, b] = colors.fit_padding;
painter.rect_filled(rect, 0., Color32::from_rgb(r, g, b));
let [r, g, b] = colors.page_background;
painter.rect_filled(target, 0., Color32::from_rgb(r, g, b));
painter.image(
texture,
target,
Rect::from_min_max(Pos2::ZERO, Pos2::new(1., 1.)),
Color32::WHITE,
);
let uv = view.uv();
// Separate clip bands keep large moving crops parallel in the bounded CPU
// renderer pool. Every band reads the same texture; no image is duplicated.
let pixels = target.area() * painter.ctx().pixels_per_point().powi(2);
let bands = if view.scale > 1. && pixels > 1_000_000. {
4
} else {
1
};
for band in 0..bands {
let a = band as f32 / bands as f32;
let b = (band + 1) as f32 / bands as f32;
let rect = Rect::from_min_max(
Pos2::new(target.left(), target.top() + target.height() * a),
Pos2::new(target.right(), target.top() + target.height() * b),
);
let crop = Rect::from_min_max(
Pos2::new(uv.left(), uv.top() + uv.height() * a),
Pos2::new(uv.right(), uv.top() + uv.height() * b),
);
painter
.with_clip_rect(painter.clip_rect().intersect(rect))
.image(texture, rect, crop, Color32::WHITE);
}
}
/// Shared presenter/output input in normalized slide coordinates; no file I/O.
pub fn zoom_gestures(
ui: &mut Ui,
target: Rect,
view: crate::zoom::View,
) -> (crate::zoom::View, egui::Response) {
let response = ui.interact(target, ui.id().with("page-zoom"), Sense::click_and_drag());
let mut next = view;
if response.hovered() {
let scroll = ui.input_mut(|i| {
let scroll = i.smooth_scroll_delta.y;
i.smooth_scroll_delta = Vec2::ZERO;
scroll
});
if scroll != 0.
&& let Some(pos) = response.hover_pos()
{
let anchor = (pos - target.min) / target.size();
next = next.zoom_at(
next.scale * (scroll * 0.002).clamp(-0.7, 0.7).exp(),
[anchor.x, anchor.y],
);
}
let pinch = ui.input(|i| i.zoom_delta());
if pinch != 1. {
next = next.zoom_at(next.scale * pinch, [0.5; 2]);
}
}
if response.dragged_by(egui::PointerButton::Primary) {
let delta = ui.input(|i| i.pointer.delta()) / target.size();
next = next.pan([delta.x, delta.y]);
}
if response.double_clicked() {
next = Default::default();
}
if response.hovered() || response.dragged() {
ui.ctx().set_cursor_icon(if response.dragged() {
egui::CursorIcon::Grabbing
} else {
egui::CursorIcon::Grab
});
}
(next, response)
}
const TEAL: Color32 = Color32::from_rgb(103, 226, 205);
pub struct UiState {
@ -51,6 +134,16 @@ impl Default for UiState {
}
impl UiState {
pub fn image(&mut self, ui: &mut Ui, s: &Studio, page: usize, rect: Rect) {
self.image_view(ui, s, page, rect, Default::default());
}
fn image_view(
&mut self,
ui: &mut Ui,
s: &Studio,
page: usize,
rect: Rect,
view: crate::zoom::View,
) {
let locale = ui.ctx().clone();
ui.painter()
.rect_filled(rect, 6., Color32::from_rgb(18, 28, 31));
@ -66,12 +159,13 @@ impl UiState {
TextureOptions::LINEAR,
)
});
paint_slide(
paint_slide_zoomed(
ui.painter(),
rect,
tex.id(),
[frame.info.width, frame.info.height],
s.settings.slide_colors,
view,
);
} else {
ui.painter().text(
@ -657,12 +751,25 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) {
ui.visuals().hyperlink_color,
);
if let Some(page) = page {
native.image(
ui,
s,
page,
Rect::from_min_max(rect.min + Vec2::new(0., 24.), rect.max),
);
let area = Rect::from_min_max(rect.min + Vec2::new(0., 24.), rect.max);
if index == 1 && s.settings.zoom_enabled {
native.image_view(ui, s, page, area, s.zoom.view);
if s.route_trial.is_none()
&& let Some(frame) = s.frame(page)
{
let target = fitted_slide(area, [frame.info.width, frame.info.height]);
let (view, response) = zoom_gestures(ui, target, s.zoom.view);
response.on_hover_text(tr(
&locale,
"Scroll to zoom · drag to pan · double-click to reset",
));
if view != s.zoom.view {
s.set_zoom(view);
}
}
} else {
native.image(ui, s, page, area);
}
} else if index == 2 && s.count() > 0 && s.requested == s.count() - 1 {
// Presenter-only decoration: never create a page, frame or navigation target.
let area = Rect::from_min_max(rect.min + Vec2::new(0., 24.), rect.max);
@ -1290,6 +1397,16 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) {
});
s.displays_open &= open;
}
if s.settings.zoom_enabled && s.zoom_warning && !s.zoom_warning_dismissed {
egui::Window::new(tr(&ctx, "Zoom performance"))
.collapsible(false).resizable(false).show(&ctx, |ui| {
ui.set_max_width(420.);
ui.label(tr(&ctx, "Zoomed frames are taking over 33 ms to draw. Panning may feel slow on this display. Reset or disable zoom to return to normal viewing."));
if ui.button(tr(&ctx, "Reset zoom")).clicked() { s.set_zoom(Default::default()); s.zoom_warning_dismissed = true; }
if ui.button(tr(&ctx, "Disable zoom")).clicked() { s.enable_zoom(false); }
if ui.button(tr(&ctx, "Keep zoom enabled")).clicked() { s.zoom_warning_dismissed = true; }
});
}
notes_import_ui(&ctx, s);
notes_editor_ui(&ctx, s);
}
@ -1860,6 +1977,10 @@ fn menu(ui: &mut Ui, s: &mut Studio) {
ui.menu_button(tr(&locale,"Preferences"), |ui| {
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
ui.set_width(370.);
let mut enabled = s.settings.zoom_enabled;
if ui.checkbox(&mut enabled, tr(&locale, "Enable page zoom")).changed() { s.enable_zoom(enabled); }
ui.small(tr(&locale, "Zoom reuses buffered images: no extra PDF rendering or image memory. Enlarged slides may look softer. Software drawing can slow down on large or multiple displays."));
ui.separator();
if ui.checkbox(&mut s.settings.auto_show,tr(&locale,"Show presentation automatically when opening a document")).changed() {s.save_preferences();}
ui.separator();
ui.label(tr(&locale,"RAM budget per process (presenter + output each use this allowance):"));
@ -1873,6 +1994,17 @@ fn menu(ui: &mut Ui, s: &mut Studio) {
});
});
});
if s.settings.zoom_enabled {
ui.menu_button(tr(&locale, "Page zoom"), |ui| {
let mut scale = s.zoom.view.scale;
if ui.add(egui::Slider::new(&mut scale, 1.0..=8.0).text("×")).changed() {
s.set_zoom(s.zoom.view.zoom_at(scale, [0.5; 2]));
}
if ui.button(tr(&locale, "Reset zoom")).clicked() { s.set_zoom(Default::default()); }
ui.small(tr(&locale, "Scroll to zoom · drag to pan · double-click to reset"));
ui.small(tr(&locale, "Use the current slide preview or a presentation screen. Changing slides resets zoom."));
});
}
ui.separator();
timer_controls(ui, s, true);
fullscreen_button(ui, s);

View File

@ -225,6 +225,7 @@ pub struct Settings {
pub thumbnail_size: f32,
pub buffer_mib: u32,
pub auto_show: bool,
pub zoom_enabled: bool,
pub theme: crate::theme::Theme,
pub language: crate::localization::Language,
}
@ -266,6 +267,7 @@ impl Default for Settings {
thumbnail_size: 220.,
buffer_mib: default_buffer_mib(),
auto_show: true,
zoom_enabled: false,
theme: Default::default(),
language: Default::default(),
}

View File

@ -127,6 +127,10 @@ pub struct Studio {
pub dirty_routes: bool,
pub privacy_hold: bool,
pub output_sequence: u64,
pub zoom: crate::zoom::Sync,
pub new_zoom: bool,
pub zoom_warning: bool,
pub zoom_warning_dismissed: bool,
pub new_output: bool,
pub close_requested: bool,
failed: HashSet<(usize, u32)>,
@ -224,6 +228,10 @@ impl Studio {
dirty_routes: true,
privacy_hold: false,
output_sequence: 0,
zoom: Default::default(),
new_zoom: false,
zoom_warning: false,
zoom_warning_dismissed: false,
new_output: true,
close_requested: false,
failed: HashSet::new(),
@ -428,6 +436,9 @@ impl Studio {
if !self.blanked && self.routes.presentation.is_empty() {
self.slide_played();
}
if self.requested != page {
self.set_zoom(crate::zoom::View::default());
}
self.requested = page;
self.jump.clear();
self.new_output = true;
@ -748,6 +759,7 @@ impl Studio {
if !self.smoke {
self.blanked = !settings.auto_show;
self.settings = settings;
self.set_zoom(crate::zoom::View::default());
self.layout = self.settings.for_project(&self.project());
self.routes = Routes::default();
}
@ -864,6 +876,7 @@ impl Studio {
self.output_buffered = 0;
self.ram_blocked = false;
self.failed.clear();
self.set_zoom(crate::zoom::View::default());
self.requested = 0;
self.presentation_started = false;
self.timer = crate::timer::Timer::default();
@ -1104,6 +1117,17 @@ impl Studio {
pub fn buffer_generation(&self) -> u64 {
(self.generation << 32) | u64::from(self.target_edge)
}
pub fn set_zoom(&mut self, view: crate::zoom::View) {
self.zoom.set(self.settings.zoom_enabled, view);
self.new_zoom = true;
}
pub fn enable_zoom(&mut self, enabled: bool) {
self.settings.zoom_enabled = enabled;
self.set_zoom(crate::zoom::View::default());
self.zoom_warning = false;
self.zoom_warning_dismissed = false;
self.save_preferences();
}
pub fn save_preferences(&mut self) {
self.pending_save = true;
}

View File

@ -0,0 +1,123 @@
//! Bounded, resolution-independent crop of an already buffered slide.
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct View {
pub scale: f32,
pub center: [f32; 2],
}
impl Default for View {
fn default() -> Self {
Self {
scale: 1.,
center: [0.5; 2],
}
}
}
impl View {
pub fn normalized(self) -> Self {
if !self.scale.is_finite() || self.center.iter().any(|v| !v.is_finite()) {
return Self::default();
}
let scale = self.scale.clamp(1., 8.);
let half = 0.5 / scale;
Self {
scale,
center: self.center.map(|v| v.clamp(half, 1. - half)),
}
}
pub fn zoom_at(self, scale: f32, anchor: [f32; 2]) -> Self {
let old = self.normalized();
let scale = if scale.is_finite() {
scale.clamp(1., 8.)
} else {
old.scale
};
let mut next = Self { scale, ..old };
for (i, a) in anchor.into_iter().enumerate() {
if a.is_finite() {
next.center[i] += (a.clamp(0., 1.) - 0.5) * (1. / old.scale - 1. / scale);
}
}
next.normalized()
}
/// Drag displacement as a fraction of the fitted slide viewport.
pub fn pan(self, delta: [f32; 2]) -> Self {
let mut next = self.normalized();
for (i, d) in delta.into_iter().enumerate() {
if d.is_finite() {
next.center[i] -= d / next.scale;
}
}
next.normalized()
}
pub fn uv(self) -> egui::Rect {
let v = self.normalized();
egui::Rect::from_center_size(
egui::pos2(v.center[0], v.center[1]),
egui::Vec2::splat(1. / v.scale),
)
}
}
/// Presenter epochs override output gestures. Output serials order local gestures
/// within an epoch, allowing bounded channels to coalesce and retry latest state.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Sync {
pub enabled: bool,
pub view: View,
pub epoch: u64,
pub serial: u64,
}
impl Sync {
pub fn normalized(mut self) -> Self {
self.view = if self.enabled {
self.view.normalized()
} else {
View::default()
};
self
}
pub fn set(&mut self, enabled: bool, view: View) {
self.enabled = enabled;
self.view = view;
self.epoch = self.epoch.wrapping_add(1);
self.serial = 0;
*self = self.normalized();
}
pub fn gesture(&mut self, view: View) {
if self.enabled {
self.view = view.normalized();
self.serial = self.serial.wrapping_add(1);
}
}
pub fn accept_output(&mut self, other: Self) -> bool {
if !self.enabled
|| !other.enabled
|| other.epoch != self.epoch
|| other.serial <= self.serial
{
return false;
}
*self = other.normalized();
true
}
pub fn accept_presenter(&mut self, other: Self) {
if (other.epoch, other.serial) >= (self.epoch, self.serial) {
*self = other.normalized();
}
}
}
#[derive(Default)]
pub struct PerformanceWatch {
slow: u8,
}
impl PerformanceWatch {
/// Three consecutive zoomed frames above a 30 Hz frame budget trigger notice.
pub fn observe(&mut self, active: bool, elapsed: std::time::Duration) -> bool {
self.slow = if active && elapsed > std::time::Duration::from_millis(33) {
self.slow.saturating_add(1)
} else {
0
};
self.slow >= 3
}
}

View File

@ -204,6 +204,15 @@ fn independent_output_acknowledges_frames_and_blanking() {
write_json(
&mut input,
&HostState {
zoom: pdf_presenter::zoom::Sync {
enabled: true,
view: pdf_presenter::zoom::View {
scale: 2.,
center: [0.5; 2],
},
epoch: sequence * 2,
serial: 0,
},
sequence,
page,
generation: 99,
@ -226,6 +235,41 @@ fn independent_output_acknowledges_frames_and_blanking() {
break;
}
}
// Zoom-only commands carry no frame, preload, routes or visibility fields.
// They must retain every buffered frame after all source/cache files are gone.
write_json(
&mut input,
&HostState {
zoom_only: true,
generation: 99,
page,
zoom: pdf_presenter::zoom::Sync {
enabled: true,
view: pdf_presenter::zoom::View {
scale: 4.,
center: [0.4, 0.6],
},
epoch: sequence * 2 + 1,
serial: 0,
},
..Default::default()
},
)
.unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let ack = rx
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.expect("zoom retained buffer deadline");
assert!(ack.status.is_empty(), "{}", ack.status);
if ack.sequence == sequence
&& ack.generation == 99
&& ack.buffered == 8
&& ack.page == (!blanked).then_some(page)
{
break;
}
}
}
write_json(
&mut input,

View File

@ -1134,3 +1134,46 @@ fn notes_import_review_requires_explicit_save_and_cancel_discards_preview() {
assert_eq!(s.deck.as_ref().unwrap().notes, original);
}
}
#[test]
fn zoom_is_opt_in_resets_on_slide_change_and_does_not_blank_output() {
let mut s = studio();
assert!(!s.settings.zoom_enabled);
s.blanked = false;
s.set_zoom(pdf_presenter::zoom::View {
scale: 4.,
center: [0.3, 0.6],
});
assert_eq!(s.zoom.view.scale, 1.);
s.enable_zoom(true);
s.set_zoom(pdf_presenter::zoom::View {
scale: 4.,
center: [0.3, 0.6],
});
let ctx = Context::default();
let mut state = UiState::default();
for size in [Vec2::new(1280., 900.), Vec2::new(600., 400.)] {
let _ = ctx.run_ui(input(size), |ui| {
presenter_ui::presenter(ui, &mut s, &mut state)
});
assert_eq!(s.zoom.view.scale, 4.);
}
let epoch = s.zoom.epoch;
s.execute(Action::Go(1));
assert_eq!(s.zoom.view.scale, 1.);
assert!(s.zoom.epoch > epoch);
assert!(!s.blanked);
s.set_zoom(pdf_presenter::zoom::View {
scale: 8.,
center: [0.5; 2],
});
s.zoom_warning = true;
let _ = ctx.run_ui(input(Vec2::new(900., 700.)), |ui| {
presenter_ui::presenter(ui, &mut s, &mut state)
});
assert!(!s.zoom_warning_dismissed);
s.enable_zoom(false);
assert_eq!(s.zoom.view, Default::default());
assert!(!s.zoom_warning);
assert!(!s.blanked);
}

View File

@ -0,0 +1,441 @@
use egui::{Context, Pos2, RawInput, Rect, TextureOptions, Vec2};
use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender};
use pdf_presenter::{
output::{HostState, coalesce},
settings::Settings,
zoom::{PerformanceWatch, Sync, View},
};
use std::time::{Duration, Instant};
#[test]
fn crop_anchor_pan_and_limits() {
let start = View::default();
let zoom = start.zoom_at(2., [0.25, 0.75]);
assert_eq!(zoom.center, [0.375, 0.625]);
assert_eq!(zoom.uv().size(), Vec2::splat(0.5));
let panned = zoom.pan([0.1, -0.1]);
assert!((panned.center[0] - 0.325).abs() < 0.00001);
let edge = panned.pan([100., -100.]);
assert_eq!(edge.center, [0.25, 0.75]);
assert_eq!(edge.zoom_at(1., [0., 0.]), start);
assert_eq!(start.zoom_at(100., [0.5; 2]).scale, 8.);
assert_eq!(
View {
scale: f32::NAN,
center: [f32::INFINITY, 0.]
}
.normalized(),
start
);
assert_eq!(start.pan([f32::NAN, f32::INFINITY]), start);
}
#[test]
fn synchronization_rejects_stale_gestures_and_coalesces_without_losing_frames() {
let mut presenter = Sync::default();
presenter.set(true, View::default());
let mut host = presenter;
host.gesture(host.view.zoom_at(3., [0.5; 2]));
let old = host;
host.gesture(host.view.pan([0.1, 0.]));
assert!(presenter.accept_output(host));
assert!(!presenter.accept_output(old));
host.accept_presenter(old);
assert_eq!(host, presenter);
presenter.set(true, View::default());
assert!(!presenter.accept_output(host));
host.accept_presenter(presenter);
assert_eq!(host.view, View::default());
presenter.set(false, host.view.zoom_at(4., [0.5; 2]));
assert_eq!(presenter.view, View::default());
let mut pending = Some(HostState {
generation: 4,
page: 2,
sequence: 12,
monitors: vec!["screen".into()],
zoom: host,
..Default::default()
});
host.gesture(host.view.zoom_at(4., [0.5; 2]));
coalesce(
&mut pending,
HostState {
zoom_only: true,
zoom: host,
generation: 4,
page: 2,
..Default::default()
},
);
let state = pending.as_ref().unwrap();
assert_eq!(state.monitors, vec!["screen"]);
assert_eq!(state.sequence, 12);
assert!(!state.zoom_only);
assert_eq!(state.zoom, host);
coalesce(
&mut pending,
HostState {
zoom_only: true,
generation: 3,
..Default::default()
},
);
assert_eq!(pending.as_ref().unwrap().zoom, host);
coalesce(
&mut pending,
HostState {
quit: true,
..Default::default()
},
);
assert!(pending.unwrap().quit);
}
#[test]
fn settings_default_opt_out_roundtrip_and_warning_threshold() {
assert!(!Settings::default().zoom_enabled);
let old: Settings = toml::from_str("version=1").unwrap();
assert!(!old.zoom_enabled);
let enabled = Settings {
zoom_enabled: true,
..Default::default()
};
let restored: Settings = toml::from_str(&toml::to_string(&enabled).unwrap()).unwrap();
assert!(restored.zoom_enabled);
let mut watch = PerformanceWatch::default();
assert!(!watch.observe(false, Duration::from_secs(1)));
assert!(!watch.observe(true, Duration::from_millis(40)));
assert!(!watch.observe(true, Duration::from_millis(40)));
assert!(watch.observe(true, Duration::from_millis(40)));
assert!(!watch.observe(true, Duration::from_millis(20)));
assert!(!watch.observe(true, Duration::from_millis(40)));
}
#[test]
fn zoom_paints_existing_texture_crop_with_constant_geometry_and_no_new_uploads() {
let ctx = Context::default();
let mut rgba = vec![0; 64 * 32 * 4];
for y in 0..32 {
for x in 0..64 {
let color = if x < 32 {
[255, 0, 0, 255]
} else {
[0, 0, 255, 255]
};
rgba[(y * 64 + x) * 4..(y * 64 + x + 1) * 4].copy_from_slice(&color);
}
}
let texture = ctx.load_texture(
"slide",
egui::ColorImage::from_rgba_unmultiplied([64, 32], &rgba),
TextureOptions::NEAREST,
);
let mut renderer = EguiSoftwareRender::new(ColorFieldOrder::Bgra);
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(200.));
let mut pixels = vec![0u32; 200 * 200];
for (index, view) in [
View::default(),
View {
scale: 2.,
center: [0.25, 0.5],
},
View {
scale: 2.,
center: [0.75, 0.5],
},
]
.into_iter()
.enumerate()
{
let output = ctx.run_ui(
RawInput {
screen_rect: Some(rect),
..Default::default()
},
|ui| {
pdf_presenter::presenter_ui::paint_slide_zoomed(
ui.painter(),
rect,
texture.id(),
[64, 32],
Default::default(),
view,
);
},
);
if index > 0 {
assert!(
output.textures_delta.set.is_empty(),
"zoom uploaded another image"
);
}
let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
for primitive in &primitives {
if let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive
&& mesh.texture_id == texture.id()
{
assert!(
mesh.vertices.iter().all(|v| rect.contains(v.pos)),
"zoom enlarged draw geometry"
);
}
}
renderer.render(
&mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), 200, 200),
&primitives,
&output.textures_delta,
output.pixels_per_point,
);
assert_eq!(pixels[5 * 200 + 5] & 0xffffff, 0); // Padding unchanged.
if index > 0 {
let expected = if index == 1 { 0xff0000 } else { 0x0000ff };
assert_eq!(pixels[100 * 200 + 30] & 0xffffff, expected);
assert_eq!(pixels[100 * 200 + 170] & 0xffffff, expected);
}
}
}
#[test]
#[ignore = "Manual Linux software drawing measurement; not a timing-sensitive CI assertion"]
fn buffered_zoom_drawing_measurement() {
for [width, height] in [[1920usize, 1080usize], [3840, 2160]] {
let ctx = Context::default();
let rgba: Vec<u8> = (0..1920 * 1080)
.flat_map(|p| [(p % 256) as u8, ((p / 1920) % 256) as u8, 128, 255])
.collect();
let texture = ctx.load_texture(
"benchmark",
egui::ColorImage::from_rgba_unmultiplied([1920, 1080], &rgba),
TextureOptions::LINEAR,
);
let mut renderer = EguiSoftwareRender::new(ColorFieldOrder::Bgra);
let mut pixels = vec![0u32; width * height];
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(width as f32, height as f32));
for scale in [1., 4., 8.] {
let mut times = Vec::new();
for i in 0..12 {
let start = Instant::now();
let view = View {
scale,
center: [0.4 + i as f32 * 0.01, 0.5],
}
.normalized();
let output = ctx.run_ui(
RawInput {
screen_rect: Some(rect),
..Default::default()
},
|ui| {
pdf_presenter::presenter_ui::paint_slide_zoomed(
ui.painter(),
rect,
texture.id(),
[1920, 1080],
Default::default(),
view,
);
},
);
let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
renderer.render(
&mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), width, height),
&primitives,
&output.textures_delta,
output.pixels_per_point,
);
if i > 1 {
times.push(start.elapsed().as_secs_f64() * 1000.);
}
}
times.sort_by(f64::total_cmp);
println!(
"{width}x{height} {scale}x: median {:.2} ms, max {:.2} ms",
times[times.len() / 2],
times.last().unwrap()
);
}
}
}
#[test]
fn wheel_drag_and_double_click_operate_in_slide_coordinates() {
let ctx = Context::default();
let target = Rect::from_min_max(Pos2::new(40., 40.), Pos2::new(440., 240.));
let mut view = View::default();
let mut time = 0.;
let mut render = |events: Vec<egui::Event>| {
time += 0.04;
let _ = ctx.run_ui(
RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(500., 300.))),
events,
time: Some(time),
..Default::default()
},
|ui| {
view = pdf_presenter::presenter_ui::zoom_gestures(ui, target, view).0;
},
);
view
};
let center = target.center();
render(vec![egui::Event::PointerMoved(center)]);
render(vec![egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
phase: egui::TouchPhase::Move,
delta: Vec2::new(0., 300.),
modifiers: egui::Modifiers::NONE,
}]);
let mut zoom = View::default();
for _ in 0..30 {
zoom = render(vec![]);
}
assert!(zoom.scale > 1.2);
let click = |pos, pressed| egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: egui::Modifiers::NONE,
};
render(vec![click(center, true)]);
let moved = center + Vec2::new(40., 10.);
let panned = render(vec![egui::Event::PointerMoved(moved)]);
assert!(panned.center[0] < zoom.center[0]);
render(vec![click(moved, false)]);
for _ in 0..20 {
render(vec![]);
}
for _ in 0..2 {
render(vec![click(moved, true)]);
zoom = render(vec![click(moved, false)]);
}
assert_eq!(zoom, View::default());
}
#[test]
fn optimized_crop_matches_general_renderer_with_alpha_clipping_and_dpi() {
for dpi in [1., 2.] {
let ctx = Context::default();
ctx.set_pixels_per_point(dpi);
let rgba: Vec<u8> = (0..64 * 32)
.flat_map(|p| {
[
(p % 64 * 4) as u8,
(p / 64 * 8) as u8,
80,
(40 + p % 64 * 3) as u8,
]
})
.collect();
let texture = ctx.load_texture(
"alpha",
egui::ColorImage::from_rgba_unmultiplied([64, 32], &rgba),
TextureOptions::LINEAR,
);
let mut fast = EguiSoftwareRender::new(ColorFieldOrder::Bgra);
let mut reference =
EguiSoftwareRender::new(ColorFieldOrder::Bgra).with_allow_raster_opt(false);
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(320., 240.));
let mut actual = vec![0u32; (320. * dpi) as usize * (240. * dpi) as usize];
let mut expected = actual.clone();
for view in [
View {
scale: 2.,
center: [0.25, 0.25],
},
View {
scale: 3.1,
center: [0.7, 0.4],
},
] {
let output = ctx.run_ui(
RawInput {
screen_rect: Some(rect),
..Default::default()
},
|ui| {
let painter = ui.painter().with_clip_rect(rect.shrink(20.));
pdf_presenter::presenter_ui::paint_slide_zoomed(
&painter,
rect,
texture.id(),
[64, 32],
Default::default(),
view,
);
},
);
let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
let width = (320. * output.pixels_per_point) as usize;
let height = (240. * output.pixels_per_point) as usize;
// egui applies a requested DPI change on a subsequent frame.
actual.resize(width * height, 0);
expected.resize(width * height, 0);
actual.fill(0);
expected.fill(0);
fast.render(
&mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut actual), width, height),
&primitives,
&output.textures_delta,
output.pixels_per_point,
);
reference.render(
&mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut expected), width, height),
&primitives,
&output.textures_delta,
output.pixels_per_point,
);
for (a, b) in actual.iter().zip(&expected) {
for (a, b) in a.to_le_bytes().iter().zip(b.to_le_bytes()) {
assert!(
a.abs_diff(b) <= 2,
"crop pixel mismatch: {a} vs {b} at DPI {dpi}"
);
}
}
}
}
}
#[test]
fn parallel_crop_bands_have_no_seams_at_fractional_boundaries() {
let ctx = Context::default();
let texture = ctx.load_texture(
"solid",
egui::ColorImage::from_rgba_unmultiplied([64, 32], &[255, 180, 60, 255].repeat(64 * 32)),
TextureOptions::LINEAR,
);
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(1931., 1087.));
let output = ctx.run_ui(
RawInput {
screen_rect: Some(rect),
..Default::default()
},
|ui| {
pdf_presenter::presenter_ui::paint_slide_zoomed(
ui.painter(),
rect,
texture.id(),
[64, 32],
Default::default(),
View {
scale: 3.7,
center: [0.4, 0.6],
},
);
},
);
let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
assert_eq!(primitives.iter().filter(|p| matches!(&p.primitive, egui::epaint::Primitive::Mesh(m) if m.texture_id == texture.id())).count(),4);
let mut pixels = vec![0u32; 1931 * 1087];
EguiSoftwareRender::new(ColorFieldOrder::Bgra).render(
&mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), 1931, 1087),
&primitives,
&output.textures_delta,
output.pixels_per_point,
);
for y in 62..1025 {
for x in [50, 965, 1880] {
assert_eq!(
pixels[y * 1931 + x] & 0xffffff,
0xffb43c,
"band seam at {x},{y}"
);
}
}
}

View File

@ -2,6 +2,18 @@
## Unreleased
### 0.1.54
- Add globally saved, default-off page zoom (1×–8×), wheel/pinch zoom, drag panning
and double-click reset from the presenter/current preview or any output. Mirror
the crop with lightweight ordered messages; reset on slide changes and preserve
visibility. Reuse buffered textures without new rendering, file I/O or image
allocations. Explain sharpness/CPU tradeoffs and warn on repeated slow frames.
Bundle a licensed renderer patch for bounded scanline sampling and parallel crop
bands (four threads maximum). Local software-drawing medians: ~5 ms at 1080p,
~16 ms at 4K; physical multicreen/OS acceptance remains separate.
Linux checks cover input, pixels, opt-in migration and disk-free output buffering.
### 0.1.53
- Import UTF-8 TXT notes separated by hyphen lines or Markdown notes separated by

View File

@ -292,3 +292,48 @@ formatting, warnings-denied Clippy/rustdoc and 13 Python tests pass; whole-app
X11 coverage is 86.38%. Niri is unavailable here, so this verifies hint delivery,
not Niri placement or physical multi-monitor acceptance. Windows/macOS were not
built or runtime-tested for this Linux-only change.
## Buffered page zoom — 0.1.54
Opt-in zoom crops UVs of the current cached texture, with bounded normalized panning
and no oversized draw rectangle. All views share crop state via small coalesced IPC;
page/epoch/serial checks prevent stale gestures from undoing navigation or reset.
The output host updates its mirrors locally and retries the latest crop at 30 Hz
until echoed. Full slide-buffer manifests are not resent for zoom-only updates.
Tests cover anchor math, bounds, pointer gestures, settings migration, software
pixels/unchanged texture uploads and host buffer preservation after deleting source
and cache files. The manual software-drawing measurement is run with:
```sh
cargo test --release --test zoom buffered_zoom_drawing_measurement -- --ignored --nocapture
```
This synthetic measurement excludes OS presentation/compositor and physical mirror
acceptance. Validate real pointer/trackpad input and simultaneous displays on each OS;
only Linux development checks were run for this subject.
The software renderer is bundled with a narrow cropped-quad optimization; see
[`vendor/egui_software_backend/PDF-PRESENTER-PATCH.md`](../../vendor/egui_software_backend/PDF-PRESENTER-PATCH.md)
for provenance and the precise changes. Fixed-point bilinear scanlines reuse two
filtered rows and bounded coordinate tables. Large crops use four disjoint bands
on a lazily initialized pool capped at four CPU threads per native process. This
keeps image buffers shared, avoids PDF jobs and bounds additional scratch memory
by viewport width. Font/tinted/general geometry keeps the original raster path.
Local release-mode measurement (2026-11-20, Intel Core i5-8500, six logical CPUs,
renderer pool capped at four): 1920×1080 source image, changing crop center every
frame, two warm-up frames then ten timed frames per case. Median software drawing:
| Output size | Fitted/static 1× | Panning at 4× | Panning at 8× |
| --- | ---: | ---: | ---: |
| 1920×1080 | 0.79 ms | 4.83 ms | 4.29 ms |
| 3840×2160 | 4.11 ms | 16.07 ms | 15.76 ms |
Maximum measured moving-frame time was 17.02 ms. The 1× case benefits from an
unchanged cached primitive; moving crops deliberately invalidate that cache.
These numbers include egui tessellation and software buffer drawing, exclude native
surface/compositor/monitor latency, and are not a guaranteed display frame rate.
The in-app watcher measures the actual native window draw/presentation call.

View File

@ -1,5 +1,6 @@
version = 1
auto_show = true
zoom_enabled = false
theme = "midra"
language = "system"
presenter_fullscreen = true

View File

@ -136,3 +136,35 @@ merges notes and writes atomically, returning the existing `Reply.notes` snapsho
Both notes jobs use the dedicated 30-second bridge, bounded JSON messages and source
generations. Notes picker results carry the source generation too. These messages
are private same-executable presenter/worker traffic, never output-host traffic.
## Shared zoom in 0.1.54
HostState adds `zoom {enabled, view {scale, center}, epoch, serial}` and
`zoom_only` (false by default). Scale is bounded to 1–8 and center is normalized
page UV coordinates, clamped to keep the full crop inside the page. Disabled or
invalid views normalize to a complete fitted page. The viewport keeps the slide's
aspect ratio and draws a cropped texture rectangle with constant-sized geometry.
No higher-resolution request, texture upload or image buffer is created by zoom.
Large crops split into disjoint clip bands on a pool capped at four CPU threads;
scanline interpolation uses O(viewport width) scratch memory.
Presenter gestures, enable/disable and slide changes advance `epoch`, reset serial
to zero and invalidate prior output gestures. Output gestures increment `serial`
within that epoch, sharing the crop immediately among output mirrors. Ack adds
optional `zoom` and boolean `zoom_slow`; crop ACKs include generation and page.
Presenter accepts only current-generation/current-page/current-epoch newer serials.
The output retains newer local serials against delayed presenter states. Pending
output changes retry at most every 33 ms until the presenter echoes the crop; pipe
queues remain bounded and the latest absolute crop replaces intermediate gestures.
Zoom-only messages contain only crop/page/generation metadata and must not replace
frame, preload, monitor, fullscreen or visibility state. Coalescing retains queued
full state and merges same-page zoom metadata. The host validates page/generation
before applying a lightweight update, without touching its RAM cache or textures.
Full state also carries zoom for recovery. Notes and other operator data remain
absent. No zoom state is persisted except the opt-in boolean in settings.
The performance watcher counts three consecutive zoomed window draws above 33 ms,
including software drawing/presentation. The presenter shows the warning locally;
output hosts report only a boolean. It does not alter visibility or navigation.

View File

@ -12,6 +12,11 @@ with an error, without rewriting the bad file. Missing files use defaults. Reads
bounded to 4 MiB. Writes validate then atomically replace using a same-directory
flushed temporary file. Unknown fields are ignored and not preserved on round trip.
- `zoom_enabled`: boolean, default false, added in 0.1.54. Global opt-in for
presenter/current-slide and output zoom gestures. Missing fields in older v1
files retain normal non-zoom behavior. Menu → Preferences saves this setting
immediately. Crop/scale, gesture serials and warning state are transient and are
never saved in global/project layouts; each newly opened slide starts fitted.
- `slide_colors.page_background` and `slide_colors.fit_padding`: opaque sRGB
arrays of exactly three integers, each 0–255, added in 0.1.26. Defaults are
`[255, 255, 255]` (white beneath transparent slide pixels) and `[0, 0, 0]`

View File

@ -317,3 +317,32 @@ file onto the presenter. Review the destination and slide count, then choose
**Import and save notes** to create/update the presentation's `.notes.toml` file.
Cancel leaves files unchanged. See the [README examples](../README.md#import-your-notes)
and [format contract](interfaces/presentation-notes.md#importing-txt-and-markdown).
## Zoom and move around a slide
Zoom is **off by default**. Enable **Menu → Preferences → Enable page zoom**.
The preference is saved globally; it does not change presentation visibility.
- On the **current slide preview** or any **presentation screen**, scroll up/down
to zoom in/out (1×–8×). The point under the mouse stays anchored when possible.
- Hold the left mouse button and drag to move the enlarged image. Movement stops
at the page edges. Double-click to reset to the complete fitted slide.
- **Menu → Page zoom** also has a zoom slider and **Reset zoom** button. If the
current preview is hidden, show it in Layout to pan from the presenter.
- All mirrored presenter/current previews and presentation outputs share the crop.
Previous/next previews, All slides thumbnails and browser previews stay unzoomed.
Moving to another slide or opening another presentation resets zoom. Display
swaps/fullscreen changes preserve it. Zoom gestures pause during display trials.
Zoom uses the already buffered image: no PDF re-render, additional image buffer,
cache rewrite or disk access is triggered by changing the zoom. This prioritizes
response time; text/images may look softer when enlarged, especially while only a
low-resolution preview is available. Normal background preparation continues.
The Preferences disclaimer explains that software drawing can slow down on large
or multiple displays. If three consecutive zoomed frames take over 33 ms each to
render/present on a window, a **Zoom performance** warning appears on the presenter
with reset, disable and keep-enabled choices. This is a detected frame-budget
warning, not proof that zoom caused the delay. It does not blank or interrupt the
output. It cannot predict compositor/hardware delays or guarantee a frame rate.

156
vendor/egui_software_backend/Cargo.toml vendored Normal file
View File

@ -0,0 +1,156 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
name = "egui_software_backend"
version = "0.0.3"
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "A CPU software render backend for egui."
homepage = "https://github.com/DGriffin91/egui_software_backend"
readme = "README.md"
keywords = [
"egui",
"raster",
"software",
"render",
"softbuffer",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/DGriffin91/egui_software_backend"
[features]
default = [
"std",
"winit",
]
log = ["dep:log"]
raster_stats = ["std"]
rayon = ["dep:rayon"]
std = []
test_render = [
"dep:image",
"dep:egui_kittest",
]
winit = [
"dep:winit",
"softbuffer",
"egui-winit",
"bytemuck",
]
[lib]
name = "egui_software_backend"
path = "src/lib.rs"
[dependencies.bytemuck]
version = "1.25"
optional = true
[dependencies.constify]
version = "0.0.1"
[dependencies.egui]
version = "0.34"
default-features = false
[dependencies.egui-winit]
version = "0.34"
optional = true
default-features = false
[dependencies.egui_kittest]
version = "0.34"
optional = true
[dependencies.image]
version = "0.25"
optional = true
[dependencies.log]
version = "0.4"
optional = true
[dependencies.rayon]
version = "1.11.0"
optional = true
[dependencies.softbuffer]
version = "0.4"
optional = true
[dependencies.strength_reduce]
version = "0.2.4"
[dependencies.winit]
version = "0.30"
optional = true
[dev-dependencies.argh]
version = "0.1"
[dev-dependencies.bytemuck]
version = "1.25"
[dev-dependencies.dify]
version = "0.7"
[dev-dependencies.eframe]
version = "0.34"
[dev-dependencies.egui]
version = "0.34"
features = ["default_fonts"]
[dev-dependencies.egui-winit]
version = "0.34"
default-features = false
[dev-dependencies.egui_demo_lib]
version = "0.34"
[dev-dependencies.egui_extras]
version = "0.34"
features = ["all_loaders"]
[dev-dependencies.egui_kittest]
version = "0.34"
features = [
"snapshot",
"wgpu",
]
[dev-dependencies.epaint_default_fonts]
version = "0.34"
[dev-dependencies.image]
version = "0.25"
features = [
"jpeg",
"png",
]
[dev-dependencies.softbuffer]
version = "0.4"
[dev-dependencies.winit]
version = "0.30"
[profile.dev]
opt-level = 3
[profile.dev.package."*"]
opt-level = 3

View File

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@ -0,0 +1,19 @@
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,31 @@
# Local renderer patch
Upstream: crates.io `egui_software_backend` 0.0.3, MIT OR Apache-2.0. Source and
license texts were copied from the Cargo registry for reproducible offline builds.
The Cargo example entries were removed because those example files are not bundled.
No generated binaries or downloaded runtime components are included.
Local changes:
- `fast_image.rs`, registered in lib.rs and called from render.rs: guarded scanline
sampling for axis-aligned, white, clamped cropped image quads. Other geometry,
font texture, full images and tint/wrapping keep the upstream raster path.
- Sampling caches two horizontally filtered rows and O(viewport width) index data.
Fixed-point bilinear interpolation preserves premultiplied color/alpha, with at
most two channel values of rounding difference versus the floating-point path.
No separate slide/zoom image is allocated.
- egui_texture.rs records opacity at upload; lib.rs conservatively clears it for
transparent partial updates. Opaque scanlines avoid unnecessary blending.
- lib.rs initializes the optional Rayon pool lazily, bounded to at most four
available CPU threads per process. Renderer workers are not created by PDF/IO
worker processes. The application splits large moving crops into four disjoint
clip bands; all bands reference the same texture.
- Tile occupancy lookup uses binary search in the existing row-major sorted list.
Cached primitives, alpha compositing, canvas buffers and general UI drawing keep
their upstream representation. No new coverage exclusions were added.
Tests: `crates/pdf-presenter/tests/zoom.rs`, `slide_colors.rs`, and native tests.
They compare optimized pixels with the general raster path, exercise clipping/DPI,
alpha and crop bounds, and check that panning does not upload another texture.
Benchmark: `cargo test --release --test zoom buffered_zoom_drawing_measurement --
--ignored --nocapture`. Physical multicreen acceptance is separate.

73
vendor/egui_software_backend/README.md vendored Normal file
View File

@ -0,0 +1,73 @@
# CPU software render backend for [egui](https://github.com/emilk/egui)
![License](https://img.shields.io/badge/license-MIT%2FApache-blue.svg) [![Crates.io](https://img.shields.io/crates/v/egui_software_backend.svg)](https://crates.io/crates/egui_software_backend)
[![Docs](https://docs.rs/egui_software_backend/badge.svg)](https://docs.rs/egui_software_backend/latest/egui_software_backend/)
![demo](demo.png)
```rs
use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender};
let buffer = &mut vec![[0u8; 4]; 512 * 512];
let mut buffer_ref = BufferMutRef::new(buffer, 512, 512);
let ctx = egui::Context::default();
let mut demo = egui_demo_lib::DemoWindows::default();
let mut sw_render = EguiSoftwareRender::new(ColorFieldOrder::Bgra);
let out = ctx.run(egui::RawInput::default(), |ctx| {
demo.ui(ctx);
});
let primitives = ctx.tessellate(out.shapes, out.pixels_per_point);
sw_render.render(
&mut buffer_ref,
&primitives,
&out.textures_delta,
out.pixels_per_point,
);
```
## winit quickstart
```rust
use egui::vec2;
use egui_software_backend::{SoftwareBackend, SoftwareBackendAppConfiguration};
struct EguiApp {}
impl EguiApp {
fn new(context: egui::Context) -> Self {
egui_extras::install_image_loaders(&context);
EguiApp {}
}
}
impl egui_software_backend::App for EguiApp {
fn ui(&mut self, ui: &mut egui::Ui, _backend: &mut SoftwareBackend) {
egui::CentralPanel::default().show_inside(ui, |ui| {
ui.label("Hello World!");
});
}
}
fn main() {
let settings = SoftwareBackendAppConfiguration::new()
.inner_size(Some(vec2(500.0, 300.0)))
.title(Some("Simple example".to_string()));
egui_software_backend::run_app_with_software_backend(settings, EguiApp::new)
//Can fail if winit fails to create the window
.expect("Failed to run app")
}
```
[egui_backend_selector](https://github.com/AlexanderSchuetz97/egui_backend_selector) can be used in conjunction with this crate to automatically fallback to using this software renderer at runtime.
## Other examples
- bevy + softbuffer see examples/bevy_example folder
## egui version mapping
| egui_software_backend | egui |
|-----------------------|--------|
| 0.0.3 | 0.34.X |
| 0.0.2 | 0.33.X |
| 0.0.1 | 0.33.X |

View File

@ -0,0 +1,321 @@
#![allow(unsafe_code)]
use core::ptr::write_unaligned;
use core::{arch::x86_64::*, ptr::read_unaligned};
use crate::color::sse41::Sse41Impl;
use crate::color::{GenericImpl, SelectedImpl};
type U8x4x4 = __m128i;
type U16x4x2 = __m128i;
type U16x4x4 = __m256i;
#[derive(Clone, Copy)]
pub(crate) struct Avx2Impl {
sse41: Sse41Impl,
}
impl Avx2Impl {
/// `std::arch::is_x86_feature_detected!("avx2")` MUST be true
/// `std::arch::is_x86_feature_detected!("sse4.1")` MUST be true
pub(crate) const unsafe fn new() -> Self {
Self {
sse41: unsafe { Sse41Impl::new() },
}
}
}
impl Avx2Impl {
#[inline]
#[target_feature(enable = "avx2")]
fn dispatch_avx2<R>(self, f: impl FnOnce(Self) -> R) -> R {
f(self)
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src[i], dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "avx2")]
fn egui_blend_u8_slice_avx2(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
assert_eq!(src.len(), dst.len());
let n = dst.len();
if n == 0 {
return;
}
let mut i = 0;
while i + 3 < n {
// Load 4 src pixels
let src_ptr = unsafe { src.as_ptr().add(i) }.cast::<__m128i>();
let src8: U8x4x4 = unsafe { read_unaligned(src_ptr) };
let src16: U16x4x4 = x8_zeroextend16(src8);
// Load 4 dst pixels
let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>();
let dst8: U8x4x4 = unsafe { read_unaligned(dst_ptr) };
let dst16: U16x4x4 = x8_zeroextend16(dst8);
let dst8: U8x4x4 = egui_blend_4_u16x4(src8, src16, dst16);
unsafe { write_unaligned(dst_ptr, dst8) };
i += 4;
}
while i < n {
dst[i] = self.egui_blend_u8(src[i], dst[i]);
i += 1;
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src[i], dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "avx2")]
fn egui_blend_u8_slice_one_src_tinted_fn_avx2(
self,
src: [u8; 4],
mut tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
let n = dst.len();
if n == 0 {
return;
}
let src8 = _mm_set1_epi32(i32::from_le_bytes(src));
let src16 = x8_zeroextend16(src8);
let mut i = 0usize;
while i + 3 < n {
// Load 4 tint values
let tint_a = i32::from_le_bytes(tint_fn());
let tint_b = i32::from_le_bytes(tint_fn());
let tint_c = i32::from_le_bytes(tint_fn());
let tint_d = i32::from_le_bytes(tint_fn());
let tint8: U8x4x4 = _mm_set_epi32(tint_d, tint_c, tint_b, tint_a);
let tint16: U16x4x4 = x8_zeroextend16(tint8);
// Load 4 dst pixels
let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>();
let dst8: U8x4x4 = unsafe { read_unaligned(dst_ptr) };
let dst16 = x8_zeroextend16(dst8);
// src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255)
let src_tinted16 = x16_div_255_approx(a16_times_b16_plus_128(src16, tint16));
let src_tinted8 = x16_pack8(src_tinted16);
let dst8 = egui_blend_4_u16x4(src_tinted8, src_tinted16, dst16);
unsafe { write_unaligned(dst_ptr, dst8) };
i += 4;
}
// Tail: handle the last pixels (if any) in scalar
while i < n {
dst[i] = self.egui_blend_u8(self.unorm_mult4x4(src, tint_fn()), dst[i]);
i += 1;
}
}
#[target_feature(enable = "avx2")]
fn egui_blend_u8_slice_tinted_avx2(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
assert_eq!(src.len(), dst.len());
let n = dst.len();
if n == 0 {
return;
}
let tint8: U8x4x4 = _mm_set1_epi32(i32::from_le_bytes(tint));
let tint16: U16x4x4 = x8_zeroextend16(tint8);
let mut i = 0usize;
while i + 3 < n {
// Load 4 src pixels
let src = unsafe { src.as_ptr().add(i) }.cast::<__m128i>();
let src8 = unsafe { read_unaligned(src) };
let src16 = x8_zeroextend16(src8);
// Load 4 dst pixels
let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>();
let dst8 = unsafe { read_unaligned(dst) };
let dst16 = x8_zeroextend16(dst8);
// src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255)
let src_tinted16 = x16_div_255_approx(a16_times_b16_plus_128(src16, tint16));
let src_tinted8 = x16_pack8(src_tinted16);
let dst8 = egui_blend_4_u16x4(src_tinted8, src_tinted16, dst16);
unsafe { write_unaligned(dst, dst8) };
i += 4;
}
// Tail: handle the last pixels (if any) in scalar
while i < n {
dst[i] = self.egui_blend_u8(self.unorm_mult4x4(src[i], tint), dst[i]);
i += 1;
}
}
#[target_feature(enable = "avx2")]
fn egui_blend_u8_slice_one_src_avx2(self, src: [u8; 4], dst: &mut [[u8; 4]]) {
let n = dst.len();
if n == 0 {
return;
}
let a = src[3];
let alpha = src[3] as i32;
let alpha_compl = 0xFF ^ alpha;
// (255 - a) in all u16 lanes
let alpha_compl16 = _mm256_set1_epi16(alpha_compl as i16);
let mut i = 0;
if a == 0 {
// Only need to saturating_add src to dst. We can do 8 at a time in this case.
let src8 = _mm256_set1_epi32(i32::from_le_bytes(src));
while i + 7 < n {
let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m256i>();
let dst8 = unsafe { read_unaligned(dst_ptr) };
let dst8 = _mm256_adds_epu8(dst8, src8);
unsafe { write_unaligned(dst_ptr, dst8) };
i += 8;
}
} else {
let src8 = _mm_set1_epi32(i32::from_le_bytes(src));
while i + 3 < n {
// Load 4 dst pixels
let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>();
let dst8: U8x4x4 = unsafe { read_unaligned(dst_ptr) };
let dst16 = x8_zeroextend16(dst8);
// dst * alpha_compl + 0x0080008000800080
let res16 = a16_times_b16_plus_128(dst16, alpha_compl16);
let res16 = x16_div_255_approx(res16);
let dst8 = x16_pack8(res16);
// dst.saturating_add(src)
let dst8 = a8_saturatingadd_b8(dst8, src8);
unsafe { write_unaligned(dst_ptr, dst8) };
i += 4;
}
}
while i < n {
dst[i] = self.egui_blend_u8(src, dst[i]);
i += 1;
}
}
}
impl SelectedImpl for Avx2Impl {
#[inline]
fn dispatch<R>(self, f: impl FnOnce(Self) -> R) -> R {
unsafe { self.dispatch_avx2(f) }
}
#[inline]
fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
unsafe { self.egui_blend_u8_slice_avx2(src, dst) }
}
#[inline]
fn egui_blend_u8_slice_one_src_tinted_fn(
self,
src: [u8; 4],
tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
unsafe { self.egui_blend_u8_slice_one_src_tinted_fn_avx2(src, tint_fn, dst) }
}
#[inline]
fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
unsafe { self.egui_blend_u8_slice_tinted_avx2(src, tint, dst) }
}
#[inline]
fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) {
unsafe { self.egui_blend_u8_slice_one_src_avx2(src, dst) }
}
#[inline]
fn egui_blend_u8(self, src: [u8; 4], dst: [u8; 4]) -> [u8; 4] {
self.sse41.egui_blend_u8(src, dst)
}
#[inline]
fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] {
GenericImpl.unorm_mult4x4(a, b)
}
}
/// src_u8x4x4 should have four 8 bit per channel rgba samples stored in the low bits
/// src_u16x4x4 should have four 16 bit per channel rgba samples
/// dst_u16x4x4 should have four 16 bit per channel rgba samples
#[inline]
#[target_feature(enable = "avx2")]
fn egui_blend_4_u16x4(src8: __m128i, src16: __m256i, dst16: __m256i) -> __m128i {
let ones_u16x4x4 = _mm256_set1_epi16(0x00FF);
// Broadcast alpha within each pixel's 4 lanes
let a_broadcast_lo = _mm256_shufflelo_epi16(src16, 0b11111111);
let a_broadcast = _mm256_shufflehi_epi16(a_broadcast_lo, 0b11111111);
// simd_alpha_compl = 255 - A for each lane, per pixel
let simd_alpha_compl = _mm256_xor_si256(ones_u16x4x4, a_broadcast);
// dst * alpha_compl + 0x0080008000800080
let res16 = a16_times_b16_plus_128(dst16, simd_alpha_compl);
let res16 = x16_div_255_approx(res16);
let dst8 = x16_pack8(res16);
a8_saturatingadd_b8(dst8, src8)
}
/// a.saturating_add(b)
#[inline]
#[target_feature(enable = "avx2")]
fn a8_saturatingadd_b8(a: U8x4x4, b: U8x4x4) -> U8x4x4 {
_mm_adds_epu8(a, b)
}
/// x as u16
#[inline]
#[target_feature(enable = "avx2")]
fn x8_zeroextend16(x: U8x4x4) -> U16x4x4 {
_mm256_cvtepu8_epi16(x)
}
/// a + b + 128
#[inline]
#[target_feature(enable = "avx2")]
fn a16_times_b16_plus_128(a: U16x4x4, b: U16x4x4) -> U16x4x4 {
let mul = _mm256_mullo_epi16(a, b);
_mm256_add_epi16(mul, _mm256_set1_epi16(128))
}
/// Fast approximation of x / 255
/// ((x >> 8) + x) >> x
#[inline]
#[target_feature(enable = "avx2")]
fn x16_div_255_approx(x: U16x4x4) -> U16x4x4 {
// This mulhi is equivalent to the ((x >> 8) + x) >> 8 operation
// 1 256 1 257
// ((x >> 8) + x) >> 8 = (x + x---)/256 = (x--- + x---)/256 = (x-----) = x*257 >> 16
// 256 256 256 65536
_mm256_mulhi_epu16(x, _mm256_set1_epi16(257))
}
// Converts packed 16-bit integers from `x` to packed 8-bit integers using unsigned saturation.
#[inline]
#[target_feature(enable = "avx2")]
fn x16_pack8(x: U16x4x4) -> U8x4x4 {
let hi: U16x4x2 = _mm256_extracti128_si256(x, 1);
let lo: U16x4x2 = _mm256_castsi256_si128(x);
_mm_packus_epi16(lo, hi)
}

View File

@ -0,0 +1,238 @@
use crate::math::vec4::{Vec4, vec4};
#[cfg(all(target_arch = "x86_64", feature = "std"))]
pub(crate) mod avx2;
#[cfg(all(target_arch = "aarch64", feature = "std"))]
pub(crate) mod neon;
#[cfg(all(target_arch = "x86_64", feature = "std"))]
pub(crate) mod sse41;
/// An available to run on this processor implementation
///
/// This enum doesn't implement `SelectedImpl` by choice, thus forcing compiler monomorphisation
/// a the call tree up to the closest [`dispatch_simd_impl!`]
///
/// This enum values can only be created from [`available_instrs()`], so there is no way to select
/// a non supported by the current processor implementation
#[derive(Clone, Copy)]
pub(crate) enum AvailableImpl {
Generic(GenericImpl),
#[cfg(all(target_arch = "x86_64", feature = "std"))]
Sse41(sse41::Sse41Impl),
#[cfg(all(target_arch = "x86_64", feature = "std"))]
Avx2(avx2::Avx2Impl),
#[cfg(all(target_arch = "aarch64", feature = "std"))]
Neon(neon::NeonImpl),
}
/// Non empty, order from most performant to least one list of supported by the current processor
/// implementations
pub(crate) fn available_instrs() -> &'static [AvailableImpl] {
const GENERIC: GenericImpl = GenericImpl;
#[cfg(all(target_arch = "x86_64", feature = "std"))]
if std::arch::is_x86_feature_detected!("sse4.1") {
const SSE41: sse41::Sse41Impl = unsafe { sse41::Sse41Impl::new() };
if std::arch::is_x86_feature_detected!("avx2") {
const AVX2: avx2::Avx2Impl = unsafe { avx2::Avx2Impl::new() };
return &[
AvailableImpl::Avx2(AVX2),
AvailableImpl::Sse41(SSE41),
AvailableImpl::Generic(GENERIC),
];
} else {
return &[AvailableImpl::Sse41(SSE41), AvailableImpl::Generic(GENERIC)];
}
}
#[cfg(all(target_arch = "aarch64", feature = "std"))]
if std::arch::is_aarch64_feature_detected!("neon") {
const NEON: neon::NeonImpl = unsafe { neon::NeonImpl::new() };
return &[AvailableImpl::Neon(NEON), AvailableImpl::Generic(GENERIC)];
}
&[AvailableImpl::Generic(GENERIC)]
}
impl Default for AvailableImpl {
/// Returns the most performant available implementation
fn default() -> Self {
*available_instrs().first().expect("at least one impl")
}
}
impl core::fmt::Display for AvailableImpl {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Generic(_) => f.write_str("Generic"),
#[cfg(all(target_arch = "x86_64", feature = "std"))]
Self::Sse41(_) => f.write_str("Sse41"),
#[cfg(all(target_arch = "x86_64", feature = "std"))]
Self::Avx2(_) => f.write_str("Avx2"),
#[cfg(all(target_arch = "aarch64", feature = "std"))]
Self::Neon(_) => f.write_str("Neon"),
}
}
}
impl core::fmt::Debug for AvailableImpl {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Display::fmt(&self, f)
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! dispatch_simd_impl {
(|$simd_impl:ident| $body:expr) => {
$crate::dispatch_simd_impl!($crate::color::AvailableImpl::default(), |$simd_impl| $body)
};
($available_impl:expr, |$simd_impl:ident| $body:expr) => {
match $available_impl {
$crate::color::AvailableImpl::Generic(i) => {
i.dispatch(|$simd_impl: $crate::color::GenericImpl| $body)
}
#[cfg(all(target_arch = "x86_64", feature = "std"))]
$crate::color::AvailableImpl::Sse41(i) => {
i.dispatch(|$simd_impl: $crate::color::sse41::Sse41Impl| $body)
}
#[cfg(all(target_arch = "x86_64", feature = "std"))]
$crate::color::AvailableImpl::Avx2(i) => {
i.dispatch(|$simd_impl: $crate::color::avx2::Avx2Impl| $body)
}
#[cfg(all(target_arch = "aarch64", feature = "std"))]
$crate::color::AvailableImpl::Neon(i) => {
i.dispatch(|$simd_impl: $crate::color::neon::NeonImpl| $body)
}
}
};
}
/// This trait holds performance sensitive methods that often can be writing in more architecture
/// dependent specialized versions
///
/// All methods of this trait contains a generic implementation
pub(crate) trait SelectedImpl: Copy + Sync + Send + 'static {
/// Trick the compiler into compiling `f` with the same target_feature as this impl.
#[inline]
fn dispatch<R>(self, f: impl FnOnce(Self) -> R) -> R {
f(self)
}
fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
for (pixel, src) in dst.iter_mut().zip(src) {
*pixel = self.egui_blend_u8(*src, *pixel);
}
}
/// dst[i] = blend(src * tint_fn(), dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
fn egui_blend_u8_slice_one_src_tinted_fn(
self,
src: [u8; 4],
mut tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
for pixel in dst.iter_mut() {
*pixel = self.egui_blend_u8(self.unorm_mult4x4(tint_fn(), src), *pixel);
}
}
/// dst[i] = blend(src[i] * tint, dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
for (pixel, tex_color) in dst.iter_mut().zip(src) {
*pixel = self.egui_blend_u8(self.unorm_mult4x4(tint, *tex_color), *pixel);
}
}
/// dst[i] = blend(src, dst[i])
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) {
for pixel in dst {
*pixel = self.egui_blend_u8(src, *pixel);
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[inline(always)]
fn egui_blend_u8(self, src: [u8; 4], mut dst: [u8; 4]) -> [u8; 4] {
let a = src[3];
if a == 255 {
return src;
}
if a != 0 {
let alpha = a as u64;
let alpha_compl = 0xFF ^ alpha;
let dst64 = as_color16(u32::from_le_bytes(dst));
let res16 = dst64 * alpha_compl + 0x0080008000800080;
let res8 = res16 + ((res16 >> 8) & 0x00FF00FF00FF00FF);
// transform the result back to 32 bytes
let res = (res8 >> 8) & 0x00FF00FF00FF00FF;
let res = (res | (res >> 8)) & 0x0000FFFF0000FFFF;
let res = res | (res >> 16);
dst = u32::to_le_bytes((res & 0x00000000FFFFFFFF) as u32);
}
[
dst[0].saturating_add(src[0]),
dst[1].saturating_add(src[1]),
dst[2].saturating_add(src[2]),
dst[3].saturating_add(src[3]),
]
}
#[inline(always)]
fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] {
[
unorm_mult(a[0] as u32, b[0] as u32) as u8,
unorm_mult(a[1] as u32, b[1] as u32) as u8,
unorm_mult(a[2] as u32, b[2] as u32) as u8,
unorm_mult(a[3] as u32, b[3] as u32) as u8,
]
}
}
#[derive(Clone, Copy)]
pub(crate) struct GenericImpl;
impl SelectedImpl for GenericImpl {}
#[inline(always)]
pub fn vec4_to_u8x4(v: &Vec4) -> [u8; 4] {
let v = v.clamp(Vec4::ZERO, Vec4::ONE) * 255.0 + 0.5;
[v.x as u8, v.y as u8, v.z as u8, v.w as u8]
}
#[inline(always)]
pub fn u8x4_to_vec4(v: &[u8; 4]) -> Vec4 {
vec4(
v[0] as f32 / 255.0,
v[1] as f32 / 255.0,
v[2] as f32 / 255.0,
v[3] as f32 / 255.0,
)
}
/// transforms 4 bytes RGBA into 8 bytes 0R0G0B0A
#[inline(always)]
pub fn as_color16(color: u32) -> u64 {
let x = color as u64;
let x = ((x & 0xFFFF0000) << 16) | (x & 0xFFFF);
((x & 0x0000FF000000FF00) << 8) | (x & 0x000000FF000000FF)
}
#[inline(always)]
// Jerry R. Van Aken - Alpha Blending with No Division Operations https://arxiv.org/pdf/2202.02864
// Input should be 0..255, is multiplied as if it were 0..1f
pub fn unorm_mult(mut a: u32, b: u32) -> u32 {
a *= b;
a += 0x80;
a += a >> 8;
a >> 8
}
#[inline(always)]
pub fn swizzle_rgba_bgra(a: [u8; 4]) -> [u8; 4] {
[a[2], a[1], a[0], a[3]]
}

View File

@ -0,0 +1,349 @@
#![allow(unsafe_code)]
use core::arch::aarch64::*;
use crate::color::SelectedImpl;
#[derive(Clone, Copy)]
pub(crate) struct NeonImpl(());
impl NeonImpl {
/// `std::arch::is_aarch64_feature_detected!("neon")` MUST be true
pub(crate) const unsafe fn new() -> Self {
Self(())
}
#[inline]
#[target_feature(enable = "neon")]
fn dispatch_neon<R>(self, f: impl FnOnce(Self) -> R) -> R {
f(self)
}
}
impl SelectedImpl for NeonImpl {
#[inline]
fn dispatch<R>(self, f: impl FnOnce(Self) -> R) -> R {
unsafe { self.dispatch_neon(f) }
}
#[inline]
fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
unsafe { egui_blend_u8_slice(src, dst) }
}
#[inline]
fn egui_blend_u8_slice_one_src_tinted_fn(
self,
src: [u8; 4],
tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
unsafe { egui_blend_u8_slice_one_src_tinted_fn(src, tint_fn, dst) }
}
#[inline]
fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
unsafe { egui_blend_u8_slice_tinted(src, tint, dst) }
}
#[inline]
fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) {
unsafe { egui_blend_u8_slice_one_src(src, dst) }
}
#[inline]
fn egui_blend_u8(self, src: [u8; 4], dst: [u8; 4]) -> [u8; 4] {
unsafe { egui_blend_u8(src, dst) }
}
#[inline]
fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] {
unsafe { unorm_mult4x4(a, b) }
}
}
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[inline]
#[target_feature(enable = "neon")]
fn egui_blend_u8(src: [u8; 4], dst: [u8; 4]) -> [u8; 4] {
let a = src[3];
let alpha_compl = vdupq_n_u16((0xFFu16) ^ (a as u16));
let e1 = vdupq_n_u16(0x0080);
let dst8 = vreinterpret_u8_u32(vdup_n_u32(u32::from_le_bytes(dst)));
let mut dst = vmovl_u8(dst8);
// dst * alpha_compl + 0x0080
dst = vaddq_u16(vmulq_u16(dst, alpha_compl), e1);
// ((x >> 8) + x) >> 8
dst = vaddq_u16(dst, vshrq_n_u16(dst, 8));
dst = vshrq_n_u16(dst, 8);
// Pack to back to u8
let dst = vqmovn_u16(dst);
let src32x2 = vdup_n_u32(u32::from_le_bytes(src));
let src8 = vreinterpret_u8_u32(src32x2);
// saturating add
let out8 = vqadd_u8(dst, src8);
let out32 = vget_lane_u32(vreinterpret_u32_u8(out8), 0);
out32.to_le_bytes()
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "neon")]
pub fn egui_blend_u8_slice_one_src(src: [u8; 4], dst: &mut [[u8; 4]]) {
let n = dst.len();
if n == 0 {
return;
}
let a = src[3];
let src32 = u32::from_le_bytes(src);
let alpha = src[3] as i32;
let alpha_compl = 0xFF ^ alpha;
let e1 = vdupq_n_u16(0x0080);
// (255 - a) in all u16 lanes
let simd_alpha_compl = vdupq_n_u16(alpha_compl as u16);
let mut i = 0;
if a == 0 {
let src8_q = vreinterpretq_u8_u32(vdupq_n_u32(src32));
// Only need to saturating_add src to dst. We can do 4 at a time in this case.
while i + 3 < n {
let p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8;
let d128 = unsafe { vld1q_u8(p) };
let out = vqaddq_u8(d128, src8_q);
unsafe { vst1q_u8(p, out) };
i += 4;
}
} else {
let src8 = vreinterpret_u8_u32(vdup_n_u32(src32));
while i + 1 < n {
let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8;
// Load two dst pixels
let d8 = unsafe { vld1_u8(dst_p) };
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let dst16 = vmovl_u8(d8);
// dst * alpha_compl + 0x0080008000800080
let res16 = vaddq_u16(vmulq_u16(dst16, simd_alpha_compl), e1);
// ((x >> 8) + x) >> 8
let res16 = vshrq_n_u16(vaddq_u16(res16, vshrq_n_u16(res16, 8)), 8);
let mut dst8 = vqmovn_u16(res16);
// dst.saturating_add(src)
dst8 = vqadd_u8(dst8, src8);
unsafe { vst1_u8(dst_p, dst8) };
i += 2;
}
}
while i < n {
dst[i] = egui_blend_u8(src, dst[i]);
i += 1;
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src[i], dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "neon")]
fn egui_blend_u8_slice(src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
assert_eq!(src.len(), dst.len());
let n = dst.len();
if n == 0 {
return;
}
let mut i = 0;
while i + 1 < n {
let src_p = unsafe { src.as_ptr().add(i) } as *mut u8;
// Load two src pixels
let src8 = unsafe { vld1_u8(src_p) };
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let src16 = vmovl_u8(src8);
// Load two dst pixels
let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8;
// Load two dst pixels
let d8 = unsafe { vld1_u8(dst_p) };
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let dst16 = vmovl_u8(d8);
let dst8 = egui_blend_two_u16x4(src8, src16, dst16);
unsafe { vst1_u8(dst_p, dst8) };
i += 2;
}
if i < n {
dst[i] = egui_blend_u8(src[i], dst[i]);
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src[i] * vert, dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "neon")]
fn egui_blend_u8_slice_tinted(src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
assert_eq!(src.len(), dst.len());
let n = dst.len();
if n == 0 {
return;
}
let e1 = vdupq_n_u16(0x0080);
let tint32 = u32::from_le_bytes(tint);
let tint8 = vreinterpret_u8_u32(vdup_n_u32(tint32));
let tint16 = vmovl_u8(tint8);
let mut i = 0usize;
while i + 1 < n {
let src_p = unsafe { src.as_ptr().add(i) } as *mut u8;
// Load two src pixels
let src8 = unsafe { vld1_u8(src_p) };
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let src16 = vmovl_u8(src8);
// Load two dst pixels
let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8;
let d8 = unsafe { vld1_u8(dst_p) };
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let dst16 = vmovl_u8(d8);
// src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255)
let mut t = vaddq_u16(vmulq_u16(src16, tint16), e1);
t = vaddq_u16(t, vshrq_n_u16(t, 8));
let src_tinted16 = vshrq_n_u16(t, 8);
let src_tinted8 = vqmovn_u16(src_tinted16);
let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16);
unsafe { vst1_u8(dst_p, dst8) };
i += 2;
}
// Tail: handle the last pixel (if any) in scalar
if i < n {
dst[i] = egui_blend_u8(unorm_mult4x4(src[i], tint), dst[i]);
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src * tint_fn(), dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "neon")]
fn egui_blend_u8_slice_one_src_tinted_fn(
src: [u8; 4],
mut tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
let n = dst.len();
if n == 0 {
return;
}
let src32 = u32::from_le_bytes(src);
let src8 = vreinterpret_u8_u32(vdup_n_u32(src32));
let src16 = vmovl_u8(src8);
let e1 = vdupq_n_u16(0x0080);
let mut i = 0usize;
while i + 1 < n {
// Load two tint values
let mut t32x2 = vdup_n_u32(0);
t32x2 = vset_lane_u32(u32::from_le_bytes(tint_fn()), t32x2, 0);
t32x2 = vset_lane_u32(u32::from_le_bytes(tint_fn()), t32x2, 1);
let tint8 = vreinterpret_u8_u32(t32x2);
let tint16 = vmovl_u8(tint8);
// Load two dst pixels
let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8;
let d8 = unsafe { vld1_u8(dst_p) };
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let dst16 = vmovl_u8(d8);
// src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255)
let mut t = vaddq_u16(vmulq_u16(src16, tint16), e1);
t = vaddq_u16(t, vshrq_n_u16(t, 8));
let src_tinted16 = vshrq_n_u16(t, 8);
let src_tinted8 = vqmovn_u16(src_tinted16);
let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16);
unsafe { vst1_u8(dst_p, dst8) };
i += 2;
}
// Tail: handle the last pixel (if any) in scalar
if i < n {
dst[i] = egui_blend_u8(unorm_mult4x4(src, tint_fn()), dst[i]);
}
}
#[inline]
#[target_feature(enable = "neon")]
fn unorm_mult4x4(a: [u8; 4], b: [u8; 4]) -> [u8; 4] {
let e1 = vdupq_n_u16(0x0080);
let a = vmovl_u8(vreinterpret_u8_u32(vdup_n_u32(u32::from_le_bytes(a))));
let b = vmovl_u8(vreinterpret_u8_u32(vdup_n_u32(u32::from_le_bytes(b))));
// a * b + 0x0080
let mut dst = vaddq_u16(vmulq_u16(a, b), e1);
// ((a >> 8) + a) >> 8
dst = vaddq_u16(dst, vshrq_n_u16(dst, 8));
dst = vshrq_n_u16(dst, 8);
// Pack to back to u8
let dst = vqmovn_u16(dst);
vget_lane_u32(vreinterpret_u32_u8(dst), 0).to_le_bytes() // Return first element of dst
}
#[inline]
/// src8 should have two 8 bit per channel rgba samples stored in the low bits
/// src16 should have two 16 bit per channel rgba samples
/// dst16 should have two 16 bit per channel rgba samples
#[target_feature(enable = "neon")]
fn egui_blend_two_u16x4(src8: uint8x8_t, src16: uint16x8_t, dst16: uint16x8_t) -> uint8x8_t {
let ones = vdupq_n_u16(0x00FF);
let e1 = vdupq_n_u16(0x0080);
// Broadcast alpha within each pixel's 4 lanes
let a_lo4 = vdup_n_u16(vgetq_lane_u16(src16, 3));
let a_hi4 = vdup_n_u16(vgetq_lane_u16(src16, 7));
let a_broadcast = vcombine_u16(a_lo4, a_hi4);
// simd_alpha_compl = 255 - A for each lane, per pixel
let simd_alpha_compl = vsubq_u16(ones, a_broadcast);
// dst * alpha_compl + 0x0080008000800080
let dst_term = vmulq_u16(dst16, simd_alpha_compl);
let res16 = vaddq_u16(dst_term, e1);
// ((x >> 8) + x) >> 8
let res16 = vaddq_u16(res16, vshrq_n_u16(res16, 8));
let res16 = vshrq_n_u16(res16, 8);
let dst8 = vqmovn_u16(res16);
// Pack back to u8
// dst.saturating_add(src)
vqadd_u8(dst8, src8)
}

View File

@ -0,0 +1,346 @@
#![allow(unsafe_code)]
use core::{arch::x86_64::*, ptr::read_unaligned};
use crate::color::SelectedImpl;
#[derive(Clone, Copy)]
pub struct Sse41Impl(());
impl Sse41Impl {
/// `std::arch::is_x86_feature_detected!("sse4.1")` MUST be true
pub const unsafe fn new() -> Self {
Self(())
}
#[inline]
#[target_feature(enable = "sse4.1")]
fn dispatch_sse41<R>(self, f: impl FnOnce(Self) -> R) -> R {
f(self)
}
}
impl SelectedImpl for Sse41Impl {
#[inline]
fn dispatch<R>(self, f: impl FnOnce(Self) -> R) -> R {
unsafe { self.dispatch_sse41(f) }
}
#[inline]
fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
unsafe { egui_blend_u8_slice(src, dst) }
}
#[inline]
fn egui_blend_u8_slice_one_src_tinted_fn(
self,
src: [u8; 4],
tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
unsafe { egui_blend_u8_slice_one_src_tinted_fn(src, tint_fn, dst) }
}
#[inline]
fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
unsafe { egui_blend_u8_slice_tinted(src, tint, dst) }
}
#[inline]
fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) {
unsafe { egui_blend_u8_slice_one_src(src, dst) }
}
#[inline]
fn egui_blend_u8(self, src: [u8; 4], dst: [u8; 4]) -> [u8; 4] {
unsafe { egui_blend_u8(src, dst) }
}
#[inline]
fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] {
unsafe { unorm_mult4x4(a, b) }
}
}
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[inline]
#[target_feature(enable = "sse4.1")]
fn egui_blend_u8(src: [u8; 4], dst: [u8; 4]) -> [u8; 4] {
let alpha = src[3];
let alpha_compl = _mm_set1_epi16(0xFFi16 ^ (alpha as i16));
let e1 = _mm_set1_epi16(0x0080);
let mut dst = _mm_cvtsi32_si128(i32::from_le_bytes(dst)); // Load dst into element a
dst = _mm_cvtepu8_epi16(dst); // [0,0,0,0,0,0,0,rgba] -> [0,0,0,0,r,g,b,a]
// dst * alpha_compl + 0x0080
dst = _mm_add_epi16(_mm_mullo_epi16(dst, alpha_compl), e1);
// ((x >> 8) + x) >> 8
dst = _mm_add_epi16(dst, _mm_srli_epi16(dst, 8));
dst = _mm_srli_epi16(dst, 8);
// Pack to back to u8
let dst = _mm_packus_epi16(dst, _mm_setzero_si128());
let src = _mm_cvtsi32_si128(i32::from_le_bytes(src)); // Load src into element a
let dst = _mm_adds_epu8(dst, src); // dst.saturating_add(src)
i32::to_le_bytes(_mm_cvtsi128_si32(dst)) // Return first element of dst
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "sse4.1")]
fn egui_blend_u8_slice_one_src(src: [u8; 4], dst: &mut [[u8; 4]]) {
let n = dst.len();
if n == 0 {
return;
}
let a = src[3];
let src32 = u32::from_le_bytes(src);
let src64 = (src32 as u64) | ((src32 as u64) << 32);
let src8 = _mm_set1_epi64x(src64 as i64);
let alpha = src[3] as i32;
let alpha_compl = 0xFF ^ alpha;
let e1 = _mm_set1_epi16(0x0080);
let e2 = _mm_set1_epi16(0x0101);
// (255 - a) in all u16 lanes
let simd_alpha_compl = _mm_set1_epi16(alpha_compl as i16);
let mut i = 0;
if a == 0 {
// Only need to saturating_add src to dst. We can do 4 at a time in this case.
while i + 3 < n {
let p = unsafe { dst.as_mut_ptr().add(i) } as *mut __m128i;
let d128 = unsafe { _mm_loadu_si128(p) };
let out = _mm_adds_epu8(d128, src8);
unsafe { _mm_storeu_si128(p, out) };
i += 4;
}
} else {
while i + 1 < n {
let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::<u64>();
// Load two dst pixels
let d8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64);
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let dst16 = _mm_cvtepu8_epi16(d8);
// dst * alpha_compl + 0x0080008000800080
let res16 = _mm_add_epi16(_mm_mullo_epi16(dst16, simd_alpha_compl), e1);
// This mulhi is equivalent to the ((x >> 8) + x) >> 8 operation. (can you see why?)
let res16 = _mm_mulhi_epu16(res16, e2);
let mut dst8 = _mm_packus_epi16(res16, res16); // Pack back to u8
// dst.saturating_add(src)
dst8 = _mm_adds_epu8(dst8, src8);
let lo64 = _mm_cvtsi128_si64(dst8) as u64;
unsafe { core::ptr::write_unaligned(dst, lo64) };
i += 2;
}
}
while i < n {
dst[i] = egui_blend_u8(src, dst[i]);
i += 1;
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src[i], dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "sse4.1")]
fn egui_blend_u8_slice(src: &[[u8; 4]], dst: &mut [[u8; 4]]) {
assert_eq!(src.len(), dst.len());
let n = dst.len();
if n == 0 {
return;
}
let mut i = 0;
while i + 1 < n {
// Load two src pixels
let src = unsafe { src.as_ptr().add(i) }.cast::<u64>();
let src8 = _mm_cvtsi64_si128(unsafe { read_unaligned(src) } as i64);
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let src16 = _mm_cvtepu8_epi16(src8);
// Load two dst pixels
let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::<u64>();
let d8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64);
let dst16 = _mm_cvtepu8_epi16(d8);
let dst8 = egui_blend_two_u16x4(src8, src16, dst16);
let lo64 = _mm_cvtsi128_si64(dst8) as u64;
unsafe { core::ptr::write_unaligned(dst, lo64) };
i += 2;
}
if i < n {
dst[i] = egui_blend_u8(src[i], dst[i]);
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src[i] * vert, dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "sse4.1")]
fn egui_blend_u8_slice_tinted(src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) {
assert_eq!(src.len(), dst.len());
let n = dst.len();
if n == 0 {
return;
}
let e1 = _mm_set1_epi16(0x0080);
let e2 = _mm_set1_epi16(0x0101);
let t32 = _mm_set1_epi32(i32::from_le_bytes(tint));
let tint16 = _mm_cvtepu8_epi16(t32);
let mut i = 0usize;
while i + 1 < n {
// Load two src pixels
let src = unsafe { src.as_ptr().add(i) }.cast::<u64>();
let src8 = _mm_cvtsi64_si128(unsafe { read_unaligned(src) } as i64);
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let src16 = _mm_cvtepu8_epi16(src8);
// Load two dst pixels
let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::<u64>();
let dst8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64);
let dst16 = _mm_cvtepu8_epi16(dst8);
// src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255)
let tint_mul = _mm_mullo_epi16(src16, tint16);
let tint_rounded = _mm_add_epi16(tint_mul, e1);
let src_tinted16 = _mm_mulhi_epu16(tint_rounded, e2);
let src_tinted8 = _mm_packus_epi16(src_tinted16, src_tinted16);
let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16);
let lo64 = _mm_cvtsi128_si64(dst8) as u64;
unsafe { core::ptr::write_unaligned(dst, lo64) };
i += 2;
}
// Tail: handle the last pixel (if any) in scalar
if i < n {
dst[i] = egui_blend_u8(unorm_mult4x4(src[i], tint), dst[i]);
}
}
// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html
/// dst[i] = blend(src * tint_fn(), dst[i]) // As unorm
/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA)
#[target_feature(enable = "sse4.1")]
fn egui_blend_u8_slice_one_src_tinted_fn(
src: [u8; 4],
mut tint_fn: impl FnMut() -> [u8; 4],
dst: &mut [[u8; 4]],
) {
let n = dst.len();
if n == 0 {
return;
}
let src32 = u32::from_le_bytes(src);
let src64 = (src32 as u64) | ((src32 as u64) << 32);
let e1 = _mm_set1_epi16(0x0080);
let e2 = _mm_set1_epi16(0x0101);
let mut i = 0usize;
while i + 1 < n {
// Load two tint values
let tint_a = u32::from_le_bytes(tint_fn()) as i64;
let tint_b = u32::from_le_bytes(tint_fn()) as i64;
let tint_simd = _mm_cvtsi64_si128((tint_b << 32) | tint_a);
let tint16 = _mm_cvtepu8_epi16(tint_simd);
let src8 = _mm_cvtsi64_si128(src64 as i64);
// [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a]
let src16 = _mm_cvtepu8_epi16(src8);
// Load two dst pixels
let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::<u64>();
let dst8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64);
let dst16 = _mm_cvtepu8_epi16(dst8);
// src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255)
let tint_mul = _mm_mullo_epi16(src16, tint16);
let tint_rounded = _mm_add_epi16(tint_mul, e1);
let src_tinted16 = _mm_mulhi_epu16(tint_rounded, e2);
let src_tinted8 = _mm_packus_epi16(src_tinted16, src_tinted16);
let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16);
let lo64 = _mm_cvtsi128_si64(dst8) as u64;
unsafe { core::ptr::write_unaligned(dst, lo64) };
i += 2;
}
// Tail: handle the last pixel (if any) in scalar
if i < n {
dst[i] = egui_blend_u8(unorm_mult4x4(src, tint_fn()), dst[i]);
}
}
#[inline]
#[target_feature(enable = "sse4.1")]
fn unorm_mult4x4(a: [u8; 4], b: [u8; 4]) -> [u8; 4] {
let e1 = _mm_set1_epi16(0x0080);
let a = _mm_cvtepu8_epi16(_mm_cvtsi32_si128(i32::from_le_bytes(a)));
let b = _mm_cvtepu8_epi16(_mm_cvtsi32_si128(i32::from_le_bytes(b)));
// a * b + 0x0080
let mut dst = _mm_add_epi16(_mm_mullo_epi16(a, b), e1);
// ((a >> 8) + a) >> 8
dst = _mm_add_epi16(dst, _mm_srli_epi16(dst, 8));
dst = _mm_srli_epi16(dst, 8);
// Pack to back to u8
let dst = _mm_packus_epi16(dst, _mm_setzero_si128());
i32::to_le_bytes(_mm_cvtsi128_si32(dst)) // Return first element of dst
}
#[inline]
/// src8 should have two 8 bit per channel rgba samples stored in the low bits
/// src16 should have two 16 bit per channel rgba samples
/// dst16 should have two 16 bit per channel rgba samples
#[target_feature(enable = "sse4.1")]
fn egui_blend_two_u16x4(src8: __m128i, src16: __m128i, dst16: __m128i) -> __m128i {
let ones = _mm_set1_epi16(0x00FF);
let e1 = _mm_set1_epi16(0x0080);
let e2 = _mm_set1_epi16(0x0101);
// Broadcast alpha within each pixel's 4 lanes
let a_broadcast_lo = _mm_shufflelo_epi16(src16, 0b11111111);
let a_broadcast = _mm_shufflehi_epi16(a_broadcast_lo, 0b11111111);
// simd_alpha_compl = 255 - A for each lane, per pixel
let simd_alpha_compl = _mm_sub_epi16(ones, a_broadcast);
// dst * alpha_compl + 0x0080008000800080
let dst_term = _mm_mullo_epi16(dst16, simd_alpha_compl);
let res16 = _mm_add_epi16(dst_term, e1);
// This mulhi is equivalent to the ((x >> 8) + x) >> 8 operation. (can you see why?)
let res16 = _mm_mulhi_epu16(res16, e2);
let dst8 = _mm_packus_epi16(res16, res16);
// Pack back to u8
// dst.saturating_add(src)
_mm_adds_epu8(dst8, src8)
}

View File

@ -0,0 +1,121 @@
use alloc::vec::Vec;
use egui::{Color32, TextureFilter, TextureOptions, Vec2, vec2};
use crate::{
ColorFieldOrder,
color::{swizzle_rgba_bgra, u8x4_to_vec4, vec4_to_u8x4},
};
pub struct EguiTexture {
pub opaque: bool,
pub data: Vec<[u8; 4]>,
// Common case: The default egui texture has the top-left corner pixel fully white.
// https://github.com/emilk/egui/blob/c97c065a575ec6e657bb42872890a00d0fb391c1/crates/epaint/src/lib.rs#L92
pub uv_zero_val: [u8; 4],
/// width - 1
pub width_extent: i32,
/// height - 1
pub height_extent: i32,
pub width: usize,
#[allow(dead_code)]
pub height: usize,
pub fsize: Vec2,
pub options: TextureOptions,
}
impl EguiTexture {
pub fn new(
field_order: ColorFieldOrder,
options: TextureOptions,
size: [usize; 2],
pixels: &[Color32],
) -> EguiTexture {
let data = pixels
.iter()
.map(|p| match field_order {
ColorFieldOrder::Rgba => p.to_array(),
ColorFieldOrder::Bgra => swizzle_rgba_bgra(p.to_array()),
})
.collect::<Vec<_>>();
let uv_zero_val = data[0];
EguiTexture {
opaque: data.iter().all(|p| p[3] == 255),
data,
width_extent: size[0] as i32 - 1,
height_extent: size[1] as i32 - 1,
width: size[0],
height: size[1],
fsize: vec2(size[0] as f32, size[1] as f32),
options,
uv_zero_val,
}
}
#[allow(dead_code)]
pub fn sample_nearest(&self, uv: Vec2) -> [u8; 4] {
let ss_x = ((uv.x * self.fsize.x) as i32).max(0).min(self.width_extent);
let ss_y = ((uv.y * self.fsize.y) as i32)
.max(0)
.min(self.height_extent);
self.data[ss_x as usize + ss_y as usize * self.width]
}
pub fn sample_bilinear(&self, uv: Vec2) -> [u8; 4] {
if uv == Vec2::ZERO {
return self.uv_zero_val;
}
let w = self.fsize.x;
let h = self.fsize.y;
#[inline(always)]
fn mirror(v: f32) -> f32 {
((v * 0.5 + 0.5).fract() - 0.5) * 2.0
}
let uv = match self.options.wrap_mode {
egui::TextureWrapMode::ClampToEdge => uv,
egui::TextureWrapMode::Repeat => vec2(uv.x.fract(), uv.y.fract()),
egui::TextureWrapMode::MirroredRepeat => vec2(mirror(uv.x), mirror(uv.y)),
};
let sx = uv.x * w - 0.5;
let sy = uv.y * h - 0.5;
let x0 = sx.floor() as i32;
let y0 = sy.floor() as i32;
let x1 = x0 + 1;
let y1 = y0 + 1;
let fx = sx - x0 as f32;
let fy = sy - y0 as f32;
let x0c = x0.max(0).min(self.width_extent);
let y0c = y0.max(0).min(self.height_extent);
let x1c = x1.max(0).min(self.width_extent);
let y1c = y1.max(0).min(self.height_extent);
let c00 = self.data[(x0c as usize) + (y0c as usize) * self.width];
if self.options.magnification == TextureFilter::Nearest || (fx == 0.0 && fy == 0.0) {
// if these are 0 the px at 0,0 will have full influence. Equivalent to nearest sampling.
return c00;
}
let c10 = self.data[(x1c as usize) + (y0c as usize) * self.width];
let c01 = self.data[(x0c as usize) + (y1c as usize) * self.width];
let c11 = self.data[(x1c as usize) + (y1c as usize) * self.width];
let v00 = u8x4_to_vec4(&c00);
let v10 = u8x4_to_vec4(&c10);
let v01 = u8x4_to_vec4(&c01);
let v11 = u8x4_to_vec4(&c11);
let w00 = (1.0 - fx) * (1.0 - fy);
let w10 = fx * (1.0 - fy);
let w01 = (1.0 - fx) * fy;
let w11 = fx * fy;
vec4_to_u8x4(&(v00 * w00 + v01 * w01 + v10 * w10 + v11 * w11))
}
}

View File

@ -0,0 +1,175 @@
//! PDF Presenter patch: bounded scanline sampling for cropped, untinted image quads.
//! Keep general meshes, fonts, wrapping, full images and tinting on the upstream path.
use crate::{BufferMutRef, EguiTexture};
use alloc::vec::Vec;
use egui::{Color32, Mesh, Rect, TextureFilter, TextureWrapMode, Vec2};
pub(crate) fn draw(
buffer: &mut BufferMutRef<'_>,
clip: &Rect,
mesh: &Mesh,
offset: Vec2,
texture: &EguiTexture,
) -> bool {
if mesh.texture_id == egui::TextureId::Managed(0)
|| mesh.vertices.len() != 4
|| mesh.indices.len() != 6
|| texture.options.wrap_mode != TextureWrapMode::ClampToEdge
|| mesh
.vertices
.iter()
.any(|v| v.color != Color32::WHITE || !v.pos.is_finite() || !v.uv.is_finite())
{
return false;
}
let mut rect = Rect::NOTHING;
let mut uv = Rect::NOTHING;
for v in &mesh.vertices {
rect.extend_with(v.pos);
uv.extend_with(v.uv);
}
if rect.width() <= 0.
|| rect.height() <= 0.
|| uv.width() <= 0.
|| uv.height() <= 0.
|| uv.min.x < 0.
|| uv.min.y < 0.
|| uv.max.x > 1.
|| uv.max.y > 1.
|| (uv.width() >= 0.99999 && uv.height() >= 0.99999)
{
return false;
}
let mut corners = [0usize; 4];
let mut seen = 0u8;
for (i, v) in mesh.vertices.iter().enumerate() {
if (v.pos.x != rect.min.x && v.pos.x != rect.max.x)
|| (v.pos.y != rect.min.y && v.pos.y != rect.max.y)
{
return false;
}
let x = usize::from(v.pos.x == rect.max.x);
let y = usize::from(v.pos.y == rect.max.y);
let c = x + y * 2;
if seen & (1 << c) != 0
|| v.uv.x != if x == 0 { uv.min.x } else { uv.max.x }
|| v.uv.y != if y == 0 { uv.min.y } else { uv.max.y }
{
return false;
}
seen |= 1 << c;
corners[i] = c;
}
let mut triangles = [[0usize; 3]; 2];
for (t, indices) in triangles.iter_mut().zip(mesh.indices.chunks_exact(3)) {
for (c, i) in t.iter_mut().zip(indices) {
let Some(corner) = corners.get(*i as usize) else {
return false;
};
*c = *corner;
}
t.sort_unstable();
}
triangles.sort_unstable();
if triangles != [[0, 1, 2], [1, 2, 3]] && triangles != [[0, 1, 3], [0, 2, 3]] {
return false;
}
rect = rect.translate(offset);
let visible = rect.intersect(*clip);
if !visible.is_positive() {
return true;
}
let bound = |v: f32, max: usize| (v - 0.5).ceil().clamp(0., max as f32) as usize;
let x0 = bound(visible.min.x, buffer.width);
let x1 = bound(visible.max.x, buffer.width);
let y0 = bound(visible.min.y, buffer.height);
let y1 = bound(visible.max.y, buffer.height);
if x0 >= x1 || y0 >= y1 {
return true;
}
let step = uv.size() / rect.size();
let linear = texture.options.magnification != TextureFilter::Nearest;
let axis = |value: f32, size: usize| {
if !linear {
let i = (value * size as f32).floor().clamp(0., (size - 1) as f32) as usize;
return (i, i, 0u32);
}
let p = value * size as f32 - 0.5;
let lo = p.floor();
let a = lo.clamp(0., (size - 1) as f32) as usize;
let b = (lo + 1.).clamp(0., (size - 1) as f32) as usize;
(a, b, ((p - lo) * 256.).round().clamp(0., 256.) as u32)
};
// O(viewport width) scratch, reused across every scanline; no image allocation.
let columns: Vec<_> = (x0..x1)
.map(|x| {
axis(
uv.min.x + (x as f32 + 0.5 - rect.min.x) * step.x,
texture.width,
)
})
.collect();
let mut row0 = alloc::vec![[0u8;4]; columns.len()];
let mut row1 = row0.clone();
let mut cached0 = usize::MAX;
let mut cached1 = usize::MAX;
let horizontal = |row: &mut [[u8; 4]], source_y: usize| {
let source = &texture.data[source_y * texture.width..(source_y + 1) * texture.width];
for (dst, &(a, b, w)) in row.iter_mut().zip(&columns) {
let a = source[a];
let b = source[b];
for c in 0..4 {
dst[c] = ((u32::from(a[c]) * (256 - w) + u32::from(b[c]) * w + 128) >> 8) as u8;
}
}
};
for y in y0..y1 {
let (ya, yb, wy) = axis(
uv.min.y + (y as f32 + 0.5 - rect.min.y) * step.y,
texture.height,
);
if ya == cached1 {
core::mem::swap(&mut row0, &mut row1);
core::mem::swap(&mut cached0, &mut cached1);
}
if ya != cached0 {
horizontal(&mut row0, ya);
cached0 = ya;
}
if yb != cached1 {
horizontal(&mut row1, yb);
cached1 = yb;
}
let destination = buffer.get_mut_span(x0, x1, y);
if texture.opaque {
// Contiguous arithmetic: LLVM vectorizes this hot loop. Enlarged rows
// reuse horizontally filtered samples instead of sampling four texels
// and recalculating X coordinates for every screen pixel.
let weight = wy as u16;
for ((dst, a), b) in destination.iter_mut().zip(&row0).zip(&row1) {
for c in 0..4 {
dst[c] = ((u16::from(a[c]) * (256 - weight) + u16::from(b[c]) * weight + 128)
>> 8) as u8;
}
}
} else {
for ((dst, a), b) in destination.iter_mut().zip(&row0).zip(&row1) {
let mut src = [0u8; 4];
for c in 0..4 {
src[c] =
((u32::from(a[c]) * (256 - wy) + u32::from(b[c]) * wy + 128) >> 8) as u8;
}
if src[3] == 255 {
*dst = src;
} else if src[3] != 0 {
let alpha = 255 - u32::from(src[3]);
for c in 0..4 {
dst[c] = (u32::from(src[c]) + (u32::from(dst[c]) * alpha + 127) / 255)
.min(255) as u8;
}
}
}
}
}
true
}

View File

@ -0,0 +1,39 @@
pub struct Hash32(pub u32);
impl Hash32 {
#[inline(always)]
pub fn new_fnv() -> Self {
Hash32(0x811c9dc5) // FNV offset basis
}
#[inline(always)]
pub fn hash_wrap(&mut self, v: u32) {
self.hash(v);
self.fnv_wrap();
}
#[inline(always)]
pub fn hash(&mut self, v: u32) {
self.0 ^= hash32(v);
}
#[inline(always)]
pub fn fnv_wrap(&mut self) {
self.0 = self.0.wrapping_mul(0x01000193); // FNV prime
}
pub fn finalize(&self) -> u32 {
self.0
}
}
#[inline(always)]
fn hash32(x: u32) -> u32 {
// from https://nullprogram.com/blog/2018/07/31/
let mut x = x ^ (x >> 16);
x = x.overflowing_mul(0x7feb352d).0;
x = x ^ (x >> 15);
x = x.overflowing_mul(0x846ca68b).0;
x = x ^ (x >> 16);
x
}

1206
vendor/egui_software_backend/src/lib.rs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,92 @@
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(C, align(16))]
pub struct I64Vec2 {
pub x: i64,
pub y: i64,
}
impl I64Vec2 {
#[inline(always)]
pub fn from_vec2(v: egui::Vec2) -> Self {
i64vec2(v.x as i64, v.y as i64)
}
#[inline(always)]
pub fn min(self, v: Self) -> Self {
i64vec2(self.x.min(v.x), self.y.min(v.y))
}
#[inline(always)]
pub fn max(self, v: Self) -> Self {
i64vec2(self.x.max(v.x), self.y.max(v.y))
}
}
impl core::ops::Mul<Self> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn mul(self, rhs: Self) -> Self {
i64vec2(self.x * rhs.x, self.y * rhs.y)
}
}
impl core::ops::Add<Self> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn add(self, rhs: Self) -> Self {
i64vec2(self.x + rhs.x, self.y + rhs.y)
}
}
impl core::ops::Sub<Self> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn sub(self, rhs: Self) -> Self {
i64vec2(self.x - rhs.x, self.y - rhs.y)
}
}
impl core::ops::Mul<i64> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn mul(self, rhs: i64) -> Self {
i64vec2(self.x * rhs, self.y * rhs)
}
}
impl core::ops::Add<i64> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn add(self, rhs: i64) -> Self {
i64vec2(self.x + rhs, self.y + rhs)
}
}
impl core::ops::Sub<i64> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn sub(self, rhs: i64) -> Self {
i64vec2(self.x - rhs, self.y - rhs)
}
}
impl core::ops::Shr<u32> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn shr(self, rhs: u32) -> Self {
i64vec2(self.x >> rhs, self.y >> rhs)
}
}
impl core::ops::Shl<u32> for I64Vec2 {
type Output = Self;
#[inline(always)]
fn shl(self, rhs: u32) -> Self {
i64vec2(self.x << rhs, self.y << rhs)
}
}
#[inline(always)]
pub fn i64vec2(x: i64, y: i64) -> I64Vec2 {
I64Vec2 { x, y }
}

View File

@ -0,0 +1,3 @@
// These exist just to avoid bringing in glam or similar since egui doesn't.
pub(crate) mod i64vec2;
pub(crate) mod vec4;

View File

@ -0,0 +1,601 @@
// This exists just to avoid bringing in glam or similar since egui doesn't.
// Might be able to use ecolor::rgba::Rgba with some additions.
// Based on emath Vec2
use core::fmt;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
#[repr(C, align(16))]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Vec4 {
pub x: f32,
pub y: f32,
pub z: f32,
pub w: f32,
}
/// `vec4(x, y, z, w) == Vec4::new(x, y, z, w)`
#[inline(always)]
pub const fn vec4(x: f32, y: f32, z: f32, w: f32) -> Vec4 {
Vec4 { x, y, z, w }
}
// ----------------------------------------------------------------------------
// Compatibility and convenience conversions to and from [f32; 4]:
impl From<[f32; 4]> for Vec4 {
#[inline(always)]
fn from(v: [f32; 4]) -> Self {
Self {
x: v[0],
y: v[1],
z: v[2],
w: v[3],
}
}
}
impl From<&[f32; 4]> for Vec4 {
#[inline(always)]
fn from(v: &[f32; 4]) -> Self {
Self {
x: v[0],
y: v[1],
z: v[2],
w: v[3],
}
}
}
impl From<Vec4> for [f32; 4] {
#[inline(always)]
fn from(v: Vec4) -> Self {
[v.x, v.y, v.z, v.w]
}
}
impl From<&Vec4> for [f32; 4] {
#[inline(always)]
fn from(v: &Vec4) -> Self {
[v.x, v.y, v.z, v.w]
}
}
// ----------------------------------------------------------------------------
// Compatibility and convenience conversions to and from (f32, f32, f32, f32):
impl From<(f32, f32, f32, f32)> for Vec4 {
#[inline(always)]
fn from(v: (f32, f32, f32, f32)) -> Self {
Self {
x: v.0,
y: v.1,
z: v.2,
w: v.3,
}
}
}
impl From<&(f32, f32, f32, f32)> for Vec4 {
#[inline(always)]
fn from(v: &(f32, f32, f32, f32)) -> Self {
Self {
x: v.0,
y: v.1,
z: v.2,
w: v.3,
}
}
}
impl From<Vec4> for (f32, f32, f32, f32) {
#[inline(always)]
fn from(v: Vec4) -> Self {
(v.x, v.y, v.z, v.w)
}
}
impl From<&Vec4> for (f32, f32, f32, f32) {
#[inline(always)]
fn from(v: &Vec4) -> Self {
(v.x, v.y, v.z, v.w)
}
}
// ----------------------------------------------------------------------------
impl Vec4 {
pub const ZERO: Self = Self {
x: 0.0,
y: 0.0,
z: 0.0,
w: 0.0,
};
pub const ONE: Self = Self {
x: 1.0,
y: 1.0,
z: 1.0,
w: 1.0,
};
pub const INFINITY: Self = Self::splat(f32::INFINITY);
pub const NAN: Self = Self::splat(f32::NAN);
#[inline(always)]
pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self {
Self { x, y, z, w }
}
/// Set `x`, `y`, `z`, `w` to the same value.
#[inline(always)]
pub const fn splat(v: f32) -> Self {
Self {
x: v,
y: v,
z: v,
w: v,
}
}
/// Safe normalize: returns zero if input is zero.
#[must_use]
#[inline(always)]
pub fn normalized(self) -> Self {
let len = self.length();
if len <= 0.0 { self } else { self / len }
}
/// Checks if `self` has length `1.0` up to a precision of `1e-6`.
#[inline(always)]
pub fn is_normalized(self) -> bool {
(self.length_sq() - 1.0).abs() < 2e-6
}
#[inline(always)]
pub fn length(self) -> f32 {
self.length_sq().sqrt()
}
#[inline(always)]
pub fn length_sq(self) -> f32 {
self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w
}
#[must_use]
#[inline(always)]
pub fn floor(self) -> Self {
vec4(
self.x.floor(),
self.y.floor(),
self.z.floor(),
self.w.floor(),
)
}
#[must_use]
#[inline(always)]
pub fn round(self) -> Self {
vec4(
self.x.round(),
self.y.round(),
self.z.round(),
self.w.round(),
)
}
#[must_use]
#[inline(always)]
pub fn ceil(self) -> Self {
vec4(self.x.ceil(), self.y.ceil(), self.z.ceil(), self.w.ceil())
}
#[must_use]
#[inline]
pub fn abs(self) -> Self {
vec4(self.x.abs(), self.y.abs(), self.z.abs(), self.w.abs())
}
/// True if all members are also finite.
#[inline(always)]
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite()
}
/// True if any member is NaN.
#[inline(always)]
pub fn any_nan(self) -> bool {
self.x.is_nan() || self.y.is_nan() || self.z.is_nan() || self.w.is_nan()
}
#[must_use]
#[inline]
pub fn min(self, other: Self) -> Self {
vec4(
self.x.min(other.x),
self.y.min(other.y),
self.z.min(other.z),
self.w.min(other.w),
)
}
#[must_use]
#[inline]
pub fn max(self, other: Self) -> Self {
vec4(
self.x.max(other.x),
self.y.max(other.y),
self.z.max(other.z),
self.w.max(other.w),
)
}
/// The dot-product of two vectors.
#[inline]
pub fn dot(self, other: Self) -> f32 {
self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w
}
/// Returns the minimum of all elements.
#[must_use]
#[inline(always)]
pub fn min_elem(self) -> f32 {
self.x.min(self.y).min(self.z).min(self.w)
}
/// Returns the maximum of all elements.
#[inline(always)]
#[must_use]
pub fn max_elem(self) -> f32 {
self.x.max(self.y).max(self.z).max(self.w)
}
#[must_use]
#[inline]
pub fn clamp(self, min: Self, max: Self) -> Self {
Self {
x: self.x.clamp(min.x, max.x),
y: self.y.clamp(min.y, max.y),
z: self.z.clamp(min.z, max.z),
w: self.w.clamp(min.w, max.w),
}
}
}
impl core::ops::Index<usize> for Vec4 {
type Output = f32;
#[inline(always)]
fn index(&self, index: usize) -> &f32 {
match index {
0 => &self.x,
1 => &self.y,
2 => &self.z,
3 => &self.w,
_ => panic!("Vec4 index out of bounds: {index}"),
}
}
}
impl core::ops::IndexMut<usize> for Vec4 {
#[inline(always)]
fn index_mut(&mut self, index: usize) -> &mut f32 {
match index {
0 => &mut self.x,
1 => &mut self.y,
2 => &mut self.z,
3 => &mut self.w,
_ => panic!("Vec4 index out of bounds: {index}"),
}
}
}
impl Eq for Vec4 {}
impl Neg for Vec4 {
type Output = Self;
#[inline(always)]
fn neg(self) -> Self {
vec4(-self.x, -self.y, -self.z, -self.w)
}
}
impl AddAssign for Vec4 {
#[inline(always)]
fn add_assign(&mut self, rhs: Self) {
*self = Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
w: self.w + rhs.w,
};
}
}
impl SubAssign for Vec4 {
#[inline(always)]
fn sub_assign(&mut self, rhs: Self) {
*self = Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
w: self.w - rhs.w,
};
}
}
impl Add for Vec4 {
type Output = Self;
#[inline(always)]
fn add(self, rhs: Self) -> Self {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
w: self.w + rhs.w,
}
}
}
impl Add<Vec4> for &Vec4 {
type Output = Vec4;
#[inline(always)]
fn add(self, rhs: Vec4) -> Vec4 {
Vec4 {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
w: self.w + rhs.w,
}
}
}
impl Add<&Vec4> for Vec4 {
type Output = Vec4;
#[inline(always)]
fn add(self, rhs: &Vec4) -> Vec4 {
Vec4 {
x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z,
w: self.w + rhs.w,
}
}
}
impl Sub for Vec4 {
type Output = Self;
#[inline(always)]
fn sub(self, rhs: Self) -> Self {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
z: self.z - rhs.z,
w: self.w - rhs.w,
}
}
}
/// Element-wise multiplication
impl Mul<Self> for Vec4 {
type Output = Self;
#[inline(always)]
fn mul(self, vec: Self) -> Self {
Self {
x: self.x * vec.x,
y: self.y * vec.y,
z: self.z * vec.z,
w: self.w * vec.w,
}
}
}
/// Element-wise division
impl Div<Self> for Vec4 {
type Output = Self;
#[inline(always)]
fn div(self, rhs: Self) -> Self {
Self {
x: self.x / rhs.x,
y: self.y / rhs.y,
z: self.z / rhs.z,
w: self.w / rhs.w,
}
}
}
impl MulAssign<f32> for Vec4 {
#[inline(always)]
fn mul_assign(&mut self, rhs: f32) {
self.x *= rhs;
self.y *= rhs;
self.z *= rhs;
self.w *= rhs;
}
}
impl DivAssign<f32> for Vec4 {
#[inline(always)]
fn div_assign(&mut self, rhs: f32) {
self.x /= rhs;
self.y /= rhs;
self.z /= rhs;
self.w /= rhs;
}
}
impl Mul<f32> for Vec4 {
type Output = Self;
#[inline(always)]
fn mul(self, factor: f32) -> Self {
Self {
x: self.x * factor,
y: self.y * factor,
z: self.z * factor,
w: self.w * factor,
}
}
}
impl Mul<f32> for &Vec4 {
type Output = Vec4;
#[inline(always)]
fn mul(self, factor: f32) -> Vec4 {
Vec4 {
x: self.x * factor,
y: self.y * factor,
z: self.z * factor,
w: self.w * factor,
}
}
}
impl Add<f32> for Vec4 {
type Output = Self;
#[inline(always)]
fn add(self, factor: f32) -> Self {
Self {
x: self.x + factor,
y: self.y + factor,
z: self.z + factor,
w: self.w + factor,
}
}
}
impl Add<f32> for &Vec4 {
type Output = Vec4;
#[inline(always)]
fn add(self, factor: f32) -> Vec4 {
Vec4 {
x: self.x + factor,
y: self.y + factor,
z: self.z + factor,
w: self.w + factor,
}
}
}
impl Mul<Vec4> for f32 {
type Output = Vec4;
#[inline(always)]
fn mul(self, vec: Vec4) -> Vec4 {
Vec4 {
x: self * vec.x,
y: self * vec.y,
z: self * vec.z,
w: self * vec.w,
}
}
}
impl Div<f32> for Vec4 {
type Output = Self;
#[inline(always)]
fn div(self, factor: f32) -> Self {
Self {
x: self.x / factor,
y: self.y / factor,
z: self.z / factor,
w: self.w / factor,
}
}
}
impl fmt::Debug for Vec4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(precision) = f.precision() {
write!(
f,
"[{1:.0$} {2:.0$} {3:.0$} {4:.0$}]",
precision, self.x, self.y, self.z, self.w
)
} else {
write!(
f,
"[{:.1} {:.1} {:.1} {:.1}]",
self.x, self.y, self.z, self.w
)
}
}
}
impl fmt::Display for Vec4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[")?;
self.x.fmt(f)?;
f.write_str(" ")?;
self.y.fmt(f)?;
f.write_str(" ")?;
self.z.fmt(f)?;
f.write_str(" ")?;
self.w.fmt(f)?;
f.write_str("]")?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
macro_rules! almost_eq {
($left: expr, $right: expr) => {
let left = $left;
let right = $right;
assert!((left - right).abs() < 1e-6, "{} != {}", left, right);
};
}
#[test]
fn test_vec4() {
let mut assignment = vec4(1.0, 2.0, 3.0, 4.0);
assignment += vec4(3.0, 4.0, 5.0, 6.0);
assert_eq!(assignment, vec4(4.0, 6.0, 8.0, 10.0));
let mut assignment = vec4(4.0, 6.0, 8.0, 10.0);
assignment -= vec4(1.0, 2.0, 3.0, 4.0);
assert_eq!(assignment, vec4(3.0, 4.0, 5.0, 6.0));
let mut assignment = vec4(1.0, 2.0, 3.0, 4.0);
assignment *= 2.0;
assert_eq!(assignment, vec4(2.0, 4.0, 6.0, 8.0));
let mut assignment = vec4(2.0, 4.0, 6.0, 8.0);
assignment /= 2.0;
assert_eq!(assignment, vec4(1.0, 2.0, 3.0, 4.0));
}
#[test]
fn test_vec4_normalized() {
fn generate_spiral(n: usize, start: Vec4, end: Vec4) -> impl Iterator<Item = Vec4> {
let angle_step = 2.0 * core::f32::consts::PI / n as f32;
let radius_step = (end.length() - start.length()) / n as f32;
(0..n).map(move |i| {
let angle = i as f32 * angle_step;
let radius = start.length() + i as f32 * radius_step;
let x = radius * angle.cos();
let y = radius * angle.sin();
vec4(x, y, x, y)
})
}
for v in generate_spiral(40, Vec4::splat(0.1), Vec4::splat(2.0)) {
let vn = v.normalized();
almost_eq!(vn.length(), 1.0);
assert!(vn.is_normalized());
}
}
}

View File

@ -0,0 +1,259 @@
use core::ops::{Add, AddAssign, Mul, Sub};
use egui::Vec2;
use crate::math::i64vec2::{I64Vec2, i64vec2};
// https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/
// https://jtsorlinis.github.io/rendering-tutorial/
// https://www.cs.cornell.edu/courses/cs4620/2011fa/lectures/16rasterizationWeb.pdf
/// ss for screen space (unit is screen pixel)
/// sp for subpixel space (unit fraction of screen pixel)
/// Here for reference for raster without using span.
#[allow(unused)]
pub fn raster_tri<const SUBPIX_BITS: i32>(
ss_bounds: [I64Vec2; 2],
ss_tri: &[Vec2; 3],
// ss_x, ss_y
mut raster: impl FnMut(i64, i64),
) {
let Some((ss_min, ss_max, _sp_inv_area, mut stepper)) =
SingleStepper::from_ss_tri_backface_cull::<SUBPIX_BITS>(ss_bounds, ss_tri)
else {
return;
};
for ss_y in ss_min.y..ss_max.y {
stepper.row_start();
for ss_x in ss_min.x..ss_max.x {
if stepper.inside_tri_pos_area() {
raster(ss_x, ss_y);
}
stepper.col_step();
}
stepper.row_step();
}
}
#[inline(always)]
pub fn is_top_left(a: &I64Vec2, b: &I64Vec2) -> bool {
let dy = b.y - a.y;
(dy > 0) || (dy == 0 && (b.x - a.x) < 0)
}
pub struct SingleStepper {
/// Edge subpixel barycentric steps. (edges are: 12, 20, 01)
pub step: [SingleStep; 3],
/// Edge subpixel space barycentric weights. Divide by subpixel area for barycentric factors.
pub sp_weight: [i64; 3],
/// Edge subpixel bias for watertightness. These are applied on SingleStepper::row_start(). If you're using
/// something else you'll need to apply them to sp_weight.
pub bias: [i8; 3],
}
impl SingleStepper {
/// For the given subpixel resolution, calculate the screen space bounds, subpixel inverse area, and subpixel Stepper.
/// returns: ss_min, ss_max, sp_inv_area, stepper
pub fn from_ss_tri_backface_cull<const SUBPIX_BITS: i32>(
ss_bounds: [I64Vec2; 2],
ss_tri: &[Vec2; 3],
) -> Option<(I64Vec2, I64Vec2, f32, SingleStepper)> {
let subpix_bits = SUBPIX_BITS as u32;
let subpix: i64 = 1 << subpix_bits;
let subpix_half: i64 = subpix >> 1;
let fsubpix = subpix as f32;
let sp0 = I64Vec2::from_vec2(ss_tri[0] * fsubpix);
let sp1 = I64Vec2::from_vec2(ss_tri[1] * fsubpix);
let sp2 = I64Vec2::from_vec2(ss_tri[2] * fsubpix);
let sp_area = orient2d(&sp0, &sp1, &sp2);
if sp_area <= 0 {
return None;
}
let sp_min = sp0.min(sp1).min(sp2);
let sp_max = sp0.max(sp1).max(sp2);
let ss_min = ((sp_min - subpix_half) >> subpix_bits)
.max(ss_bounds[0])
.min(ss_bounds[1]);
let ss_max = ((sp_max + subpix_half) >> subpix_bits)
.max(ss_bounds[0])
.min(ss_bounds[1]);
let sp_min_p = ss_min * subpix + subpix_half;
let ss_size = ss_max - ss_min;
if ss_size.x <= 0 || ss_size.y <= 0 {
return None;
}
let sp_inv_area = 1.0 / (sp_area as f32);
let stepper = SingleStepper::new(&sp0, &sp1, &sp2, &sp_min_p, subpix);
Some((ss_min, ss_max, sp_inv_area, stepper))
}
pub fn new(
sp0: &I64Vec2,
sp1: &I64Vec2,
sp2: &I64Vec2,
sp_min_p: &I64Vec2,
subpix: i64,
) -> Self {
SingleStepper {
step: [
SingleStep::new(sp1, sp2, sp_min_p, subpix),
SingleStep::new(sp2, sp0, sp_min_p, subpix),
SingleStep::new(sp0, sp1, sp_min_p, subpix),
],
sp_weight: [0; 3],
bias: [
if is_top_left(sp1, sp2) { 0 } else { -1 },
if is_top_left(sp2, sp0) { 0 } else { -1 },
if is_top_left(sp0, sp1) { 0 } else { -1 },
],
}
}
#[inline(always)]
/// Check if the current step of the stepper is inside the triangle.
pub fn inside_tri_pos_area(&self) -> bool {
// None w are negative
let m =
(self.sp_weight[0] as u64) | (self.sp_weight[1] as u64) | (self.sp_weight[2] as u64);
(m & 0x8000_0000_0000_0000) == 0
}
#[inline(always)]
/// Take one step along y to the next row.
pub fn row_step(&mut self) {
self.step[0].row += self.step[0].step.y;
self.step[1].row += self.step[1].step.y;
self.step[2].row += self.step[2].step.y;
}
#[inline(always)]
/// Take one step along x to the next column.
pub fn col_step(&mut self) {
self.sp_weight[0] += self.step[0].step.x;
self.sp_weight[1] += self.step[1].step.x;
self.sp_weight[2] += self.step[2].step.x;
}
#[inline(always)]
/// Initialize weights to the start of the current row and apply the bias.
pub fn row_start(&mut self) {
self.sp_weight[0] = self.step[0].row + self.bias[0] as i64;
self.sp_weight[1] = self.step[1].row + self.bias[1] as i64;
self.sp_weight[2] = self.step[2].row + self.bias[2] as i64;
}
/// Generate stepper for float attribute (like vertex UVs or vertex colors)
/// Depends on SingleStepper's initial state. Make sure to run before using SingleStepper::row_step() or
/// SingleStepper::col_step()
pub fn attr<T>(&self, attr: &[T; 3], sp_inv_area: f32) -> AttributeStepper<T>
where
T: Copy + Add<Output = T> + Sub<Output = T> + AddAssign + Mul<f32, Output = T>,
{
// Get attribute value of top left
let w0 = self.step[0].row;
let w1 = self.step[1].row;
let (b0, b1, b2) = subpixel_bary_to_factor(w0, w1, sp_inv_area);
let attr_tl = attr[0] * b0 + attr[1] * b1 + attr[2] * b2;
// Get attribute value of one x step right from top left
let w0sx = w0 + self.step[0].step.x;
let w1sx = w1 + self.step[1].step.x;
let (b0, b1, b2) = subpixel_bary_to_factor(w0sx, w1sx, sp_inv_area);
let attr_1x = attr[0] * b0 + attr[1] * b1 + attr[2] * b2;
// Get attribute value of one y step down from top left
let w0sy = w0 + self.step[0].step.y;
let w1sy = w1 + self.step[1].step.y;
let (b0, b1, b2) = subpixel_bary_to_factor(w0sy, w1sy, sp_inv_area);
let attr_1y = attr[0] * b0 + attr[1] * b1 + attr[2] * b2;
// Compute deltas
let step_x = attr_1x - attr_tl;
let step_y = attr_1y - attr_tl;
let row = attr_tl;
AttributeStepper {
step_x,
step_y,
row,
attr: attr_tl,
}
}
}
pub struct SingleStep {
pub step: I64Vec2,
pub row: i64,
}
impl SingleStep {
#[inline(always)]
pub fn new(sp0: &I64Vec2, sp1: &I64Vec2, sp_min_p: &I64Vec2, subpix: i64) -> Self {
let a = sp0.y - sp1.y;
let b = sp1.x - sp0.x;
let c = (sp0.x) * (sp1.y) - (sp0.y) * (sp1.x);
Self {
step: i64vec2(a * subpix, b * subpix),
row: a * sp_min_p.x + b * sp_min_p.y + c,
}
}
}
#[inline(always)]
/// Returns twice the signed area of triangle abc
pub fn orient2d(a: &I64Vec2, b: &I64Vec2, c: &I64Vec2) -> i64 {
(b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}
#[inline(always)]
/// Convert subpixel space barycentric weights to barycentric factors (0..1)
pub fn subpixel_bary_to_factor(sp_w0: i64, sp_w1: i64, inv_area: f32) -> (f32, f32, f32) {
let b0 = (sp_w0 as f32) * inv_area;
let b1 = (sp_w1 as f32) * inv_area;
let b2 = 1.0 - b0 - b1;
(b0, b1, b2)
}
#[derive(Default)]
pub struct AttributeStepper<T>
where
T: Copy + Add<Output = T> + Sub<Output = T> + AddAssign + Mul<f32, Output = T>,
{
pub step_x: T,
pub step_y: T,
pub row: T,
pub attr: T,
}
impl<T> AttributeStepper<T>
where
T: Copy + Add<Output = T> + Sub<Output = T> + AddAssign + Mul<f32, Output = T>,
{
#[inline(always)]
pub fn row_step(&mut self) {
self.row += self.step_y;
}
#[inline(always)]
pub fn col_step(&mut self) {
self.attr += self.step_x;
}
#[inline(always)]
pub fn row_start(&mut self) {
self.attr = self.row;
}
}

View File

@ -0,0 +1,4 @@
pub(crate) mod bary;
pub(crate) mod rect;
pub(crate) mod span;
pub(crate) mod tri;

View File

@ -0,0 +1,134 @@
use constify::constify;
use egui::{Vec2, vec2};
use crate::{BufferMutRef, color::SelectedImpl, egui_texture::EguiTexture, render::DrawInfo};
#[constify]
pub fn draw_rect(
simd_impl: impl SelectedImpl,
buffer: &mut BufferMutRef,
texture: &EguiTexture,
draw: &DrawInfo,
#[constify] vert_col_vary: bool,
#[constify] vert_uvs_vary: bool,
#[constify] alpha_blend: bool,
) {
simd_impl.dispatch(|simd_impl| {
draw_rect_impl::<vert_col_vary, vert_uvs_vary, alpha_blend>(
simd_impl, buffer, texture, draw,
)
})
}
#[inline]
#[allow(non_upper_case_globals)]
fn draw_rect_impl<const vert_col_vary: bool, const vert_uvs_vary: bool, const alpha_blend: bool>(
simd_impl: impl SelectedImpl,
buffer: &mut BufferMutRef,
texture: &EguiTexture,
draw: &DrawInfo,
) {
let const_tri_color_u8x4 = draw.const_tri_color_u8x4;
let clip_bounds = &draw.clip_bounds;
let tri_min = draw.tri_min;
let tri_max = draw.tri_max;
let min_x = ((tri_min.x + 0.5) as i64).max(clip_bounds[0].x);
let min_y = ((tri_min.y + 0.5) as i64).max(clip_bounds[0].y);
let max_x = ((tri_max.x + 0.5) as i64).min(clip_bounds[1].x);
let max_y = ((tri_max.y + 0.5) as i64).min(clip_bounds[1].y);
let sizex = max_x - min_x;
let sizey = max_y - min_y;
if sizex <= 0 || sizey <= 0 {
return;
}
let min_x = min_x as usize;
let min_y = min_y as usize;
let max_x = max_x as usize;
let max_y = max_y as usize;
if !vert_uvs_vary && !vert_col_vary {
for y in min_y..max_y {
if alpha_blend {
simd_impl.egui_blend_u8_slice_one_src(
const_tri_color_u8x4,
buffer.get_mut_span(min_x, max_x, y),
);
} else {
buffer
.get_mut_span(min_x, max_x, y)
.fill(const_tri_color_u8x4);
}
}
} else {
// TODO could another level of constify make this cleaner (const use_nearest_sampling?)
let mut min_uv = vec2(
draw.uv[0].x.min(draw.uv[1].x).min(draw.uv[2].x),
draw.uv[0].y.min(draw.uv[1].y).min(draw.uv[2].y),
);
let max_uv = vec2(
draw.uv[0].x.max(draw.uv[1].x).max(draw.uv[2].x),
draw.uv[0].y.max(draw.uv[1].y).max(draw.uv[2].y),
);
let uv_step = (max_uv - min_uv) / (tri_max - tri_min);
min_uv += uv_step * (vec2(min_x as f32, min_y as f32) - tri_min).max(Vec2::ZERO); // Offset to account for clip
min_uv += uv_step * 0.5; // Raster at pixel centers
let ts_min = min_uv * texture.fsize;
let ts_max = max_uv * texture.fsize;
let use_nearest_sampling = {
let ss_step = uv_step * texture.fsize;
let dist_from_px_center = (ts_min - ts_min.floor() - vec2(0.5, 0.5)).abs();
let steps_off_from_1px = (ss_step - Vec2::ONE).abs();
let eps = 0.01;
let steps_are_1px = steps_off_from_1px.x < eps && steps_off_from_1px.y < eps;
let start_on_texture_px_center =
dist_from_px_center.x < eps && dist_from_px_center.y < eps;
steps_are_1px && start_on_texture_px_center
};
let no_texture_wrap_or_overflow =
(ts_max.x as usize) < texture.width && (ts_max.y as usize) < texture.height;
if use_nearest_sampling && no_texture_wrap_or_overflow {
// Can just directly blend the texture over the dst buffer, no need to sample with uv
let min_uv = [ts_min.x as i32, ts_min.y as i32];
let mut tex_row = min_uv[1];
for y in min_y..max_y {
let tex_row_start = tex_row as usize * texture.width;
let tex_start = tex_row_start + min_uv[0] as usize;
let tex_end = tex_start + max_x - min_x;
let dst = &mut buffer.get_mut_span(min_x, max_x, y);
let src = &texture.data[tex_start..tex_end];
simd_impl.egui_blend_u8_slice_tinted(src, draw.const_vert_color_u8x4, dst);
tex_row += 1;
}
} else {
// There's overflow or can't use nearest. So we need to do full sample.
// TODO perf: there could be a situation where we could nearest sample but with wrapping/clipping.
// We don't have a fast path for that and are falling back to the more general solution below.
// This would be (use_nearest_sampling && !no_texture_wrap_or_overflow) which at least never occurs in the
// demo as far as I can tell
let mut uv = min_uv;
for y in min_y..max_y {
uv.x = min_uv.x;
let buf_y = y * buffer.width;
for x in min_x..max_x {
let tex_color = texture.sample_bilinear(uv);
let pixel = &mut buffer.data[x + buf_y];
let src = simd_impl.unorm_mult4x4(draw.const_vert_color_u8x4, tex_color);
*pixel = simd_impl.egui_blend_u8(src, *pixel);
uv.x += uv_step.x;
}
uv.y += uv_step.y;
}
}
};
}

View File

@ -0,0 +1,66 @@
use crate::raster::bary::SingleStepper;
use strength_reduce::StrengthReducedU64;
/// Returns Some((start, end)) for the current row in the triangle. The end points are defined within the aabb of the
/// triangle so add ss_min.x to each to get the screen space coordinate. Returns None if there is no span intersecting
/// this row.
pub fn calc_row_span(
stepper: &SingleStepper,
max_cols: i64,
step_rcp: &[StrengthReducedU64; 3],
) -> Option<(i64, i64)> {
let mut start = 0;
let mut end = u64::MAX;
let w = &stepper.sp_weight;
let sx = [
stepper.step[0].step.x,
stepper.step[1].step.x,
stepper.step[2].step.x,
];
for i in 0..3 {
let w = w[i];
let sx = sx[i];
let step_rcp = step_rcp[i];
if w < 0 {
if sx > 0 {
// unoptimized: start = start.max(div_ceil(-w, sx));
start = start.max(div_ceil_sr(-w as u64, step_rcp));
} else {
return None;
}
} else if sx < 0 {
// unoptimized: end = end.min(div_floor(w, -sx) + 1);
// sx < 0 and stepper.step_x_rcp is already abs so no need to negate
// w >= 0 due to if condition above so cast to u64 is fine
end = end.min((w as u64 / step_rcp) + 1);
}
}
end = end.clamp(0, max_cols as u64);
if start >= end {
return None;
}
Some((start as i64, end as i64))
}
// based on https://github.com/rust-lang/rust/blob/e4b521903b3b1a671e26a70b9475bcff385767e5/library/core/src/num/int_macros.rs#L3238
#[inline(always)]
pub fn div_ceil_sr(lhs: u64, rhs: StrengthReducedU64) -> u64 {
let (d, r) = StrengthReducedU64::div_rem(lhs, rhs);
// When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b),
// so we can re-use the algorithm from div_floor, just adding 1.
let correction = 1 + ((lhs ^ rhs.get()) >> (u64::BITS - 1));
if r != 0 { d + correction } else { d }
}
pub fn step_rcp(stepper: &SingleStepper) -> [StrengthReducedU64; 3] {
// max(1) is fine here since the element will already be skipped if step.x == 0
[
StrengthReducedU64::new(stepper.step[0].step.x.abs().max(1) as u64),
StrengthReducedU64::new(stepper.step[1].step.x.abs().max(1) as u64),
StrengthReducedU64::new(stepper.step[2].step.x.abs().max(1) as u64),
]
}

View File

@ -0,0 +1,142 @@
use constify::constify;
use crate::{
BufferMutRef,
color::{SelectedImpl, vec4_to_u8x4},
egui_texture::EguiTexture,
raster::{
bary::SingleStepper,
span::{calc_row_span, step_rcp},
},
render::DrawInfo,
};
#[constify]
pub fn draw_tri<const SUBPIX_BITS: i32>(
simd_impl: impl SelectedImpl,
buffer: &mut BufferMutRef,
texture: &EguiTexture,
draw: &DrawInfo,
#[constify] vert_col_vary: bool,
#[constify] vert_uvs_vary: bool,
#[constify] alpha_blend: bool,
) {
simd_impl.dispatch(|simd_impl| {
draw_tri_impl::<SUBPIX_BITS, vert_col_vary, vert_uvs_vary, alpha_blend>(
simd_impl, buffer, texture, draw,
)
})
}
#[inline]
#[allow(non_upper_case_globals)]
fn draw_tri_impl<
const SUBPIX_BITS: i32,
const vert_col_vary: bool,
const vert_uvs_vary: bool,
const alpha_blend: bool,
>(
simd_impl: impl SelectedImpl,
buffer: &mut BufferMutRef,
texture: &EguiTexture,
draw: &DrawInfo,
) {
let Some((ss_min, ss_max, sp_inv_area, mut stepper)) =
SingleStepper::from_ss_tri_backface_cull::<SUBPIX_BITS>(draw.clip_bounds, &draw.ss_tri)
else {
return;
};
let step_rcp = step_rcp(&stepper);
let mut vert_col_stepper = if vert_col_vary {
stepper.attr(&draw.colors, sp_inv_area)
} else {
Default::default()
};
let mut vert_uv_stepper = if vert_uvs_vary {
stepper.attr(&draw.uv, sp_inv_area)
} else {
Default::default()
};
let max_cols = ss_max.x - ss_min.x;
for ss_y in ss_min.y..ss_max.y {
stepper.row_start();
if vert_col_vary {
vert_col_stepper.row_start();
}
if vert_uvs_vary {
vert_uv_stepper.row_start();
}
if let Some((start, end)) = calc_row_span(&stepper, max_cols, &step_rcp) {
if vert_col_vary {
vert_col_stepper.attr += vert_col_stepper.step_x * start as f32;
}
if vert_uvs_vary {
vert_uv_stepper.attr += vert_uv_stepper.step_x * start as f32;
}
let ss_start = (ss_min.x + start) as usize;
let ss_end = (ss_min.x + end) as usize;
if alpha_blend && !vert_uvs_vary {
let dst = buffer.get_mut_span(ss_start, ss_end, ss_y as usize);
if vert_col_vary {
simd_impl.egui_blend_u8_slice_one_src_tinted_fn(
draw.const_tex_color_u8x4,
|| {
let v = vec4_to_u8x4(&vert_col_stepper.attr);
vert_col_stepper.col_step();
v
},
dst,
)
} else {
simd_impl.egui_blend_u8_slice_one_src(draw.const_tri_color_u8x4, dst)
}
} else {
for ss_x in ss_start..ss_end {
let src = if vert_uvs_vary || vert_col_vary {
let tex_color = if vert_uvs_vary {
texture.sample_bilinear(vert_uv_stepper.attr)
} else {
draw.const_tex_color_u8x4
};
let vert_color = if vert_col_vary {
vec4_to_u8x4(&vert_col_stepper.attr)
} else {
draw.const_vert_color_u8x4
};
crate::color::GenericImpl.unorm_mult4x4(vert_color, tex_color)
//^ `simd_impl.unorm_mult4x4` is slower at least in avx2 and sse4.1
} else {
draw.const_tri_color_u8x4
};
let pixel = buffer.get_mut(ss_x, ss_y as usize);
*pixel = if alpha_blend {
simd_impl.egui_blend_u8(src, *pixel)
} else {
src
};
if vert_col_vary {
vert_col_stepper.col_step();
}
if vert_uvs_vary {
vert_uv_stepper.col_step();
}
}
}
};
stepper.row_step();
if vert_col_vary {
vert_col_stepper.row_step();
}
if vert_uvs_vary {
vert_uv_stepper.row_step();
}
}
}

View File

@ -0,0 +1,325 @@
#![allow(unsafe_code)]
use crate::{
BufferMutRef, EguiTexture,
color::{AvailableImpl, SelectedImpl, u8x4_to_vec4, vec4_to_u8x4},
math::{
i64vec2::{I64Vec2, i64vec2},
vec4::Vec4,
},
raster::{rect::draw_rect, tri::draw_tri},
};
use egui::{Pos2, Vec2, ahash::HashMap, epaint::Vertex, vec2};
#[allow(clippy::too_many_arguments)]
pub fn draw_egui_mesh<const SUBPIX_BITS: i32>(
simd_impl: AvailableImpl,
textures: &HashMap<egui::TextureId, EguiTexture>,
buffer: &mut BufferMutRef,
clip_rect: &egui::Rect,
mesh: &egui::Mesh,
vert_offset: Vec2,
allow_raster_opt: bool,
convert_tris_to_rects: bool,
#[cfg(all(feature = "raster_stats", not(feature = "rayon")))]
stats: &mut crate::stats::RasterStats,
) {
crate::dispatch_simd_impl!(simd_impl, |simd_impl| draw_egui_mesh_impl::<SUBPIX_BITS>(
simd_impl,
textures,
buffer,
clip_rect,
mesh,
vert_offset,
allow_raster_opt,
convert_tris_to_rects,
#[cfg(all(feature = "raster_stats", not(feature = "rayon")))]
stats,
))
}
#[allow(clippy::too_many_arguments)]
fn draw_egui_mesh_impl<const SUBPIX_BITS: i32>(
simd_impl: impl SelectedImpl,
textures: &HashMap<egui::TextureId, EguiTexture>,
buffer: &mut BufferMutRef,
clip_rect: &egui::Rect,
mesh: &egui::Mesh,
vert_offset: Vec2,
allow_raster_opt: bool,
convert_tris_to_rects: bool,
#[cfg(all(feature = "raster_stats", not(feature = "rayon")))]
stats: &mut crate::stats::RasterStats,
) {
if mesh.vertices.is_empty() || mesh.indices.is_empty() {
return;
}
let Some(texture) = textures.get(&mesh.texture_id) else {
return;
};
if allow_raster_opt && crate::fast_image::draw(buffer, clip_rect, mesh, vert_offset, texture) {
return;
}
let indices = &mesh.indices;
let vertices = &mesh.vertices;
let clip_bounds = [
i64vec2(
(clip_rect.min.x as i64).clamp(0, buffer.width as i64),
(clip_rect.min.y as i64).clamp(0, buffer.height as i64),
),
i64vec2(
(clip_rect.max.x.ceil() as i64).clamp(0, buffer.width as i64),
(clip_rect.max.y.ceil() as i64).clamp(0, buffer.height as i64),
),
];
if clip_bounds[1].x - clip_bounds[0].x <= 0 || clip_bounds[1].y - clip_bounds[0].y <= 0 {
return;
}
let mut i = 0;
// Get texture
while i < indices.len() {
let mut tri = [
vertices[indices[i] as usize],
vertices[indices[i + 1] as usize],
vertices[indices[i + 2] as usize],
];
tri[0].pos += vert_offset;
tri[1].pos += vert_offset;
tri[2].pos += vert_offset;
let tri_min = vec2(
tri[0].pos.x.min(tri[1].pos.x).min(tri[2].pos.x),
tri[0].pos.y.min(tri[1].pos.y).min(tri[2].pos.y),
);
let tri_max = vec2(
tri[0].pos.x.max(tri[1].pos.x).max(tri[2].pos.x),
tri[0].pos.y.max(tri[1].pos.y).max(tri[2].pos.y),
);
let fsize = tri_max - tri_min;
if fsize.x <= 0.0 || fsize.y <= 0.0 {
i += 3;
continue;
}
let color0_u8x4 = tri[0].color.to_array();
let color1_u8x4 = tri[1].color.to_array();
let color2_u8x4 = tri[2].color.to_array();
let mut draw = DrawInfo::new(
clip_bounds,
[
u8x4_to_vec4(&color0_u8x4),
u8x4_to_vec4(&color1_u8x4),
u8x4_to_vec4(&color2_u8x4),
],
[
tri[0].pos.to_vec2(),
tri[1].pos.to_vec2(),
tri[2].pos.to_vec2(),
],
[
vec2(tri[0].uv.x, tri[0].uv.y),
vec2(tri[1].uv.x, tri[1].uv.y),
vec2(tri[2].uv.x, tri[2].uv.y),
],
tri_min,
tri_max,
);
if !allow_raster_opt {
draw_tri::<SUBPIX_BITS>(simd_impl, buffer, texture, &draw, true, true, true);
i += 3;
continue;
}
let mut vert_uvs_vary = !(draw.uv[0] == draw.uv[1] && draw.uv[0] == draw.uv[2]);
let mut vert_col_vary = !(color0_u8x4 == color1_u8x4 && color0_u8x4 == color2_u8x4);
let mut alpha_blend = true;
if !vert_uvs_vary {
draw.const_tex_color_u8x4 = texture.sample_bilinear(draw.uv[0]);
draw.const_tex_color = u8x4_to_vec4(&draw.const_tex_color_u8x4);
}
if !vert_col_vary {
draw.const_vert_color = draw.colors[0];
draw.const_vert_color_u8x4 = color0_u8x4;
}
if !vert_uvs_vary && !vert_col_vary {
let const_tri_color = draw.const_vert_color * draw.const_tex_color;
draw.const_tri_color_u8x4 = vec4_to_u8x4(&const_tri_color);
if draw.const_tri_color_u8x4[3] == 255 {
alpha_blend = false;
}
}
if !vert_uvs_vary
&& vert_col_vary
&& draw.const_tex_color_u8x4[3] == 255
&& color0_u8x4[3] == 255
&& color1_u8x4[3] == 255
&& color2_u8x4[3] == 255
{
alpha_blend = false;
}
let find_rects = convert_tris_to_rects && !vert_col_vary && i + 6 < indices.len();
let mut found_rect = false;
if find_rects {
let mut tri2 = [
vertices[indices[i + 3] as usize],
vertices[indices[i + 4] as usize],
vertices[indices[i + 5] as usize],
];
tri2[0].pos += vert_offset;
tri2[1].pos += vert_offset;
tri2[2].pos += vert_offset;
found_rect = tri_verts_match_corners(tri_min, tri_max, tri, tri2);
if found_rect {
let tri_area = egui_orient2df(&tri[0].pos, &tri[1].pos, &tri[2].pos).abs();
let rect_area = (tri_max.x - tri_min.x) * (tri_max.y - tri_min.y);
let areas_match = (tri_area - rect_area).abs() < 0.5;
if areas_match {
if rect_area.abs() < 0.25 {
i += 6; // Skip both tris
continue; // early out of rects smaller than quarter px
}
if !vert_uvs_vary {
let tri2_uvs_match = tri[0].uv == tri2[0].uv
&& tri[0].uv == tri2[1].uv
&& tri[0].uv == tri2[2].uv;
vert_uvs_vary = vert_uvs_vary && tri2_uvs_match;
}
if !vert_col_vary {
let tri2_colors_match = tri[0].color == tri2[0].color
&& tri[0].color == tri2[1].color
&& tri[0].color == tri2[2].color;
vert_col_vary = vert_col_vary && tri2_colors_match;
}
} else {
found_rect = false;
}
}
}
let rect = found_rect && !vert_col_vary; // vert_col_vary not supported by rect render
#[cfg(all(feature = "raster_stats", not(feature = "rayon")))]
stats.start_raster();
if rect {
draw_rect(
simd_impl,
buffer,
texture,
&draw,
vert_col_vary,
vert_uvs_vary,
alpha_blend,
);
#[cfg(all(feature = "raster_stats", not(feature = "rayon")))]
stats.finish_rect(fsize, vert_uvs_vary, vert_col_vary, alpha_blend);
i += 6;
} else {
draw_tri::<SUBPIX_BITS>(
simd_impl,
buffer,
texture,
&draw,
vert_col_vary,
vert_uvs_vary,
alpha_blend,
);
#[cfg(all(feature = "raster_stats", not(feature = "rayon")))]
stats.finish_tri(fsize, vert_uvs_vary, vert_col_vary, alpha_blend);
i += 3;
}
}
}
pub struct DrawInfo {
pub clip_bounds: [I64Vec2; 2],
pub colors: [Vec4; 3],
pub ss_tri: [Vec2; 3],
pub uv: [Vec2; 3],
pub tri_min: Vec2,
pub tri_max: Vec2,
pub const_tex_color: Vec4,
pub const_tex_color_u8x4: [u8; 4],
pub const_vert_color: Vec4,
pub const_vert_color_u8x4: [u8; 4],
pub const_tri_color_u8x4: [u8; 4],
}
impl DrawInfo {
fn new(
clip_bounds: [I64Vec2; 2],
colors: [Vec4; 3],
ss_tri: [Vec2; 3],
uv: [Vec2; 3],
tri_min: Vec2,
tri_max: Vec2,
) -> Self {
Self {
clip_bounds,
colors,
ss_tri,
uv,
tri_min,
tri_max,
const_tex_color: Vec4::ONE,
const_tex_color_u8x4: [255; 4],
const_vert_color: Vec4::ONE,
const_vert_color_u8x4: [255; 4],
const_tri_color_u8x4: [255; 4],
}
}
}
#[inline(always)]
/// Returns twice the signed area of triangle abc
pub fn egui_orient2df(a: &Pos2, b: &Pos2, c: &Pos2) -> f32 {
(b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}
fn tri_verts_match_corners(
tri_min: Vec2,
tri_max: Vec2,
tri: [Vertex; 3],
tri2: [Vertex; 3],
) -> bool {
#[inline(always)]
fn close(a: f32, b: f32) -> bool {
//(a - b).abs() <= 0.1
a == b
}
// https://github.com/emilk/imgui_software_renderer/blob/b5ae63a9e42eccf7db3bf64696761a53424c53dd/src/imgui_sw.cpp#L577
(close(tri[0].pos.x, tri_min.x) || close(tri[0].pos.x, tri_max.x))
&& (close(tri[0].pos.y, tri_min.y) || close(tri[0].pos.y, tri_max.y))
&& (close(tri[1].pos.x, tri_min.x) || close(tri[1].pos.x, tri_max.x))
&& (close(tri[1].pos.y, tri_min.y) || close(tri[1].pos.y, tri_max.y))
&& (close(tri[2].pos.x, tri_min.x) || close(tri[2].pos.x, tri_max.x))
&& (close(tri[2].pos.y, tri_min.y) || close(tri[2].pos.y, tri_max.y))
&& (close(tri2[0].pos.x, tri_min.x) || close(tri2[0].pos.x, tri_max.x))
&& (close(tri2[0].pos.y, tri_min.y) || close(tri2[0].pos.y, tri_max.y))
&& (close(tri2[1].pos.x, tri_min.x) || close(tri2[1].pos.x, tri_max.x))
&& (close(tri2[1].pos.y, tri_min.y) || close(tri2[1].pos.y, tri_max.y))
&& (close(tri2[2].pos.x, tri_min.x) || close(tri2[2].pos.x, tri_max.x))
&& (close(tri2[2].pos.y, tri_min.y) || close(tri2[2].pos.y, tri_max.y))
}

View File

@ -0,0 +1,258 @@
use crate::alloc::string::ToString;
use alloc::format;
use alloc::vec::Vec;
use egui::ahash::HashMap;
use std::time::Instant;
#[allow(unused_imports)]
use egui::{Ui, Vec2, Vec2b};
#[derive(Clone, Copy)]
pub struct Stat {
pub count: u32,
pub time: f32,
pub sum_area: f32,
}
pub struct RasterStats {
pub tri_width_buckets: HashMap<u32, Stat>, // Key is tri width
pub tri_height_buckets: HashMap<u32, Stat>, // Key is tri height
pub rect_width_buckets: HashMap<u32, Stat>, // Key is rect width
pub rect_height_buckets: HashMap<u32, Stat>, // Key is rect height
pub tri_vert_col_vary: u32, // Count of tris where the vertex colors varied
pub tri_vert_uvs_vary: u32, // Count of tris where the vertex uvs varied
pub tri_alpha_blend: u32, // Count of tris that required alpha blending
pub rect_vert_col_vary: u32, // Count of rects where the vertex colors varied
pub rect_vert_uvs_vary: u32, // Count of rects where the vertex uvs varied
pub rect_alpha_blend: u32, // Count of rects that required alpha blending
pub tris: u32, // Total tris drawn
pub rects: u32, // Total rects drawn
pub start: Instant, // Time just before latest rasterization
pub set_textures: f32,
pub update_dirty_tiles: f32,
pub update_canvas_from_cached: f32,
pub render_prims_to_cache: f32,
pub render_direct: f32,
pub blit_canvas_to_buffer: f32,
}
impl Default for RasterStats {
fn default() -> Self {
Self {
tri_width_buckets: Default::default(),
tri_height_buckets: Default::default(),
tri_vert_col_vary: Default::default(),
tri_vert_uvs_vary: Default::default(),
tri_alpha_blend: Default::default(),
rect_width_buckets: Default::default(),
rect_height_buckets: Default::default(),
rect_vert_col_vary: Default::default(),
rect_vert_uvs_vary: Default::default(),
rect_alpha_blend: Default::default(),
rects: Default::default(),
tris: Default::default(),
set_textures: Default::default(),
update_dirty_tiles: Default::default(),
update_canvas_from_cached: Default::default(),
render_prims_to_cache: Default::default(),
render_direct: Default::default(),
blit_canvas_to_buffer: Default::default(),
start: Instant::now(),
}
}
}
#[cfg(not(feature = "rayon"))]
fn insert_or_increment(long_side_size: u32, elapsed: f32, area: f32, map: &mut HashMap<u32, Stat>) {
if let Some(stat) = map.get_mut(&long_side_size) {
stat.count += 1;
stat.time += elapsed;
stat.sum_area += area;
} else {
map.insert(
long_side_size,
Stat {
count: 1,
time: elapsed,
sum_area: area,
},
);
}
}
impl RasterStats {
pub(crate) fn clear(&mut self) {
*self = RasterStats::default();
}
#[cfg(not(feature = "rayon"))]
pub(crate) fn start_raster(&mut self) {
self.start = Instant::now();
}
#[cfg(not(feature = "rayon"))]
pub(crate) fn finish_rect(
&mut self,
fsize: Vec2,
vert_uvs_vary: bool,
vert_col_vary: bool,
alpha_blend: bool,
) {
let elapsed = self.start.elapsed().as_secs_f32();
self.rects += 1;
let tri_area = (fsize.x * fsize.y) * 0.5;
insert_or_increment(
(fsize.x as u32).max(1),
elapsed,
tri_area,
&mut self.rect_width_buckets,
);
insert_or_increment(
(fsize.y as u32).max(1),
elapsed,
tri_area,
&mut self.rect_height_buckets,
);
self.rect_vert_col_vary += vert_col_vary as u32;
self.rect_vert_uvs_vary += vert_uvs_vary as u32;
self.rect_alpha_blend += alpha_blend as u32;
}
#[cfg(not(feature = "rayon"))]
pub(crate) fn finish_tri(
&mut self,
fsize: Vec2,
vert_uvs_vary: bool,
vert_col_vary: bool,
alpha_blend: bool,
) {
let elapsed = self.start.elapsed().as_secs_f32();
self.tris += 1;
let rect_area = fsize.x * fsize.y;
insert_or_increment(
(fsize.x as u32).max(1),
elapsed,
rect_area,
&mut self.tri_width_buckets,
);
insert_or_increment(
(fsize.y as u32).max(1),
elapsed,
rect_area,
&mut self.tri_height_buckets,
);
self.tri_vert_col_vary += vert_col_vary as u32;
self.tri_vert_uvs_vary += vert_uvs_vary as u32;
self.tri_alpha_blend += alpha_blend as u32;
}
pub fn render(&self, ui: &mut Ui) {
egui::ScrollArea::both()
.auto_shrink(Vec2b::new(false, false))
.min_scrolled_width(900.0)
.show(ui, |ui| {
egui::Grid::new("stats_grid").striped(true).show(ui, |ui| {
let mut stat = |label: &str, val: f32| {
ui.label(label);
ui.label(format!("{:.2}ms", val * 1000.0));
ui.end_row();
};
stat("set_textures", self.set_textures);
stat("render_prims_to_cache", self.render_prims_to_cache);
stat("update_dirty_tiles", self.update_dirty_tiles);
stat("update_canvas_from_cached", self.update_canvas_from_cached);
stat("blit_canvas_to_buffer", self.blit_canvas_to_buffer);
stat("render_direct", self.render_direct);
ui.heading("");
ui.heading("Tri");
ui.heading("Rect");
ui.end_row();
let mut stat = |label: &str, val: u32, val2: u32| {
ui.label(label);
ui.label(val.to_string());
ui.label(val2.to_string());
ui.end_row();
};
stat(
"Vertex colors vary",
self.tri_vert_col_vary,
self.rect_vert_col_vary,
);
stat(
"Vertex uvs vary",
self.tri_vert_uvs_vary,
self.rect_vert_uvs_vary,
);
stat(
"Requires alpha blend",
self.tri_alpha_blend,
self.rect_alpha_blend,
);
});
ui.label("");
ui.end_row();
fn collect_and_sort(map: &HashMap<u32, Stat>) -> Vec<(u32, Stat)> {
let mut v: Vec<_> = map.iter().map(|(&k, &s)| (k, s)).collect();
v.sort_by_key(|&(_, s)| std::cmp::Reverse((s.time * 1000000.0) as u32)); // Seconds to microseconds
v
}
let tri_width_bucket = collect_and_sort(&self.tri_width_buckets);
let tri_height_bucket = collect_and_sort(&self.tri_height_buckets);
let rect_width_bucket = collect_and_sort(&self.rect_width_buckets);
let rect_height_bucket = collect_and_sort(&self.rect_height_buckets);
let max_rows = tri_width_bucket
.len()
.max(tri_height_bucket.len())
.max(rect_width_bucket.len())
.max(rect_height_bucket.len());
egui::Grid::new("stats_grid2").striped(true).show(ui, |ui| {
ui.heading("Tris");
ui.heading(format!("{}", self.tris));
(0..=5).for_each(|_| _ = ui.heading(""));
ui.heading(" ");
ui.heading("Rects");
ui.heading(format!("{}", self.rects));
(0..=5).for_each(|_| _ = ui.heading(""));
ui.end_row();
let headers = ["W", "Qty", "μs", "area"];
headers.iter().for_each(|s| _ = ui.heading(*s));
headers.iter().for_each(|s| _ = ui.heading(*s));
ui.heading(" ");
headers.iter().for_each(|s| _ = ui.heading(*s));
headers.iter().for_each(|s| _ = ui.heading(*s));
ui.end_row();
fn row(ui: &mut Ui, i: usize, v: &[(u32, Stat)]) {
if let Some((size, stat)) = v.get(i) {
ui.label(format!("{size}"));
ui.label(format!("{}", stat.count));
ui.label(format!("{:.0}", stat.time * 1000000.0)); // Seconds to microseconds
ui.label(format!("{}", stat.sum_area as u32));
} else {
ui.label("");
ui.label("");
ui.label("");
ui.label("");
}
}
for i in 0..max_rows {
row(ui, i, &tri_width_bucket);
row(ui, i, &tri_height_bucket);
ui.label(" ");
row(ui, i, &rect_width_bucket);
row(ui, i, &rect_height_bucket);
ui.end_row();
}
});
});
}
}

View File

@ -0,0 +1,42 @@
use alloc::{string::String, vec, vec::Vec};
use egui::TexturesDelta;
use egui_kittest::TestRenderer;
use image::ImageBuffer;
use crate::{BufferMutRef, EguiSoftwareRender};
impl TestRenderer for EguiSoftwareRender {
fn handle_delta(&mut self, delta: &TexturesDelta) {
self.set_textures(delta);
self.free_textures(delta);
}
fn render(
&mut self,
ctx: &egui::Context,
output: &egui::FullOutput,
) -> Result<image::RgbaImage, String> {
let paint_jobs = ctx.tessellate(output.shapes.clone(), output.pixels_per_point);
let width = (ctx.content_rect().width() * output.pixels_per_point).ceil() as usize;
let height = (ctx.content_rect().height() * output.pixels_per_point).ceil() as usize;
let mut buffer = vec![[0u8; 4]; width * height];
let mut buffer_ref = BufferMutRef::new(&mut buffer, width as usize, height as usize);
self.render(
&mut buffer_ref,
&paint_jobs,
&output.textures_delta,
output.pixels_per_point,
);
Ok(ImageBuffer::<image::Rgba<u8>, Vec<_>>::from_raw(
width as u32,
height as u32,
buffer.iter().flatten().cloned().collect::<Vec<_>>(),
)
.unwrap())
}
}

1166
vendor/egui_software_backend/src/winit.rs vendored Normal file

File diff suppressed because it is too large Load Diff