Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: custom cursor implementation and render

Richie McIlroyd0f31d5db283
diff --git a/Cargo.lock b/Cargo.lock
index c22e355c7..e5bf984e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -747,6 +747,7 @@ dependencies = [
"ffmpeg-sys-next",
"futures",
"futures-intrusive",
+ "image 0.25.2",
"lru",
"nix 0.29.0",
"serde",
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 48f03adf6..ab2d59e22 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1061,6 +1061,7 @@ async fn render_to_file_impl(
tx_image_data,
decoders,
editor_instance.cursor.clone(),
+ editor_instance.project_path.clone(),
)
.await?;
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index d1837756f..1f2ec837e 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -280,6 +280,10 @@ pub async fn start(
let mut cursor_images = HashMap::new();
let mut seen_cursor_data: HashMap<Vec<u8>, String> = HashMap::new();
let mut next_cursor_id = 0;
+
+ // Create cursors directory if it doesn't exist
+ std::fs::create_dir_all(&cursors_dir).unwrap();
+
while !*stop_signal.lock().await {
let mouse_state = device_state.get_mouse();
let elapsed = start_time.elapsed().as_secs_f64() * 1000.0;
@@ -296,11 +300,16 @@ pub async fn start(
let filename = format!("cursor_{}.png", cursor_id);
let cursor_path = cursors_dir.join(&filename);
+ println!("Saving new cursor image to: {:?}", cursor_path);
+
if let Ok(image) = image::load_from_memory(&data) {
- if let Err(e) = image.save(&cursor_path) {
+ // Convert to RGBA
+ let rgba_image = image.into_rgba8();
+ if let Err(e) = rgba_image.save(&cursor_path) {
eprintln!("Failed to save cursor image: {}", e);
} else {
- cursor_images.insert(cursor_id.clone(), filename);
+ println!("Successfully saved cursor image {}", cursor_id);
+ cursor_images.insert(cursor_id.clone(), filename.clone());
seen_cursor_data.insert(data, cursor_id.clone());
next_cursor_id += 1;
}
@@ -339,14 +348,22 @@ pub async fn start(
tokio::time::sleep(Duration::from_millis(10)).await;
}
- // Save cursor data along with events
- let mut file = File::create(content_dir.join("cursor.json")).unwrap();
+ // Save cursor data to cursor.json
let cursor_data = CursorData {
clicks: clicks.clone(),
moves: moves.clone(),
cursor_images,
};
- serde_json::to_writer(&mut file, &cursor_data).unwrap();
+
+ let cursor_json_path = content_dir.join("cursor.json");
+ println!("Saving cursor data to: {:?}", cursor_json_path);
+ if let Ok(mut file) = File::create(&cursor_json_path) {
+ if let Err(e) = serde_json::to_writer(&mut file, &cursor_data) {
+ eprintln!("Failed to save cursor data: {}", e);
+ } else {
+ println!("Successfully saved cursor data");
+ }
+ }
move_tx.send(moves).unwrap();
click_tx.send(clicks).unwrap();
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 4cb6a6a51..f0b8a414c 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -103,6 +103,7 @@ pub enum RendererMessage {
camera_frame: Option<DecodedFrame>,
background: BackgroundSource,
uniforms: ProjectUniforms,
+ time: f32, // Add this field
finished: oneshot::Sender<()>,
},
Stop {
@@ -149,6 +150,7 @@ impl Renderer {
camera_frame,
background,
uniforms,
+ time, // Add this
finished,
} => {
if let Some(task) = frame_task.as_ref() {
@@ -163,17 +165,18 @@ impl Renderer {
let frame_tx = self.frame_tx.clone();
frame_task = Some(tokio::spawn(async move {
- let time = Instant::now();
+ let time_instant = Instant::now();
let frame = produce_frame(
&render_constants,
&screen_frame,
&camera_frame,
cap_rendering::Background::from(background),
&uniforms,
+ time, // Pass the actual time value
)
.await
.unwrap();
- // println!("produced frame in {:?}", time.elapsed());
+ // println!("produced frame in {:?}", time_instant.elapsed());
frame_tx
.send(SocketMessage::Frame {
@@ -212,6 +215,7 @@ impl RendererHandle {
camera_frame: Option<DecodedFrame>,
background: BackgroundSource,
uniforms: ProjectUniforms,
+ time: f32, // Add this parameter
) {
let (finished_tx, finished_rx) = oneshot::channel();
@@ -220,6 +224,7 @@ impl RendererHandle {
camera_frame,
background,
uniforms,
+ time, // Pass the time
finished: finished_tx,
})
.await;
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 59492009a..fcc0bc61a 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -110,9 +110,13 @@ impl EditorInstance {
let cursor = Arc::new(meta.cursor_data());
let render_constants = Arc::new(
- RenderVideoConstants::new(render_options, cursor.clone())
- .await
- .unwrap(),
+ RenderVideoConstants::new(
+ render_options,
+ cursor.clone(),
+ project_path.clone(), // Add project path argument
+ )
+ .await
+ .unwrap(),
);
let renderer = Arc::new(editor::Renderer::spawn(render_constants.clone(), frame_tx));
@@ -286,6 +290,7 @@ impl EditorInstance {
camera_frame,
project.background.source.clone(),
ProjectUniforms::new(&self.render_constants, &project, time as f32),
+ time as f32, // Add the time parameter
)
.await;
}
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 41498abdc..0a5027a6d 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -102,7 +102,8 @@ impl Playback {
screen_frame,
camera_frame,
project.background.source.clone(),
- uniforms.clone()
+ uniforms.clone(),
+ time as f32 // Add the time parameter
)
.await;
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 0ca599f2b..17f69b825 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -123,7 +123,7 @@ impl ScreenCaptureSource {
let options = Options {
fps,
- show_cursor: true,
+ show_cursor: false,
show_highlight: true,
excluded_targets: Some(excluded_targets),
output_type: FrameType::BGRAFrame,
diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rs
index b62c03bde..9d7f441c5 100644
--- a/crates/project/src/cursor.rs
+++ b/crates/project/src/cursor.rs
@@ -1,6 +1,9 @@
use serde::{Deserialize, Serialize};
+use serde_json;
use specta::Type;
use std::collections::HashMap;
+use std::fs::File;
+use std::path::Path;
#[derive(Serialize, Deserialize, Clone, Type, Debug)]
pub struct CursorEvent {
@@ -12,9 +15,17 @@ pub struct CursorEvent {
pub y: f64,
}
-#[derive(Default, Serialize, Deserialize, Debug)]
+#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct CursorData {
pub clicks: Vec<CursorEvent>,
pub moves: Vec<CursorEvent>,
pub cursor_images: HashMap<String, String>,
}
+
+impl CursorData {
+ // Add a helper method to load from a file
+ pub fn load_from_file(path: &Path) -> Result<Self, String> {
+ let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {}", e))?;
+ serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {}", e))
+ }
+}
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index bed309d21..b41642efe 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -92,10 +92,56 @@ impl RecordingMeta {
}
pub fn cursor_data(&self) -> CursorData {
- self.cursor
- .as_ref()
- .and_then(|c| std::fs::read(self.project_path.join(c)).ok())
- .and_then(|b| serde_json::from_slice(&b).ok())
- .unwrap_or_default()
+ if let Some(cursor_path) = &self.cursor {
+ let full_path = self.project_path.join(cursor_path);
+ println!("Loading cursor data from: {:?}", full_path);
+
+ // Try to load the cursor data
+ match CursorData::load_from_file(&full_path) {
+ Ok(mut data) => {
+ // If cursor_images is empty but cursor files exist, populate it
+ if data.cursor_images.is_empty() {
+ let cursors_dir = self.project_path.join("content").join("cursors");
+ if cursors_dir.exists() {
+ println!("Scanning cursors directory: {:?}", cursors_dir);
+ if let Ok(entries) = std::fs::read_dir(&cursors_dir) {
+ for entry in entries {
+ if let Ok(entry) = entry {
+ let filename = entry.file_name();
+ let filename_str = filename.to_string_lossy();
+ if filename_str.starts_with("cursor_")
+ && filename_str.ends_with(".png")
+ {
+ // Extract cursor ID from filename (cursor_X.png -> X)
+ if let Some(id) = filename_str
+ .strip_prefix("cursor_")
+ .and_then(|s| s.strip_suffix(".png"))
+ {
+ println!(
+ "Found cursor image: {} -> {}",
+ id, filename_str
+ );
+ data.cursor_images.insert(
+ id.to_string(),
+ filename.to_string_lossy().into_owned(),
+ );
+ }
+ }
+ }
+ }
+ }
+ println!("Found {} cursor images", data.cursor_images.len());
+ }
+ }
+ data
+ }
+ Err(e) => {
+ eprintln!("Failed to load cursor data: {}", e);
+ CursorData::default()
+ }
+ }
+ } else {
+ CursorData::default()
+ }
}
}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 57a018e17..eb165c38d 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -10,6 +10,7 @@ futures-intrusive = "0.5.0"
serde = "1.0.209"
specta = "2.0.0-rc.19"
wgpu = "22.1.0"
+image = "0.25.2"
cap-ffmpeg = { path = "../ffmpeg" }
cap-project = { path = "../project" }
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index f98e53878..0b250257e 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -10,15 +10,24 @@ use wgpu::util::DeviceExt;
use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
use cap_project::{
- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorData,
+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorData, CursorEvent,
ProjectConfiguration, XY,
};
use std::time::Instant;
+// Add this import at the top with the other imports
+use std::path::PathBuf;
+
+// Add this import at the top
+use image::GenericImageView;
+
pub mod decoder;
pub use decoder::DecodedFrame;
+// Add this constant at the top of the file
+const STANDARD_CURSOR_HEIGHT: f32 = 100.0; // Standard height for all cursors
+
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct RenderOptions {
pub camera_size: Option<(u32, u32)>,
@@ -112,8 +121,9 @@ pub async fn render_video_to_channel(
sender: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
decoders: RecordingDecoders,
cursor: Arc<CursorData>,
+ project_path: PathBuf, // Add project_path parameter
) -> Result<(), String> {
- let constants = RenderVideoConstants::new(options, cursor).await?;
+ let constants = RenderVideoConstants::new(options, cursor, project_path).await?;
println!("Setting up FFmpeg input for screen recording...");
@@ -156,6 +166,7 @@ pub async fn render_video_to_channel(
&camera_frame,
background,
&uniforms,
+ time as f32,
)
.await
{
@@ -208,10 +219,16 @@ pub struct RenderVideoConstants {
composite_video_frame_pipeline: CompositeVideoFramePipeline,
gradient_or_color_pipeline: GradientOrColorPipeline,
pub cursor: Arc<CursorData>,
+ pub cursor_textures: HashMap<String, wgpu::Texture>,
+ cursor_pipeline: CursorPipeline,
}
impl RenderVideoConstants {
- pub async fn new(options: RenderOptions, cursor: Arc<CursorData>) -> Result<Self, String> {
+ pub async fn new(
+ options: RenderOptions,
+ cursor: Arc<CursorData>,
+ project_path: PathBuf, // Add project_path parameter
+ ) -> Result<Self, String> {
println!("Initializing wgpu...");
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
let adapter = instance
@@ -223,6 +240,11 @@ impl RenderVideoConstants {
.await
.map_err(|e| e.to_string())?;
+ // Pass project_path to load_cursor_textures
+ let cursor_textures = Self::load_cursor_textures(&device, &queue, &cursor, &project_path)?;
+
+ let cursor_pipeline = CursorPipeline::new(&device);
+
Ok(Self {
composite_video_frame_pipeline: CompositeVideoFramePipeline::new(&device),
gradient_or_color_pipeline: GradientOrColorPipeline::new(&device),
@@ -232,8 +254,101 @@ impl RenderVideoConstants {
device,
options,
cursor,
+ cursor_textures,
+ cursor_pipeline,
})
}
+
+ fn load_cursor_textures(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ cursor: &CursorData,
+ project_path: &PathBuf, // Add project_path parameter
+ ) -> Result<HashMap<String, wgpu::Texture>, String> {
+ println!("Starting to load cursor textures");
+ println!("Project path: {:?}", project_path);
+ println!("Cursor images to load: {:?}", cursor.cursor_images);
+
+ let mut textures = HashMap::new();
+
+ // Create the full path to the cursors directory
+ let cursors_dir = project_path.join("content").join("cursors");
+ println!("Cursors directory: {:?}", cursors_dir);
+
+ for (cursor_id, filename) in &cursor.cursor_images {
+ println!("Loading cursor image: {} -> {}", cursor_id, filename);
+
+ let cursor_path = cursors_dir.join(filename);
+ println!("Full cursor path: {:?}", cursor_path);
+
+ if !cursor_path.exists() {
+ println!("Cursor image file does not exist: {:?}", cursor_path);
+ continue;
+ }
+
+ match image::open(&cursor_path) {
+ Ok(img) => {
+ let dimensions = img.dimensions();
+ println!(
+ "Loaded cursor image dimensions: {}x{}",
+ dimensions.0, dimensions.1
+ );
+
+ let rgba = img.into_rgba8();
+
+ // Create the texture
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(&format!("Cursor Texture {}", cursor_id)),
+ 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: &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: None,
+ },
+ wgpu::Extent3d {
+ width: dimensions.0,
+ height: dimensions.1,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ textures.insert(cursor_id.clone(), texture);
+ println!("Successfully loaded cursor texture: {}", cursor_id);
+ }
+ Err(e) => {
+ println!("Failed to load cursor image {}: {}", filename, e);
+ // Don't return error, just skip this cursor image
+ continue;
+ }
+ }
+ }
+
+ println!(
+ "Completed loading cursor textures. Total loaded: {}",
+ textures.len()
+ );
+ Ok(textures)
+ }
}
#[derive(Clone, Debug)]
@@ -467,20 +582,14 @@ impl ProjectUniforms {
}
pub async fn produce_frame(
- RenderVideoConstants {
- device,
- options,
- composite_video_frame_pipeline,
- gradient_or_color_pipeline,
- queue,
- ..
- }: &RenderVideoConstants,
+ constants: &RenderVideoConstants,
screen_frame: &Vec<u8>,
camera_frame: &Option<DecodedFrame>,
background: Background,
uniforms: &ProjectUniforms,
+ time: f32,
) -> Result<Vec<u8>, String> {
- let mut encoder = device.create_command_encoder(
+ let mut encoder = constants.device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
}),
@@ -504,8 +613,8 @@ pub async fn produce_frame(
};
let textures = (
- device.create_texture(&output_texture_desc),
- device.create_texture(&output_texture_desc),
+ constants.device.create_texture(&output_texture_desc),
+ constants.device.create_texture(&output_texture_desc),
);
let textures = (&textures.0, &textures.1);
@@ -523,30 +632,31 @@ pub async fn produce_frame(
let mut output_is_left = true;
- // background
+ // First, clear the background
{
do_render_pass(
&mut encoder,
get_either(texture_views, output_is_left),
- &gradient_or_color_pipeline.render_pipeline,
- gradient_or_color_pipeline.bind_group(
- device,
- &GradientOrColorUniforms::from(background).to_buffer(device),
+ &constants.gradient_or_color_pipeline.render_pipeline,
+ constants.gradient_or_color_pipeline.bind_group(
+ &constants.device,
+ &GradientOrColorUniforms::from(background).to_buffer(&constants.device),
),
+ wgpu::LoadOp::Clear(wgpu::Color::BLACK), // Clear on first pass
);
output_is_left = !output_is_left;
}
- // display
+ // Then render the screen frame
{
- let frame_size = options.screen_size;
+ let frame_size = constants.options.screen_size;
- let texture = device.create_texture(
+ let texture = constants.device.create_texture(
&(wgpu::TextureDescriptor {
size: wgpu::Extent3d {
- width: options.screen_size.0,
- height: options.screen_size.1,
+ width: constants.options.screen_size.0,
+ height: constants.options.screen_size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
@@ -563,7 +673,7 @@ pub async fn produce_frame(
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
- queue.write_texture(
+ constants.queue.write_texture(
wgpu::ImageCopyTexture {
texture: &texture,
mip_level: 0,
@@ -573,7 +683,7 @@ pub async fn produce_frame(
screen_frame,
wgpu::ImageDataLayout {
offset: 0,
- bytes_per_row: Some(options.screen_size.0 * 4),
+ bytes_per_row: Some(constants.options.screen_size.0 * 4),
rows_per_image: None,
},
wgpu::Extent3d {
@@ -586,23 +696,26 @@ pub async fn produce_frame(
do_render_pass(
&mut encoder,
get_either(texture_views, output_is_left),
- &composite_video_frame_pipeline.render_pipeline,
- composite_video_frame_pipeline.bind_group(
- device,
- &uniforms.display.to_buffer(device),
+ &constants.composite_video_frame_pipeline.render_pipeline,
+ constants.composite_video_frame_pipeline.bind_group(
+ &constants.device,
+ &uniforms.display.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;
}
// camera
- if let (Some(camera_size), Some(camera_frame), Some(uniforms)) =
- (options.camera_size, camera_frame, &uniforms.camera)
- {
- let texture = device.create_texture(
+ if let (Some(camera_size), Some(camera_frame), Some(uniforms)) = (
+ constants.options.camera_size,
+ camera_frame,
+ &uniforms.camera,
+ ) {
+ let texture = constants.device.create_texture(
&(wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width: camera_size.0,
@@ -623,7 +736,7 @@ pub async fn produce_frame(
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
- queue.write_texture(
+ constants.queue.write_texture(
wgpu::ImageCopyTexture {
texture: &texture,
mip_level: 0,
@@ -646,19 +759,127 @@ pub async fn produce_frame(
do_render_pass(
&mut encoder,
get_either(texture_views, output_is_left),
- &composite_video_frame_pipeline.render_pipeline,
- composite_video_frame_pipeline.bind_group(
- device,
- &uniforms.to_buffer(device),
+ &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;
}
- queue.submit(std::iter::once(encoder.finish()));
+ // Finally, render the cursor directly to the output texture
+ {
+ if let Some(cursor_position) = interpolate_cursor_position(&constants.cursor, time) {
+ println!(
+ "Raw cursor position: ({}, {})",
+ cursor_position.0, cursor_position.1
+ );
+
+ let cursor_event = find_cursor_event(&constants.cursor, time);
+ println!("Found cursor event with ID: {}", cursor_event.cursor_id);
+
+ if let Some(cursor_texture) = constants.cursor_textures.get(&cursor_event.cursor_id) {
+ let cursor_size = cursor_texture.size();
+ let aspect_ratio = cursor_size.width as f32 / cursor_size.height as f32;
+
+ // Calculate normalized size maintaining aspect ratio
+ let normalized_size = [
+ STANDARD_CURSOR_HEIGHT * aspect_ratio,
+ STANDARD_CURSOR_HEIGHT,
+ ];
+
+ println!(
+ "Original cursor size: {}x{}, Normalized size: {}x{}",
+ cursor_size.width, cursor_size.height, normalized_size[0], normalized_size[1]
+ );
+
+ // Convert normalized cursor position to screen space
+ let screen_x = cursor_position.0 * uniforms.output_size.0 as f64;
+ let screen_y = cursor_position.1 * uniforms.output_size.1 as f64;
+
+ println!("Screen position: ({}, {})", screen_x, screen_y);
+
+ let cursor_uniforms = CursorUniforms {
+ position: [screen_x as f32, screen_y as f32],
+ padding1: [0.0; 2],
+ size: normalized_size, // Use normalized size instead of original size
+ padding2: [0.0; 2],
+ output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],
+ padding3: [0.0; 2],
+ screen_bounds: uniforms.display.target_bounds,
+ };
+
+ println!("Cursor uniforms: {:?}", cursor_uniforms);
+
+ 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: 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.cursor_pipeline.render_pipeline);
+ render_pass.set_bind_group(0, &cursor_bind_group, &[]);
+ render_pass.draw(0..4, 0..1);
+
+ println!("Drew cursor");
+ }
+ }
+ }
+
+ // Now submit the encoder
+ constants.queue.submit(std::iter::once(encoder.finish()));
let output_texture_size = wgpu::Extent3d {
width: uniforms.output_size.0,
@@ -677,17 +898,15 @@ pub async fn produce_frame(
let output_buffer_size = (padded_bytes_per_row * uniforms.output_size.1) as u64;
- let output_buffer = 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 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 = device.create_command_encoder(
+ let mut encoder = constants.device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
label: Some("Copy Encoder"),
}),
@@ -711,7 +930,7 @@ pub async fn produce_frame(
output_texture_size,
);
- queue.submit(std::iter::once(encoder.finish()));
+ constants.queue.submit(std::iter::once(encoder.finish()));
}
let buffer_slice = output_buffer.slice(..);
@@ -719,7 +938,7 @@ pub async fn produce_frame(
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
tx.send(result).ok();
});
- device.poll(wgpu::Maintain::Wait);
+ constants.device.poll(wgpu::Maintain::Wait);
let Some(frame_result) = rx.receive().await else {
return Err("2: Channel closed unexpectedly".to_string());
@@ -976,11 +1195,13 @@ impl GradientOrColorPipeline {
}
}
+// Update the do_render_pass function to accept a LoadOp parameter
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 {
@@ -989,7 +1210,7 @@ fn do_render_pass(
view: output_view,
resolve_target: None,
ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ load: load_op,
store: wgpu::StoreOp::Store,
},
})],
@@ -1014,26 +1235,26 @@ fn create_shader_render_pipeline(
source: wgpu::ShaderSource::Wgsl(wgsl_shader.into()),
});
- let compilation_options = wgpu::PipelineCompilationOptions {
- constants: &HashMap::new(),
- zero_initialize_workgroup_memory: false,
- vertex_pulling_transform: false,
- };
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Render Pipeline Layout"),
+ bind_group_layouts: &[bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ let empty_constants: HashMap<String, f64> = HashMap::new();
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
- layout: Some(&device.create_pipeline_layout(
- &(wgpu::PipelineLayoutDescriptor {
- label: Some("Render Pipeline Layout"),
- bind_group_layouts: &[bind_group_layout],
- push_constant_ranges: &[],
- }),
- )),
+ layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[],
- compilation_options: compilation_options.clone(),
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &empty_constants,
+ zero_initialize_workgroup_memory: false,
+ vertex_pulling_transform: false,
+ },
},
fragment: Some(wgpu::FragmentState {
module: &shader,
@@ -1043,7 +1264,11 @@ fn create_shader_render_pipeline(
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
- compilation_options,
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &empty_constants,
+ zero_initialize_workgroup_memory: false,
+ vertex_pulling_transform: false,
+ },
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
@@ -1130,3 +1355,151 @@ fn interpolate_cursor_position(cursor: &CursorData, time_secs: f32) -> Option<(f
cursor_position
}
+
+struct CursorPipeline {
+ bind_group_layout: wgpu::BindGroupLayout,
+ render_pipeline: wgpu::RenderPipeline,
+}
+
+// Add this before the CursorPipeline struct definition
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Pod, Zeroable)]
+struct CursorUniforms {
+ position: [f32; 2], // 8 bytes
+ padding1: [f32; 2], // 8 bytes padding to align next field
+ size: [f32; 2], // 8 bytes
+ padding2: [f32; 2], // 8 bytes padding to align next field
+ output_size: [f32; 2], // 8 bytes
+ padding3: [f32; 2], // 8 bytes padding to align next field
+ screen_bounds: [f32; 4], // 16 bytes
+}
+
+// Add this function near the other cursor-related functions
+fn find_cursor_event<'a>(cursor: &'a CursorData, time: f32) -> &'a CursorEvent {
+ let time_ms = time * 1000.0;
+ println!("Finding cursor event for time: {}ms", time_ms);
+ println!("Total cursor moves: {}", cursor.moves.len());
+
+ // Find the last cursor event before or at the current time
+ 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]);
+
+ println!("Found cursor event: {:?}", event);
+ event
+}
+
+// Add the implementation for CursorPipeline
+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(64).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::SrcAlpha,
+ 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,
+ }
+ }
+}
diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgsl
new file mode 100644
index 000000000..3c283c025
--- /dev/null
+++ b/crates/rendering/src/shaders/cursor.wgsl
@@ -0,0 +1,47 @@
+struct Uniforms {
+ position: vec2<f32>,
+ padding1: vec2<f32>,
+ size: vec2<f32>,
+ padding2: vec2<f32>,
+ output_size: vec2<f32>,
+ padding3: vec2<f32>,
+ screen_bounds: vec4<f32>,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: Uniforms;
+@group(0) @binding(1) var cursor_texture: texture_2d<f32>;
+@group(0) @binding(2) var cursor_sampler: sampler;
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+ @location(0) tex_coords: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
+ var out: VertexOutput;
+
+ // Create a quad from two triangles using triangle strip
+ let x = f32(vertex_index & 1u);
+ let y = f32((vertex_index >> 1u) & 1u);
+
+ // Calculate position in screen space
+ let pos = uniforms.position + vec2<f32>(x * uniforms.size.x, y * uniforms.size.y);
+
+ // Convert to clip space (-1 to 1)
+ let clip_pos = vec2<f32>(
+ (pos.x / uniforms.output_size.x) * 2.0 - 1.0,
+ -((pos.y / uniforms.output_size.y) * 2.0 - 1.0)
+ );
+
+ out.position = vec4<f32>(clip_pos, 0.0, 1.0);
+ out.tex_coords = vec2<f32>(x, y);
+
+ return out;
+}
+
+@fragment
+fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
+ let color = textureSample(cursor_texture, cursor_sampler, in.tex_coords);
+ return color;
+}