Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
TadaTeruki committed Aug 18, 2024
1 parent e29bce5 commit 9943c19
Show file tree
Hide file tree
Showing 11 changed files with 1,166 additions and 80 deletions.
796 changes: 796 additions & 0 deletions graphics/Cargo.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions graphics/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@ wasm-logger = "0.2.0"
wee_alloc = "0.4.5"
bytemuck = { version = "1.16.3", features = [ "derive" ] }
cgmath = "0.18.0"
image = "0.25.2"
anyhow = "1.0.86"
tobj = "4.0.2"
getrandom = { version = "0.2", features = ["js"] }
Binary file added graphics/resources/sphere/sphere-diffuse.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added graphics/resources/sphere/sphere-normal.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes.
1 change: 1 addition & 0 deletions graphics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

mod camera;
mod key;
mod model;
mod state;

#[wasm_bindgen(start)]
Expand Down
3 changes: 3 additions & 0 deletions graphics/src/model/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod model;
mod texture;
mod vertex;
174 changes: 174 additions & 0 deletions graphics/src/model/model.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
// code from: https://github.com/sotrh/learn-wgpu

use std::ops::Range;

use wgpu::{util::DeviceExt, BindGroupDescriptor, BindGroupEntry, BindingResource};

use super::{texture, vertex::ModelVertex};

pub struct Model {
pub mesh: Mesh,
pub material: Material,
}

pub struct Material {
pub name: String,
pub diffuse_texture: texture::TextureSet,
pub bind_group: wgpu::BindGroup,
}

pub struct Mesh {
pub name: String,
pub vertex_buffer: wgpu::Buffer,
pub index_buffer: wgpu::Buffer,
pub num_elements: u32,
pub material: usize,
}

impl Model {
pub fn create(
device: &wgpu::Device,
queue: &wgpu::Queue,
obj_src: &str,
raw_texture_diffuse: &[u8],
texture_bind_group_layout: &wgpu::BindGroupLayout,
) -> anyhow::Result<Self> {
let texture = texture::TextureSet::from_bytes(
device,
queue,
raw_texture_diffuse,
"texture",
)?;

let (raw_models, _) = tobj::load_obj(obj_src, &tobj::GPU_LOAD_OPTIONS)?;

let raw_model = &raw_models.get(0).expect("No model loaded");
let raw_mesh = &raw_model.mesh;
let mut vertices = Vec::new();
for i in 0..raw_mesh.positions.len() / 3 {
vertices.push(ModelVertex {
position: [
raw_mesh.positions[i * 3],
raw_mesh.positions[i * 3 + 1],
raw_mesh.positions[i * 3 + 2],
],
tex_coords: [
raw_mesh.texcoords[i * 2],
1.0 - raw_mesh.texcoords[i * 2 + 1],
],
normal: [
raw_mesh.normals[i * 3],
raw_mesh.normals[i * 3 + 1],
raw_mesh.normals[i * 3 + 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(&raw_mesh.indices),
usage: wgpu::BufferUsages::INDEX,
});

let mesh = Mesh {
name: "Mesh".to_string(),
vertex_buffer,
index_buffer,
num_elements: raw_mesh.indices.len() as u32,
material: raw_mesh.material_id.unwrap_or(0),
};

let material = Material {
name: "Material".to_string(),
diffuse_texture: texture.clone(),
bind_group: device.create_bind_group(&BindGroupDescriptor {
label: Some("material_bind_group"),
layout: texture_bind_group_layout,
entries: &[
BindGroupEntry {
binding: 0,
resource: BindingResource::TextureView(&texture.view()),
},
BindGroupEntry {
binding: 1,
resource: BindingResource::Sampler(&texture.sampler()),
},
],
}),
};

Ok(Self { mesh, material })
}
}

pub trait DrawModel<'a> {
fn draw_mesh(
&mut self,
mesh: &'a Mesh,
material: &'a Material,
camera_bind_group: &'a wgpu::BindGroup,
);

fn draw_mesh_instanced(
&mut self,
mesh: &'a Mesh,
material: &'a Material,
instances: Range<u32>,
camera_bind_group: &'a wgpu::BindGroup,
);

fn draw_model(&mut self, model: &'a Model, camera_bind_group: &'a wgpu::BindGroup);
fn draw_model_instanced(
&mut self,
model: &'a Model,
instances: Range<u32>,
camera_bind_group: &'a wgpu::BindGroup,
);
}

impl<'a> DrawModel<'a> for wgpu::RenderPass<'a> {
fn draw_mesh(
&mut self,
mesh: &'a Mesh,
material: &'a Material,
camera_bind_group: &'a wgpu::BindGroup,
) {
self.draw_mesh_instanced(mesh, material, 0..1, camera_bind_group);
}

fn draw_mesh_instanced(
&mut self,
mesh: &'a Mesh,
material: &'a Material,
instances: Range<u32>,
camera_bind_group: &'a wgpu::BindGroup,
) {
self.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
self.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
self.set_bind_group(0, &material.bind_group, &[]);
self.set_bind_group(1, camera_bind_group, &[]);
self.draw_indexed(0..mesh.num_elements, 0, instances);
}

fn draw_model(&mut self, model: &'a Model, camera_bind_group: &'a wgpu::BindGroup) {
self.draw_model_instanced(model, 0..1, camera_bind_group);
}

fn draw_model_instanced(
&mut self,
model: &'a Model,
instances: Range<u32>,
camera_bind_group: &'a wgpu::BindGroup,
) {
for mesh in &model.meshes {
let material = &model.materials[mesh.material];
self.draw_mesh_instanced(mesh, material, instances.clone(), camera_bind_group);
}
}
}
134 changes: 134 additions & 0 deletions graphics/src/model/texture.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// code from: https://github.com/sotrh/learn-wgpu

use image::GenericImageView;

pub struct TextureSet {
texture: wgpu::Texture,
view: wgpu::TextureView,
sampler: wgpu::Sampler,
}

impl TextureSet {
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

pub fn create_depth_texture(
device: &wgpu::Device,
config: &wgpu::SurfaceConfiguration,
label: &str,
) -> Self {
let size = wgpu::Extent3d {
width: config.width,
height: config.height,
depth_or_array_layers: 1,
};
let desc = wgpu::TextureDescriptor {
label: Some(label),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: Self::DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
};
let texture = device.create_texture(&desc);

let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
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,
compare: Some(wgpu::CompareFunction::LessEqual),
lod_min_clamp: 0.0,
lod_max_clamp: 100.0,
..Default::default()
});

Self {
texture,
view,
sampler,
}
}

pub fn from_bytes(
device: &wgpu::Device,
queue: &wgpu::Queue,
bytes: &[u8],
label: &str,
) -> anyhow::Result<Self> {
let img = image::load_from_memory(bytes)?;
Self::from_image(device, queue, &img, Some(label))
}

pub fn from_image(
device: &wgpu::Device,
queue: &wgpu::Queue,
img: &image::DynamicImage,
label: Option<&str>,
) -> anyhow::Result<Self> {
let dimensions = img.dimensions();
let rgba = img.to_rgba8();

let size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
depth_or_array_layers: 1,
};
let format = wgpu::TextureFormat::Rgba8UnormSrgb;
let texture = device.create_texture(&wgpu::TextureDescriptor {
label,
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});

queue.write_texture(
wgpu::ImageCopyTexture {
aspect: wgpu::TextureAspect::All,
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
},
&rgba,
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(4 * dimensions.0),
rows_per_image: Some(dimensions.1),
},
size,
);

let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
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::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});

Ok(Self {
texture,
view,
sampler,
})
}

pub fn view(&self) -> &wgpu::TextureView {
&self.view
}

pub fn sampler(&self) -> &wgpu::Sampler {
&self.sampler
}
}
39 changes: 39 additions & 0 deletions graphics/src/model/vertex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::mem;

pub trait Vertex {
fn desc() -> wgpu::VertexBufferLayout<'static>;
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct ModelVertex {
pub position: [f32; 3],
pub tex_coords: [f32; 2],
pub normal: [f32; 3],
}

impl Vertex for ModelVertex {
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<ModelVertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 5]>() as wgpu::BufferAddress,
shader_location: 2,
format: wgpu::VertexFormat::Float32x3,
},
],
}
}
}
Loading

0 comments on commit 9943c19

Please sign in to comment.