BREP_app 0.36.1

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! The picture side of the stream: 64 px tiles, damage generations, and the
//! per-client plan of which tiles to send in which codec.
use std::time::{Duration, Instant};

pub const TILE: u32 = 64;
pub const CODEC_PNG: u8 = 1;
pub const CODEC_JPEG: u8 = 2;
/// The 3D viewport counts as moving this long after its tiles last changed;
/// after that its lossy tiles are re-sent lossless.
pub const SETTLE: Duration = Duration::from_millis(150);

/// The latest frame, cut into tiles, with the generation each tile last
/// changed in. Generations only grow, across sizes too, so a client's
/// record of what it holds stays comparable.
pub struct Screen {
    pub w: u32,
    pub h: u32,
    /// Straight RGBA, row-major.
    pub rgba: Vec<u8>,
    cols: u32,
    rows: u32,
    pub gens: Vec<u64>,
    gen: u64,
    /// Generation at which the size last changed: a client holding less
    /// gets a keyframe.
    pub size_gen: u64,
    /// The 3D viewport in pixels `[x0, y0, x1, y1]`.
    view: Option<[u32; 4]>,
    /// Until when the viewport counts as moving.
    moving_until: Option<Instant>,
    /// When each tile last changed: a lossy copy of it is refreshed once it
    /// has been still for [`SETTLE`].
    changed_at: Vec<Instant>,
    /// When the last change of any tile settles (the host wakes for refreshes then).
    settle_at: Option<Instant>,
}

/// On a slow link, at most this many lossless refresh tiles go in one frame:
/// a frame that answers input never waits behind a large refresh.
pub const SLOW_REFRESH_TILES: usize = 6;

impl Default for Screen {
    fn default() -> Self {
        Screen {
            w: 0,
            h: 0,
            rgba: Vec::new(),
            cols: 0,
            rows: 0,
            gens: Vec::new(),
            gen: 0,
            size_gen: 0,
            view: None,
            moving_until: None,
            changed_at: Vec::new(),
            settle_at: None,
        }
    }
}

impl Screen {
    pub fn tiles(&self) -> usize {
        (self.cols * self.rows) as usize
    }

    pub fn has_frame(&self) -> bool {
        self.w > 0 && self.h > 0
    }

    /// `(x, y, w, h)` of tile `i` in pixels.
    pub fn rect(&self, i: usize) -> (u32, u32, u32, u32) {
        let (cx, cy) = (i as u32 % self.cols, i as u32 / self.cols);
        let (x, y) = (cx * TILE, cy * TILE);
        (x, y, TILE.min(self.w - x), TILE.min(self.h - y))
    }

    fn in_view(&self, i: usize) -> bool {
        let Some([x0, y0, x1, y1]) = self.view else { return false };
        let (x, y, w, h) = self.rect(i);
        x >= x0 && y >= y0 && x + w <= x1 && y + h <= y1
    }

    /// Whether the viewport is still moving at `now`.
    pub fn moving(&self, now: Instant) -> bool {
        self.moving_until.is_some_and(|t| now < t)
    }

    /// When the last change settles (lossy tiles are then refreshed).
    pub fn settles_at(&self) -> Option<Instant> {
        self.settle_at
    }

    /// Whether tile `i` has been still long enough for a lossless refresh.
    fn settled(&self, i: usize, now: Instant) -> bool {
        now >= self.changed_at[i] + SETTLE && !(self.in_view(i) && self.moving(now))
    }

    /// Take a new frame; returns how many tiles changed.
    pub fn update(&mut self, w: u32, h: u32, rgba: Vec<u8>, view: Option<[u32; 4]>, now: Instant) -> usize {
        debug_assert_eq!(rgba.len(), (w * h * 4) as usize);
        self.gen += 1;
        self.view = view;
        if w != self.w || h != self.h {
            self.w = w;
            self.h = h;
            self.cols = w.div_ceil(TILE);
            self.rows = h.div_ceil(TILE);
            self.gens = vec![self.gen; self.tiles()];
            self.changed_at = vec![now; self.tiles()];
            self.settle_at = Some(now + SETTLE);
            self.size_gen = self.gen;
            self.rgba = rgba;
            return self.tiles();
        }
        let mut changed = 0;
        let mut view_changed = false;
        let stride = (w * 4) as usize;
        for i in 0..self.tiles() {
            let (x, y, tw, th) = self.rect(i);
            let differs = (y..y + th).any(|row| {
                let a = row as usize * stride + x as usize * 4;
                let b = a + tw as usize * 4;
                self.rgba[a..b] != rgba[a..b]
            });
            if differs {
                self.gens[i] = self.gen;
                self.changed_at[i] = now;
                changed += 1;
                view_changed |= self.in_view(i);
            }
        }
        if view_changed {
            self.moving_until = Some(now + SETTLE);
        }
        if changed > 0 {
            self.settle_at = Some(now + SETTLE);
        }
        self.rgba = rgba;
        changed
    }

    /// Encode tile `i`.
    pub fn encode(&self, i: usize, codec: u8, jpeg_quality: u8) -> Vec<u8> {
        let (x, y, w, h) = self.rect(i);
        let stride = (self.w * 4) as usize;
        let mut out = Vec::new();
        if codec == CODEC_JPEG {
            let mut rgb = Vec::with_capacity((w * h * 3) as usize);
            for row in y..y + h {
                let a = row as usize * stride + x as usize * 4;
                for px in self.rgba[a..a + w as usize * 4].chunks_exact(4) {
                    rgb.extend_from_slice(&px[..3]);
                }
            }
            let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, jpeg_quality.clamp(1, 100));
            let _ = image::ImageEncoder::write_image(encoder, &rgb, w, h, image::ExtendedColorType::Rgb8);
        } else {
            let mut px = Vec::with_capacity((w * h * 4) as usize);
            for row in y..y + h {
                let a = row as usize * stride + x as usize * 4;
                px.extend_from_slice(&self.rgba[a..a + w as usize * 4]);
            }
            let encoder = image::codecs::png::PngEncoder::new_with_quality(&mut out, image::codecs::png::CompressionType::Fast, image::codecs::png::FilterType::Sub);
            let _ = image::ImageEncoder::write_image(encoder, &px, w, h, image::ExtendedColorType::Rgba8);
        }
        out
    }
}

/// What one client holds: per tile, the generation it was sent and whether
/// that copy was lossy.
#[derive(Default)]
pub struct Held {
    have: Vec<u64>,
    lossy: Vec<bool>,
    size_gen: u64,
}

impl Held {
    /// Whether this client holds lossy tiles a settled viewport owes it.
    pub fn owes_refresh(&self) -> bool {
        self.lossy.iter().any(|l| *l)
    }

    /// Plan the next frame for this client and record it as held: the tiles
    /// newer than what it has (all of them after a size change or for a new
    /// client), plus a lossless copy of each lossy tile once the viewport
    /// settled. Returns `(keyframe, [(tile, codec)])`.
    pub fn plan(&mut self, screen: &Screen, now: Instant, slow: bool) -> (bool, Vec<(usize, u8)>) {
        let n = screen.tiles();
        let keyframe = self.size_gen != screen.size_gen || self.have.len() != n;
        if keyframe {
            self.have = vec![0; n];
            self.lossy = vec![false; n];
            self.size_gen = screen.size_gen;
        }
        let moving = screen.moving(now);
        let mut tiles = Vec::new();
        let mut refreshes = 0;
        for i in 0..n {
            let stale = screen.gens[i] > self.have[i];
            let mut refresh = !stale && self.lossy[i] && screen.settled(i, now);
            if refresh && slow {
                // In chunks: an input's frame waits behind one chunk at most.
                refresh = refreshes < SLOW_REFRESH_TILES;
                refreshes += usize::from(refresh);
            }
            if !stale && !refresh {
                continue;
            }
            // Lossy: the moving 3D view, and on a slow link every change
            // (refreshed lossless once it has been still).
            let lossy = stale && (slow || (moving && !keyframe && screen.in_view(i)));
            let codec = if lossy { CODEC_JPEG } else { CODEC_PNG };
            self.have[i] = screen.gens[i];
            self.lossy[i] = lossy;
            tiles.push((i, codec));
        }
        (keyframe, tiles)
    }
}

/// The binary frame message.
pub fn frame_message(screen: &Screen, seq: u32, keyframe: bool, tiles: &[(usize, u8, std::sync::Arc<Vec<u8>>)]) -> Vec<u8> {
    let size: usize = tiles.iter().map(|t| 14 + t.2.len()).sum();
    let mut m = Vec::with_capacity(12 + size);
    m.push(1u8);
    m.push(u8::from(keyframe));
    m.extend_from_slice(&(tiles.len() as u16).to_le_bytes());
    m.extend_from_slice(&seq.to_le_bytes());
    m.extend_from_slice(&(screen.w as u16).to_le_bytes());
    m.extend_from_slice(&(screen.h as u16).to_le_bytes());
    for (i, codec, bytes) in tiles {
        let (x, y, w, h) = screen.rect(*i);
        for v in [x, y, w, h] {
            m.extend_from_slice(&(v as u16).to_le_bytes());
        }
        m.push(*codec);
        m.push(0);
        m.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
        m.extend_from_slice(bytes);
    }
    m
}