Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Split renderer into layers (#310)
Brendan Allan8be8949ea8f5
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex cb94c5d4c..133135447 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -95,12 +95,7 @@ impl Renderer {// frame_task = Some(tokio::spawn(async move {let frame = frame_renderer- .render(- segment_frames,- cap_rendering::Background::from(background),- &uniforms,- resolution_base,- )+ .render(segment_frames, background, &uniforms, resolution_base).await.unwrap();diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rsindex 429e35945..70af3ce0e 100644--- a/crates/project/src/configuration.rs+++ b/crates/project/src/configuration.rs@@ -161,7 +161,7 @@ pub struct ShadowConfiguration {#[serde(rename_all = "camelCase")]pub struct BackgroundConfiguration {pub source: BackgroundSource,- pub blur: u32,+ pub blur: f64,pub padding: f64,pub rounding: f64,pub inset: u32,@@ -175,7 +175,7 @@ impl Default for BackgroundConfiguration {fn default() -> Self {Self {source: BackgroundSource::default(),- blur: 0,+ blur: 0.0,padding: 0.0,rounding: 0.0,inset: 0,diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rsnew file mode 100644index 000000000..950a81315--- /dev/null+++ b/crates/rendering/src/composite_frame.rs@@ -0,0 +1,209 @@+use bytemuck::{Pod, Zeroable};+use wgpu::{include_wgsl, util::DeviceExt};++use crate::create_shader_render_pipeline;++pub struct CompositeVideoFramePipeline {+ pub bind_group_layout: wgpu::BindGroupLayout,+ pub render_pipeline: wgpu::RenderPipeline,+}++#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]+#[repr(C)]+pub struct CompositeVideoFrameUniforms {+ pub crop_bounds: [f32; 4],+ pub target_bounds: [f32; 4],+ pub output_size: [f32; 2],+ pub frame_size: [f32; 2],+ pub velocity_uv: [f32; 2],+ pub target_size: [f32; 2],+ pub rounding_px: f32,+ pub mirror_x: f32,+ pub motion_blur_amount: f32,+ pub camera_motion_blur_amount: f32,+ pub shadow: f32,+ pub shadow_size: f32,+ pub shadow_opacity: f32,+ pub shadow_blur: f32,+ pub _padding: [f32; 3],+}++impl CompositeVideoFrameUniforms {+ pub fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer {+ device.create_buffer_init(+ &(wgpu::util::BufferInitDescriptor {+ label: Some("CompositeVideoFrameUniforms Buffer"),+ contents: bytemuck::cast_slice(&[self]),+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ }),+ )+ }+}++pub struct CompositeFrameResources {+ pub bind_group: wgpu::BindGroup,+ pub bind_group_layout: wgpu::BindGroupLayout,+ pub uniforms_buffer: wgpu::Buffer,+ pub sampler: wgpu::Sampler,+}++impl CompositeVideoFramePipeline {+ pub fn new(device: &wgpu::Device) -> Self {+ let bind_group_layout = Self::bind_group_layout(device);+ let render_pipeline = create_shader_render_pipeline(+ device,+ &bind_group_layout,+ include_wgsl!("shaders/composite-video-frame.wgsl"),+ );++ Self {+ bind_group_layout,+ render_pipeline,+ }+ }++ // fn resources(+ // device: &wgpu::Device,+ // source_frame: &wgpu::TextureView,+ // target_frame: &wgpu::TextureView,+ // ) -> CompositeFrameResources {+ // let sampler = device.create_sampler(+ // &(wgpu::SamplerDescriptor {+ // address_mode_u: wgpu::AddressMode::ClampToEdge,+ // address_mode_v: wgpu::AddressMode::ClampToEdge,+ // address_mode_w: wgpu::AddressMode::ClampToEdge,+ // mag_filter: wgpu::FilterMode::Linear,+ // min_filter: wgpu::FilterMode::Linear,+ // mipmap_filter: wgpu::FilterMode::Nearest,+ // ..Default::default()+ // }),+ // );++ // let uniforms_buffer = CompositeVideoFrameUniforms::default().to_buffer(device);++ // let bind_group_layout = Self::bind_group_layout(device);++ // let bind_group = device.create_bind_group(+ // &(wgpu::BindGroupDescriptor {+ // layout: &bind_group_layout,+ // entries: &[+ // wgpu::BindGroupEntry {+ // binding: 0,+ // resource: uniforms_buffer.as_entire_binding(),+ // },+ // wgpu::BindGroupEntry {+ // binding: 1,+ // resource: wgpu::BindingResource::TextureView(source_frame),+ // },+ // wgpu::BindGroupEntry {+ // binding: 2,+ // resource: wgpu::BindingResource::TextureView(target_frame),+ // },+ // wgpu::BindGroupEntry {+ // binding: 3,+ // resource: wgpu::BindingResource::Sampler(&sampler),+ // },+ // ],+ // label: Some("bind_group"),+ // }),+ // );++ // CompositeFrameResources {+ // bind_group,+ // bind_group_layout,+ // uniforms_buffer,+ // sampler,+ // }+ // }++ fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("composite-video-frame.wgsl Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 3,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ })+ }++ pub fn bind_group(+ &self,+ device: &wgpu::Device,+ uniforms: &wgpu::Buffer,+ frame: &wgpu::TextureView,+ intermediate: &wgpu::TextureView,+ ) -> wgpu::BindGroup {+ let sampler = device.create_sampler(+ &(wgpu::SamplerDescriptor {+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ address_mode_w: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::FilterMode::Nearest,+ ..Default::default()+ }),+ );++ let bind_group = device.create_bind_group(+ &(wgpu::BindGroupDescriptor {+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: uniforms.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(frame),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::TextureView(intermediate),+ },+ wgpu::BindGroupEntry {+ binding: 3,+ resource: wgpu::BindingResource::Sampler(&sampler),+ },+ ],+ label: Some("bind_group"),+ }),+ );++ bind_group+ }+}diff --git a/crates/rendering/src/coord.rs b/crates/rendering/src/coord.rsnew file mode 100644index 000000000..17ab72a4f--- /dev/null+++ b/crates/rendering/src/coord.rs@@ -0,0 +1,127 @@+use std::ops::{Add, Deref, Mul, Sub};++use cap_project::{ProjectConfiguration, XY};++use crate::{ProjectUniforms, RenderOptions};++#[derive(Default, Clone, Copy, Debug)]+pub struct RawDisplaySpace;++// raw cursor data+#[derive(Default, Clone, Copy, Debug)]+pub struct RawDisplayUVSpace;++#[derive(Default, Clone, Copy, Debug)]+pub struct CroppedDisplaySpace;++#[derive(Default, Clone, Copy, Debug)]+pub struct FrameSpace;++#[derive(Default, Clone, Copy, Debug)]+pub struct TransformedDisplaySpace;++#[derive(Clone, Copy, Debug)]+pub struct Coord<TSpace> {+ pub coord: XY<f64>,+ pub space: TSpace,+}++impl<TSpace: Default> Coord<TSpace> {+ pub fn new(coord: XY<f64>) -> Self {+ Self {+ coord,+ space: TSpace::default(),+ }+ }++ pub fn clamp(self, min: XY<f64>, max: XY<f64>) -> Self {+ Self {+ coord: XY {+ x: self.coord.x.clamp(min.x, max.x),+ y: self.coord.y.clamp(min.y, max.y),+ },+ space: self.space,+ }+ }+}++impl<T> Deref for Coord<T> {+ type Target = XY<f64>;++ fn deref(&self) -> &Self::Target {+ &self.coord+ }+}++impl Coord<RawDisplayUVSpace> {+ pub fn to_raw_display_space(&self, options: &RenderOptions) -> Coord<RawDisplaySpace> {+ Coord::new(self.coord * options.screen_size.map(|v| v as f64))+ }++ pub fn to_frame_space(+ &self,+ options: &RenderOptions,+ project: &ProjectConfiguration,+ resolution_base: XY<u32>,+ ) -> Coord<FrameSpace> {+ self.to_raw_display_space(options)+ .to_cropped_display_space(options, project)+ .to_frame_space(options, project, resolution_base)+ }+}++impl Coord<RawDisplaySpace> {+ pub fn to_cropped_display_space(+ &self,+ options: &RenderOptions,+ project: &ProjectConfiguration,+ ) -> Coord<CroppedDisplaySpace> {+ let crop = ProjectUniforms::get_crop(options, project);+ Coord::new(self.coord - crop.position.map(|v| v as f64))+ }+}++impl Coord<CroppedDisplaySpace> {+ pub fn to_frame_space(+ &self,+ options: &RenderOptions,+ project: &ProjectConfiguration,+ resolution_base: XY<u32>,+ ) -> Coord<FrameSpace> {+ let padding = ProjectUniforms::get_display_offset(options, project, resolution_base);+ Coord::new(self.coord + *padding)+ }+}++impl<T> Add for Coord<T> {+ type Output = Self;++ fn add(self, rhs: Self) -> Self {+ Coord {+ coord: self.coord + rhs.coord,+ space: self.space,+ }+ }+}++impl<T> Sub for Coord<T> {+ type Output = Self;++ fn sub(self, rhs: Self) -> Self {+ Coord {+ coord: self.coord - rhs.coord,+ space: self.space,+ }+ }+}++impl<T> Mul<f64> for Coord<T> {+ type Output = Self;++ fn mul(self, rhs: f64) -> Self {+ Coord {+ coord: self.coord * rhs,+ space: self.space,+ }+ }+}diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rsnew file mode 100644index 000000000..2591afd49--- /dev/null+++ b/crates/rendering/src/frame_pipeline.rs@@ -0,0 +1,195 @@+use futures_intrusive::channel::shared::oneshot_channel;+use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;++use crate::{get_either, ProjectUniforms, RenderVideoConstants, RenderingError};++pub struct FramePipeline<'a, 'b> {+ pub state: &'a mut FramePipelineState<'b>,+ pub encoder: &'a mut FramePipelineEncoder,+}++pub struct FramePipelineState<'a> {+ pub constants: &'a RenderVideoConstants,+ pub uniforms: &'a ProjectUniforms,+ pub textures: &'a (wgpu::Texture, wgpu::Texture),+ pub texture_views: (wgpu::TextureView, wgpu::TextureView),+ output_is_left: bool,+}++impl<'a> FramePipelineState<'a> {+ pub fn new(+ constants: &'a RenderVideoConstants,+ uniforms: &'a ProjectUniforms,+ textures: &'a (wgpu::Texture, wgpu::Texture),+ ) -> Self {+ let texture_views = (+ textures+ .0+ .create_view(&wgpu::TextureViewDescriptor::default()),+ textures+ .1+ .create_view(&wgpu::TextureViewDescriptor::default()),+ );++ Self {+ constants,+ uniforms,+ textures,+ texture_views,+ output_is_left: true,+ }+ }++ pub fn get_current_texture_view(&self) -> &wgpu::TextureView {+ get_either(+ (&self.texture_views.0, &self.texture_views.1),+ self.output_is_left,+ )+ }++ pub fn get_other_texture_view(&self) -> &wgpu::TextureView {+ get_either(+ (&self.texture_views.0, &self.texture_views.1),+ !self.output_is_left,+ )+ }++ pub fn get_current_texture(&self) -> &wgpu::Texture {+ get_either((&self.textures.1, &self.textures.0), self.output_is_left)+ }++ pub fn get_other_texture(&self) -> &wgpu::Texture {+ get_either((&self.textures.1, &self.textures.0), !self.output_is_left)+ }++ pub fn switch_output(&mut self) {+ self.output_is_left = !self.output_is_left;+ }+}++pub struct FramePipelineEncoder {+ pub encoder: wgpu::CommandEncoder,+}++impl FramePipelineEncoder {+ pub fn new(state: &FramePipelineState) -> Self {+ Self {+ encoder: state.constants.device.create_command_encoder(+ &(wgpu::CommandEncoderDescriptor {+ label: Some("Render Encoder"),+ }),+ ),+ }+ }+ pub fn do_render_pass(+ &mut self,+ output_view: &wgpu::TextureView,+ render_pipeline: &wgpu::RenderPipeline,+ bind_group: wgpu::BindGroup,+ load_op: wgpu::LoadOp<wgpu::Color>,+ ) {+ let mut render_pass = self.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("Render Pass"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: output_view,+ resolve_target: None,+ ops: wgpu::Operations {+ load: load_op,+ store: wgpu::StoreOp::Store,+ },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ });++ render_pass.set_pipeline(render_pipeline);+ render_pass.set_bind_group(0, &bind_group, &[]);+ render_pass.draw(0..3, 0..1);+ }++ pub fn padded_bytes_per_row(&self, state: &FramePipelineState<'_>) -> u32 {+ // Calculate the aligned bytes per row+ let align = COPY_BYTES_PER_ROW_ALIGNMENT;+ let unpadded_bytes_per_row = state.uniforms.output_size.0 * 4;+ let padding = (align - (unpadded_bytes_per_row % align)) % align;+ let padded_bytes_per_row = unpadded_bytes_per_row + padding;++ // Ensure the padded_bytes_per_row is a multiple of 4 (32 bits)+ (padded_bytes_per_row + 3) & !3+ }++ pub async fn copy_output(+ self,+ state: FramePipelineState<'_>,+ ) -> Result<Vec<u8>, RenderingError> {+ let padded_bytes_per_row = self.padded_bytes_per_row(&state);+ let constants = &state.constants;++ constants+ .queue+ .submit(std::iter::once(self.encoder.finish()));++ let output_texture_size = wgpu::Extent3d {+ width: state.uniforms.output_size.0,+ height: state.uniforms.output_size.1,+ depth_or_array_layers: 1,+ };++ let output_buffer_size = (padded_bytes_per_row * state.uniforms.output_size.1) as u64;++ let output_buffer = constants.device.create_buffer(&wgpu::BufferDescriptor {+ size: output_buffer_size,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ label: Some("Output Buffer"),+ mapped_at_creation: false,+ });++ {+ let mut encoder = constants.device.create_command_encoder(+ &(wgpu::CommandEncoderDescriptor {+ label: Some("Copy Encoder"),+ }),+ );++ encoder.copy_texture_to_buffer(+ wgpu::ImageCopyTexture {+ texture: state.get_current_texture(),+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ wgpu::ImageCopyBuffer {+ buffer: &output_buffer,+ layout: wgpu::ImageDataLayout {+ offset: 0,+ bytes_per_row: Some(padded_bytes_per_row),+ rows_per_image: Some(state.uniforms.output_size.1),+ },+ },+ output_texture_size,+ );++ constants.queue.submit(std::iter::once(encoder.finish()));+ }++ let buffer_slice = output_buffer.slice(..);+ let (tx, rx) = oneshot_channel();+ buffer_slice.map_async(wgpu::MapMode::Read, move |result| {+ tx.send(result).ok();+ });+ constants.device.poll(wgpu::Maintain::Wait);++ rx.receive()+ .await+ .ok_or(RenderingError::BufferMapWaitingFailed)??;++ let data = buffer_slice.get_mapped_range();+ let data_vec = data.to_vec();++ drop(data);+ output_buffer.unmap();++ Ok(data_vec)+ }+}diff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rsnew file mode 100644index 000000000..6ce266a55--- /dev/null+++ b/crates/rendering/src/layers/background.rs@@ -0,0 +1,611 @@+use std::collections::HashMap;++use bytemuck::{Pod, Zeroable};+use cap_project::BackgroundSource;+use image::GenericImageView;+use serde::{Deserialize, Serialize};+use specta::Type;+use wgpu::{include_wgsl, util::DeviceExt};++use crate::{+ create_shader_render_pipeline, frame_pipeline::FramePipeline, srgb_to_linear, RenderingError,+};++#[derive(Debug, Clone, Serialize, Deserialize, Type)]+pub enum Background {+ Color([f32; 4]),+ Gradient {+ start: [f32; 4],+ end: [f32; 4],+ angle: f32,+ },+ Image {+ path: String,+ },+}++impl From<BackgroundSource> for Background {+ fn from(value: BackgroundSource) -> Self {+ match value {+ BackgroundSource::Color { value } => Background::Color([+ srgb_to_linear(value[0]),+ srgb_to_linear(value[1]),+ srgb_to_linear(value[2]),+ 1.0,+ ]),+ BackgroundSource::Gradient { from, to, angle } => Background::Gradient {+ start: [+ srgb_to_linear(from[0]),+ srgb_to_linear(from[1]),+ srgb_to_linear(from[2]),+ 1.0,+ ],+ end: [+ srgb_to_linear(to[0]),+ srgb_to_linear(to[1]),+ srgb_to_linear(to[2]),+ 1.0,+ ],+ angle: angle as f32,+ },+ BackgroundSource::Image { path } | BackgroundSource::Wallpaper { path } => {+ if let Some(path) = path {+ if !path.is_empty() {+ let clean_path = path+ .replace("asset://localhost/", "/")+ .replace("asset://", "")+ .replace("localhost//", "/");++ if std::path::Path::new(&clean_path).exists() {+ return Background::Image { path: clean_path };+ }+ }+ }+ Background::Color([1.0, 1.0, 1.0, 1.0])+ }+ }+ }+}++pub struct BackgroundLayer;++impl BackgroundLayer {+ pub async fn render<'a, 'b>(+ pipeline: &mut FramePipeline<'a, 'b>,+ background: Background,+ ) -> Result<(), RenderingError> {+ let constants = pipeline.state.constants;+ let uniforms = pipeline.state.uniforms;++ // First, handle the background+ match background {+ Background::Image { path } => {+ let mut textures = constants.background_textures.write().await;+ let texture = match textures.entry(path.clone()) {+ std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),+ std::collections::hash_map::Entry::Vacant(e) => {+ let img = image::open(&path)+ .map_err(|e| RenderingError::ImageLoadError(e.to_string()))?;+ let rgba = img.to_rgba8();+ let dimensions = img.dimensions();++ let texture = constants.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("Background Image Texture"),+ size: wgpu::Extent3d {+ width: dimensions.0,+ height: dimensions.1,+ depth_or_array_layers: 1,+ },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::Rgba8UnormSrgb,+ usage: wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ });++ constants.queue.write_texture(+ wgpu::ImageCopyTexture {+ texture: &texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ &rgba,+ wgpu::ImageDataLayout {+ offset: 0,+ bytes_per_row: Some(4 * dimensions.0),+ rows_per_image: Some(dimensions.1),+ },+ wgpu::Extent3d {+ width: dimensions.0,+ height: dimensions.1,+ depth_or_array_layers: 1,+ },+ );++ e.insert(texture)+ }+ };++ let output_ar = uniforms.output_size.1 as f32 / uniforms.output_size.0 as f32;+ let image_ar = texture.height() as f32 / texture.width() as f32;++ let y_height = if output_ar < image_ar {+ ((image_ar - output_ar) / 2.0) / image_ar+ } else {+ 0.0+ };++ let x_width = if output_ar > image_ar {+ let output_ar = 1.0 / output_ar;+ let image_ar = 1.0 / image_ar;++ ((image_ar - output_ar) / 2.0) / image_ar+ } else {+ 0.0+ };++ let image_uniforms = ImageBackgroundUniforms {+ output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],+ padding: 0.0,+ x_width,+ y_height,+ _padding: 0.0,+ };++ let uniform_buffer =+ constants+ .device+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: Some("Image Background Uniforms"),+ contents: bytemuck::cast_slice(&[image_uniforms]),+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ });++ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());+ let bind_group = constants.image_background_pipeline.bind_group(+ &constants.device,+ &uniform_buffer,+ &texture_view,+ );++ pipeline.encoder.do_render_pass(+ pipeline.state.get_current_texture_view(),+ &constants.image_background_pipeline.render_pipeline,+ bind_group,+ wgpu::LoadOp::Clear(wgpu::Color::BLACK),+ );+ }+ _ => {+ let bind_group = constants.gradient_or_color_pipeline.bind_group(+ &constants.device,+ &GradientOrColorUniforms::from(background).to_buffer(&constants.device),+ );++ pipeline.encoder.do_render_pass(+ pipeline.state.get_current_texture_view(),+ &constants.gradient_or_color_pipeline.render_pipeline,+ bind_group,+ wgpu::LoadOp::Clear(wgpu::Color::BLACK),+ );+ }+ }++ pipeline.state.switch_output();++ if uniforms.project.background.blur > 0.0 {+ let blur_strength = uniforms.project.background.blur as f32 / 100.0;+ let blur_uniform = BackgroundBlurUniforms {+ output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],+ blur_strength,+ _padding: 0.0,+ };+ let blur_buffer =+ constants+ .device+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: Some("BackgroundBlur Uniform Buffer"),+ contents: bytemuck::cast_slice(&[blur_uniform]),+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ });+ let sampler = constants.device.create_sampler(&wgpu::SamplerDescriptor {+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ address_mode_w: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::FilterMode::Nearest,+ ..Default::default()+ });++ let blur_bind_group = constants.background_blur_pipeline.bind_group(+ &constants.device,+ &blur_buffer,+ pipeline.state.get_other_texture_view(),+ &sampler,+ );++ pipeline.encoder.do_render_pass(+ pipeline.state.get_current_texture_view(),+ &constants.background_blur_pipeline.render_pipeline,+ blur_bind_group,+ wgpu::LoadOp::Clear(wgpu::Color::BLACK),+ );++ pipeline.state.switch_output();+ }++ Ok(())+ }+}++pub struct ImageBackgroundPipeline {+ pub bind_group_layout: wgpu::BindGroupLayout,+ pub render_pipeline: wgpu::RenderPipeline,+}++#[repr(C)]+#[derive(Copy, Clone, Pod, Zeroable)]+pub struct ImageBackgroundUniforms {+ output_size: [f32; 2],+ padding: f32,+ x_width: f32,+ y_height: f32,+ _padding: f32, // For alignment+}++impl ImageBackgroundPipeline {+ pub fn new(device: &wgpu::Device) -> Self {+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("ImageBackgroundBindGroupLayout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });+ let shader = device.create_shader_module(include_wgsl!("../shaders/image-background.wgsl"));++ let empty_constants: HashMap<String, f64> = HashMap::new();++ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("ImageBackgroundPipeline"),+ layout: Some(+ &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("ImageBackgroundPipelineLayout"),+ bind_group_layouts: &[&bind_group_layout],+ push_constant_ranges: &[],+ }),+ ),+ vertex: wgpu::VertexState {+ module: &shader,+ entry_point: "vs_main",+ buffers: &[],+ compilation_options: wgpu::PipelineCompilationOptions {+ constants: &empty_constants,+ zero_initialize_workgroup_memory: false,+ vertex_pulling_transform: false,+ },+ },+ fragment: Some(wgpu::FragmentState {+ module: &shader,+ entry_point: "fs_main",+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8UnormSrgb,+ blend: Some(wgpu::BlendState::REPLACE),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: wgpu::PipelineCompilationOptions {+ constants: &empty_constants,+ zero_initialize_workgroup_memory: false,+ vertex_pulling_transform: false,+ },+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleList,+ strip_index_format: None,+ front_face: wgpu::FrontFace::Ccw,+ cull_mode: Some(wgpu::Face::Back),+ unclipped_depth: false,+ polygon_mode: wgpu::PolygonMode::Fill,+ conservative: false,+ },+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview: None,+ cache: None,+ });++ Self {+ bind_group_layout,+ render_pipeline,+ }+ }++ pub fn bind_group(+ &self,+ device: &wgpu::Device,+ uniforms: &wgpu::Buffer,+ texture: &wgpu::TextureView,+ ) -> wgpu::BindGroup {+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ address_mode_w: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::FilterMode::Linear,+ ..Default::default()+ });++ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("ImageBackgroundBindGroup"),+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: uniforms.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(texture),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::Sampler(&sampler),+ },+ ],+ })+ }+}++pub struct GradientOrColorPipeline {+ pub bind_group_layout: wgpu::BindGroupLayout,+ pub render_pipeline: wgpu::RenderPipeline,+}++#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]+#[repr(C)]+pub struct GradientOrColorUniforms {+ pub start: [f32; 4],+ pub end: [f32; 4],+ pub angle: f32,+ _padding: [f32; 3],+}++impl GradientOrColorUniforms {+ fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer {+ device.create_buffer_init(+ &(wgpu::util::BufferInitDescriptor {+ label: Some("GradientOrColorUniforms Buffer"),+ contents: bytemuck::cast_slice(&[self]),+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ }),+ )+ }+}++impl From<Background> for GradientOrColorUniforms {+ fn from(value: Background) -> Self {+ match value {+ Background::Color(color) => Self {+ start: color,+ end: color,+ angle: 0.0,+ _padding: [0.0; 3],+ },+ Background::Gradient { start, end, angle } => Self {+ start,+ end,+ angle,+ _padding: [0.0; 3],+ },+ Background::Image { .. } => {+ unreachable!("Image backgrounds should be handled separately")+ }+ }+ }+}++impl GradientOrColorPipeline {+ pub fn new(device: &wgpu::Device) -> Self {+ let bind_group_layout = Self::bind_group_layout(device);+ let render_pipeline = create_shader_render_pipeline(+ device,+ &bind_group_layout,+ include_wgsl!("../shaders/gradient-or-color.wgsl"),+ );++ Self {+ bind_group_layout,+ render_pipeline,+ }+ }++ fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("composite-video-frame.wgsl Bind Group Layout"),+ entries: &[wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ }],+ })+ }++ pub fn bind_group(&self, device: &wgpu::Device, uniforms: &wgpu::Buffer) -> wgpu::BindGroup {+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ layout: &self.bind_group_layout,+ entries: &[wgpu::BindGroupEntry {+ binding: 0,+ resource: uniforms.as_entire_binding(),+ }],+ label: Some("bind_group"),+ });++ bind_group+ }+}++#[repr(C)]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+pub struct BackgroundBlurUniforms {+ output_size: [f32; 2],+ blur_strength: f32,+ _padding: f32,+}++pub struct BackgroundBlurPipeline {+ pub bind_group_layout: wgpu::BindGroupLayout,+ pub render_pipeline: wgpu::RenderPipeline,+}++impl BackgroundBlurPipeline {+ pub fn new(device: &wgpu::Device) -> Self {+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("background-blur Bind Group Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("Background Blur Shader"),+ source: wgpu::ShaderSource::Wgsl(+ include_str!("../shaders/background-blur.wgsl").into(),+ ),+ });+ let empty_constants: HashMap<String, f64> = HashMap::new();+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("Background Blur Pipeline Layout"),+ bind_group_layouts: &[&bind_group_layout],+ push_constant_ranges: &[],+ });+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("Background Blur Pipeline"),+ layout: Some(&pipeline_layout),+ vertex: wgpu::VertexState {+ module: &shader,+ entry_point: "vs_main",+ buffers: &[],+ compilation_options: wgpu::PipelineCompilationOptions {+ constants: &empty_constants,+ zero_initialize_workgroup_memory: false,+ vertex_pulling_transform: false,+ },+ },+ fragment: Some(wgpu::FragmentState {+ module: &shader,+ entry_point: "fs_main",+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8UnormSrgb,+ blend: Some(wgpu::BlendState::REPLACE),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: wgpu::PipelineCompilationOptions {+ constants: &empty_constants,+ zero_initialize_workgroup_memory: false,+ vertex_pulling_transform: false,+ },+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleList,+ strip_index_format: None,+ front_face: wgpu::FrontFace::Ccw,+ cull_mode: Some(wgpu::Face::Back),+ polygon_mode: wgpu::PolygonMode::Fill,+ unclipped_depth: false,+ conservative: false,+ },+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview: None,+ cache: None,+ });+ Self {+ bind_group_layout,+ render_pipeline,+ }+ }++ pub fn bind_group(+ &self,+ device: &wgpu::Device,+ uniform_buffer: &wgpu::Buffer,+ texture_view: &wgpu::TextureView,+ sampler: &wgpu::Sampler,+ ) -> wgpu::BindGroup {+ device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("BackgroundBlur Bind Group"),+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: uniform_buffer.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(texture_view),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::Sampler(sampler),+ },+ ],+ })+ }+}diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rsnew file mode 100644index 000000000..3d25b3a4b--- /dev/null+++ b/crates/rendering/src/layers/camera.rs@@ -0,0 +1,51 @@+use cap_project::XY;++use crate::{frame_pipeline::FramePipeline, CompositeVideoFrameUniforms, DecodedFrame};++pub struct CameraLayer;++impl CameraLayer {+ pub fn render(+ pipeline: &mut FramePipeline,+ camera_size: XY<u32>,+ camera_frame: &DecodedFrame,+ uniforms: &CompositeVideoFrameUniforms,+ (texture, texture_view): (&wgpu::Texture, &wgpu::TextureView),+ ) {+ let constants = pipeline.state.constants;++ constants.queue.write_texture(+ wgpu::ImageCopyTexture {+ texture: &texture,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ camera_frame,+ wgpu::ImageDataLayout {+ offset: 0,+ bytes_per_row: Some(camera_size.x * 4),+ rows_per_image: None,+ },+ wgpu::Extent3d {+ width: camera_size.x,+ height: camera_size.y,+ depth_or_array_layers: 1,+ },+ );++ pipeline.encoder.do_render_pass(+ pipeline.state.get_current_texture_view(),+ &constants.composite_video_frame_pipeline.render_pipeline,+ constants.composite_video_frame_pipeline.bind_group(+ &constants.device,+ &uniforms.to_buffer(&constants.device),+ &texture_view,+ pipeline.state.get_other_texture_view(),+ ),+ wgpu::LoadOp::Load,+ );++ pipeline.state.switch_output();+ }+}diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rsnew file mode 100644index 000000000..c161ccb9a--- /dev/null+++ b/crates/rendering/src/layers/cursor.rs@@ -0,0 +1,418 @@+use std::collections::HashMap;++use bytemuck::{Pod, Zeroable};+use cap_project::*;+use wgpu::{include_wgsl, util::DeviceExt};++use crate::{+ frame_pipeline::{FramePipeline, FramePipelineState},+ Coord, DecodedSegmentFrames, RawDisplayUVSpace, STANDARD_CURSOR_HEIGHT,+};++pub struct CursorLayer;++impl CursorLayer {+ pub fn render(+ pipeline: &mut FramePipeline,+ segment_frames: &DecodedSegmentFrames,+ resolution_base: XY<u32>,+ ) {+ let FramePipelineState {+ uniforms,+ constants,+ ..+ } = &pipeline.state;+ let segment_time = segment_frames.segment_time;++ let Some(cursor_position) = interpolate_cursor_position(+ &Default::default(), // constants.cursor,+ segment_time,+ &uniforms.project.cursor.animation_style,+ ) else {+ return;+ };++ // Calculate previous position for velocity+ let prev_position = interpolate_cursor_position(+ &Default::default(), // constants.cursor,+ segment_time - 1.0 / 30.0,+ &uniforms.project.cursor.animation_style,+ );++ // Calculate velocity in screen space+ let velocity = if let Some(prev_pos) = prev_position {+ let curr_frame_pos = cursor_position.to_frame_space(+ &constants.options,+ &uniforms.project,+ resolution_base,+ );+ let prev_frame_pos =+ prev_pos.to_frame_space(&constants.options, &uniforms.project, resolution_base);+ let frame_velocity = curr_frame_pos.coord - prev_frame_pos.coord;++ // Convert to pixels per frame+ [frame_velocity.x as f32, frame_velocity.y as f32]+ } else {+ [0.0, 0.0]+ };++ // Calculate motion blur amount based on velocity magnitude+ let speed = (velocity[0] * velocity[0] + velocity[1] * velocity[1]).sqrt();+ let motion_blur_amount =+ (speed * 0.3).min(1.0) * uniforms.project.motion_blur.unwrap_or(0.8);++ let cursor = Default::default();+ let cursor_event = find_cursor_event(&cursor /* constants.cursor */, segment_time);++ let last_click_time = /* constants+ .cursor+ .clicks */ Vec::<CursorClickEvent>::new()+ .iter()+ .filter(|click| click.down && click.process_time_ms <= (segment_time as f64) * 1000.0)+ .max_by_key(|click| click.process_time_ms as i64)+ .map(|click| ((segment_time as f64) * 1000.0 - click.process_time_ms) as f32 / 1000.0)+ .unwrap_or(1.0);++ let Some(cursor_texture) = constants.cursor_textures.get(&cursor_event.cursor_id) else {+ return;+ };++ let cursor_size = cursor_texture.size();+ let aspect_ratio = cursor_size.width as f32 / cursor_size.height as f32;++ let cursor_size_percentage = if uniforms.cursor_size <= 0.0 {+ 100.0+ } else {+ uniforms.cursor_size / 100.0+ };++ let normalized_size = [+ STANDARD_CURSOR_HEIGHT * aspect_ratio * cursor_size_percentage,+ STANDARD_CURSOR_HEIGHT * cursor_size_percentage,+ ];++ let frame_position =+ cursor_position.to_frame_space(&constants.options, &uniforms.project, resolution_base);+ // let position = uniforms.zoom.apply_scale(frame_position);+ let position = frame_position;+ let relative_position = [position.x as f32, position.y as f32];++ let cursor_uniforms = CursorUniforms {+ position: [relative_position[0], relative_position[1], 0.0, 0.0],+ size: [normalized_size[0], normalized_size[1], 0.0, 0.0],+ output_size: [+ uniforms.output_size.0 as f32,+ uniforms.output_size.1 as f32,+ 0.0,+ 0.0,+ ],+ screen_bounds: uniforms.display.target_bounds,+ cursor_size: cursor_size_percentage,+ last_click_time,+ velocity,+ motion_blur_amount,+ _alignment: [0.0; 7],+ };++ let cursor_uniform_buffer =+ constants+ .device+ .create_buffer_init(&wgpu::util::BufferInitDescriptor {+ label: Some("Cursor Uniform Buffer"),+ contents: bytemuck::cast_slice(&[cursor_uniforms]),+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ });++ let cursor_bind_group = constants+ .device+ .create_bind_group(&wgpu::BindGroupDescriptor {+ layout: &constants.cursor_pipeline.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: cursor_uniform_buffer.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(+ &cursor_texture.create_view(&wgpu::TextureViewDescriptor::default()),+ ),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::Sampler(+ &constants+ .device+ .create_sampler(&wgpu::SamplerDescriptor::default()),+ ),+ },+ ],+ label: Some("Cursor Bind Group"),+ });++ pipeline.encoder.do_render_pass(+ pipeline.state.get_current_texture_view(),+ &constants.cursor_pipeline.render_pipeline,+ cursor_bind_group,+ wgpu::LoadOp::Load,+ );++ pipeline.state.switch_output();+ }+}++pub struct CursorPipeline {+ bind_group_layout: wgpu::BindGroupLayout,+ render_pipeline: wgpu::RenderPipeline,+}++#[repr(C, align(16))]+#[derive(Debug, Clone, Copy, Pod, Zeroable)]+pub struct CursorUniforms {+ position: [f32; 4],+ size: [f32; 4],+ output_size: [f32; 4],+ screen_bounds: [f32; 4],+ cursor_size: f32,+ last_click_time: f32,+ velocity: [f32; 2],+ motion_blur_amount: f32,+ _alignment: [f32; 7],+}++pub fn find_cursor_event(cursor: &CursorData, time: f32) -> &CursorMoveEvent {+ let time_ms = time * 1000.0;++ let event = cursor+ .moves+ .iter()+ .rev()+ .find(|event| {+ // println!("Checking event at time: {}ms", event.process_time_ms);+ event.process_time_ms <= time_ms.into()+ })+ .unwrap_or(&cursor.moves[0]);++ event+}++impl CursorPipeline {+ pub fn new(device: &wgpu::Device) -> Self {+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("Cursor Pipeline Layout"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: Some(std::num::NonZeroU64::new(112).unwrap()),+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });++ let shader = device.create_shader_module(include_wgsl!("../shaders/cursor.wgsl"));++ let empty_constants: HashMap<String, f64> = HashMap::new();++ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("Cursor Pipeline"),+ layout: Some(+ &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("Cursor Pipeline Layout"),+ bind_group_layouts: &[&bind_group_layout],+ push_constant_ranges: &[],+ }),+ ),+ vertex: wgpu::VertexState {+ module: &shader,+ entry_point: "vs_main",+ buffers: &[],+ compilation_options: wgpu::PipelineCompilationOptions {+ constants: &empty_constants,+ zero_initialize_workgroup_memory: false,+ vertex_pulling_transform: false,+ },+ },+ fragment: Some(wgpu::FragmentState {+ module: &shader,+ entry_point: "fs_main",+ targets: &[Some(wgpu::ColorTargetState {+ format: wgpu::TextureFormat::Rgba8UnormSrgb,+ blend: Some(wgpu::BlendState {+ color: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+ alpha: wgpu::BlendComponent {+ src_factor: wgpu::BlendFactor::One,+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,+ operation: wgpu::BlendOperation::Add,+ },+ }),+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: wgpu::PipelineCompilationOptions {+ constants: &empty_constants,+ zero_initialize_workgroup_memory: false,+ vertex_pulling_transform: false,+ },+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleStrip,+ strip_index_format: None,+ front_face: wgpu::FrontFace::Ccw,+ cull_mode: None,+ unclipped_depth: false,+ polygon_mode: wgpu::PolygonMode::Fill,+ conservative: false,+ },+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ multiview: None,+ cache: None,+ });++ Self {+ bind_group_layout,+ render_pipeline,+ }+ }+}++fn interpolate_cursor_position(+ cursor: &CursorData,+ time_secs: f32,+ animation_style: &CursorAnimationStyle,+) -> Option<Coord<RawDisplayUVSpace>> {+ let time_ms = (time_secs * 1000.0) as f64;++ if cursor.moves.is_empty() {+ return None;+ }++ // Get style-specific parameters+ let (num_samples, velocity_threshold) = match animation_style {+ CursorAnimationStyle::Slow => (SLOW_SMOOTHING_SAMPLES, SLOW_VELOCITY_THRESHOLD),+ CursorAnimationStyle::Regular => (REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD),+ CursorAnimationStyle::Fast => (FAST_SMOOTHING_SAMPLES, FAST_VELOCITY_THRESHOLD),+ };++ // Find the closest move events around current time+ let mut closest_events: Vec<&CursorMoveEvent> = cursor+ .moves+ .iter()+ .filter(|m| (m.process_time_ms - time_ms).abs() <= 100.0) // Look at events within 100ms+ .collect();++ closest_events.sort_by(|a, b| {+ (a.process_time_ms - time_ms)+ .abs()+ .partial_cmp(&(b.process_time_ms - time_ms).abs())+ .unwrap()+ });++ // Take the nearest events up to num_samples+ let samples: Vec<(f64, f64, f64)> = closest_events+ .iter()+ .take(num_samples)+ .map(|m| (m.process_time_ms, m.x, m.y))+ .collect();++ if samples.is_empty() {+ // Fallback to nearest event if no samples in range+ let nearest = cursor+ .moves+ .iter()+ .min_by_key(|m| (m.process_time_ms - time_ms).abs() as i64)?;+ return Some(Coord::new(XY {+ x: nearest.x.clamp(0.0, 1.0),+ y: nearest.y.clamp(0.0, 1.0),+ }));+ }++ // Calculate velocities between consecutive points+ let mut velocities = Vec::with_capacity(samples.len() - 1);+ for i in 0..samples.len() - 1 {+ let (t1, x1, y1) = samples[i];+ let (t2, x2, y2) = samples[i + 1];+ let dt = (t2 - t1).max(1.0); // Avoid division by zero+ let dx = x2 - x1;+ let dy = y2 - y1;+ let velocity = ((dx * dx + dy * dy) / (dt * dt)).sqrt();+ velocities.push(velocity);+ }++ // Apply adaptive smoothing based on velocities and time distance+ let mut x = 0.0;+ let mut y = 0.0;+ let mut total_weight = 0.0;++ for (i, &(t, px, py)) in samples.iter().enumerate() {+ // Time-based weight with style-specific falloff+ let time_diff = (t - time_ms).abs();+ let style_factor = match animation_style {+ CursorAnimationStyle::Slow => 0.0005,+ CursorAnimationStyle::Regular => 0.001,+ CursorAnimationStyle::Fast => 0.002,+ };+ let time_weight = 1.0 / (1.0 + time_diff * style_factor);++ // Velocity-based weight+ let velocity_weight = if i < velocities.len() {+ let vel = velocities[i];+ if vel > velocity_threshold {+ (velocity_threshold / vel).powf(match animation_style {+ CursorAnimationStyle::Slow => 1.5,+ CursorAnimationStyle::Regular => 1.0,+ CursorAnimationStyle::Fast => 0.5,+ })+ } else {+ 1.0+ }+ } else {+ 1.0+ };++ // Combine weights with style-specific emphasis+ let weight = match animation_style {+ CursorAnimationStyle::Slow => time_weight * velocity_weight.powf(1.5),+ CursorAnimationStyle::Regular => time_weight * velocity_weight,+ CursorAnimationStyle::Fast => time_weight * velocity_weight.powf(0.5),+ };++ x += px * weight;+ y += py * weight;+ total_weight += weight;+ }++ if total_weight > 0.0 {+ x /= total_weight;+ y /= total_weight;+ }++ Some(Coord::new(XY {+ x: x.clamp(0.0, 1.0),+ y: y.clamp(0.0, 1.0),+ }))+}diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rsnew file mode 100644index 000000000..20fa01281--- /dev/null+++ b/crates/rendering/src/layers/display.rs@@ -0,0 +1,47 @@+use crate::{frame_pipeline::FramePipeline, DecodedSegmentFrames};++pub struct DisplayLayer {+ // composite_resources: CompositeFrameResources,+}++impl DisplayLayer {+ pub fn render(pipeline: &mut FramePipeline, segment_frames: &DecodedSegmentFrames) {+ let constants = pipeline.state.constants;+ let uniforms = pipeline.state.uniforms;+ let frame_size = pipeline.state.constants.options.screen_size;++ constants.queue.write_texture(+ wgpu::ImageCopyTexture {+ texture: &constants.screen_frame.0,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::All,+ },+ &segment_frames.screen_frame,+ wgpu::ImageDataLayout {+ offset: 0,+ bytes_per_row: Some(constants.options.screen_size.x * 4),+ rows_per_image: None,+ },+ wgpu::Extent3d {+ width: frame_size.x,+ height: frame_size.y,+ depth_or_array_layers: 1,+ },+ );++ pipeline.encoder.do_render_pass(+ pipeline.state.get_current_texture_view(),+ &constants.composite_video_frame_pipeline.render_pipeline,+ constants.composite_video_frame_pipeline.bind_group(+ &constants.device,+ &uniforms.display.to_buffer(&constants.device),+ &constants.screen_frame.1,+ pipeline.state.get_other_texture_view(),+ ),+ wgpu::LoadOp::Load,+ );++ pipeline.state.switch_output();+ }+}diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rsnew file mode 100644index 000000000..8323af4f2--- /dev/null+++ b/crates/rendering/src/layers/mod.rs@@ -0,0 +1,9 @@+mod background;+mod camera;+mod cursor;+mod display;++pub use background::*;+pub use camera::*;+pub use cursor::*;+pub use display::*;diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 543d23d60..dce85da66 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -1,36 +1,34 @@use anyhow::Result;-use bytemuck::{Pod, Zeroable};-use cap_flags::FLAGS;use cap_project::{- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Content, Crop,- CursorAnimationStyle, CursorClickEvent, CursorData, CursorEvents, CursorMoveEvent,- ProjectConfiguration, RecordingMeta, FAST_SMOOTHING_SAMPLES, FAST_VELOCITY_THRESHOLD,- REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD, SLOW_SMOOTHING_SAMPLES,- SLOW_VELOCITY_THRESHOLD, XY,+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Content, Crop, CursorEvents,+ ProjectConfiguration, RecordingMeta, XY,};+use composite_frame::{CompositeVideoFramePipeline, CompositeVideoFrameUniforms};use core::f64;use decoder::{spawn_decoder, AsyncVideoDecoderHandle};+use frame_pipeline::{FramePipeline, FramePipelineEncoder, FramePipelineState};use futures::future::OptionFuture;use futures::FutureExt;-use futures_intrusive::channel::shared::oneshot_channel;-use reactive_graph::computed::ArcMemo;-use reactive_graph::signal::{arc_signal, ArcReadSignal, ArcWriteSignal};-use reactive_graph::traits::{Get, Write};-use serde::{Deserialize, Serialize};+use layers::{+ Background, BackgroundBlurPipeline, BackgroundLayer, CameraLayer, CursorLayer, CursorPipeline,+ DisplayLayer, GradientOrColorPipeline, ImageBackgroundPipeline,+};use specta::Type;-use std::ops::{Add, Deref, Mul, Sub};use std::{collections::HashMap, sync::Arc};use tokio::sync::mpsc;-use wgpu::util::DeviceExt;-use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};use image::GenericImageView;-use std::path::{Path, PathBuf};-use std::time::{Duration, Instant};+use std::{path::PathBuf, time::Instant};+mod composite_frame;+mod coord;pub mod decoder;+mod frame_pipeline;+mod layers;mod project_recordings;mod zoom;++pub use coord::*;pub use decoder::DecodedFrame;pub use project_recordings::{ProjectRecordings, SegmentRecordings, Video};@@ -44,70 +42,6 @@ pub struct RenderOptions {pub screen_size: XY<u32>,}-#[derive(Debug, Clone, Type)]-pub struct WebcamStyle {- pub border_radius: f32,- pub shadow_color: [f32; 4],- pub shadow_blur: f32,- pub shadow_offset: (f32, f32),-}--#[derive(Debug, Clone, Serialize, Deserialize, Type)]-pub enum Background {- Color([f32; 4]),- Gradient {- start: [f32; 4],- end: [f32; 4],- angle: f32,- },- Image {- path: String,- },-}--impl From<BackgroundSource> for Background {- fn from(value: BackgroundSource) -> Self {- match value {- BackgroundSource::Color { value } => Background::Color([- srgb_to_linear(value[0]),- srgb_to_linear(value[1]),- srgb_to_linear(value[2]),- 1.0,- ]),- BackgroundSource::Gradient { from, to, angle } => Background::Gradient {- start: [- srgb_to_linear(from[0]),- srgb_to_linear(from[1]),- srgb_to_linear(from[2]),- 1.0,- ],- end: [- srgb_to_linear(to[0]),- srgb_to_linear(to[1]),- srgb_to_linear(to[2]),- 1.0,- ],- angle: angle as f32,- },- BackgroundSource::Image { path } | BackgroundSource::Wallpaper { path } => {- if let Some(path) = path {- if !path.is_empty() {- let clean_path = path- .replace("asset://localhost/", "/")- .replace("asset://", "")- .replace("localhost//", "/");-- if std::path::Path::new(&clean_path).exists() {- return Background::Image { path: clean_path };- }- }- }- Background::Color([1.0, 1.0, 1.0, 1.0])- }- }- }-}-#[derive(Clone)]pub struct RecordingSegmentDecoders {screen: AsyncVideoDecoderHandle,@@ -220,7 +154,7 @@ pub async fn render_video_to_channel();let mut frame_number = 0;- let background = Background::from(project.background.source.clone());+ let background = project.background.source.clone();let mut frame_renderer = FrameRenderer::new(&constants);@@ -333,18 +267,14 @@ pub struct RenderVideoConstants {pub device: wgpu::Device,pub options: RenderOptions,composite_video_frame_pipeline: CompositeVideoFramePipeline,- gradient_or_color_pipeline: GradientOrColorPipeline,pub cursor_textures: HashMap<String, wgpu::Texture>,cursor_pipeline: CursorPipeline,- watermark_pipeline: WatermarkPipeline,- watermark_texture: wgpu::Texture,- watermark_bind_group: wgpu::BindGroup,- watermark_dimensions: (u32, u32),+ gradient_or_color_pipeline: GradientOrColorPipeline,image_background_pipeline: ImageBackgroundPipeline,+ pub background_blur_pipeline: BackgroundBlurPipeline,background_textures: std::sync::Arc<tokio::sync::RwLock<HashMap<String, wgpu::Texture>>>,screen_frame: (wgpu::Texture, wgpu::TextureView),camera_frame: Option<(wgpu::Texture, wgpu::TextureView)>,- pub background_blur_pipeline: BackgroundBlurPipeline,}impl RenderVideoConstants {@@ -367,96 +297,9 @@ impl RenderVideoConstants {let cursor_textures = Self::load_cursor_textures(&device, &queue, meta);let cursor_pipeline = CursorPipeline::new(&device);- let watermark_pipeline = WatermarkPipeline::new(&device);let composite_video_frame_pipeline = CompositeVideoFramePipeline::new(&device);let gradient_or_color_pipeline = GradientOrColorPipeline::new(&device);- let watermark_bytes = include_bytes!("../assets/watermark.png");- println!(- "Loading watermark texture from embedded bytes: {} bytes",- watermark_bytes.len()- );-- let watermark_image = image::load_from_memory(watermark_bytes).unwrap();- let watermark_rgba = watermark_image.to_rgba8();- let dimensions = watermark_image.dimensions();- println!(- "Loaded watermark image dimensions: {}x{}",- dimensions.0, dimensions.1- );-- let watermark_texture = device.create_texture(&wgpu::TextureDescriptor {- label: Some("WatermarkTexture"),- size: wgpu::Extent3d {- width: dimensions.0,- height: dimensions.1,- depth_or_array_layers: 1,- },- mip_level_count: 1,- sample_count: 1,- dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,- view_formats: &[],- });-- queue.write_texture(- wgpu::ImageCopyTexture {- texture: &watermark_texture,- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::All,- },- &watermark_rgba,- wgpu::ImageDataLayout {- offset: 0,- bytes_per_row: Some(4 * dimensions.0),- rows_per_image: Some(dimensions.1),- },- wgpu::Extent3d {- width: dimensions.0,- height: dimensions.1,- depth_or_array_layers: 1,- },- );-- let watermark_view = watermark_texture.create_view(&wgpu::TextureViewDescriptor::default());- let watermark_sampler = device.create_sampler(&wgpu::SamplerDescriptor {- address_mode_u: wgpu::AddressMode::ClampToEdge,- address_mode_v: wgpu::AddressMode::ClampToEdge,- address_mode_w: wgpu::AddressMode::ClampToEdge,- mag_filter: wgpu::FilterMode::Linear,- min_filter: wgpu::FilterMode::Linear,- mipmap_filter: wgpu::FilterMode::Linear,- ..Default::default()- });-- let watermark_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {- label: Some("WatermarkUniformBuffer"),- size: std::mem::size_of::<WatermarkUniforms>() as u64,- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- mapped_at_creation: false,- });-- let watermark_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("WatermarkBindGroup"),- layout: &watermark_pipeline.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: wgpu::BindingResource::TextureView(&watermark_view),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::Sampler(&watermark_sampler),- },- wgpu::BindGroupEntry {- binding: 2,- resource: watermark_uniform_buffer.as_entire_binding(),- },- ],- });-let image_background_pipeline = ImageBackgroundPipeline::new(&device);let background_textures = Arc::new(tokio::sync::RwLock::new(HashMap::new()));@@ -522,10 +365,6 @@ impl RenderVideoConstants {gradient_or_color_pipeline,cursor_textures,cursor_pipeline,- watermark_pipeline,- watermark_texture,- watermark_bind_group,- watermark_dimensions: dimensions,image_background_pipeline,background_textures,screen_frame,@@ -795,11 +634,11 @@ impl ProjectUniforms {let output_size = Self::get_output_size(options, project, resolution_base);let frame_time = frame_number as f32 / fps as f32;- let cursor_position = interpolate_cursor_position(- &Default::default(), /*constants.cursor*/- frame_time,- &project.cursor.animation_style,- );+ // let cursor_position = interpolate_cursor_position(+ // &Default::default(), /*constants.cursor*/+ // frame_time,+ // &project.cursor.animation_style,+ // );// let zoom_keyframes = ZoomKeyframes::new(project);// let current_zoom = zoom_keyframes.interpolate(time as f64);@@ -1059,7 +898,7 @@ impl<'a> FrameRenderer<'a> {pub async fn render(&mut self,segment_frames: DecodedSegmentFrames,- background: Background,+ background: BackgroundSource,uniforms: &ProjectUniforms,resolution_base: XY<u32>,) -> Result<RenderedFrame, RenderingError> {@@ -1080,474 +919,51 @@ impl<'a> FrameRenderer<'a> {async fn produce_frame(constants: &RenderVideoConstants,segment_frames: DecodedSegmentFrames,- background: Background,+ background: BackgroundSource,uniforms: &ProjectUniforms,resolution_base: XY<u32>,textures: &(wgpu::Texture, wgpu::Texture),) -> Result<RenderedFrame, RenderingError> {- let mut encoder = constants.device.create_command_encoder(- &(wgpu::CommandEncoderDescriptor {- label: Some("Render Encoder"),- }),- );+ let background = Background::from(background);- let textures = (&textures.0, &textures.1);+ let mut state = FramePipelineState::new(constants, uniforms, textures);+ let mut encoder = FramePipelineEncoder::new(&state);- let texture_views = (- textures- .0- .create_view(&wgpu::TextureViewDescriptor::default()),- textures- .1- .create_view(&wgpu::TextureViewDescriptor::default()),- );- let texture_views = (&texture_views.0, &texture_views.1);-- let mut output_is_left = true;-- // First, handle the background- match background {- Background::Image { path } => {- let mut textures = constants.background_textures.write().await;- let texture = match textures.entry(path.clone()) {- std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),- std::collections::hash_map::Entry::Vacant(e) => {- let img = image::open(&path)- .map_err(|e| RenderingError::ImageLoadError(e.to_string()))?;- let rgba = img.to_rgba8();- let dimensions = img.dimensions();-- let texture = constants.device.create_texture(&wgpu::TextureDescriptor {- label: Some("Background Image Texture"),- size: wgpu::Extent3d {- width: dimensions.0,- height: dimensions.1,- depth_or_array_layers: 1,- },- mip_level_count: 1,- sample_count: 1,- dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,- view_formats: &[],- });-- constants.queue.write_texture(- wgpu::ImageCopyTexture {- texture: &texture,- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::All,- },- &rgba,- wgpu::ImageDataLayout {- offset: 0,- bytes_per_row: Some(4 * dimensions.0),- rows_per_image: Some(dimensions.1),- },- wgpu::Extent3d {- width: dimensions.0,- height: dimensions.1,- depth_or_array_layers: 1,- },- );-- e.insert(texture)- }- };-- let output_ar = uniforms.output_size.1 as f32 / uniforms.output_size.0 as f32;- let image_ar = texture.height() as f32 / texture.width() as f32;-- let y_height = if output_ar < image_ar {- ((image_ar - output_ar) / 2.0) / image_ar- } else {- 0.0- };-- let x_width = if output_ar > image_ar {- let output_ar = 1.0 / output_ar;- let image_ar = 1.0 / image_ar;-- ((image_ar - output_ar) / 2.0) / image_ar- } else {- 0.0- };-- let image_uniforms = ImageBackgroundUniforms {- output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],- padding: 0.0,- x_width,- y_height,- _padding: 0.0,- };-- let uniform_buffer =- constants- .device- .create_buffer_init(&wgpu::util::BufferInitDescriptor {- label: Some("Image Background Uniforms"),- contents: bytemuck::cast_slice(&[image_uniforms]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- });-- let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());- let bind_group = constants.image_background_pipeline.bind_group(- &constants.device,- &uniform_buffer,- &texture_view,- );-- do_render_pass(- &mut encoder,- get_either(texture_views, output_is_left),- &constants.image_background_pipeline.render_pipeline,- bind_group,- wgpu::LoadOp::Clear(wgpu::Color::BLACK),- );-- output_is_left = !output_is_left;- }- _ => {- let bind_group = constants.gradient_or_color_pipeline.bind_group(- &constants.device,- &GradientOrColorUniforms::from(background).to_buffer(&constants.device),- );-- do_render_pass(- &mut encoder,- get_either(texture_views, output_is_left),- &constants.gradient_or_color_pipeline.render_pipeline,- bind_group,- wgpu::LoadOp::Clear(wgpu::Color::BLACK),- );-- output_is_left = !output_is_left;- }- }-- {- let background_view = get_either(texture_views, !output_is_left);- if uniforms.project.background.blur > 0 {- let blur_strength = uniforms.project.background.blur as f32 / 100.0;- let blur_uniform = BackgroundBlurUniforms {- output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],- blur_strength,- _padding: 0.0,- };- let blur_buffer =- constants- .device- .create_buffer_init(&wgpu::util::BufferInitDescriptor {- label: Some("BackgroundBlur Uniform Buffer"),- contents: bytemuck::cast_slice(&[blur_uniform]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- });- let sampler = constants.device.create_sampler(&wgpu::SamplerDescriptor {- address_mode_u: wgpu::AddressMode::ClampToEdge,- address_mode_v: wgpu::AddressMode::ClampToEdge,- address_mode_w: wgpu::AddressMode::ClampToEdge,- mag_filter: wgpu::FilterMode::Linear,- min_filter: wgpu::FilterMode::Linear,- mipmap_filter: wgpu::FilterMode::Nearest,- ..Default::default()- });-- // Use the other texture view as the output target- let output_view = get_either(texture_views, output_is_left);-- let blur_bind_group = constants.background_blur_pipeline.bind_group(- &constants.device,- &blur_buffer,- background_view,- &sampler,- );-- do_render_pass(- &mut encoder,- output_view,- &constants.background_blur_pipeline.render_pipeline,- blur_bind_group,- wgpu::LoadOp::Clear(wgpu::Color::BLACK),- );-- output_is_left = !output_is_left;- }- }-- // Then render the screen frame{- let frame_size = constants.options.screen_size;-- constants.queue.write_texture(- wgpu::ImageCopyTexture {- texture: &constants.screen_frame.0,- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::All,- },- &segment_frames.screen_frame,- wgpu::ImageDataLayout {- offset: 0,- bytes_per_row: Some(constants.options.screen_size.x * 4),- rows_per_image: None,- },- wgpu::Extent3d {- width: frame_size.x,- height: frame_size.y,- depth_or_array_layers: 1,- },- );-- do_render_pass(- &mut encoder,- get_either(texture_views, output_is_left),- &constants.composite_video_frame_pipeline.render_pipeline,- constants.composite_video_frame_pipeline.bind_group(- &constants.device,- &uniforms.display.to_buffer(&constants.device),- &constants.screen_frame.1,- get_either(texture_views, !output_is_left),- ),- wgpu::LoadOp::Load,- );-- output_is_left = !output_is_left;- }-- // Then render the cursor- draw_cursor(- constants,- uniforms,- segment_frames.segment_time,- &mut encoder,- get_either(texture_views, !output_is_left),- resolution_base,- );-- // camera- if let (Some(camera_size), Some(camera_frame), Some(uniforms), Some((texture, texture_view))) = (- constants.options.camera_size,- &segment_frames.camera_frame,- &uniforms.camera,- &constants.camera_frame,- ) {- constants.queue.write_texture(- wgpu::ImageCopyTexture {- texture: &texture,- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::All,- },- camera_frame,- wgpu::ImageDataLayout {- offset: 0,- bytes_per_row: Some(camera_size.x * 4),- rows_per_image: None,- },- wgpu::Extent3d {- width: camera_size.x,- height: camera_size.y,- depth_or_array_layers: 1,- },- );-- do_render_pass(- &mut encoder,- get_either(texture_views, output_is_left),- &constants.composite_video_frame_pipeline.render_pipeline,- constants.composite_video_frame_pipeline.bind_group(- &constants.device,- &uniforms.to_buffer(&constants.device),- &texture_view,- get_either(texture_views, !output_is_left),- ),- wgpu::LoadOp::Load, // Load existing content- );-- output_is_left = !output_is_left;- }-- // Now submit the encoder- constants.queue.submit(std::iter::once(encoder.finish()));-- // Add watermark if not upgraded - moved to after all other rendering- if uniforms.project.background.inset <= 0 {- // Calculate watermark width as 10% of frame width, but no larger than 200px- let frame_width = uniforms.output_size.0 as f32;- let target_width = (frame_width * 0.15).min(280.0);- let aspect_ratio =- constants.watermark_dimensions.1 as f32 / constants.watermark_dimensions.0 as f32;-- // Increase padding from edges- let padding = frame_width * 0.02; // 2% of frame width for padding-- let watermark_uniforms = WatermarkUniforms {- output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],- watermark_size: [target_width, target_width * aspect_ratio],- position: [- padding,- uniforms.output_size.1 as f32 - (target_width * aspect_ratio) - padding,- ],- opacity: if uniforms.is_upgraded { 0.0 } else { 0.5 },- is_upgraded: if uniforms.is_upgraded { 1.0 } else { 0.0 },+ let mut pipeline = FramePipeline {+ state: &mut state,+ encoder: &mut encoder,};- // println!(- // "Rendering watermark at position: {:?}, size: {:?}, output_size: {:?}",- // watermark_uniforms.position,- // watermark_uniforms.watermark_size,- // watermark_uniforms.output_size- // );-- let watermark_buffer =- constants- .device- .create_buffer_init(&wgpu::util::BufferInitDescriptor {- label: Some("Watermark Uniforms Buffer"),- contents: bytemuck::cast_slice(&[watermark_uniforms]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- });-- let watermark_bind_group = constants- .device- .create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("WatermarkBindGroup"),- layout: &constants.watermark_pipeline.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: wgpu::BindingResource::TextureView(- &constants- .watermark_texture- .create_view(&wgpu::TextureViewDescriptor::default()),- ),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::Sampler(&constants.device.create_sampler(- &wgpu::SamplerDescriptor {- address_mode_u: wgpu::AddressMode::ClampToEdge,- address_mode_v: wgpu::AddressMode::ClampToEdge,- address_mode_w: wgpu::AddressMode::ClampToEdge,- mag_filter: wgpu::FilterMode::Linear,- min_filter: wgpu::FilterMode::Linear,- mipmap_filter: wgpu::FilterMode::Linear,- anisotropy_clamp: 16, // Add anisotropic filtering- ..Default::default()- },- )),- },- wgpu::BindGroupEntry {- binding: 2,- resource: watermark_buffer.as_entire_binding(),- },- ],- });-- let mut watermark_encoder =- constants- .device- .create_command_encoder(&wgpu::CommandEncoderDescriptor {- label: Some("WatermarkEncoder"),- });-- {- let mut render_pass =- watermark_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {- label: Some("WatermarkRenderPass"),- color_attachments: &[Some(wgpu::RenderPassColorAttachment {- view: get_either(texture_views, !output_is_left),- resolve_target: None,- ops: wgpu::Operations {- load: wgpu::LoadOp::Load,- store: wgpu::StoreOp::Store,- },- })],- depth_stencil_attachment: None,- timestamp_writes: None,- occlusion_query_set: None,- });-- render_pass.set_pipeline(&constants.watermark_pipeline.render_pipeline);- render_pass.set_bind_group(0, &watermark_bind_group, &[]);- render_pass.draw(0..6, 0..1); // Using 6 vertices for two triangles- // println!("Drew watermark with 6 vertices");+ BackgroundLayer::render(&mut pipeline, background).await?;++ DisplayLayer::render(&mut pipeline, &segment_frames);++ CursorLayer::render(&mut pipeline, &segment_frames, resolution_base);++ if let (+ Some(camera_size),+ Some(camera_frame),+ Some(uniforms),+ Some((texture, texture_view)),+ ) = (+ constants.options.camera_size,+ &segment_frames.camera_frame,+ &uniforms.camera,+ &constants.camera_frame,+ ) {+ CameraLayer::render(+ &mut pipeline,+ camera_size,+ camera_frame,+ uniforms,+ (texture, texture_view),+ );}-- constants.queue.submit(Some(watermark_encoder.finish()));}- let output_texture_size = wgpu::Extent3d {- width: uniforms.output_size.0,- height: uniforms.output_size.1,- depth_or_array_layers: 1,- };-- // Calculate the aligned bytes per row- let align = COPY_BYTES_PER_ROW_ALIGNMENT;- let unpadded_bytes_per_row = uniforms.output_size.0 * 4;- let padding = (align - (unpadded_bytes_per_row % align)) % align;- let padded_bytes_per_row = unpadded_bytes_per_row + padding;-- // Ensure the padded_bytes_per_row is a multiple of 4 (32 bits)- let padded_bytes_per_row = (padded_bytes_per_row + 3) & !3;-- let output_buffer_size = (padded_bytes_per_row * uniforms.output_size.1) as u64;-- let output_buffer = constants.device.create_buffer(&wgpu::BufferDescriptor {- size: output_buffer_size,- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,- label: Some("Output Buffer"),- mapped_at_creation: false,- });-- {- let mut encoder = constants.device.create_command_encoder(- &(wgpu::CommandEncoderDescriptor {- label: Some("Copy Encoder"),- }),- );-- encoder.copy_texture_to_buffer(- wgpu::ImageCopyTexture {- texture: get_either(textures, !output_is_left),- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::All,- },- wgpu::ImageCopyBuffer {- buffer: &output_buffer,- layout: wgpu::ImageDataLayout {- offset: 0,- bytes_per_row: Some(padded_bytes_per_row),- rows_per_image: Some(uniforms.output_size.1),- },- },- output_texture_size,- );-- constants.queue.submit(std::iter::once(encoder.finish()));- }-- let buffer_slice = output_buffer.slice(..);- let (tx, rx) = oneshot_channel();- buffer_slice.map_async(wgpu::MapMode::Read, move |result| {- tx.send(result).ok();- });- constants.device.poll(wgpu::Maintain::Wait);-- rx.receive()- .await- .ok_or(RenderingError::BufferMapWaitingFailed)??;-- let data = buffer_slice.get_mapped_range();-- let image_data = data.to_vec();-- // Unmap the buffer- drop(data);- output_buffer.unmap();+ let padded_bytes_per_row = encoder.padded_bytes_per_row(&state);+ let image_data = encoder.copy_output(state).await?;Ok(RenderedFrame {data: image_data,@@ -1557,564 +973,12 @@ async fn produce_frame(})}-fn draw_cursor(- constants: &RenderVideoConstants,- uniforms: &ProjectUniforms,- segment_time: f32,- encoder: &mut CommandEncoder,- view: &wgpu::TextureView,- resolution_base: XY<u32>,-) {- let Some(cursor_position) = interpolate_cursor_position(- &Default::default(), // constants.cursor,- segment_time,- &uniforms.project.cursor.animation_style,- ) else {- return;- };-- // Calculate previous position for velocity- let prev_position = interpolate_cursor_position(- &Default::default(), // constants.cursor,- segment_time - 1.0 / 30.0,- &uniforms.project.cursor.animation_style,- );-- // Calculate velocity in screen space- let velocity = if let Some(prev_pos) = prev_position {- let curr_frame_pos =- cursor_position.to_frame_space(&constants.options, &uniforms.project, resolution_base);- let prev_frame_pos =- prev_pos.to_frame_space(&constants.options, &uniforms.project, resolution_base);- let frame_velocity = curr_frame_pos.coord - prev_frame_pos.coord;-- // Convert to pixels per frame- [frame_velocity.x as f32, frame_velocity.y as f32]- } else {- [0.0, 0.0]- };-- // Calculate motion blur amount based on velocity magnitude- let speed = (velocity[0] * velocity[0] + velocity[1] * velocity[1]).sqrt();- let motion_blur_amount = (speed * 0.3).min(1.0) * uniforms.project.motion_blur.unwrap_or(0.8);-- let cursor = Default::default();- let cursor_event = find_cursor_event(&cursor /* constants.cursor */, segment_time);-- let last_click_time = /* constants- .cursor- .clicks */ Vec::<CursorClickEvent>::new()- .iter()- .filter(|click| click.down && click.process_time_ms <= (segment_time as f64) * 1000.0)- .max_by_key(|click| click.process_time_ms as i64)- .map(|click| ((segment_time as f64) * 1000.0 - click.process_time_ms) as f32 / 1000.0)- .unwrap_or(1.0);-- let Some(cursor_texture) = constants.cursor_textures.get(&cursor_event.cursor_id) else {- return;- };-- let cursor_size = cursor_texture.size();- let aspect_ratio = cursor_size.width as f32 / cursor_size.height as f32;-- let cursor_size_percentage = if uniforms.cursor_size <= 0.0 {- 100.0- } else {- uniforms.cursor_size / 100.0- };-- let normalized_size = [- STANDARD_CURSOR_HEIGHT * aspect_ratio * cursor_size_percentage,- STANDARD_CURSOR_HEIGHT * cursor_size_percentage,- ];-- let frame_position =- cursor_position.to_frame_space(&constants.options, &uniforms.project, resolution_base);- // let position = uniforms.zoom.apply_scale(frame_position);- let position = frame_position;- let relative_position = [position.x as f32, position.y as f32];-- let cursor_uniforms = CursorUniforms {- position: [relative_position[0], relative_position[1], 0.0, 0.0],- size: [normalized_size[0], normalized_size[1], 0.0, 0.0],- output_size: [- uniforms.output_size.0 as f32,- uniforms.output_size.1 as f32,- 0.0,- 0.0,- ],- screen_bounds: uniforms.display.target_bounds,- cursor_size: cursor_size_percentage,- last_click_time,- velocity,- motion_blur_amount,- _alignment: [0.0; 7],- };-- let cursor_uniform_buffer =- constants- .device- .create_buffer_init(&wgpu::util::BufferInitDescriptor {- label: Some("Cursor Uniform Buffer"),- contents: bytemuck::cast_slice(&[cursor_uniforms]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- });-- let cursor_bind_group = constants- .device- .create_bind_group(&wgpu::BindGroupDescriptor {- layout: &constants.cursor_pipeline.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: cursor_uniform_buffer.as_entire_binding(),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::TextureView(- &cursor_texture.create_view(&wgpu::TextureViewDescriptor::default()),- ),- },- wgpu::BindGroupEntry {- binding: 2,- resource: wgpu::BindingResource::Sampler(- &constants- .device- .create_sampler(&wgpu::SamplerDescriptor::default()),- ),- },- ],- label: Some("Cursor Bind Group"),- });-- let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {- label: Some("Cursor Render Pass"),- color_attachments: &[Some(wgpu::RenderPassColorAttachment {- view,- resolve_target: None,- ops: wgpu::Operations {- load: wgpu::LoadOp::Load,- store: wgpu::StoreOp::Store,- },- })],- depth_stencil_attachment: None,- timestamp_writes: None,- occlusion_query_set: None,- });-- render_pass.set_pipeline(&constants.cursor_pipeline.render_pipeline);- render_pass.set_bind_group(0, &cursor_bind_group, &[]);- render_pass.draw(0..4, 0..1);-}--struct CompositeVideoFramePipeline {- pub bind_group_layout: wgpu::BindGroupLayout,- pub render_pipeline: wgpu::RenderPipeline,-}--#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]-#[repr(C)]-struct CompositeVideoFrameUniforms {- pub crop_bounds: [f32; 4],- pub target_bounds: [f32; 4],- pub output_size: [f32; 2],- pub frame_size: [f32; 2],- pub velocity_uv: [f32; 2],- pub target_size: [f32; 2],- pub rounding_px: f32,- pub mirror_x: f32,- pub motion_blur_amount: f32,- pub camera_motion_blur_amount: f32,- pub shadow: f32,- pub shadow_size: f32,- pub shadow_opacity: f32,- pub shadow_blur: f32,- _padding: [f32; 3],-}--impl CompositeVideoFrameUniforms {- fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer {- device.create_buffer_init(- &(wgpu::util::BufferInitDescriptor {- label: Some("CompositeVideoFrameUniforms Buffer"),- contents: bytemuck::cast_slice(&[self]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- }),- )- }-}--impl CompositeVideoFramePipeline {- pub fn new(device: &wgpu::Device) -> Self {- let bind_group_layout = Self::bind_group_layout(device);- let render_pipeline =- create_shader_render_pipeline(device, &bind_group_layout, Self::shader());-- Self {- bind_group_layout,- render_pipeline,- }- }-- fn shader() -> &'static str {- include_str!("shaders/composite-video-frame.wgsl")- }-- fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("composite-video-frame.wgsl Bind Group Layout"),- entries: &[- wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,- ty: wgpu::BindingType::Buffer {- ty: wgpu::BufferBindingType::Uniform,- has_dynamic_offset: false,- min_binding_size: None,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 1,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Texture {- sample_type: wgpu::TextureSampleType::Float { filterable: true },- view_dimension: wgpu::TextureViewDimension::D2,- multisampled: false,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 2,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Texture {- sample_type: wgpu::TextureSampleType::Float { filterable: true },- view_dimension: wgpu::TextureViewDimension::D2,- multisampled: false,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 3,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),- count: None,- },- ],- })- }-- pub fn bind_group(- &self,- device: &wgpu::Device,- uniforms: &wgpu::Buffer,- frame: &wgpu::TextureView,- intermediate: &wgpu::TextureView,- ) -> wgpu::BindGroup {- let sampler = device.create_sampler(- &(wgpu::SamplerDescriptor {- address_mode_u: wgpu::AddressMode::ClampToEdge,- address_mode_v: wgpu::AddressMode::ClampToEdge,- address_mode_w: wgpu::AddressMode::ClampToEdge,- mag_filter: wgpu::FilterMode::Linear,- min_filter: wgpu::FilterMode::Linear,- mipmap_filter: wgpu::FilterMode::Nearest,- ..Default::default()- }),- );-- let bind_group = device.create_bind_group(- &(wgpu::BindGroupDescriptor {- layout: &self.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: uniforms.as_entire_binding(),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::TextureView(frame),- },- wgpu::BindGroupEntry {- binding: 2,- resource: wgpu::BindingResource::TextureView(intermediate),- },- wgpu::BindGroupEntry {- binding: 3,- resource: wgpu::BindingResource::Sampler(&sampler),- },- ],- label: Some("bind_group"),- }),- );-- bind_group- }-}--struct GradientOrColorPipeline {- pub bind_group_layout: wgpu::BindGroupLayout,- pub render_pipeline: wgpu::RenderPipeline,-}--#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]-#[repr(C)]-struct GradientOrColorUniforms {- pub start: [f32; 4],- pub end: [f32; 4],- pub angle: f32,- _padding: [f32; 3],-}--impl GradientOrColorUniforms {- fn to_buffer(self, device: &wgpu::Device) -> wgpu::Buffer {- device.create_buffer_init(- &(wgpu::util::BufferInitDescriptor {- label: Some("GradientOrColorUniforms Buffer"),- contents: bytemuck::cast_slice(&[self]),- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,- }),- )- }-}--impl From<Background> for GradientOrColorUniforms {- fn from(value: Background) -> Self {- match value {- Background::Color(color) => Self {- start: color,- end: color,- angle: 0.0,- _padding: [0.0; 3],- },- Background::Gradient { start, end, angle } => Self {- start,- end,- angle,- _padding: [0.0; 3],- },- Background::Image { .. } => {- unreachable!("Image backgrounds should be handled separately")- }- }- }-}--impl GradientOrColorPipeline {- pub fn new(device: &wgpu::Device) -> Self {- let bind_group_layout = Self::bind_group_layout(device);- let render_pipeline =- create_shader_render_pipeline(device, &bind_group_layout, Self::shader());-- Self {- bind_group_layout,- render_pipeline,- }- }-- fn shader() -> &'static str {- include_str!("shaders/gradient-or-color.wgsl")- }-- fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {- device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("composite-video-frame.wgsl Bind Group Layout"),- entries: &[wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,- ty: wgpu::BindingType::Buffer {- ty: wgpu::BufferBindingType::Uniform,- has_dynamic_offset: false,- min_binding_size: None,- },- count: None,- }],- })- }-- pub fn bind_group(&self, device: &wgpu::Device, uniforms: &wgpu::Buffer) -> wgpu::BindGroup {- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {- layout: &self.bind_group_layout,- entries: &[wgpu::BindGroupEntry {- binding: 0,- resource: uniforms.as_entire_binding(),- }],- label: Some("bind_group"),- });-- bind_group- }-}--#[repr(C)]-#[derive(Debug, Clone, Copy, Pod, Zeroable)]-struct BackgroundBlurUniforms {- output_size: [f32; 2],- blur_strength: f32,- _padding: f32,-}--struct BackgroundBlurPipeline {- pub bind_group_layout: wgpu::BindGroupLayout,- pub render_pipeline: wgpu::RenderPipeline,-}--impl BackgroundBlurPipeline {- pub fn new(device: &wgpu::Device) -> Self {- let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("background-blur Bind Group Layout"),- entries: &[- wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,- ty: wgpu::BindingType::Buffer {- ty: wgpu::BufferBindingType::Uniform,- has_dynamic_offset: false,- min_binding_size: None,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 1,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Texture {- sample_type: wgpu::TextureSampleType::Float { filterable: true },- view_dimension: wgpu::TextureViewDimension::D2,- multisampled: false,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 2,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),- count: None,- },- ],- });- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {- label: Some("Background Blur Shader"),- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/background-blur.wgsl").into()),- });- let empty_constants: HashMap<String, f64> = HashMap::new();- let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {- label: Some("Background Blur Pipeline Layout"),- bind_group_layouts: &[&bind_group_layout],- push_constant_ranges: &[],- });- let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("Background Blur Pipeline"),- layout: Some(&pipeline_layout),- vertex: wgpu::VertexState {- module: &shader,- entry_point: "vs_main",- buffers: &[],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- },- fragment: Some(wgpu::FragmentState {- module: &shader,- entry_point: "fs_main",- targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,- blend: Some(wgpu::BlendState::REPLACE),- write_mask: wgpu::ColorWrites::ALL,- })],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- }),- primitive: wgpu::PrimitiveState {- topology: wgpu::PrimitiveTopology::TriangleList,- strip_index_format: None,- front_face: wgpu::FrontFace::Ccw,- cull_mode: Some(wgpu::Face::Back),- polygon_mode: wgpu::PolygonMode::Fill,- unclipped_depth: false,- conservative: false,- },- depth_stencil: None,- multisample: wgpu::MultisampleState::default(),- multiview: None,- cache: None,- });- Self {- bind_group_layout,- render_pipeline,- }- }-- pub fn bind_group(- &self,- device: &wgpu::Device,- uniform_buffer: &wgpu::Buffer,- texture_view: &wgpu::TextureView,- sampler: &wgpu::Sampler,- ) -> wgpu::BindGroup {- device.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("BackgroundBlur Bind Group"),- layout: &self.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: uniform_buffer.as_entire_binding(),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::TextureView(texture_view),- },- wgpu::BindGroupEntry {- binding: 2,- resource: wgpu::BindingResource::Sampler(sampler),- },- ],- })- }-}--fn do_render_pass(- encoder: &mut wgpu::CommandEncoder,- output_view: &wgpu::TextureView,- render_pipeline: &wgpu::RenderPipeline,- bind_group: wgpu::BindGroup,- load_op: wgpu::LoadOp<wgpu::Color>,-) {- let mut render_pass = encoder.begin_render_pass(- &(wgpu::RenderPassDescriptor {- label: Some("Render Pass"),- color_attachments: &[Some(wgpu::RenderPassColorAttachment {- view: output_view,- resolve_target: None,- ops: wgpu::Operations {- load: load_op,- store: wgpu::StoreOp::Store,- },- })],- depth_stencil_attachment: None,- timestamp_writes: None,- occlusion_query_set: None,- }),- );-- render_pass.set_pipeline(render_pipeline);- render_pass.set_bind_group(0, &bind_group, &[]);- render_pass.draw(0..3, 0..1);-}--fn create_shader_render_pipeline(+pub fn create_shader_render_pipeline(device: &wgpu::Device,bind_group_layout: &wgpu::BindGroupLayout,- wgsl_shader: &str,+ shader: wgpu::ShaderModuleDescriptor,) -> wgpu::RenderPipeline {- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {- label: Some("Shader"),- source: wgpu::ShaderSource::Wgsl(wgsl_shader.into()),- });+ let shader = device.create_shader_module(shader);let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {label: Some("Render Pipeline Layout"),@@ -2187,653 +1051,3 @@ fn get_either<T>((a, b): (T, T), left: bool) -> T {b}}--fn interpolate_cursor_position(- cursor: &CursorData,- time_secs: f32,- animation_style: &CursorAnimationStyle,-) -> Option<Coord<RawDisplayUVSpace>> {- let time_ms = (time_secs * 1000.0) as f64;-- if cursor.moves.is_empty() {- return None;- }-- // Get style-specific parameters- let (num_samples, velocity_threshold) = match animation_style {- CursorAnimationStyle::Slow => (SLOW_SMOOTHING_SAMPLES, SLOW_VELOCITY_THRESHOLD),- CursorAnimationStyle::Regular => (REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD),- CursorAnimationStyle::Fast => (FAST_SMOOTHING_SAMPLES, FAST_VELOCITY_THRESHOLD),- };-- // Find the closest move events around current time- let mut closest_events: Vec<&CursorMoveEvent> = cursor- .moves- .iter()- .filter(|m| (m.process_time_ms - time_ms).abs() <= 100.0) // Look at events within 100ms- .collect();-- closest_events.sort_by(|a, b| {- (a.process_time_ms - time_ms)- .abs()- .partial_cmp(&(b.process_time_ms - time_ms).abs())- .unwrap()- });-- // Take the nearest events up to num_samples- let samples: Vec<(f64, f64, f64)> = closest_events- .iter()- .take(num_samples)- .map(|m| (m.process_time_ms, m.x, m.y))- .collect();-- if samples.is_empty() {- // Fallback to nearest event if no samples in range- let nearest = cursor- .moves- .iter()- .min_by_key(|m| (m.process_time_ms - time_ms).abs() as i64)?;- return Some(Coord::new(XY {- x: nearest.x.clamp(0.0, 1.0),- y: nearest.y.clamp(0.0, 1.0),- }));- }-- // Calculate velocities between consecutive points- let mut velocities = Vec::with_capacity(samples.len() - 1);- for i in 0..samples.len() - 1 {- let (t1, x1, y1) = samples[i];- let (t2, x2, y2) = samples[i + 1];- let dt = (t2 - t1).max(1.0); // Avoid division by zero- let dx = x2 - x1;- let dy = y2 - y1;- let velocity = ((dx * dx + dy * dy) / (dt * dt)).sqrt();- velocities.push(velocity);- }-- // Apply adaptive smoothing based on velocities and time distance- let mut x = 0.0;- let mut y = 0.0;- let mut total_weight = 0.0;-- for (i, &(t, px, py)) in samples.iter().enumerate() {- // Time-based weight with style-specific falloff- let time_diff = (t - time_ms).abs();- let style_factor = match animation_style {- CursorAnimationStyle::Slow => 0.0005,- CursorAnimationStyle::Regular => 0.001,- CursorAnimationStyle::Fast => 0.002,- };- let time_weight = 1.0 / (1.0 + time_diff * style_factor);-- // Velocity-based weight- let velocity_weight = if i < velocities.len() {- let vel = velocities[i];- if vel > velocity_threshold {- (velocity_threshold / vel).powf(match animation_style {- CursorAnimationStyle::Slow => 1.5,- CursorAnimationStyle::Regular => 1.0,- CursorAnimationStyle::Fast => 0.5,- })- } else {- 1.0- }- } else {- 1.0- };-- // Combine weights with style-specific emphasis- let weight = match animation_style {- CursorAnimationStyle::Slow => time_weight * velocity_weight.powf(1.5),- CursorAnimationStyle::Regular => time_weight * velocity_weight,- CursorAnimationStyle::Fast => time_weight * velocity_weight.powf(0.5),- };-- x += px * weight;- y += py * weight;- total_weight += weight;- }-- if total_weight > 0.0 {- x /= total_weight;- y /= total_weight;- }-- Some(Coord::new(XY {- x: x.clamp(0.0, 1.0),- y: y.clamp(0.0, 1.0),- }))-}--struct CursorPipeline {- bind_group_layout: wgpu::BindGroupLayout,- render_pipeline: wgpu::RenderPipeline,-}--#[repr(C, align(16))]-#[derive(Debug, Clone, Copy, Pod, Zeroable)]-struct CursorUniforms {- position: [f32; 4],- size: [f32; 4],- output_size: [f32; 4],- screen_bounds: [f32; 4],- cursor_size: f32,- last_click_time: f32,- velocity: [f32; 2],- motion_blur_amount: f32,- _alignment: [f32; 7],-}--fn find_cursor_event(cursor: &CursorData, time: f32) -> &CursorMoveEvent {- let time_ms = time * 1000.0;-- let event = cursor- .moves- .iter()- .rev()- .find(|event| {- // println!("Checking event at time: {}ms", event.process_time_ms);- event.process_time_ms <= time_ms.into()- })- .unwrap_or(&cursor.moves[0]);-- event-}--impl CursorPipeline {- pub fn new(device: &wgpu::Device) -> Self {- let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("Cursor Pipeline Layout"),- entries: &[- wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,- ty: wgpu::BindingType::Buffer {- ty: wgpu::BufferBindingType::Uniform,- has_dynamic_offset: false,- min_binding_size: Some(std::num::NonZeroU64::new(112).unwrap()),- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 1,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Texture {- sample_type: wgpu::TextureSampleType::Float { filterable: true },- view_dimension: wgpu::TextureViewDimension::D2,- multisampled: false,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 2,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),- count: None,- },- ],- });-- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {- label: Some("Cursor Shader"),- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/cursor.wgsl").into()),- });-- let empty_constants: HashMap<String, f64> = HashMap::new();-- let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("Cursor Pipeline"),- layout: Some(- &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {- label: Some("Cursor Pipeline Layout"),- bind_group_layouts: &[&bind_group_layout],- push_constant_ranges: &[],- }),- ),- vertex: wgpu::VertexState {- module: &shader,- entry_point: "vs_main",- buffers: &[],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- },- fragment: Some(wgpu::FragmentState {- module: &shader,- entry_point: "fs_main",- targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,- blend: Some(wgpu::BlendState {- color: wgpu::BlendComponent {- src_factor: wgpu::BlendFactor::One,- dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,- operation: wgpu::BlendOperation::Add,- },- alpha: wgpu::BlendComponent {- src_factor: wgpu::BlendFactor::One,- dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,- operation: wgpu::BlendOperation::Add,- },- }),- write_mask: wgpu::ColorWrites::ALL,- })],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- }),- primitive: wgpu::PrimitiveState {- topology: wgpu::PrimitiveTopology::TriangleStrip,- strip_index_format: None,- front_face: wgpu::FrontFace::Ccw,- cull_mode: None,- unclipped_depth: false,- polygon_mode: wgpu::PolygonMode::Fill,- conservative: false,- },- depth_stencil: None,- multisample: wgpu::MultisampleState::default(),- multiview: None,- cache: None,- });-- Self {- bind_group_layout,- render_pipeline,- }- }-}--#[derive(Default, Clone, Copy, Debug)]-struct RawDisplaySpace;--// raw cursor data-#[derive(Default, Clone, Copy, Debug)]-struct RawDisplayUVSpace;--#[derive(Default, Clone, Copy, Debug)]-struct CroppedDisplaySpace;--#[derive(Default, Clone, Copy, Debug)]-pub struct FrameSpace;--#[derive(Default, Clone, Copy, Debug)]-struct TransformedDisplaySpace;--#[derive(Clone, Copy, Debug)]-pub struct Coord<TSpace> {- coord: XY<f64>,- space: TSpace,-}--impl<TSpace: Default> Coord<TSpace> {- pub fn new(coord: XY<f64>) -> Self {- Self {- coord,- space: TSpace::default(),- }- }-- pub fn clamp(self, min: XY<f64>, max: XY<f64>) -> Self {- Self {- coord: XY {- x: self.coord.x.clamp(min.x, max.x),- y: self.coord.y.clamp(min.y, max.y),- },- space: self.space,- }- }-}--impl<T> Deref for Coord<T> {- type Target = XY<f64>;-- fn deref(&self) -> &Self::Target {- &self.coord- }-}--impl Coord<RawDisplayUVSpace> {- fn to_raw_display_space(&self, options: &RenderOptions) -> Coord<RawDisplaySpace> {- Coord::new(self.coord * options.screen_size.map(|v| v as f64))- }-- fn to_frame_space(- &self,- options: &RenderOptions,- project: &ProjectConfiguration,- resolution_base: XY<u32>,- ) -> Coord<FrameSpace> {- self.to_raw_display_space(options)- .to_cropped_display_space(options, project)- .to_frame_space(options, project, resolution_base)- }-}--impl Coord<RawDisplaySpace> {- fn to_cropped_display_space(- &self,- options: &RenderOptions,- project: &ProjectConfiguration,- ) -> Coord<CroppedDisplaySpace> {- let crop = ProjectUniforms::get_crop(options, project);- Coord::new(self.coord - crop.position.map(|v| v as f64))- }-}--impl Coord<CroppedDisplaySpace> {- fn to_frame_space(- &self,- options: &RenderOptions,- project: &ProjectConfiguration,- resolution_base: XY<u32>,- ) -> Coord<FrameSpace> {- let padding = ProjectUniforms::get_display_offset(options, project, resolution_base);- Coord::new(self.coord + *padding)- }-}--impl<T> Add for Coord<T> {- type Output = Self;-- fn add(self, rhs: Self) -> Self {- Coord {- coord: self.coord + rhs.coord,- space: self.space,- }- }-}--impl<T> Sub for Coord<T> {- type Output = Self;-- fn sub(self, rhs: Self) -> Self {- Coord {- coord: self.coord - rhs.coord,- space: self.space,- }- }-}--impl<T> Mul<f64> for Coord<T> {- type Output = Self;-- fn mul(self, rhs: f64) -> Self {- Coord {- coord: self.coord * rhs,- space: self.space,- }- }-}--struct WatermarkPipeline {- bind_group_layout: wgpu::BindGroupLayout,- render_pipeline: wgpu::RenderPipeline,-}--impl WatermarkPipeline {- pub fn new(device: &wgpu::Device) -> Self {- let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("WatermarkBindGroupLayout"),- entries: &[- wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Texture {- sample_type: wgpu::TextureSampleType::Float { filterable: true },- view_dimension: wgpu::TextureViewDimension::D2,- multisampled: false,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 1,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 2,- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,- ty: wgpu::BindingType::Buffer {- ty: wgpu::BufferBindingType::Uniform,- has_dynamic_offset: false,- min_binding_size: None,- },- count: None,- },- ],- });-- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {- label: Some("WatermarkShader"),- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/watermark.wgsl").into()),- });-- let empty_constants: HashMap<String, f64> = HashMap::new();-- let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("WatermarkPipeline"),- layout: Some(- &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {- label: Some("WatermarkPipelineLayout"),- bind_group_layouts: &[&bind_group_layout],- push_constant_ranges: &[],- }),- ),- vertex: wgpu::VertexState {- module: &shader,- entry_point: "vs_main",- buffers: &[],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- },- fragment: Some(wgpu::FragmentState {- module: &shader,- entry_point: "fs_main",- targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,- blend: Some(wgpu::BlendState {- color: wgpu::BlendComponent {- src_factor: wgpu::BlendFactor::One,- dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,- operation: wgpu::BlendOperation::Add,- },- alpha: wgpu::BlendComponent {- src_factor: wgpu::BlendFactor::One,- dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,- operation: wgpu::BlendOperation::Add,- },- }),- write_mask: wgpu::ColorWrites::ALL,- })],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- }),- primitive: wgpu::PrimitiveState {- topology: wgpu::PrimitiveTopology::TriangleStrip,- strip_index_format: None,- front_face: wgpu::FrontFace::Ccw,- cull_mode: None,- unclipped_depth: false,- polygon_mode: wgpu::PolygonMode::Fill,- conservative: false,- },- depth_stencil: None,- multisample: wgpu::MultisampleState::default(),- multiview: None,- cache: None,- });-- Self {- bind_group_layout,- render_pipeline,- }- }-}--#[repr(C)]-#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]-struct WatermarkUniforms {- output_size: [f32; 2],- watermark_size: [f32; 2],- position: [f32; 2],- opacity: f32,- is_upgraded: f32,-}--struct ImageBackgroundPipeline {- pub bind_group_layout: wgpu::BindGroupLayout,- pub render_pipeline: wgpu::RenderPipeline,-}--#[repr(C)]-#[derive(Copy, Clone, Pod, Zeroable)]-struct ImageBackgroundUniforms {- output_size: [f32; 2],- padding: f32,- x_width: f32,- y_height: f32,- _padding: f32, // For alignment-}--impl ImageBackgroundPipeline {- pub fn new(device: &wgpu::Device) -> Self {- let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {- label: Some("ImageBackgroundBindGroupLayout"),- entries: &[- wgpu::BindGroupLayoutEntry {- binding: 0,- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,- ty: wgpu::BindingType::Buffer {- ty: wgpu::BufferBindingType::Uniform,- has_dynamic_offset: false,- min_binding_size: None,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 1,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Texture {- sample_type: wgpu::TextureSampleType::Float { filterable: true },- view_dimension: wgpu::TextureViewDimension::D2,- multisampled: false,- },- count: None,- },- wgpu::BindGroupLayoutEntry {- binding: 2,- visibility: wgpu::ShaderStages::FRAGMENT,- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),- count: None,- },- ],- });-- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {- label: Some("ImageBackgroundShader"),- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/image-background.wgsl").into()),- });-- let empty_constants: HashMap<String, f64> = HashMap::new();-- let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("ImageBackgroundPipeline"),- layout: Some(- &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {- label: Some("ImageBackgroundPipelineLayout"),- bind_group_layouts: &[&bind_group_layout],- push_constant_ranges: &[],- }),- ),- vertex: wgpu::VertexState {- module: &shader,- entry_point: "vs_main",- buffers: &[],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- },- fragment: Some(wgpu::FragmentState {- module: &shader,- entry_point: "fs_main",- targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,- blend: Some(wgpu::BlendState::REPLACE),- write_mask: wgpu::ColorWrites::ALL,- })],- compilation_options: wgpu::PipelineCompilationOptions {- constants: &empty_constants,- zero_initialize_workgroup_memory: false,- vertex_pulling_transform: false,- },- }),- primitive: wgpu::PrimitiveState {- topology: wgpu::PrimitiveTopology::TriangleList,- strip_index_format: None,- front_face: wgpu::FrontFace::Ccw,- cull_mode: Some(wgpu::Face::Back),- unclipped_depth: false,- polygon_mode: wgpu::PolygonMode::Fill,- conservative: false,- },- depth_stencil: None,- multisample: wgpu::MultisampleState::default(),- multiview: None,- cache: None,- });-- Self {- bind_group_layout,- render_pipeline,- }- }-- pub fn bind_group(- &self,- device: &wgpu::Device,- uniforms: &wgpu::Buffer,- texture: &wgpu::TextureView,- ) -> wgpu::BindGroup {- let sampler = device.create_sampler(&wgpu::SamplerDescriptor {- address_mode_u: wgpu::AddressMode::ClampToEdge,- address_mode_v: wgpu::AddressMode::ClampToEdge,- address_mode_w: wgpu::AddressMode::ClampToEdge,- mag_filter: wgpu::FilterMode::Linear,- min_filter: wgpu::FilterMode::Linear,- mipmap_filter: wgpu::FilterMode::Linear,- ..Default::default()- });-- device.create_bind_group(&wgpu::BindGroupDescriptor {- label: Some("ImageBackgroundBindGroup"),- layout: &self.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: uniforms.as_entire_binding(),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::TextureView(texture),- },- wgpu::BindGroupEntry {- binding: 2,- resource: wgpu::BindingResource::Sampler(&sampler),- },- ],- })- }-}