first commit

This commit is contained in:
marwy 2026-11-27 13:16:36 +03:00
commit a408df2a76
218 changed files with 52376 additions and 0 deletions

320
src/gl/mod.rs Normal file
View file

@ -0,0 +1,320 @@
pub mod ui_renderer;
pub mod vibe_renderer;
use std::num::NonZeroU32;
use std::sync::Arc;
use anyhow::{anyhow, Context, Result};
use glow::HasContext;
use glutin::config::{ConfigTemplateBuilder, GlConfig};
use glutin::context::{
ContextApi, ContextAttributesBuilder, GlProfile, NotCurrentGlContext, PossiblyCurrentContext,
PossiblyCurrentGlContext, Version,
};
use glutin::display::{GetGlDisplay, GlDisplay};
use glutin::surface::{GlSurface, Surface, SwapInterval, WindowSurface};
use glutin_winit::{DisplayBuilder, GlWindow};
use winit::dpi::PhysicalSize;
use winit::event_loop::ActiveEventLoop;
use winit::raw_window_handle::HasWindowHandle;
use winit::window::{Window, WindowAttributes};
use crate::engine::types::{DisplayList, TextureUpload, VIBE_TEXTURE_ID};
use crate::vulkan::vibe_renderer::VibePushConstants;
use ui_renderer::UiGlRenderer;
use vibe_renderer::VibeGlRenderer;
/// Compile and link a strict OpenGL 3.3 Core vertex + fragment shader program.
pub(crate) unsafe fn compile_program(
gl: &glow::Context,
vert_src: &str,
frag_src: &str,
label: &str,
) -> Result<glow::Program> {
let vs = gl
.create_shader(glow::VERTEX_SHADER)
.map_err(|e| anyhow!("GL create_shader (vert {label}) failed: {e}"))?;
gl.shader_source(vs, vert_src);
gl.compile_shader(vs);
if !gl.get_shader_compile_status(vs) {
let log = gl.get_shader_info_log(vs);
gl.delete_shader(vs);
return Err(anyhow!("GL vertex shader ({label}) compile failed:\n{log}"));
}
let fs = match gl.create_shader(glow::FRAGMENT_SHADER) {
Ok(s) => s,
Err(e) => {
gl.delete_shader(vs);
return Err(anyhow!("GL create_shader (frag {label}) failed: {e}"));
}
};
gl.shader_source(fs, frag_src);
gl.compile_shader(fs);
if !gl.get_shader_compile_status(fs) {
let log = gl.get_shader_info_log(fs);
gl.delete_shader(vs);
gl.delete_shader(fs);
return Err(anyhow!(
"GL fragment shader ({label}) compile failed:\n{log}"
));
}
let program = match gl.create_program() {
Ok(p) => p,
Err(e) => {
gl.delete_shader(vs);
gl.delete_shader(fs);
return Err(anyhow!("GL create_program ({label}) failed: {e}"));
}
};
gl.attach_shader(program, vs);
gl.attach_shader(program, fs);
gl.link_program(program);
gl.detach_shader(program, vs);
gl.detach_shader(program, fs);
gl.delete_shader(vs);
gl.delete_shader(fs);
if !gl.get_program_link_status(program) {
let log = gl.get_program_info_log(program);
gl.delete_program(program);
return Err(anyhow!("GL program ({label}) link failed:\n{log}"));
}
Ok(program)
}
/// Strict OpenGL 3.3 Core fallback GPU context (targets legacy Intel HD 3000 Sandy Bridge /
/// NVIDIA GT 520MX Fermi / Mesa Crocus / Nouveau / Windows WGL with zero Vulkan requirement).
pub struct GlContext {
pub gpu_name: String,
gl: glow::Context,
gl_surface: Surface<WindowSurface>,
gl_context: PossiblyCurrentContext,
ui_renderer: UiGlRenderer,
vibe_renderer: VibeGlRenderer,
surface_width: u32,
surface_height: u32,
}
impl GlContext {
/// Create both the native `winit::window::Window` and a current OpenGL 3.3 Core context/surface.
/// Using `glutin_winit::DisplayBuilder` guarantees the right X11 visual / WGL pixel format on Linux & Windows.
pub fn create_window_and_context(
event_loop: &ActiveEventLoop,
window_attrs: WindowAttributes,
) -> Result<(Arc<Window>, Self)> {
let template = ConfigTemplateBuilder::new()
.with_depth_size(0)
.with_stencil_size(0);
let display_builder = DisplayBuilder::new().with_window_attributes(Some(window_attrs));
let (window_opt, gl_config) = display_builder
.build(event_loop, template, |configs| {
// Prefer non-MSAA (0 samples) and >= 8-bit alpha for crisp analytical SDF rendering
configs
.reduce(|accum, config| {
let accum_msaa = accum.num_samples();
let cfg_msaa = config.num_samples();
if cfg_msaa < accum_msaa {
config
} else if cfg_msaa == accum_msaa
&& config.alpha_size() > accum.alpha_size()
{
config
} else {
accum
}
})
.expect("No compatible OpenGL framebuffer config found")
})
.map_err(|e| anyhow!("glutin DisplayBuilder::build failed: {e}"))?;
let window = Arc::new(
window_opt.ok_or_else(|| anyhow!("glutin DisplayBuilder did not create a window"))?,
);
let raw_window_handle = window
.window_handle()
.map_err(|e| anyhow!("Failed to query raw window handle: {e}"))?
.as_raw();
let gl_display = gl_config.display();
// Request strict OpenGL 3.3 Core first, falling back gracefully on quirky drivers
let attrs_33_core = ContextAttributesBuilder::new()
.with_context_api(ContextApi::OpenGl(Some(Version::new(3, 3))))
.with_profile(GlProfile::Core)
.build(Some(raw_window_handle));
let attrs_33_any = ContextAttributesBuilder::new()
.with_context_api(ContextApi::OpenGl(Some(Version::new(3, 3))))
.build(Some(raw_window_handle));
let attrs_default = ContextAttributesBuilder::new().build(Some(raw_window_handle));
let not_current = unsafe {
gl_display
.create_context(&gl_config, &attrs_33_core)
.or_else(|_| gl_display.create_context(&gl_config, &attrs_33_any))
.or_else(|_| gl_display.create_context(&gl_config, &attrs_default))
.context("Failed to create OpenGL 3.3 Core context")?
};
let surface_attrs = window
.build_surface_attributes(Default::default())
.map_err(|e| anyhow!("build_surface_attributes failed: {e}"))?;
let gl_surface = unsafe {
gl_display
.create_window_surface(&gl_config, &surface_attrs)
.context("Failed to create OpenGL window surface")?
};
let gl_context = not_current
.make_current(&gl_surface)
.context("Failed to make OpenGL context current")?;
// Enable vsync (1 frame interval) so idle / scrolling doesn't peg legacy GPUs at 100%
let _ = gl_surface.set_swap_interval(
&gl_context,
SwapInterval::Wait(NonZeroU32::new(1).unwrap()),
);
let gl = unsafe {
glow::Context::from_loader_function_cstr(|s| gl_display.get_proc_address(s) as *const _)
};
let (gpu_name, major, minor) = unsafe {
let renderer = gl.get_parameter_string(glow::RENDERER);
let version = gl.get_parameter_string(glow::VERSION);
let major = gl.get_parameter_i32(glow::MAJOR_VERSION);
let minor = gl.get_parameter_i32(glow::MINOR_VERSION);
// Disable sRGB framebuffer conversion so linear-sRGB premultiplied blending matches Chromium & Vulkan UNORM 1-to-1
gl.disable(glow::FRAMEBUFFER_SRGB);
gl.disable(glow::DEPTH_TEST);
gl.disable(glow::CULL_FACE);
gl.disable(glow::SCISSOR_TEST);
let label = if version.contains("OpenGL") {
format!("{renderer} ({version})")
} else {
format!("{renderer} (OpenGL {version})")
};
(label, major, minor)
};
if major < 3 || (major == 3 && minor < 3) {
return Err(anyhow!(
"OpenGL 3.3 Core is required, but driver reported {major}.{minor} ({gpu_name})"
));
}
let mut ui_renderer = unsafe { UiGlRenderer::new(&gl)? };
let vibe_renderer = match unsafe { VibeGlRenderer::new(&gl, 512, 512) } {
Ok(v) => v,
Err(e) => {
unsafe { ui_renderer.destroy(&gl) };
return Err(e);
}
};
ui_renderer.register_external_texture(
VIBE_TEXTURE_ID,
vibe_renderer.texture,
vibe_renderer.width,
vibe_renderer.height,
);
let size = window.inner_size();
log::info!(
"OpenGL {major}.{minor} Core renderer ready: {gpu_name} ({}x{})",
size.width,
size.height
);
Ok((
window,
Self {
gpu_name,
gl,
gl_surface,
gl_context,
ui_renderer,
vibe_renderer,
surface_width: size.width.max(1),
surface_height: size.height.max(1),
},
))
}
pub fn estimated_vram_bytes(&self) -> u64 {
self.ui_renderer.estimated_vram_bytes() + self.vibe_renderer.byte_size
}
pub fn resize(&mut self, width: u32, height: u32) {
if width == 0 || height == 0 {
return;
}
if width == self.surface_width && height == self.surface_height {
return;
}
self.surface_width = width;
self.surface_height = height;
self.gl_surface.resize(
&self.gl_context,
NonZeroU32::new(width).unwrap(),
NonZeroU32::new(height).unwrap(),
);
}
pub fn render_frame(
&mut self,
size: PhysicalSize<u32>,
pixels_per_point: f32,
clear_color: [f32; 4],
vibe_push: Option<VibePushConstants>,
uploads: &[TextureUpload],
display_list: &DisplayList,
) -> Result<()> {
if size.width == 0 || size.height == 0 {
return Ok(());
}
if size.width != self.surface_width || size.height != self.surface_height {
self.resize(size.width, size.height);
}
unsafe {
// 1. Process pending texture creates/updates/frees
self.ui_renderer.process_uploads(&self.gl, uploads)?;
// 2. Render My Vibe offscreen 512x512 FBO only when active & parameters changed
if let Some(vp) = vibe_push {
self.vibe_renderer.render_if_needed(&self.gl, vp);
}
// 3. Render UI DisplayList (+ Dual Kawase Blur if any BlurRegions exist)
self.ui_renderer.render_display_list(
&self.gl,
size.width,
size.height,
pixels_per_point,
clear_color,
display_list,
)?;
}
self.gl_surface
.swap_buffers(&self.gl_context)
.context("OpenGL swap_buffers failed")?;
Ok(())
}
}
impl Drop for GlContext {
fn drop(&mut self) {
let _ = self.gl_context.make_current(&self.gl_surface);
unsafe {
self.vibe_renderer.destroy(&self.gl);
self.ui_renderer.destroy(&self.gl);
}
}
}

851
src/gl/ui_renderer.rs Normal file
View file

@ -0,0 +1,851 @@
use std::collections::HashMap;
use std::mem::size_of;
use anyhow::{anyhow, Result};
use glow::HasContext;
use crate::engine::types::{
DisplayList, TextureFormat, TextureId, TextureUpload, UiInstance, BLUR_TEXTURE_ID,
MODE_BACKDROP_BLUR, MODE_GLYPH, MODE_TEXTURED, NONE_TEXTURE_ID, VIBE_TEXTURE_ID,
};
const UI_VERT_SRC: &str = include_str!("../../shaders/gl/ui_sdf.vert");
const UI_FRAG_SRC: &str = include_str!("../../shaders/gl/ui_sdf.frag");
const BLUR_VERT_SRC: &str = include_str!("../../shaders/gl/blur.vert");
const BLUR_FRAG_SRC: &str = include_str!("../../shaders/gl/blur.frag");
struct ManagedGlTexture {
texture: glow::Texture,
width: u32,
height: u32,
format: TextureFormat,
byte_size: u64,
owned: bool,
}
struct SceneAndBlurTargets {
width: u32,
height: u32,
half_w: u32,
half_h: u32,
quarter_w: u32,
quarter_h: u32,
scene_tex: glow::Texture,
scene_fbo: glow::Framebuffer,
half_tex: glow::Texture,
half_fbo: glow::Framebuffer,
quarter_tex: glow::Texture,
quarter_fbo: glow::Framebuffer,
byte_size: u64,
}
impl SceneAndBlurTargets {
unsafe fn new(gl: &glow::Context, width: u32, height: u32) -> Result<Self> {
let width = width.max(1);
let height = height.max(1);
let half_w = (width / 2).max(1);
let half_h = (height / 2).max(1);
let quarter_w = (width / 4).max(1);
let quarter_h = (height / 4).max(1);
let (scene_tex, scene_fbo) = create_rgba8_fbo(gl, width, height, "scene")?;
let (half_tex, half_fbo) = match create_rgba8_fbo(gl, half_w, half_h, "blur_half") {
Ok(pair) => pair,
Err(e) => {
gl.delete_framebuffer(scene_fbo);
gl.delete_texture(scene_tex);
return Err(e);
}
};
let (quarter_tex, quarter_fbo) =
match create_rgba8_fbo(gl, quarter_w, quarter_h, "blur_quarter") {
Ok(pair) => pair,
Err(e) => {
gl.delete_framebuffer(half_fbo);
gl.delete_texture(half_tex);
gl.delete_framebuffer(scene_fbo);
gl.delete_texture(scene_tex);
return Err(e);
}
};
let byte_size = ((width as u64) * (height as u64)
+ (half_w as u64) * (half_h as u64)
+ (quarter_w as u64) * (quarter_h as u64))
* 4;
Ok(Self {
width,
height,
half_w,
half_h,
quarter_w,
quarter_h,
scene_tex,
scene_fbo,
half_tex,
half_fbo,
quarter_tex,
quarter_fbo,
byte_size,
})
}
unsafe fn destroy(&mut self, gl: &glow::Context) {
gl.delete_framebuffer(self.scene_fbo);
gl.delete_texture(self.scene_tex);
gl.delete_framebuffer(self.half_fbo);
gl.delete_texture(self.half_tex);
gl.delete_framebuffer(self.quarter_fbo);
gl.delete_texture(self.quarter_tex);
}
}
unsafe fn create_rgba8_fbo(
gl: &glow::Context,
width: u32,
height: u32,
label: &str,
) -> Result<(glow::Texture, glow::Framebuffer)> {
let tex = gl
.create_texture()
.map_err(|e| anyhow!("GL create_texture ({label}) failed: {e}"))?;
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MIN_FILTER,
glow::LINEAR as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MAG_FILTER,
glow::LINEAR as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_S,
glow::CLAMP_TO_EDGE as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_T,
glow::CLAMP_TO_EDGE as i32,
);
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
glow::RGBA8 as i32,
width as i32,
height as i32,
0,
glow::RGBA,
glow::UNSIGNED_BYTE,
None,
);
gl.bind_texture(glow::TEXTURE_2D, None);
let fbo = gl
.create_framebuffer()
.map_err(|e| anyhow!("GL create_framebuffer ({label}) failed: {e}"))?;
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo));
gl.framebuffer_texture_2d(
glow::FRAMEBUFFER,
glow::COLOR_ATTACHMENT0,
glow::TEXTURE_2D,
Some(tex),
0,
);
let status = gl.check_framebuffer_status(glow::FRAMEBUFFER);
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
if status != glow::FRAMEBUFFER_COMPLETE {
gl.delete_framebuffer(fbo);
gl.delete_texture(tex);
return Err(anyhow!("GL FBO ({label}) incomplete (status = 0x{status:x})"));
}
Ok((tex, fbo))
}
/// Strict OpenGL 3.3 Core Uber-SDF + Dual Kawase Blur UI renderer.
/// Zero SSBOs, zero `glDrawArraysInstancedBaseInstance` (GL 4.2): streams `UiInstance`
/// into an instanced VBO (divisor = 1) and rebinds vertex attribute byte offsets per texture batch.
pub struct UiGlRenderer {
ui_program: glow::Program,
blur_program: glow::Program,
ui_vao: glow::VertexArray,
instance_vbo: glow::Buffer,
instance_vbo_capacity: usize,
fullscreen_vao: glow::VertexArray,
// UI uniform locations
loc_ui_screen_size: Option<glow::UniformLocation>,
loc_ui_scale_factor: Option<glow::UniformLocation>,
loc_ui_flip_v: Option<glow::UniformLocation>,
loc_ui_tex: Option<glow::UniformLocation>,
// Blur uniform locations
loc_blur_tex: Option<glow::UniformLocation>,
loc_blur_texel_size: Option<glow::UniformLocation>,
loc_blur_offset: Option<glow::UniformLocation>,
loc_blur_mode: Option<glow::UniformLocation>,
textures: HashMap<TextureId, ManagedGlTexture>,
scene_blur: Option<SceneAndBlurTargets>,
}
impl UiGlRenderer {
pub unsafe fn new(gl: &glow::Context) -> Result<Self> {
let ui_program = super::compile_program(gl, UI_VERT_SRC, UI_FRAG_SRC, "ui_sdf")?;
let blur_program = match super::compile_program(gl, BLUR_VERT_SRC, BLUR_FRAG_SRC, "blur") {
Ok(p) => p,
Err(e) => {
gl.delete_program(ui_program);
return Err(e);
}
};
let ui_vao = gl
.create_vertex_array()
.map_err(|e| anyhow!("GL create_vertex_array (ui) failed: {e}"))?;
let instance_vbo = gl
.create_buffer()
.map_err(|e| anyhow!("GL create_buffer (instance_vbo) failed: {e}"))?;
let fullscreen_vao = gl
.create_vertex_array()
.map_err(|e| anyhow!("GL create_vertex_array (blur) failed: {e}"))?;
let initial_capacity = 4096 * size_of::<UiInstance>();
gl.bind_vertex_array(Some(ui_vao));
gl.bind_buffer(glow::ARRAY_BUFFER, Some(instance_vbo));
gl.buffer_data_size(
glow::ARRAY_BUFFER,
initial_capacity as i32,
glow::STREAM_DRAW,
);
for loc in 0..7u32 {
gl.enable_vertex_attrib_array(loc);
gl.vertex_attrib_divisor(loc, 1);
}
Self::bind_instance_attrib_pointers(gl, 0);
gl.bind_vertex_array(None);
gl.bind_buffer(glow::ARRAY_BUFFER, None);
let loc_ui_screen_size = gl.get_uniform_location(ui_program, "u_screen_size");
let loc_ui_scale_factor = gl.get_uniform_location(ui_program, "u_scale_factor");
let loc_ui_flip_v = gl.get_uniform_location(ui_program, "u_flip_v");
let loc_ui_tex = gl.get_uniform_location(ui_program, "u_tex");
let loc_blur_tex = gl.get_uniform_location(blur_program, "u_tex");
let loc_blur_texel_size = gl.get_uniform_location(blur_program, "u_texel_size");
let loc_blur_offset = gl.get_uniform_location(blur_program, "u_offset");
let loc_blur_mode = gl.get_uniform_location(blur_program, "u_mode");
// Bind sampler uniforms to texture unit 0 once
gl.use_program(Some(ui_program));
gl.uniform_1_i32(loc_ui_tex.as_ref(), 0);
gl.use_program(Some(blur_program));
gl.uniform_1_i32(loc_blur_tex.as_ref(), 0);
gl.use_program(None);
let mut renderer = Self {
ui_program,
blur_program,
ui_vao,
instance_vbo,
instance_vbo_capacity: initial_capacity,
fullscreen_vao,
loc_ui_screen_size,
loc_ui_scale_factor,
loc_ui_flip_v,
loc_ui_tex,
loc_blur_tex,
loc_blur_texel_size,
loc_blur_offset,
loc_blur_mode,
textures: HashMap::with_capacity(128),
scene_blur: None,
};
// Upload default 1x1 white texture at NONE_TEXTURE_ID so unit 0 always has a valid texture
renderer.process_uploads(
gl,
&[TextureUpload::CreateOrReplace {
id: NONE_TEXTURE_ID,
width: 1,
height: 1,
format: TextureFormat::Rgba8Premul,
pixels: vec![255, 255, 255, 255],
}],
)?;
Ok(renderer)
}
/// Rebind the 7 per-instance vertex attribute pointers at `base_byte` into `self.instance_vbo`.
/// Strict OpenGL 3.3 Core alternative to GL 4.2's `glDrawArraysInstancedBaseInstance`.
#[inline]
unsafe fn bind_instance_attrib_pointers(gl: &glow::Context, base_byte: i32) {
let stride = size_of::<UiInstance>() as i32; // 112 bytes
// 0: rect: [f32; 4] (offset 0)
gl.vertex_attrib_pointer_f32(0, 4, glow::FLOAT, false, stride, base_byte);
// 1: radii: [f32; 4] (offset 16)
gl.vertex_attrib_pointer_f32(1, 4, glow::FLOAT, false, stride, base_byte + 16);
// 2: uv_or_params: [f32; 4] (offset 32)
gl.vertex_attrib_pointer_f32(2, 4, glow::FLOAT, false, stride, base_byte + 32);
// 3: clip_rect: [f32; 4] (offset 48)
gl.vertex_attrib_pointer_f32(3, 4, glow::FLOAT, false, stride, base_byte + 48);
// 4: colors: [u32; 4] (offset 64)
gl.vertex_attrib_pointer_i32(4, 4, glow::UNSIGNED_INT, stride, base_byte + 64);
// 5: metrics: [f32; 4] (offset 80)
gl.vertex_attrib_pointer_f32(5, 4, glow::FLOAT, false, stride, base_byte + 80);
// 6: meta: [u32; 4] (offset 96)
gl.vertex_attrib_pointer_i32(6, 4, glow::UNSIGNED_INT, stride, base_byte + 96);
}
pub fn estimated_vram_bytes(&self) -> u64 {
let tex_bytes: u64 = self
.textures
.values()
.filter(|t| t.owned)
.map(|t| t.byte_size)
.sum();
let blur_bytes = self.scene_blur.as_ref().map_or(0, |b| b.byte_size);
tex_bytes + blur_bytes + (self.instance_vbo_capacity as u64)
}
pub fn register_external_texture(
&mut self,
id: TextureId,
texture: glow::Texture,
width: u32,
height: u32,
) {
self.textures.insert(
id,
ManagedGlTexture {
texture,
width,
height,
format: TextureFormat::Rgba8Premul,
byte_size: 0,
owned: false,
},
);
}
pub unsafe fn process_uploads(
&mut self,
gl: &glow::Context,
uploads: &[TextureUpload],
) -> Result<()> {
if uploads.is_empty() {
return Ok(());
}
// Critical for odd-width R8 glyph atlas regions and tightly packed RGBA8 buffers
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
for upload in uploads {
match upload {
TextureUpload::Free { id } => {
if *id == NONE_TEXTURE_ID || *id == VIBE_TEXTURE_ID || *id == BLUR_TEXTURE_ID {
continue;
}
if let Some(old) = self.textures.remove(id) {
if old.owned {
gl.delete_texture(old.texture);
}
}
}
TextureUpload::CreateOrReplace {
id,
width,
height,
format,
pixels,
} => {
if *width == 0 || *height == 0 || pixels.is_empty() {
continue;
}
let expected_bpp = match format {
TextureFormat::R8 => 1usize,
TextureFormat::Rgba8Premul => 4usize,
};
if pixels.len() < (*width as usize) * (*height as usize) * expected_bpp {
continue;
}
// Reuse existing owned GL texture handle if present, else allocate a new one
let tex = if let Some(existing) = self.textures.remove(id) {
if existing.owned {
existing.texture
} else {
gl.create_texture()
.map_err(|e| anyhow!("GL create_texture failed: {e}"))?
}
} else {
gl.create_texture()
.map_err(|e| anyhow!("GL create_texture failed: {e}"))?
};
let (internal_fmt, pixel_fmt, use_mips) = match format {
TextureFormat::R8 => (glow::R8 as i32, glow::RED, false),
TextureFormat::Rgba8Premul => {
(glow::RGBA8 as i32, glow::RGBA, (*width).max(*height) > 1)
}
};
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_S,
glow::CLAMP_TO_EDGE as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_T,
glow::CLAMP_TO_EDGE as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MAG_FILTER,
glow::LINEAR as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MIN_FILTER,
if use_mips {
glow::LINEAR_MIPMAP_LINEAR as i32
} else {
glow::LINEAR as i32
},
);
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
internal_fmt,
*width as i32,
*height as i32,
0,
pixel_fmt,
glow::UNSIGNED_BYTE,
Some(pixels.as_slice()),
);
if use_mips {
gl.generate_mipmap(glow::TEXTURE_2D);
}
gl.bind_texture(glow::TEXTURE_2D, None);
let base_bytes = (*width as u64) * (*height as u64) * (expected_bpp as u64);
let byte_size = if use_mips {
(base_bytes * 4) / 3
} else {
base_bytes
};
self.textures.insert(
*id,
ManagedGlTexture {
texture: tex,
width: *width,
height: *height,
format: *format,
byte_size,
owned: true,
},
);
}
TextureUpload::UpdateRegion {
id,
x,
y,
width,
height,
format,
pixels,
} => {
if *width == 0 || *height == 0 || pixels.is_empty() {
continue;
}
let Some(tex) = self.textures.get(id) else {
continue;
};
if *x + *width > tex.width || *y + *height > tex.height {
continue;
}
let expected_bpp = match format {
TextureFormat::R8 => 1usize,
TextureFormat::Rgba8Premul => 4usize,
};
if pixels.len() < (*width as usize) * (*height as usize) * expected_bpp {
continue;
}
let pixel_fmt = match tex.format {
TextureFormat::R8 => glow::RED,
TextureFormat::Rgba8Premul => glow::RGBA,
};
gl.bind_texture(glow::TEXTURE_2D, Some(tex.texture));
gl.tex_sub_image_2d(
glow::TEXTURE_2D,
0,
*x as i32,
*y as i32,
*width as i32,
*height as i32,
pixel_fmt,
glow::UNSIGNED_BYTE,
glow::PixelUnpackData::Slice(pixels.as_slice()),
);
if matches!(tex.format, TextureFormat::Rgba8Premul)
&& tex.width.max(tex.height) > 1
{
gl.generate_mipmap(glow::TEXTURE_2D);
}
gl.bind_texture(glow::TEXTURE_2D, None);
}
}
}
Ok(())
}
unsafe fn ensure_scene_blur_targets(
&mut self,
gl: &glow::Context,
width: u32,
height: u32,
) -> Result<()> {
let matches = self
.scene_blur
.as_ref()
.is_some_and(|b| b.width == width && b.height == height);
if matches {
return Ok(());
}
if let Some(mut old) = self.scene_blur.take() {
old.destroy(gl);
}
let targets = SceneAndBlurTargets::new(gl, width, height)?;
self.register_external_texture(
BLUR_TEXTURE_ID,
targets.half_tex,
targets.half_w,
targets.half_h,
);
self.scene_blur = Some(targets);
Ok(())
}
unsafe fn upload_instances(&mut self, gl: &glow::Context, instances: &[UiInstance]) {
if instances.is_empty() {
return;
}
let raw = bytemuck::cast_slice::<UiInstance, u8>(instances);
let bytes_needed = raw.len();
gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
if bytes_needed > self.instance_vbo_capacity {
let new_cap = bytes_needed.next_power_of_two();
gl.buffer_data_size(glow::ARRAY_BUFFER, new_cap as i32, glow::STREAM_DRAW);
self.instance_vbo_capacity = new_cap;
} else {
// Buffer orphaning prevents driver stalls on Intel/Mesa without re-allocating descriptor state
gl.buffer_data_size(
glow::ARRAY_BUFFER,
self.instance_vbo_capacity as i32,
glow::STREAM_DRAW,
);
}
gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, 0, raw);
gl.bind_buffer(glow::ARRAY_BUFFER, None);
}
unsafe fn run_kawase_blur(&self, gl: &glow::Context, radius: f32) {
let Some(bt) = &self.scene_blur else {
return;
};
let offset = radius.clamp(0.5, 4.0);
gl.disable(glow::BLEND);
gl.use_program(Some(self.blur_program));
gl.uniform_1_i32(self.loc_blur_tex.as_ref(), 0);
gl.active_texture(glow::TEXTURE0);
gl.bind_vertex_array(Some(self.fullscreen_vao));
// Pass 1: Downsample Full -> Half
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(bt.half_fbo));
gl.viewport(0, 0, bt.half_w as i32, bt.half_h as i32);
gl.bind_texture(glow::TEXTURE_2D, Some(bt.scene_tex));
gl.uniform_2_f32(
self.loc_blur_texel_size.as_ref(),
1.0 / bt.width.max(1) as f32,
1.0 / bt.height.max(1) as f32,
);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset);
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), 0);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
// Pass 2: Downsample Half -> Quarter
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(bt.quarter_fbo));
gl.viewport(0, 0, bt.quarter_w as i32, bt.quarter_h as i32);
gl.bind_texture(glow::TEXTURE_2D, Some(bt.half_tex));
gl.uniform_2_f32(
self.loc_blur_texel_size.as_ref(),
1.0 / bt.half_w.max(1) as f32,
1.0 / bt.half_h.max(1) as f32,
);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset * 1.25);
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), 0);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
// Pass 3: Upsample Quarter -> Half (BLUR_TEXTURE_ID samples half_tex with linear filter)
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(bt.half_fbo));
gl.viewport(0, 0, bt.half_w as i32, bt.half_h as i32);
gl.bind_texture(glow::TEXTURE_2D, Some(bt.quarter_tex));
gl.uniform_2_f32(
self.loc_blur_texel_size.as_ref(),
1.0 / bt.quarter_w.max(1) as f32,
1.0 / bt.quarter_h.max(1) as f32,
);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset * 1.25);
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), 1);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
gl.bind_vertex_array(None);
gl.bind_texture(glow::TEXTURE_2D, None);
}
unsafe fn draw_range(
&self,
gl: &glow::Context,
width: u32,
height: u32,
pixels_per_point: f32,
display_list: &DisplayList,
range_start: usize,
range_end: usize,
) {
let end = range_end.min(display_list.instances.len());
if range_start >= end {
return;
}
let scale = pixels_per_point.max(0.5);
let logical_w = width as f32 / scale;
let logical_h = height as f32 / scale;
gl.viewport(0, 0, width as i32, height as i32);
gl.enable(glow::BLEND);
gl.blend_func_separate(
glow::ONE,
glow::ONE_MINUS_SRC_ALPHA,
glow::ONE,
glow::ONE_MINUS_SRC_ALPHA,
);
gl.use_program(Some(self.ui_program));
gl.uniform_2_f32(self.loc_ui_screen_size.as_ref(), logical_w, logical_h);
gl.uniform_1_f32(self.loc_ui_scale_factor.as_ref(), scale);
gl.uniform_1_i32(self.loc_ui_tex.as_ref(), 0);
gl.active_texture(glow::TEXTURE0);
gl.bind_vertex_array(Some(self.ui_vao));
gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.instance_vbo));
let default_tex = self.textures[&NONE_TEXTURE_ID].texture;
let mut bound_tex: Option<TextureId> = None;
let mut bound_flip_v: i32 = -1;
let mut batch_start = range_start;
let mut batch_tex = NONE_TEXTURE_ID;
let mut batch_has_tex = false;
let flush = |start: usize,
count: usize,
tex_id: TextureId,
bound: &mut Option<TextureId>,
flip_state: &mut i32| {
if count == 0 {
return;
}
let gl_tex = self
.textures
.get(&tex_id)
.map(|t| t.texture)
.unwrap_or(default_tex);
if *bound != Some(tex_id) {
gl.bind_texture(glow::TEXTURE_2D, Some(gl_tex));
*bound = Some(tex_id);
}
let want_flip = if tex_id == VIBE_TEXTURE_ID { 1 } else { 0 };
if *flip_state != want_flip {
gl.uniform_1_i32(self.loc_ui_flip_v.as_ref(), want_flip);
*flip_state = want_flip;
}
let base_byte = (start * size_of::<UiInstance>()) as i32;
Self::bind_instance_attrib_pointers(gl, base_byte);
gl.draw_arrays_instanced(glow::TRIANGLES, 0, 6, count as i32);
};
for idx in range_start..end {
let inst = &display_list.instances[idx];
let mode = inst.meta[0];
let needs_tex =
mode == MODE_TEXTURED || mode == MODE_GLYPH || mode == MODE_BACKDROP_BLUR;
if needs_tex {
let req_tex = TextureId(inst.meta[1]);
if batch_has_tex && req_tex != batch_tex {
flush(
batch_start,
idx - batch_start,
batch_tex,
&mut bound_tex,
&mut bound_flip_v,
);
batch_start = idx;
}
batch_tex = req_tex;
batch_has_tex = true;
}
}
flush(
batch_start,
end - batch_start,
batch_tex,
&mut bound_tex,
&mut bound_flip_v,
);
gl.bind_buffer(glow::ARRAY_BUFFER, None);
gl.bind_vertex_array(None);
gl.bind_texture(glow::TEXTURE_2D, None);
}
/// Render the entire `DisplayList` into the default framebuffer (`0`), automatically routing
/// through an offscreen scene FBO + 2-pass Dual Kawase Blur only when `blur_regions` is non-empty.
pub unsafe fn render_display_list(
&mut self,
gl: &glow::Context,
width: u32,
height: u32,
pixels_per_point: f32,
clear_color: [f32; 4],
display_list: &DisplayList,
) -> Result<()> {
self.upload_instances(gl, &display_list.instances);
let use_scene_blur = !display_list.blur_regions.is_empty();
if use_scene_blur {
self.ensure_scene_blur_targets(gl, width, height)?;
let scene_fbo = self.scene_blur.as_ref().unwrap().scene_fbo;
let mut cursor = 0usize;
let mut cleared = false;
for br in &display_list.blur_regions {
let split = br.instance_index.min(display_list.instances.len());
if !cleared || split > cursor {
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(scene_fbo));
if !cleared {
gl.viewport(0, 0, width as i32, height as i32);
gl.clear_color(
clear_color[0],
clear_color[1],
clear_color[2],
clear_color[3],
);
gl.clear(glow::COLOR_BUFFER_BIT);
cleared = true;
}
self.draw_range(
gl,
width,
height,
pixels_per_point,
display_list,
cursor,
split,
);
}
self.run_kawase_blur(gl, br.radius);
cursor = cursor.max(split);
}
// Final overlay segment rendered on top of the blurred scene
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(scene_fbo));
if !cleared {
gl.viewport(0, 0, width as i32, height as i32);
gl.clear_color(
clear_color[0],
clear_color[1],
clear_color[2],
clear_color[3],
);
gl.clear(glow::COLOR_BUFFER_BIT);
}
self.draw_range(
gl,
width,
height,
pixels_per_point,
display_list,
cursor,
display_list.instances.len(),
);
// Fast GPU blit from scene_fbo -> default framebuffer 0
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(scene_fbo));
gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None);
gl.blit_framebuffer(
0,
0,
width as i32,
height as i32,
0,
0,
width as i32,
height as i32,
glow::COLOR_BUFFER_BIT,
glow::NEAREST,
);
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
} else {
// Fast zero-copy path directly into default framebuffer 0
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
gl.viewport(0, 0, width as i32, height as i32);
gl.clear_color(
clear_color[0],
clear_color[1],
clear_color[2],
clear_color[3],
);
gl.clear(glow::COLOR_BUFFER_BIT);
self.draw_range(
gl,
width,
height,
pixels_per_point,
display_list,
0,
display_list.instances.len(),
);
}
Ok(())
}
pub unsafe fn destroy(&mut self, gl: &glow::Context) {
if let Some(mut sb) = self.scene_blur.take() {
sb.destroy(gl);
}
for (_, tex) in self.textures.drain() {
if tex.owned {
gl.delete_texture(tex.texture);
}
}
gl.delete_buffer(self.instance_vbo);
gl.delete_vertex_array(self.ui_vao);
gl.delete_vertex_array(self.fullscreen_vao);
gl.delete_program(self.ui_program);
gl.delete_program(self.blur_program);
}
}

164
src/gl/vibe_renderer.rs Normal file
View file

@ -0,0 +1,164 @@
use anyhow::{anyhow, Result};
use glow::HasContext;
use crate::vulkan::vibe_renderer::{build_vibe_gpu_push, VibePushConstants};
const VIBE_VERT_SRC: &str = include_str!("../../shaders/gl/vibe.vert");
const VIBE_FRAG_SRC: &str = include_str!("../../shaders/gl/vibe.frag");
/// Offscreen OpenGL 3.3 Core renderer for the animated "Моя волна" (My Vibe) shader.
/// Renders into a `512x512` `RGBA8` FBO and skips re-rendering whenever `VibePushConstants`
/// is unchanged (saving GPU power on Intel HD 3000 / GT 520MX when paused or off-home).
pub struct VibeGlRenderer {
program: glow::Program,
vao: glow::VertexArray,
fbo: glow::Framebuffer,
pub texture: glow::Texture,
pub width: u32,
pub height: u32,
pub byte_size: u64,
last_push: Option<VibePushConstants>,
loc_uv_scale_time_maxr: Option<glow::UniformLocation>,
loc_rot01: Option<glow::UniformLocation>,
loc_rot2_inner01: Option<glow::UniformLocation>,
loc_inner2_glow012: Option<glow::UniformLocation>,
loc_audio012_pad: Option<glow::UniformLocation>,
loc_colors_a: Option<glow::UniformLocation>,
loc_colors_b: Option<glow::UniformLocation>,
}
impl VibeGlRenderer {
pub unsafe fn new(gl: &glow::Context, width: u32, height: u32) -> Result<Self> {
let width = width.max(64);
let height = height.max(64);
let program = super::compile_program(gl, VIBE_VERT_SRC, VIBE_FRAG_SRC, "vibe")?;
let vao = gl
.create_vertex_array()
.map_err(|e| anyhow!("GL create_vertex_array (vibe) failed: {e}"))?;
let texture = gl
.create_texture()
.map_err(|e| anyhow!("GL create_texture (vibe) failed: {e}"))?;
gl.bind_texture(glow::TEXTURE_2D, Some(texture));
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MIN_FILTER,
glow::LINEAR as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MAG_FILTER,
glow::LINEAR as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_S,
glow::CLAMP_TO_EDGE as i32,
);
gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_WRAP_T,
glow::CLAMP_TO_EDGE as i32,
);
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
glow::RGBA8 as i32,
width as i32,
height as i32,
0,
glow::RGBA,
glow::UNSIGNED_BYTE,
None,
);
gl.bind_texture(glow::TEXTURE_2D, None);
let fbo = gl
.create_framebuffer()
.map_err(|e| anyhow!("GL create_framebuffer (vibe) failed: {e}"))?;
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo));
gl.framebuffer_texture_2d(
glow::FRAMEBUFFER,
glow::COLOR_ATTACHMENT0,
glow::TEXTURE_2D,
Some(texture),
0,
);
let status = gl.check_framebuffer_status(glow::FRAMEBUFFER);
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
if status != glow::FRAMEBUFFER_COMPLETE {
gl.delete_framebuffer(fbo);
gl.delete_texture(texture);
gl.delete_vertex_array(vao);
gl.delete_program(program);
return Err(anyhow!(
"GL vibe FBO incomplete (status = 0x{status:x})"
));
}
let loc_uv_scale_time_maxr = gl.get_uniform_location(program, "u_uv_scale_time_maxr");
let loc_rot01 = gl.get_uniform_location(program, "u_rot01");
let loc_rot2_inner01 = gl.get_uniform_location(program, "u_rot2_inner01");
let loc_inner2_glow012 = gl.get_uniform_location(program, "u_inner2_glow012");
let loc_audio012_pad = gl.get_uniform_location(program, "u_audio012_pad");
let loc_colors_a = gl.get_uniform_location(program, "u_colors_a");
let loc_colors_b = gl.get_uniform_location(program, "u_colors_b");
Ok(Self {
program,
vao,
fbo,
texture,
width,
height,
byte_size: (width as u64) * (height as u64) * 4,
last_push: None,
loc_uv_scale_time_maxr,
loc_rot01,
loc_rot2_inner01,
loc_inner2_glow012,
loc_audio012_pad,
loc_colors_a,
loc_colors_b,
})
}
/// Re-render the My Vibe offscreen texture only if `push` changed since the previous frame.
pub unsafe fn render_if_needed(&mut self, gl: &glow::Context, push: VibePushConstants) {
if self.last_push == Some(push) {
return;
}
self.last_push = Some(push);
let gpu = build_vibe_gpu_push(push, self.width, self.height);
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
gl.viewport(0, 0, self.width as i32, self.height as i32);
gl.disable(glow::BLEND);
gl.clear_color(0.0, 0.0, 0.0, 0.0);
gl.clear(glow::COLOR_BUFFER_BIT);
gl.use_program(Some(self.program));
gl.uniform_4_f32_slice(self.loc_uv_scale_time_maxr.as_ref(), &gpu.uv_scale_time_maxr);
gl.uniform_4_f32_slice(self.loc_rot01.as_ref(), &gpu.rot01);
gl.uniform_4_f32_slice(self.loc_rot2_inner01.as_ref(), &gpu.rot2_inner01);
gl.uniform_4_f32_slice(self.loc_inner2_glow012.as_ref(), &gpu.inner2_glow012);
gl.uniform_4_f32_slice(self.loc_audio012_pad.as_ref(), &gpu.audio012_pad);
gl.uniform_4_u32_slice(self.loc_colors_a.as_ref(), &gpu.colors_a);
gl.uniform_4_u32_slice(self.loc_colors_b.as_ref(), &gpu.colors_b);
gl.bind_vertex_array(Some(self.vao));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
gl.bind_vertex_array(None);
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
}
pub unsafe fn destroy(&mut self, gl: &glow::Context) {
gl.delete_framebuffer(self.fbo);
gl.delete_texture(self.texture);
gl.delete_vertex_array(self.vao);
gl.delete_program(self.program);
}
}