feat: add obj model loading

Co-authored-by: Chance <caznix01@gmail.com>
This commit is contained in:
BitSyndicate 2025-04-18 23:45:11 +02:00
parent 8632f5a2b2
commit 4a674176cd
Signed by untrusted user: bitsyndicate
GPG key ID: 443E4198D6BBA6DE
6 changed files with 269 additions and 184 deletions

View file

@ -1,7 +1,7 @@
use crate::model::parse_obj;
use bytemuck::bytes_of;
use image::EncodableLayout;
use std::collections::BTreeMap;
use std::io::BufReader;
use std::sync::Arc;
use tobj::LoadOptions;
use tracing::info;
@ -19,6 +19,7 @@ use zlog::config::LoggerConfig;
pub mod camera;
pub mod model;
pub mod texture;
struct WindowContext<'window> {
window: Arc<Window>,
renderer: WgpuRenderer<'window>,
@ -37,17 +38,15 @@ struct WgpuRenderer<'surface> {
surface: wgpu::Surface<'surface>,
surface_config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
diffuse_bind_group: wgpu::BindGroup,
depth_texture: wgpu::Texture,
depth_texture_view: wgpu::TextureView,
camera: camera::Camera,
camera_uniform: camera::CameraUniform,
camera_buffer: wgpu::Buffer,
camera_bind_group: wgpu::BindGroup,
index_count: u32,
pumpkin: model::Model,
zenyx_logo: wgpu::BindGroup,
}
impl WgpuRenderer<'_> {
@ -82,12 +81,19 @@ impl WgpuRenderer<'_> {
timestamp_writes: None,
});
rpass.set_pipeline(&self.render_pipeline);
rpass.set_bind_group(0, &self.diffuse_bind_group, &[]);
rpass.set_bind_group(0, &self.camera_bind_group, &[]);
rpass.set_bind_group(1, &self.camera_bind_group, &[]);
rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
rpass.set_index_buffer(self.index_buffer.slice(..), IndexFormat::Uint32);
rpass.draw_indexed(0..self.index_count, 0, 0..1);
for mesh in &self.pumpkin.meshes {
let bind_group = mesh
.material
.and_then(|i| self.pumpkin.materials.get(i))
.map(|m| &m.bind_group)
.unwrap_or(&self.zenyx_logo);
rpass.set_bind_group(1, bind_group, &[]);
rpass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
rpass.set_index_buffer(mesh.index_buffer.slice(..), IndexFormat::Uint32);
rpass.draw_indexed(0..mesh.num_elements, 0, 0..1);
}
}
self.queue.submit(Some(encoder.finish()));
surface_texture.present()
@ -127,50 +133,7 @@ impl App<'_> {
struct WgpuState {
instance: wgpu::Instance,
}
unsafe impl bytemuck::Pod for Vertex {}
unsafe impl bytemuck::Zeroable for Vertex {}
#[derive(Copy, Clone, Debug)]
#[repr(C)]
struct Vertex {
position: cgmath::Vector3<f32>,
color: cgmath::Vector3<f32>,
normal: cgmath::Vector3<f32>,
tex_coords: cgmath::Vector2<f32>,
}
impl Vertex {
const ATTRIBS: [wgpu::VertexAttribute; 4] = [
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::offset_of!(Vertex, color) as u64,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::offset_of!(Vertex, normal) as u64,
shader_location: 2,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::offset_of!(Vertex, tex_coords) as u64,
shader_location: 3,
format: wgpu::VertexFormat::Float32x2,
},
];
const fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &Self::ATTRIBS,
}
}
}
static ICON: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/Badge.png"));
static PUMPKIN: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/Pumpkin.obj"));
@ -244,7 +207,7 @@ impl WgpuState {
struct ShaderCode<const N: usize>([u8; N]);
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Pipeline Layout"),
bind_group_layouts: &[&texture_bind_group_layout, &camera_bind_group_layout],
bind_group_layouts: &[&camera_bind_group_layout, &texture_bind_group_layout],
push_constant_ranges: &[],
});
@ -279,7 +242,7 @@ impl WgpuState {
vertex: wgpu::VertexState {
module: &vert_shader,
entry_point: Some("main"),
buffers: &[Vertex::desc()],
buffers: &[model::Vertex::desc()],
compilation_options: Default::default(),
},
primitive: wgpu::PrimitiveState {
@ -334,50 +297,32 @@ impl WgpuState {
};
surface.configure(&device, &surface_config);
let pumpkin = tobj::load_obj("Pumpkin.obj", &tobj::GPU_LOAD_OPTIONS).unwrap();
let (vertices, indices) = parse_obj(&pumpkin.0);
let (depth_texture, depth_texture_view) =
create_depth_texture(&device, surface_config.width, surface_config.height);
let materials = pumpkin.1.unwrap();
let diffuse_texture =
texture::Texture::from_bytes(&device, &queue, ICON, "zenyx-icon").unwrap();
let model = tobj::load_obj_buf(
&mut PUMPKIN.as_bytes(),
&LoadOptions {
triangulate: true,
single_index: true,
..Default::default()
},
|_| Ok(Default::default()),
)
.unwrap();
let pumpkin = model::Model::load_obj(
&mut BufReader::new(std::fs::File::open("Pumpkin.obj").unwrap()),
&device,
&queue,
&texture_bind_group_layout,
);
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex buffer"),
contents: bytemuck::cast_slice(vertices.as_ref()),
usage: BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index buffer"),
contents: bytemuck::cast_slice(indices.as_ref()),
usage: BufferUsages::INDEX,
});
let zenyx_logo = texture::Texture::from_bytes(&device, &queue, ICON, "zenyx-icon").unwrap();
let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
let zenyx_logo = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("zenyx-logo-diffuse"),
layout: &texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&diffuse_texture.view),
resource: wgpu::BindingResource::TextureView(&zenyx_logo.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&diffuse_texture.sampler),
resource: wgpu::BindingResource::Sampler(&zenyx_logo.sampler),
},
],
label: Some("diffuse_bind_group"),
});
let (depth_texture, depth_texture_view) =
create_depth_texture(&device, surface_config.width, surface_config.height);
let camera = camera::Camera {
// position the camera 1 unit up and 2 units back
// +z is out of the screen
@ -415,19 +360,17 @@ impl WgpuState {
WgpuRenderer {
surface,
surface_config,
diffuse_bind_group,
depth_texture,
render_pipeline,
device,
vertex_buffer,
index_buffer,
camera,
queue,
camera_uniform,
camera_buffer,
camera_bind_group,
index_count: indices.len() as u32,
depth_texture_view,
pumpkin,
zenyx_logo,
}
}
@ -460,37 +403,6 @@ fn create_depth_texture(
(texture, view)
}
static VERTICES: [Vertex; 4] = {
[
Vertex {
position: cgmath::vec3(-0.5, -0.5, 0.0),
color: cgmath::vec3(1.0, 0.0, 0.0),
normal: cgmath::vec3(0.0, 0.0, 0.0),
tex_coords: cgmath::vec2(1.0, 0.0),
},
Vertex {
position: cgmath::vec3(0.5, -0.5, 0.0),
color: cgmath::vec3(0.0, 1.0, 0.0),
normal: cgmath::vec3(0.0, 0.0, 0.0),
tex_coords: cgmath::vec2(0.0, 0.0),
},
Vertex {
position: cgmath::vec3(0.5, 0.5, 0.0),
color: cgmath::vec3(0.0, 0.0, 1.0),
normal: cgmath::vec3(0.0, 0.0, 0.0),
tex_coords: cgmath::vec2(0.0, 1.0),
},
Vertex {
position: cgmath::vec3(-0.5, 0.5, 0.0),
color: cgmath::vec3(0.0, 0.0, 1.0),
normal: cgmath::vec3(0.0, 0.0, 0.0),
tex_coords: cgmath::vec2(1.0, 1.0),
},
]
};
static INDICIES: [u32; 6] = [0, 1, 2, 2, 3, 0];
impl ApplicationHandler for App<'_> {
fn window_event(
&mut self,
@ -535,7 +447,8 @@ impl ApplicationHandler for App<'_> {
let mut new_config = window_ctx.renderer.surface_config.clone();
new_config.width = size.width;
new_config.height = size.height;
let (depth_texture, depth_view) = create_depth_texture(&window_ctx.renderer.device, size.width, size.height);
let (depth_texture, depth_view) =
create_depth_texture(&window_ctx.renderer.device, size.width, size.height);
window_ctx.renderer.depth_texture = depth_texture;
window_ctx.renderer.depth_texture_view = depth_view;