init commit
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/target
|
2695
Cargo.lock
generated
Normal file
2695
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
Cargo.toml
Normal file
21
Cargo.toml
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
[package]
|
||||||
|
name = "procedu"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "precdu"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.98"
|
||||||
|
winit = { version = "0.30.11" }
|
||||||
|
env_logger = "0.11.8"
|
||||||
|
log = "0.4.27"
|
||||||
|
wgpu = "25.0.2"
|
||||||
|
pollster = "0.4.0"
|
||||||
|
bytemuck = { version = "1.18", features = ["derive"] }
|
||||||
|
rand = "0.9.1"
|
1
src/lib.rs
Normal file
1
src/lib.rs
Normal file
@ -0,0 +1 @@
|
|||||||
|
// Empty library file to satisfy Cargo.toml configuration
|
529
src/main.rs
Normal file
529
src/main.rs
Normal file
@ -0,0 +1,529 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use bytemuck::{Pod, Zeroable};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
use wgpu::util::DeviceExt;
|
||||||
|
use winit::{
|
||||||
|
application::ApplicationHandler,
|
||||||
|
event::{ElementState, KeyEvent, WindowEvent},
|
||||||
|
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
|
||||||
|
keyboard::{KeyCode, PhysicalKey},
|
||||||
|
window::{Window, WindowId},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[repr(C)] // Vertex structure for the ball
|
||||||
|
#[derive(Copy, Clone, Debug, Pod, Zeroable)] // Ensure the structure is compatible with GPU memory layout
|
||||||
|
// Represents a vertex with position and color
|
||||||
|
struct Vertex {
|
||||||
|
position: [f32; 3], // 3D position of the vertex <-- x, y, z
|
||||||
|
color: [f32; 3], // Color of the vertex in RGB format <-- r, g, b
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vertex {
|
||||||
|
fn desc() -> wgpu::VertexBufferLayout<'static> { // Returns the vertex buffer layout for the Vertex structure - VertexBufferLayout Specifies an interpretation of the bytes of a vertex buffer as vertex attributes.
|
||||||
|
wgpu::VertexBufferLayout {
|
||||||
|
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress, // The size of a single vertex in bytes
|
||||||
|
step_mode: wgpu::VertexStepMode::Vertex, // Indicates that each vertex has its own attributes if `VertexStepMode::Vertex` is used, or that the attributes are shared across instances if `VertexStepMode::Instance` is used.
|
||||||
|
// Specifies the attributes of the vertex buffer
|
||||||
|
attributes: &[
|
||||||
|
// first attribute: position
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
offset: 0,
|
||||||
|
shader_location: 0,
|
||||||
|
format: wgpu::VertexFormat::Float32x3, // The format of the position attribute is a 3D vector of floats (x, y, z)
|
||||||
|
},
|
||||||
|
// second attribute: color
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
|
||||||
|
shader_location: 1,
|
||||||
|
format: wgpu::VertexFormat::Float32x3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Debug, Copy, Clone, Pod, Zeroable)]
|
||||||
|
struct Uniforms {
|
||||||
|
transform: [[f32; 4]; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Uniforms {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
transform: [
|
||||||
|
[1.0, 0.0, 0.0, 0.0],
|
||||||
|
[0.0, 1.0, 0.0, 0.0],
|
||||||
|
[0.0, 0.0, 1.0, 0.0],
|
||||||
|
[0.0, 0.0, 0.0, 1.0],
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_position(&mut self, x: f32, y: f32) {
|
||||||
|
self.transform[3][0] = x;
|
||||||
|
self.transform[3][1] = y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Ball {
|
||||||
|
position: [f32; 2],
|
||||||
|
velocity: [f32; 2],
|
||||||
|
radius: f32,
|
||||||
|
color: [f32; 3], // RGB color
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ball {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
position: [0.0, 0.0], // Initial position at the center
|
||||||
|
velocity: [0.5, 0.5], // Initial velocity <-- x, y
|
||||||
|
radius: 0.1, // Radius of the ball
|
||||||
|
color: [1.0, 0.5, 0.2], // Orange color
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(&mut self, dt: f32, window_width: f32, window_height: f32) {
|
||||||
|
// Update position
|
||||||
|
self.position[0] += self.velocity[0] * dt; // Update x position
|
||||||
|
self.position[1] += self.velocity[1] * dt; // Update y position
|
||||||
|
|
||||||
|
// Convert window dimensions to normalized coordinates
|
||||||
|
let aspect_ratio = window_width / window_height;
|
||||||
|
let bounds_x = aspect_ratio;
|
||||||
|
let bounds_y = 1.0;
|
||||||
|
|
||||||
|
// update ball size according to window size
|
||||||
|
self.radius = 0.1 * (window_width / 800.0); // // Assuming the original window width is 800px
|
||||||
|
|
||||||
|
// Bounce off walls
|
||||||
|
if self.position[0] + self.radius > bounds_x || self.position[0] - self.radius < -bounds_x {
|
||||||
|
self.velocity[0] = -self.velocity[0] + 0.1 * rand::random::<f32>(); // Add a small random factor to the velocity
|
||||||
|
self.position[0] = self.position[0].clamp(-bounds_x + self.radius, bounds_x - self.radius);
|
||||||
|
// assign a new random color when bouncing off the wall
|
||||||
|
self.color = [
|
||||||
|
rand::random::<f32>(),
|
||||||
|
rand::random::<f32>(),
|
||||||
|
rand::random::<f32>(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
// if the y position plus the radius is greater than the bounds_y or the y position minus the radius is less than -bounds_y, then bounce off the wall
|
||||||
|
if self.position[1] + self.radius > bounds_y || self.position[1] - self.radius < -bounds_y {
|
||||||
|
self.velocity[1] = -self.velocity[1] + 0.1 * rand::random::<f32>(); // Add a small random factor to the velocity
|
||||||
|
self.position[1] = self.position[1].clamp(-bounds_y + self.radius, bounds_y - self.radius);
|
||||||
|
// assign a new random color when bouncing off the wall
|
||||||
|
self.color = [
|
||||||
|
rand::random::<f32>(),
|
||||||
|
rand::random::<f32>(),
|
||||||
|
rand::random::<f32>(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
surface: wgpu::Surface<'static>,
|
||||||
|
device: wgpu::Device,
|
||||||
|
queue: wgpu::Queue,
|
||||||
|
config: wgpu::SurfaceConfiguration,
|
||||||
|
size: winit::dpi::PhysicalSize<u32>,
|
||||||
|
render_pipeline: wgpu::RenderPipeline,
|
||||||
|
vertex_buffer: wgpu::Buffer,
|
||||||
|
index_buffer: wgpu::Buffer,
|
||||||
|
num_indices: u32,
|
||||||
|
uniform_buffer: wgpu::Buffer,
|
||||||
|
uniform_bind_group: wgpu::BindGroup,
|
||||||
|
uniforms: Uniforms,
|
||||||
|
ball: Ball,
|
||||||
|
last_frame_time: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
async fn new(window: Arc<Window>) -> Result<Self> {
|
||||||
|
let size = window.inner_size();
|
||||||
|
|
||||||
|
// Create the wgpu instance
|
||||||
|
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
|
||||||
|
backends: wgpu::Backends::all(),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
let surface = instance.create_surface(window)?;
|
||||||
|
|
||||||
|
let adapter = instance
|
||||||
|
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||||
|
power_preference: wgpu::PowerPreference::default(),
|
||||||
|
compatible_surface: Some(&surface),
|
||||||
|
force_fallback_adapter: false,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (device, queue) = adapter
|
||||||
|
.request_device(
|
||||||
|
&wgpu::DeviceDescriptor {
|
||||||
|
required_features: wgpu::Features::empty(),
|
||||||
|
required_limits: wgpu::Limits::default(),
|
||||||
|
label: None,
|
||||||
|
memory_hints: Default::default(),
|
||||||
|
trace: wgpu::Trace::default(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let surface_caps = surface.get_capabilities(&adapter);
|
||||||
|
let surface_format = surface_caps
|
||||||
|
.formats
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.find(|f| f.is_srgb())
|
||||||
|
.unwrap_or(surface_caps.formats[0]);
|
||||||
|
|
||||||
|
let config = wgpu::SurfaceConfiguration {
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||||
|
format: surface_format,
|
||||||
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
present_mode: surface_caps.present_modes[0],
|
||||||
|
alpha_mode: surface_caps.alpha_modes[0],
|
||||||
|
view_formats: vec![],
|
||||||
|
desired_maximum_frame_latency: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
surface.configure(&device, &config);
|
||||||
|
|
||||||
|
// Create circle vertices (for the ball)
|
||||||
|
let mut vertices = Vec::new();
|
||||||
|
let mut indices = Vec::new();
|
||||||
|
|
||||||
|
let segments = 32;
|
||||||
|
let radius = 0.1;
|
||||||
|
|
||||||
|
// Center vertex
|
||||||
|
vertices.push(Vertex {
|
||||||
|
position: [0.0, 0.0, 0.0],
|
||||||
|
color: [1.0, 0.2, 0.2], // Orange color
|
||||||
|
});
|
||||||
|
|
||||||
|
// Circle vertices
|
||||||
|
for i in 0..segments {
|
||||||
|
let angle = 2.0 * std::f32::consts::PI * i as f32 / segments as f32;
|
||||||
|
let x = radius * angle.cos();
|
||||||
|
let y = radius * angle.sin();
|
||||||
|
|
||||||
|
vertices.push(Vertex {
|
||||||
|
position: [x, y, 0.0],
|
||||||
|
color: [0.1, 0.5, 0.2], // Orange color
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create triangles
|
||||||
|
for i in 0..segments {
|
||||||
|
indices.push(0); // Center
|
||||||
|
indices.push(i + 1);
|
||||||
|
indices.push(if i + 2 > segments { 1 } else { i + 2 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Vertex Buffer"),
|
||||||
|
contents: bytemuck::cast_slice(&vertices),
|
||||||
|
usage: wgpu::BufferUsages::VERTEX,
|
||||||
|
});
|
||||||
|
|
||||||
|
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Index Buffer"),
|
||||||
|
contents: bytemuck::cast_slice(&indices),
|
||||||
|
usage: wgpu::BufferUsages::INDEX,
|
||||||
|
});
|
||||||
|
|
||||||
|
let num_indices = indices.len() as u32;
|
||||||
|
|
||||||
|
// Create uniform buffer
|
||||||
|
let uniforms = Uniforms::new();
|
||||||
|
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Uniform Buffer"),
|
||||||
|
contents: bytemuck::cast_slice(&[uniforms]),
|
||||||
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
|
||||||
|
let uniform_bind_group_layout =
|
||||||
|
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
entries: &[wgpu::BindGroupLayoutEntry {
|
||||||
|
binding: 0,
|
||||||
|
visibility: wgpu::ShaderStages::VERTEX,
|
||||||
|
ty: wgpu::BindingType::Buffer {
|
||||||
|
ty: wgpu::BufferBindingType::Uniform,
|
||||||
|
has_dynamic_offset: false,
|
||||||
|
min_binding_size: None,
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
}],
|
||||||
|
label: Some("uniform_bind_group_layout"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &uniform_bind_group_layout,
|
||||||
|
entries: &[wgpu::BindGroupEntry {
|
||||||
|
binding: 0,
|
||||||
|
resource: uniform_buffer.as_entire_binding(),
|
||||||
|
}],
|
||||||
|
label: Some("uniform_bind_group"),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Load shader
|
||||||
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||||
|
label: Some("Shader"),
|
||||||
|
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
|
||||||
|
});
|
||||||
|
|
||||||
|
let render_pipeline_layout =
|
||||||
|
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
|
label: Some("Render Pipeline Layout"),
|
||||||
|
bind_group_layouts: &[&uniform_bind_group_layout],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
|
label: Some("Render Pipeline"),
|
||||||
|
layout: Some(&render_pipeline_layout),
|
||||||
|
vertex: wgpu::VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: Some("vs_main"),
|
||||||
|
buffers: &[Vertex::desc()],
|
||||||
|
compilation_options: Default::default(),
|
||||||
|
},
|
||||||
|
fragment: Some(wgpu::FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: Some("fs_main"),
|
||||||
|
targets: &[Some(wgpu::ColorTargetState {
|
||||||
|
format: config.format,
|
||||||
|
blend: Some(wgpu::BlendState::REPLACE),
|
||||||
|
write_mask: wgpu::ColorWrites::ALL,
|
||||||
|
})],
|
||||||
|
compilation_options: Default::default(),
|
||||||
|
}),
|
||||||
|
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 {
|
||||||
|
count: 1,
|
||||||
|
mask: !0,
|
||||||
|
alpha_to_coverage_enabled: false,
|
||||||
|
},
|
||||||
|
multiview: None,
|
||||||
|
cache: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
let ball = Ball::new();
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
surface,
|
||||||
|
device,
|
||||||
|
queue,
|
||||||
|
config,
|
||||||
|
size,
|
||||||
|
render_pipeline,
|
||||||
|
vertex_buffer,
|
||||||
|
index_buffer,
|
||||||
|
num_indices,
|
||||||
|
uniform_buffer,
|
||||||
|
uniform_bind_group,
|
||||||
|
uniforms,
|
||||||
|
ball,
|
||||||
|
last_frame_time: Instant::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
|
||||||
|
if new_size.width > 0 && new_size.height > 0 {
|
||||||
|
self.size = new_size;
|
||||||
|
self.config.width = new_size.width;
|
||||||
|
self.config.height = new_size.height;
|
||||||
|
self.surface.configure(&self.device, &self.config);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(&mut self) {
|
||||||
|
let now = Instant::now();
|
||||||
|
let dt = (now - self.last_frame_time).as_secs_f32();
|
||||||
|
self.last_frame_time = now;
|
||||||
|
|
||||||
|
// Update ball physics
|
||||||
|
self.ball.update(dt, self.size.width as f32, self.size.height as f32);
|
||||||
|
|
||||||
|
// Update uniforms
|
||||||
|
self.uniforms.update_position(self.ball.position[0], self.ball.position[1]);
|
||||||
|
self.queue.write_buffer(
|
||||||
|
&self.uniform_buffer,
|
||||||
|
0,
|
||||||
|
bytemuck::cast_slice(&[self.uniforms]),
|
||||||
|
);
|
||||||
|
|
||||||
|
self.update_vertex_colors();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_vertex_colors(&mut self) {
|
||||||
|
let mut vertices = Vec::new();
|
||||||
|
let segments = 32; // Number of segments for the circle
|
||||||
|
let radius = self.ball.radius;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Center vertex with ball's color
|
||||||
|
vertices.push(Vertex {
|
||||||
|
position: [0.0, 0.0, 0.0],
|
||||||
|
color: self.ball.color,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Circle vertices with ball's color
|
||||||
|
for i in 0..segments {
|
||||||
|
let angle = 2.0 * std::f32::consts::PI * i as f32 / segments as f32;
|
||||||
|
let x = radius * angle.cos();
|
||||||
|
let y = radius * angle.sin();
|
||||||
|
|
||||||
|
vertices.push(Vertex {
|
||||||
|
position: [x, y, 0.0],
|
||||||
|
color: self.ball.color,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the vertex buffer with new colors
|
||||||
|
self.vertex_buffer = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("Vertex Buffer"),
|
||||||
|
contents: bytemuck::cast_slice(&vertices),
|
||||||
|
usage: wgpu::BufferUsages::VERTEX,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
|
||||||
|
let output = self.surface.get_current_texture()?;
|
||||||
|
let view = output
|
||||||
|
.texture
|
||||||
|
.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
|
|
||||||
|
let mut encoder = self
|
||||||
|
.device
|
||||||
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||||
|
label: Some("Render Encoder"),
|
||||||
|
});
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||||
|
label: Some("Render Pass"),
|
||||||
|
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||||
|
view: &view,
|
||||||
|
resolve_target: None,
|
||||||
|
ops: wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||||
|
r: 0.1,
|
||||||
|
g: 0.2,
|
||||||
|
b: 0.3,
|
||||||
|
a: 1.0,
|
||||||
|
}),
|
||||||
|
store: wgpu::StoreOp::Store,
|
||||||
|
},
|
||||||
|
})],
|
||||||
|
depth_stencil_attachment: None,
|
||||||
|
occlusion_query_set: None,
|
||||||
|
timestamp_writes: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
render_pass.set_pipeline(&self.render_pipeline);
|
||||||
|
render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
|
||||||
|
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
||||||
|
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
|
||||||
|
render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.queue.submit(std::iter::once(encoder.finish()));
|
||||||
|
output.present();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct App {
|
||||||
|
state: Option<State>,
|
||||||
|
window: Option<Arc<Window>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApplicationHandler for App {
|
||||||
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
let window_attributes = Window::default_attributes()
|
||||||
|
.with_title("Bouncing Ball")
|
||||||
|
.with_inner_size(winit::dpi::LogicalSize::new(800, 800))
|
||||||
|
.with_min_inner_size(winit::dpi::LogicalSize::new(200, 200));
|
||||||
|
|
||||||
|
let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
|
||||||
|
let state = pollster::block_on(State::new(Arc::clone(&window))).unwrap();
|
||||||
|
self.window = Some(window);
|
||||||
|
self.state = Some(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
|
||||||
|
let Some(state) = &mut self.state else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested
|
||||||
|
| WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
physical_key: PhysicalKey::Code(KeyCode::Escape),
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => event_loop.exit(),
|
||||||
|
WindowEvent::Resized(physical_size) => {
|
||||||
|
state.resize(physical_size);
|
||||||
|
}
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
state.update();
|
||||||
|
match state.render() {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(wgpu::SurfaceError::Lost) => state.resize(state.size),
|
||||||
|
Err(wgpu::SurfaceError::OutOfMemory) => event_loop.exit(),
|
||||||
|
Err(e) => eprintln!("{:?}", e),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request another frame for continuous animation
|
||||||
|
if let Some(window) = &self.window {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
|
||||||
|
// Request initial redraw
|
||||||
|
if let Some(window) = &self.window {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<()> {
|
||||||
|
env_logger::init();
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new()?;
|
||||||
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
|
|
||||||
|
let mut app = App {
|
||||||
|
state: None,
|
||||||
|
window: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
event_loop.run_app(&mut app)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
32
src/shader.wgsl
Normal file
32
src/shader.wgsl
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
// Vertex shader
|
||||||
|
struct VertexInput {
|
||||||
|
// position and color attributes
|
||||||
|
@location(0) position: vec3<f32>, // Position in 3D space
|
||||||
|
@location(1) color: vec3<f32>, // Color attribute
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VertexOutput {
|
||||||
|
@builtin(position) clip_position: vec4<f32>, // Clip space position
|
||||||
|
@location(0) color: vec3<f32>, // Color output
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Uniforms {
|
||||||
|
transform: mat4x4<f32>, // Transformation matrix
|
||||||
|
}
|
||||||
|
|
||||||
|
@group(0) @binding(0)
|
||||||
|
var<uniform> uniforms: Uniforms;
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_main(model: VertexInput) -> VertexOutput {
|
||||||
|
var out: VertexOutput; // Initialize output structure
|
||||||
|
out.color = model.color; // Pass through color attribute
|
||||||
|
out.clip_position = uniforms.transform * vec4<f32>(model.position, 1.0); // Transform position by the uniform matrix
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fragment shader
|
||||||
|
@fragment
|
||||||
|
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||||
|
return vec4<f32>(in.color, 1.0);
|
||||||
|
}
|
Reference in New Issue
Block a user