diff --git a/Cargo.lock b/Cargo.lock index 85393071..e9131ac9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16054,7 +16054,9 @@ dependencies = [ "anyrender", "anyrender_vello", "blitz-paint", + "png 0.18.1", "rustc-hash 2.1.3", + "skrifa 0.44.0", "vello", "wgpu", ] diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rs index 79fc8bb1..94b5cd17 100644 --- a/engine/render/src/engine/open.rs +++ b/engine/render/src/engine/open.rs @@ -225,6 +225,8 @@ impl Engine { image.texture_descriptor.view_formats = &[TextureFormat::Rgba8Unorm]; let target = app.world_mut().resource_mut::>().add(image); app.insert_resource(TagRowTarget(target.clone())).init_resource::().add_systems(PostUpdate, tag_row_view.before(bevy::camera::CameraUpdateSystems)); + // a camera drawing a box's view culls by it (#261), once Bevy has made its own frusta + app.add_systems(PostUpdate, sub_view_frusta.after(bevy::camera::visibility::VisibilitySystems::UpdateFrusta).before(bevy::camera::visibility::VisibilitySystems::CheckVisibility)); // a free camera over the scene (docs/preview.feature PV1c): off until a preview asks for one app.init_resource::().add_systems(PostUpdate, raea_sys_frame::view::apply.before(bevy::transform::TransformSystems::Propagate)); // without native nothing ever comes back (frames are read back only to be encoded or analysed) diff --git a/engine/render/src/engine/target.rs b/engine/render/src/engine/target.rs index f23c795d..2bc6ab82 100644 --- a/engine/render/src/engine/target.rs +++ b/engine/render/src/engine/target.rs @@ -2,7 +2,7 @@ //! raea-runtime-gpuframe), the render world's diagnostics forwarded. use super::*; -pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, tag_row_view}; +pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, sub_view_frusta, tag_row_view}; /// Bevy's render diagnostics (each pass's elapsed time, `render/...`): each new measurement into the run's totals (stats.read, the stats table: nobuild NB2a), the smoothed ones into its trace once a second. #[cfg(feature = "native")] diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rs index 94157e9f..fb272458 100644 --- a/runtime/export/src/render.rs +++ b/runtime/export/src/render.rs @@ -198,9 +198,9 @@ const LIVE_PAST: i64 = 3600; /// raea-render program drawn by raea-render into `out` (.mp4, .png for one frame, a folder of PNGs). `dir` is where relative media resolves. `wanted`: the frames (all when None). pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option>) -> R { // stills of a 3D scene: its engine opened live beside the page (as the fed path opens it), the page laid over each - // frame's 3D and each painted from the page's own picture of it + // frame's 3D and each painted from the page's own picture of it. A .png with no --frame is frame 0, drawn as --frame 0 draws it: the frames path gave a camera in a page element (an in a box) the whole frame's view (#261) let ext = out_ext(out); - let stills = (ext == "png" && wanted.as_ref().is_some_and(|w| w.len() == 1)) || ext.is_empty(); + let stills = (ext == "png" && wanted.as_ref().is_none_or(|w| w.len() == 1)) || ext.is_empty(); let how = std::env::var_os("RAEA_3D").and_then(|v| v.into_string().ok()).unwrap_or_default(); // a game: its 3D made frame by frame as it's stepped (rows made beforehand hold every frame's scene: a 10-minute // game took 24 GB before its first frame); RAEA_3D=live or =program chooses @@ -210,16 +210,16 @@ pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option> return render_bundle_with(js, dir, out, wanted, video, None, true); } if stills && how != "files" { - let upto = wanted.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1); - // a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a - // scene for every frame up to it: raea check --quick's three stills of a 13,175-frame film took 10.4 GB that - // way and 0.8 GB live, the same pixels as the film's (SG4a) - if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && wanted.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) { + let still = if ext == "png" && wanted.is_none() { Some(vec![0]) } else { wanted.clone() }; + let upto = still.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1); + // a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a scene for every frame up to it: + // raea check --quick's three stills of a 13,175-frame film took 10.4 GB that way and 0.8 GB live, the same pixels as the film's (SG4a) + if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && still.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) { raea_runtime_react::startup_mark("stills past the rows' reach: the 3D made live at each"); - return render_bundle_with(js, dir, out, wanted, false, None, true); + return render_bundle_with(js, dir, out, still, false, None, true); } - if let Some(scene) = scene_program_checked(js, dir, upto, wanted.as_deref())? { - return render_bundle_with(js, dir, out, wanted, false, Some(scene), false); + if let Some(scene) = scene_program_checked(js, dir, upto, still.as_deref())? { + return render_bundle_with(js, dir, out, still, false, Some(scene), false); } } // a video: fed, its pages handed to the encoder on the GPU (B1d), until a frame holds 3D, which starts it again diff --git a/sdk/raea/src/frame-globals.ts b/sdk/raea/src/frame-globals.ts index c1d01129..62da7ec0 100644 --- a/sdk/raea/src/frame-globals.ts +++ b/sdk/raea/src/frame-globals.ts @@ -4,6 +4,7 @@ // frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask, // so a preload resolves, and by then naturalWidth and naturalHeight are the picture's size (#253): a data: URL's from its // header, a file's or URL's from the host (native asset.load, which finds staticFile's /media/ paths as does). +// currentSrc is then the file the host found, which a canvas's drawImage draws from (#260). // width and height are the ones given (the constructor's, or set) else the natural size, as a browser has them. A file // the host can't find fires error (and onerror) instead. Under plain bun, with no host, a file's size stays 0. @@ -59,13 +60,14 @@ export function frameCallbacks(f: number, fps: number): void { type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void; -/** A picture's size: a data: URL's from its header, anything else from the host (asset.load); null when it has none - * (no host, or a format the header doesn't say). Throws the host's error for a file that isn't there. */ -function pictureSize(src: string): [number, number] | null { - if (src.startsWith("data:")) return sniffSize(src); - if (src.startsWith("blob:") || !hasNative()) return null; +/** A picture's size, and the file the host found for it: a data: URL's size from its header, anything else from the host + * (asset.load); no size when it has none (no host, or a format the header doesn't say). Throws the host's error for a + * file that isn't there. */ +function picture(src: string): { size: [number, number] | null; file?: string } { + if (src.startsWith("data:")) return { size: sniffSize(src) }; + if (src.startsWith("blob:") || !hasNative()) return { size: null }; const got = native("asset.load", { path: src }); - return got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null; + return { size: got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null, file: typeof got?.path === "string" ? got.path : undefined }; } /** A preloadable image: its src set, load fires, with the picture's size. */ @@ -75,6 +77,10 @@ class FrameImage { complete = true; naturalWidth = 0; naturalHeight = 0; + /** the picture as it loaded: the file the host found for the src (staticFile's /media/x is the project's media/x), + * which is what a canvas's drawImage draws from (#260: read back off the page, a canvas has no project folder to + * find /media/ in, and the picture drew nothing); "" until it loads, as in a browser */ + currentSrc = ""; alt = ""; crossOrigin: string | null = null; decoding = "auto"; @@ -116,14 +122,16 @@ class FrameImage { this.complete = false; this.naturalWidth = 0; this.naturalHeight = 0; + this.currentSrc = ""; const load = ++this.#loads; queueMicrotask(() => { // a src set again before this one loaded: only the last one's load fires, as in a browser if (load !== this.#loads) return; let type = "load"; try { - const size = pictureSize(src); + const { size, file } = picture(src); if (size) [this.naturalWidth, this.naturalHeight] = size; + this.currentSrc = file ?? src; } catch (err) { type = "error"; console.warn(`new Image(): ${src} didn't load: ${err instanceof Error ? err.message : String(err)}`); diff --git a/systems/canvas/src/lib.rs b/systems/canvas/src/lib.rs index 94812c40..cd0f8c63 100644 --- a/systems/canvas/src/lib.rs +++ b/systems/canvas/src/lib.rs @@ -143,11 +143,13 @@ pub(crate) fn page_options() -> usvg::Options<'static> { /// Where a video's or a picture's src is as a file, for drawing it on a canvas (`videos`). static VIDEO_PATHS: std::sync::RwLock Option>> = std::sync::RwLock::new(None); -/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too). +/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too); a src that is a file as it +/// stands (a loaded Image's currentSrc, the file its host found: #260) is that file whatever the roots make of it. fn media_file(src: &str) -> Option { + let plain = std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src)); match *VIDEO_PATHS.read().unwrap() { - Some(f) => f(src), - None => Some(std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src))), + Some(f) => f(src).filter(|p| p.exists() || !(plain.is_absolute() && plain.is_file())).or(Some(plain)), + None => Some(plain), } } diff --git a/systems/filters/Cargo.toml b/systems/filters/Cargo.toml index aa22638b..75002fd0 100644 --- a/systems/filters/Cargo.toml +++ b/systems/filters/Cargo.toml @@ -14,4 +14,7 @@ blitz-paint = { version = "=0.3.0-beta.4", default-features = false } # every call's arguments hashed, so the same print draws the same picture rustc-hash = "2" vello = { version = "=0.11.0", default-features = false, features = ["wgpu"] } +# a bitmap emoji's strike and its PNG, for the grey ones Vello's glyph run skips (emoji.rs, #262): Vello's own versions +skrifa = "0.44.0" +png = "0.18.1" wgpu = "=30.0.1" diff --git a/systems/filters/src/emoji.rs b/systems/filters/src/emoji.rs new file mode 100644 index 00000000..f037d594 --- /dev/null +++ b/systems/filters/src/emoji.rs @@ -0,0 +1,136 @@ +//! Bitmap emoji whose PNG Vello doesn't draw: grey ones. Apple Color Emoji keeps 52 of its glyphs as grey + alpha PNGs +//! (💬 and 🗨 among them), and Vello's glyph run asks png for RGBA with a transformation that adds alpha and leaves +//! grey as it is, logs "Unsupported `output_color_type`" and skips the glyph: its space was kept and nothing drawn +//! (#262). Those glyphs are taken out of the run and drawn here, as images placed the way Vello places a bitmap glyph. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::Arc; + +use anyrender::Glyph; +use skrifa::bitmap::{BitmapData, BitmapFormat, Origin}; +use skrifa::raw::TableProvider; +use skrifa::{GlyphId, MetadataProvider, instance::Size}; +use vello::kurbo::{Affine, Vec2}; +use vello::peniko::{Blob, FontData, ImageAlphaType, ImageData, ImageFormat}; + +thread_local! { + /// a font (its data's id and index) with bitmap strikes: its units per em, and whether it's Apple Color Emoji; None for a font with none + static FONTS: RefCell>> = RefCell::new(HashMap::new()); + /// a glyph's picture once decoded (font, glyph, strike), so the same image is drawn each frame + static PICTURES: RefCell>> = RefCell::new(HashMap::new()); +} + +/// A PNG's colour type Vello's glyph run draws: truecolour, with alpha or without (2 and 6); grey and palette ones it skips. +fn vello_draws(png: &[u8]) -> bool { + png.get(25).is_none_or(|t| matches!(t, 2 | 6)) +} + +/// A PNG as RGBA8, grey and palette ones expanded. +pub(crate) fn rgba(data: &[u8]) -> Option<(u32, u32, Vec)> { + let mut decoder = png::Decoder::new(std::io::Cursor::new(data)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA); + let mut reader = decoder.read_info().ok()?; + let mut buf = vec![0; reader.output_buffer_size()?]; + let info = reader.next_frame(&mut buf).ok()?; + buf.truncate(info.buffer_size()); + if info.color_type == png::ColorType::Indexed { + return None; + } + // each pixel's samples as four: grey (1 or 2 samples) spread over the three colours, and alpha the last sample + // of an even count, opaque otherwise + let n = info.color_type.samples(); + let mut px = Vec::with_capacity(buf.len() / n * 4); + for p in buf.chunks_exact(n) { + let a = if n % 2 == 0 { p[n - 1] } else { 255 }; + px.extend_from_slice(&if n < 3 { [p[0], p[0], p[0], a] } else { [p[0], p[1], p[2], a] }); + } + (px.len() as u64 == u64::from(info.width) * u64::from(info.height) * 4).then_some((info.width, info.height, px)) +} + +/// The glyphs of a run Vello would skip, each as its picture and where it goes in the run's space, and the rest of the +/// run for Vello; None when the run has none (every font without bitmaps, nearly every emoji). +pub(crate) fn skipped(font: &FontData, font_size: f32, glyph_transform: Option, glyphs: impl Iterator + Clone) -> Option<(Vec, Vec<(ImageData, Affine)>)> { + let key = (font.data.id(), font.index); + let known = FONTS.with_borrow(|f| f.get(&key).copied()); + if known == Some(None) { + return None; + } + let face = skrifa::FontRef::from_index(font.data.as_ref(), font.index).ok()?; + let strikes = face.bitmap_strikes(); + let (upem, apple) = match known { + Some(Some(k)) => k, + _ => { + let k = strikes.format().and_then(|format| { + let upem = f32::from(face.head().ok()?.units_per_em()); + let apple = format == BitmapFormat::Sbix && face.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).any(|n| n.chars().eq("AppleColorEmoji".chars())); + Some((upem, apple)) + }); + FONTS.with(|f| f.borrow_mut().insert(key, k)); + k? + } + }; + let png_of = |g: &Glyph| match strikes.glyph_for_size(Size::new(font_size), GlyphId::new(g.id)) { + Some(b) => match b.data { + BitmapData::Png(d) if !vello_draws(d) => Some((b, d)), + _ => None, + }, + None => None, + }; + if !glyphs.clone().any(|g| png_of(&g).is_some()) { + return None; + } + let (mut rest, mut ours) = (Vec::new(), Vec::new()); + for g in glyphs { + let Some((b, data)) = png_of(&g) else { + rest.push(g); + continue; + }; + let pic = PICTURES.with(|p| { + p.borrow_mut() + .entry((key.0, key.1, g.id, b.ppem_y.to_bits())) + .or_insert_with(|| rgba(data).filter(|&(w, h, _)| w == b.width && h == b.height).map(|(width, height, px)| ImageData { data: Blob::new(Arc::new(px)), format: ImageFormat::Rgba8, alpha_type: ImageAlphaType::Alpha, width, height })) + .clone() + }); + // one png can't read is left out, as Vello leaves it + let Some(pic) = pic else { continue }; + // Vello's placement of a bitmap glyph (scene.rs, after Skia's): Apple Color Emoji an eighth of the size down + let outer = if apple { Vec2::new(0.0, f64::from(font_size) / 8.0) } else { Vec2::new(f64::from(b.bearing_x * font_size / upem), -f64::from(b.bearing_y * font_size / upem)) }; + let mut at = Affine::translate((f64::from(g.x), f64::from(g.y))) * Affine::translate(outer) * Affine::scale(f64::from(font_size / b.ppem_y)) * Affine::translate((f64::from(b.inner_bearing_x), -f64::from(b.inner_bearing_y))); + if matches!(b.placement_origin, Origin::BottomLeft) { + at *= Affine::translate((0.0, -f64::from(pic.height))); + } + if let Some(t) = glyph_transform { + at *= t; + } + ours.push((pic, at)); + } + Some((rest, ours)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// a 2 x 1 PNG of colour type `kind`, 8 bits a channel, its rows given unfiltered + fn png_of(kind: png::ColorType, row: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut e = png::Encoder::new(&mut out, 2, 1); + e.set_color(kind); + e.set_depth(png::BitDepth::Eight); + e.write_header().unwrap().write_image_data(row).unwrap(); + out + } + + #[test] + fn a_grey_png_is_the_one_vello_skips_and_reads_as_rgba() { + // #262: 💬 in Apple Color Emoji is grey + alpha + let grey = png_of(png::ColorType::GrayscaleAlpha, &[200, 255, 10, 128]); + assert!(!vello_draws(&grey)); + assert_eq!(rgba(&grey), Some((2, 1, vec![200, 200, 200, 255, 10, 10, 10, 128]))); + let colour = png_of(png::ColorType::Rgba, &[1, 2, 3, 4, 5, 6, 7, 8]); + assert!(vello_draws(&colour) && vello_draws(&png_of(png::ColorType::Rgb, &[1, 2, 3, 4, 5, 6]))); + assert_eq!(rgba(&colour), Some((2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]))); + assert_eq!(rgba(&png_of(png::ColorType::Grayscale, &[7, 9])), Some((2, 1, vec![7, 7, 7, 255, 9, 9, 9, 255]))); + } +} diff --git a/systems/filters/src/lib.rs b/systems/filters/src/lib.rs index 09ee9016..885372a1 100644 --- a/systems/filters/src/lib.rs +++ b/systems/filters/src/lib.rs @@ -7,6 +7,7 @@ //! The passes work as Chrome's do: on premultiplied, sRGB-encoded values (no linearising), blur radii scaled by the //! layer's transform; edges are transparent (CSS's `EdgeMode::None`). +mod emoji; mod painter; mod passes; mod premul; diff --git a/systems/filters/src/painter.rs b/systems/filters/src/painter.rs index f1a1ac75..65b2e19f 100644 --- a/systems/filters/src/painter.rs +++ b/systems/filters/src/painter.rs @@ -387,6 +387,14 @@ impl PaintScene for Painter<'_> { self.hash.write_u32(g.y.to_bits()); } let (scene, at) = self.top(); + // the bitmap emoji Vello skips (grey PNGs: 💬, #262) drawn here, the rest of the run by Vello + if let Some((rest, ours)) = crate::emoji::skipped(font, font_size, glyph_transform, glyphs.clone()) { + VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, rest.into_iter()); + for (pic, place) in &ours { + scene.draw_image(pic, at * transform * *place); + } + return; + } VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, glyphs); } diff --git a/systems/viewbox/src/lib.rs b/systems/viewbox/src/lib.rs index 76dd95fe..786f483d 100644 --- a/systems/viewbox/src/lib.rs +++ b/systems/viewbox/src/lib.rs @@ -68,6 +68,29 @@ pub fn tag_row_view(t: Res, images: Res>, view_box: } } +/// A camera with a sub view culls by that view. Bevy's update_frusta takes the projection's whole view at the target's +/// shape, so with a box wider than the frame (1080 x 389 in a 1080 x 600 frame, the same field of view up and down) a +/// mesh inside the box's view and outside the frame's was culled and never drawn: a curved shelf's side cards, where +/// the same cards turned the other way reached into the frame's view and drew (#261). After Bevy's own frusta, before +/// visibility is checked; a camera whose sub view went gets Bevy's frustum back. +pub fn sub_view_frusta(mut ours: Local>, mut q: Query<(Entity, &Camera, &GlobalTransform, &Projection, &mut bevy::camera::primitives::Frustum)>) { + for (e, c, at, p, mut f) in &mut q { + let next = match c.sub_camera_view.as_ref() { + Some(v) => { + ours.insert(e); + let clip_from_world = p.get_clip_from_view_for_sub(v) * at.affine().inverse(); + bevy::camera::primitives::Frustum(bevy::shape::ViewFrustum::from_clip_from_world_custom_far(&clip_from_world, &at.translation(), &at.back(), p.far())) + } + None if ours.remove(&e) => p.compute_frustum(at), + None => continue, + }; + // written only when it moves, so the frustum reads as changed when it is + if (0..6).any(|i| next.half_spaces[i].normal() != f.half_spaces[i].normal() || next.half_spaces[i].d() != f.half_spaces[i].d()) { + *f = next; + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -126,6 +149,30 @@ mod tests { assert!(app.world().get::(cam).unwrap().sub_camera_view.is_none()); } + #[test] + fn a_wide_box_culls_by_its_own_view() { + use bevy::camera::primitives::{Frustum, Sphere}; + // #261's shapes on this 600 x 600 target: fov 30 up and down, the frame 1.8 wide to 1 high and a box 600 x 216 + // (1080 x 389's shape); a point 1.7 to the side, 3 ahead, is outside the frame's view (half of it is 1.45 + // wide there) and inside the box's (2.23) + let (mut app, cam, _) = app(); + app.add_systems(Update, sub_view_frusta.after(tag_row_view)); + let p = PerspectiveProjection { fov: 30f32.to_radians(), aspect_ratio: 1080.0 / 600.0, ..default() }; + let whole = Projection::Perspective(p.clone()).compute_frustum(&GlobalTransform::IDENTITY); + app.world_mut().entity_mut(cam).insert((Projection::Perspective(p), GlobalTransform::IDENTITY, whole)); + let card = Sphere { center: bevy::math::Vec3A::new(1.7, 0.0, -3.0), radius: 0.05 }; + let seen = |app: &App| app.world().get::(cam).unwrap().intersects_sphere(&card, true); + app.update(); + assert!(!seen(&app), "outside the frame's view"); + app.world_mut().resource_mut::().0 = Some([0, 100, 600, 216]); + app.update(); + assert!(seen(&app), "inside the box's view"); + // the box goes: Bevy's frustum again + app.world_mut().resource_mut::().0 = None; + app.update(); + assert!(!seen(&app)); + } + #[test] fn a_cameras_own_viewport_is_left_as_it_is() { let (mut app, _, h) = app();