Implement Chunk, including a raycasting algorithm

This commit is contained in:
Sijmen 2021-05-29 19:07:40 +02:00
parent 1b1daad1f7
commit 17fbd875e2
Signed by: vijfhoek
GPG key ID: 82D05C89B28B0DAE
8 changed files with 334 additions and 136 deletions

View file

@ -23,14 +23,16 @@ impl Camera {
}
}
pub fn calculate_matrix(&self) -> Matrix4<f32> {
let direction = Vector3::new(
pub fn direction(&self) -> Vector3<f32> {
Vector3::new(
self.yaw.0.cos() * self.pitch.0.cos(),
self.pitch.0.sin(),
self.yaw.0.sin() * self.pitch.0.cos(),
);
)
}
Matrix4::look_to_rh(self.position, direction, Vector3::unit_y())
pub fn calculate_matrix(&self) -> Matrix4<f32> {
Matrix4::look_to_rh(self.position, self.direction(), Vector3::unit_y())
}
}

119
src/chunk.rs Normal file
View file

@ -0,0 +1,119 @@
use crate::instance::Instance;
use cgmath::{Deg, InnerSpace, Quaternion, Rotation3, Vector3};
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BlockType {
Dirt,
Cobblestone,
}
impl BlockType {
pub fn texture_index(self) -> u32 {
match self {
Self::Dirt => 0,
Self::Cobblestone => 1,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Block {
pub block_type: BlockType,
}
const CHUNK_SIZE: usize = 16;
pub struct Chunk {
pub blocks: [[[Option<Block>; CHUNK_SIZE]; CHUNK_SIZE]; CHUNK_SIZE],
}
impl Chunk {
pub fn to_instances(&self) -> Vec<(BlockType, Vec<Instance>)> {
let mut map: HashMap<BlockType, Vec<Instance>> = HashMap::new();
for (y, y_blocks) in self.blocks.iter().enumerate() {
for (z, z_blocks) in y_blocks.iter().enumerate() {
for (x, block) in z_blocks.iter().enumerate() {
if let Some(block) = block {
let position = Vector3 {
x: x as f32,
y: y as f32,
z: z as f32,
};
let rotation = Quaternion::from_axis_angle(Vector3::unit_z(), Deg(0.0));
let instances = map.entry(block.block_type).or_default();
instances.push(Instance {
position,
rotation,
block_type: block.block_type,
});
}
}
}
}
map.drain().collect()
}
fn calc_scale(a: Vector3<f32>, b: f32) -> f32 {
if b == 0.0 {
f32::INFINITY
} else {
(a / b).magnitude()
}
}
pub fn dda(&self, position: Vector3<f32>, direction: Vector3<f32>) -> Option<Vector3<usize>> {
assert!(f32::abs(direction.magnitude() - 1.0) < f32::EPSILON);
let scale_x = Self::calc_scale(direction, direction.x);
let scale_y = Self::calc_scale(direction, direction.y);
let scale_z = Self::calc_scale(direction, direction.z);
dbg!(direction, scale_x, scale_y, scale_z);
let mut new_position = position;
let mut x_length = 0.0;
let mut y_length = 0.0;
let mut z_length = 0.0;
loop {
let new_x_length = x_length + scale_x;
let new_y_length = y_length + scale_y;
let new_z_length = z_length + scale_z;
if new_x_length < f32::min(new_y_length, new_z_length) {
x_length = new_x_length;
new_position += direction * scale_x;
} else if new_y_length < f32::min(new_x_length, new_z_length) {
y_length = new_y_length;
new_position += direction * scale_y;
} else if new_z_length < f32::min(new_x_length, new_y_length) {
z_length = new_z_length;
new_position += direction * scale_z;
}
let pos_usize = new_position.map(|field| field.round() as usize);
let block = self
.blocks
.get(pos_usize.y)
.and_then(|a| a.get(pos_usize.z))
.and_then(|a| a.get(pos_usize.x));
match block {
None => {
// Went outside the chunk, intersection no longer possible
break None;
}
Some(None) => (),
Some(Some(_)) => {
// Intersected with a block, round position to coordinates and return it.
break Some(pos_usize);
}
}
}
}
}

View file

@ -3,40 +3,40 @@ use crate::vertex::Vertex;
#[rustfmt::skip]
pub const VERTICES: &[Vertex] = &[
// Left
Vertex { position: [-1.0, -1.0, -1.0], texture_coordinates: [1.0, 1.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-1.0, -1.0, 1.0], texture_coordinates: [0.0, 1.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-1.0, 1.0, 1.0], texture_coordinates: [0.0, 0.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-1.0, 1.0, -1.0], texture_coordinates: [1.0, 0.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-0.5, -0.5, -0.5], texture_coordinates: [1.0, 1.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-0.5, -0.5, 0.5], texture_coordinates: [0.0, 1.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-0.5, 0.5, 0.5], texture_coordinates: [0.0, 0.0], normal: [-1.0, 0.0, 0.0] },
Vertex { position: [-0.5, 0.5, -0.5], texture_coordinates: [1.0, 0.0], normal: [-1.0, 0.0, 0.0] },
// Right
Vertex { position: [ 1.0, -1.0, -1.0], texture_coordinates: [0.0, 1.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 1.0, -1.0, 1.0], texture_coordinates: [1.0, 1.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 1.0, 1.0, 1.0], texture_coordinates: [1.0, 0.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 1.0, 1.0, -1.0], texture_coordinates: [0.0, 0.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 0.5, -0.5, -0.5], texture_coordinates: [0.0, 1.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 0.5, -0.5, 0.5], texture_coordinates: [1.0, 1.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 0.5, 0.5, 0.5], texture_coordinates: [1.0, 0.0], normal: [ 1.0, 0.0, 0.0] },
Vertex { position: [ 0.5, 0.5, -0.5], texture_coordinates: [0.0, 0.0], normal: [ 1.0, 0.0, 0.0] },
// Back
Vertex { position: [-1.0, -1.0, -1.0], texture_coordinates: [1.0, 1.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [-1.0, 1.0, -1.0], texture_coordinates: [1.0, 0.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [ 1.0, 1.0, -1.0], texture_coordinates: [0.0, 0.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [ 1.0, -1.0, -1.0], texture_coordinates: [0.0, 1.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [-0.5, -0.5, -0.5], texture_coordinates: [1.0, 1.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [-0.5, 0.5, -0.5], texture_coordinates: [1.0, 0.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [ 0.5, 0.5, -0.5], texture_coordinates: [0.0, 0.0], normal: [ 0.0, 0.0, -1.0] },
Vertex { position: [ 0.5, -0.5, -0.5], texture_coordinates: [0.0, 1.0], normal: [ 0.0, 0.0, -1.0] },
// Front
Vertex { position: [-1.0, -1.0, 1.0], texture_coordinates: [0.0, 1.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [-1.0, 1.0, 1.0], texture_coordinates: [0.0, 0.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [ 1.0, 1.0, 1.0], texture_coordinates: [1.0, 0.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [ 1.0, -1.0, 1.0], texture_coordinates: [1.0, 1.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [-0.5, -0.5, 0.5], texture_coordinates: [0.0, 1.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [-0.5, 0.5, 0.5], texture_coordinates: [0.0, 0.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [ 0.5, 0.5, 0.5], texture_coordinates: [1.0, 0.0], normal: [ 0.0, 0.0, 1.0] },
Vertex { position: [ 0.5, -0.5, 0.5], texture_coordinates: [1.0, 1.0], normal: [ 0.0, 0.0, 1.0] },
// Bottom
Vertex { position: [-1.0, -1.0, -1.0], texture_coordinates: [1.0, 0.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [-1.0, -1.0, 1.0], texture_coordinates: [1.0, 1.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [ 1.0, -1.0, 1.0], texture_coordinates: [0.0, 1.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [ 1.0, -1.0, -1.0], texture_coordinates: [0.0, 0.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [-0.5, -0.5, -0.5], texture_coordinates: [1.0, 0.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [-0.5, -0.5, 0.5], texture_coordinates: [1.0, 1.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [ 0.5, -0.5, 0.5], texture_coordinates: [0.0, 1.0], normal: [ 0.0, -1.0, 0.0] },
Vertex { position: [ 0.5, -0.5, -0.5], texture_coordinates: [0.0, 0.0], normal: [ 0.0, -1.0, 0.0] },
// Top
Vertex { position: [ -1.0, 1.0, -1.0], texture_coordinates: [0.0, 0.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [ -1.0, 1.0, 1.0], texture_coordinates: [0.0, 1.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [ 1.0, 1.0, 1.0], texture_coordinates: [1.0, 1.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [ 1.0, 1.0, -1.0], texture_coordinates: [1.0, 0.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [-0.5, 0.5, -0.5], texture_coordinates: [0.0, 0.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [-0.5, 0.5, 0.5], texture_coordinates: [0.0, 1.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [ 0.5, 0.5, 0.5], texture_coordinates: [1.0, 1.0], normal: [ 0.0, 1.0, 0.0] },
Vertex { position: [ 0.5, 0.5, -0.5], texture_coordinates: [1.0, 0.0], normal: [ 0.0, 1.0, 0.0] },
];
#[rustfmt::skip]

View file

@ -1,12 +1,17 @@
use crate::chunk::BlockType;
#[derive(Debug)]
pub struct Instance {
pub position: cgmath::Vector3<f32>,
pub rotation: cgmath::Quaternion<f32>,
pub block_type: BlockType,
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct InstanceRaw {
model: [[f32; 4]; 4],
texture_index: u32,
}
impl Instance {
@ -16,6 +21,7 @@ impl Instance {
InstanceRaw {
model: (position * rotation).into(),
texture_index: self.block_type.texture_index(),
}
}
}
@ -47,6 +53,11 @@ impl InstanceRaw {
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 16]>() as wgpu::BufferAddress,
shader_location: 9,
format: wgpu::VertexFormat::Uint32,
},
],
}
}

View file

@ -1,4 +1,6 @@
mod aabb;
mod camera;
mod chunk;
mod cube;
mod instance;
mod light;
@ -21,7 +23,7 @@ fn main() {
env_logger::init();
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title(r#"minecrab"#)
.with_title("minecrab")
.with_inner_size(Size::Physical(PhysicalSize {
width: 1280,
height: 720,
@ -29,10 +31,7 @@ fn main() {
.build(&event_loop)
.unwrap();
use futures::executor::block_on;
// Since main can't be async, we're going to need to block
let mut state = block_on(State::new(&window));
let mut state = futures::executor::block_on(State::new(&window));
let mut frames = 0;
let mut instant = Instant::now();

View file

@ -34,6 +34,7 @@ struct InstanceInput {
[[location(6)]] model_matrix_1: vec4<f32>;
[[location(7)]] model_matrix_2: vec4<f32>;
[[location(8)]] model_matrix_3: vec4<f32>;
[[location(9)]] texture_index: u32;
};
@ -58,16 +59,13 @@ fn main(model: VertexInput, instance: InstanceInput) -> VertexOutput {
return out;
}
[[group(0), binding(0)]]
var texture_diffuse: texture_2d<f32>;
[[group(0), binding(1)]]
var sampler_diffuse: sampler;
[[group(0), binding(0)]] var sampler_diffuse: sampler;
[[group(0), binding(1)]] var texture: texture_2d<f32>;
[[stage(fragment)]]
fn main(in: VertexOutput) -> [[location(0)]] vec4<f32> {
let object_color: vec4<f32> =
textureSample(texture_diffuse, sampler_diffuse, in.texture_coordinates);
textureSample(texture, sampler_diffuse, in.texture_coordinates);
let ambient_strength = 0.2;
let ambient_color = light.color * ambient_strength;

View file

@ -1,6 +1,9 @@
use std::time::Duration;
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use cgmath::{InnerSpace, Rotation3};
use cgmath::{EuclideanSpace, InnerSpace, Rad};
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use winit::{
event::{DeviceEvent, ElementState, KeyboardInput, VirtualKeyCode},
@ -9,6 +12,7 @@ use winit::{
use crate::{
camera::{Camera, Projection},
chunk::{Block, BlockType, Chunk},
cube,
instance::{Instance, InstanceRaw},
light::Light,
@ -17,8 +21,6 @@ use crate::{
vertex::Vertex,
};
const NUM_INSTANCES_PER_ROW: u32 = 10;
pub struct State {
render_surface: wgpu::Surface,
render_device: wgpu::Device,
@ -29,10 +31,10 @@ pub struct State {
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
texture_bind_group: wgpu::BindGroup,
texture_bind_groups: HashMap<BlockType, wgpu::BindGroup>,
uniform_bind_group: wgpu::BindGroup,
instances: Vec<Instance>,
instance_buffer: wgpu::Buffer,
instance_lists: Vec<(BlockType, Vec<Instance>)>,
instance_buffers: Vec<(BlockType, wgpu::Buffer)>,
depth_texture: Texture,
_light: Light,
_light_buffer: wgpu::Buffer,
@ -129,8 +131,12 @@ impl State {
.request_device(
&wgpu::DeviceDescriptor {
label: Some("render_device"),
features: wgpu::Features::NON_FILL_POLYGON_MODE,
limits: wgpu::Limits::default(),
features: wgpu::Features::NON_FILL_POLYGON_MODE
| wgpu::Features::SAMPLED_TEXTURE_BINDING_ARRAY,
limits: wgpu::Limits {
max_push_constant_size: 4,
..wgpu::Limits::default()
},
},
None,
)
@ -165,63 +171,84 @@ impl State {
fn create_textures(
render_device: &wgpu::Device,
queue: &wgpu::Queue,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
let texture = Texture::from_bytes(
) -> (wgpu::BindGroupLayout, HashMap<BlockType, wgpu::BindGroup>) {
let dirt_texture = Texture::from_bytes(
render_device,
queue,
include_bytes!("../assets/block/cobblestone.png"),
"dirt_diffuse",
include_bytes!("../assets/block/dirt.png"),
"dirt",
)
.unwrap();
let texture_bind_group_layout =
let cobblestone_texture = Texture::from_bytes(
render_device,
queue,
include_bytes!("../assets/block/cobblestone.png"),
"cobblestone",
)
.unwrap();
let sampler = render_device.create_sampler(&wgpu::SamplerDescriptor::default());
let bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("texture_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler {
comparison: false,
filtering: true,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let texture_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("dirt_diffuse_bind_group"),
layout: &texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&texture.sampler),
},
],
});
let bind_groups: HashMap<BlockType, wgpu::BindGroup> = [
(BlockType::Dirt, dirt_texture),
(BlockType::Cobblestone, cobblestone_texture),
]
.iter()
.map(|(block_type, texture)| {
(
*block_type,
render_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("texture_bind_group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
],
}),
)
})
.collect();
(texture_bind_group_layout, texture_bind_group)
(bind_group_layout, bind_groups)
}
fn create_camera(swap_chain_descriptor: &wgpu::SwapChainDescriptor) -> (Camera, Projection) {
let camera = Camera::new(
(0.0, 5.0, 10.0).into(),
cgmath::Deg(-90.0).into(),
cgmath::Deg(0.0).into(),
cgmath::Deg(-20.0).into(),
);
@ -334,49 +361,83 @@ impl State {
)
}
fn create_instances(render_device: &wgpu::Device) -> (Vec<Instance>, wgpu::Buffer) {
let instances = (0..NUM_INSTANCES_PER_ROW as i32)
.flat_map(|z| {
(0..NUM_INSTANCES_PER_ROW as i32).map(move |x| {
let position = cgmath::Vector3 {
x: (x - NUM_INSTANCES_PER_ROW as i32 / 2) as f32 * 2.0,
y: 0.0,
z: (z - NUM_INSTANCES_PER_ROW as i32 / 2) as f32 * 2.0,
};
fn create_instances(
render_device: &wgpu::Device,
chunk: &Chunk,
) -> (
Vec<(BlockType, Vec<Instance>)>,
Vec<(BlockType, wgpu::Buffer)>,
) {
let instance_lists = chunk.to_instances();
let rotation = cgmath::Quaternion::from_axis_angle(
cgmath::Vector3::unit_z(),
cgmath::Deg(0.0),
);
let instance_buffers = instance_lists
.iter()
.map(|(block_type, instance_list)| {
let instance_data: Vec<InstanceRaw> =
instance_list.iter().map(Instance::to_raw).collect();
Instance { position, rotation }
})
(
*block_type,
render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("instance_buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsage::VERTEX,
}),
)
})
.collect::<Vec<_>>();
.collect();
let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>();
let instance_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("Instance Buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsage::VERTEX,
});
(instances, instance_buffer)
(instance_lists, instance_buffers)
}
pub async fn new(window: &Window) -> Self {
let size = window.inner_size();
let mut chunk = Chunk {
blocks: [
[[Some(Block {
block_type: BlockType::Cobblestone,
}); 16]; 16],
[[Some(Block {
block_type: BlockType::Dirt,
}); 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
],
};
let (render_surface, adapter, render_device, queue) =
Self::create_render_device(window).await;
let (swap_chain_descriptor, swap_chain) =
Self::create_swap_chain(window, &adapter, &render_device, &render_surface);
let (texture_layout, texture_bind_group) = Self::create_textures(&render_device, &queue);
let (texture_layout, texture_bind_groups) = Self::create_textures(&render_device, &queue);
let (camera, projection) = Self::create_camera(&swap_chain_descriptor);
let dda_start = Instant::now();
let coll_pos = chunk
.dda(camera.position.to_vec(), camera.direction())
.unwrap();
dbg!(dda_start.elapsed());
chunk.blocks[coll_pos.y][coll_pos.z][coll_pos.x] = Some(Block {
block_type: BlockType::Cobblestone,
});
let (uniforms, uniform_buffer, uniform_layout, uniform_bind_group) =
Self::create_uniforms(&camera, &projection, &render_device);
@ -398,7 +459,7 @@ impl State {
usage: wgpu::BufferUsage::INDEX,
});
let (instances, instance_buffer) = Self::create_instances(&render_device);
let (instance_lists, instance_buffers) = Self::create_instances(&render_device, &chunk);
let depth_texture =
Texture::create_depth_texture(&render_device, &swap_chain_descriptor, "depth_texture");
@ -416,11 +477,11 @@ impl State {
uniforms,
uniform_buffer,
uniform_bind_group,
texture_bind_group,
texture_bind_groups,
camera,
projection,
instances,
instance_buffer,
instance_lists,
instance_buffers,
depth_texture,
_light: light,
_light_buffer: light_buffer,
@ -470,16 +531,23 @@ impl State {
}
}
fn update_camera(&mut self, dx: f64, dy: f64) {
self.camera.yaw += Rad(dx as f32 * 0.005);
self.camera.pitch -= Rad(dy as f32 * 0.005);
if self.camera.pitch < Rad::from(cgmath::Deg(-80.0)) {
self.camera.pitch = Rad::from(cgmath::Deg(-80.0));
} else if self.camera.pitch > Rad::from(cgmath::Deg(89.0)) {
self.camera.pitch = Rad::from(cgmath::Deg(89.0));
}
}
fn update_aim(&mut self) {}
fn input_mouse(&mut self, dx: f64, dy: f64) {
if self.mouse_grabbed {
self.camera.yaw += cgmath::Rad(dx as f32 * 0.005);
self.camera.pitch -= cgmath::Rad(dy as f32 * 0.005);
if self.camera.pitch < cgmath::Rad::from(cgmath::Deg(-80.0)) {
self.camera.pitch = cgmath::Rad::from(cgmath::Deg(-80.0));
} else if self.camera.pitch > cgmath::Rad::from(cgmath::Deg(89.0)) {
self.camera.pitch = cgmath::Rad::from(cgmath::Deg(89.0));
}
self.update_camera(dx, dy);
self.update_aim();
}
}
@ -551,20 +619,25 @@ impl State {
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.texture_bind_group, &[]);
render_pass.set_bind_group(1, &self.uniform_bind_group, &[]);
render_pass.set_bind_group(2, &self.light_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(
0..cube::INDICES.len() as u32,
0,
0..self.instances.len() as u32,
);
for (i, (block_type, instance_list)) in self.instance_lists.iter().enumerate() {
let (_, instance_buffer) = &self.instance_buffers[i];
let texture_bind_group = &self.texture_bind_groups[block_type];
render_pass.set_bind_group(0, texture_bind_group, &[]);
render_pass.set_vertex_buffer(1, instance_buffer.slice(..));
render_pass.draw_indexed(
0..cube::INDICES.len() as u32,
0,
0..instance_list.len() as u32,
);
}
}
self.queue.submit(std::iter::once(render_encoder.finish()));

View file

@ -4,7 +4,7 @@ use image::EncodableLayout;
pub struct Texture {
pub texture: wgpu::Texture,
pub sampler: wgpu::Sampler,
pub sampler: Option<wgpu::Sampler>,
pub view: wgpu::TextureView,
}
@ -48,7 +48,7 @@ impl Texture {
Self {
texture,
sampler,
sampler: Some(sampler),
view,
}
}
@ -94,20 +94,16 @@ impl Texture {
texture_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,
..wgpu::SamplerDescriptor::default()
let view = texture.create_view(&wgpu::TextureViewDescriptor {
label: Some(&format!("texture_view_{}", label)),
dimension: Some(wgpu::TextureViewDimension::D2),
array_layer_count: NonZeroU32::new(1),
..wgpu::TextureViewDescriptor::default()
});
Ok(Self {
texture,
sampler,
sampler: None,
view,
})
}