initial (bad) voxel renderer
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
use std::marker::PhantomData;
|
||||
use wgpu::{BufferAddress, BufferUsages};
|
||||
|
||||
pub struct ArrBuf<T: bytemuck::Pod> {
|
||||
len: usize,
|
||||
buffer: wgpu::Buffer,
|
||||
label: String,
|
||||
typ: PhantomData<T>,
|
||||
usage: BufferUsages,
|
||||
moves: Vec<BufMove>,
|
||||
}
|
||||
|
||||
impl<T: bytemuck::Pod> ArrBuf<T> {
|
||||
pub fn update(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
size: usize,
|
||||
updates: &[ArrBufUpdate<T>],
|
||||
) -> bool {
|
||||
let mut resized = false;
|
||||
if size != self.len || !self.moves.is_empty() {
|
||||
let new = Self::init_buf(device, &self.label, size, self.usage);
|
||||
let cpy_len = self.len.min(size);
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.buffer,
|
||||
0,
|
||||
&new,
|
||||
0,
|
||||
(cpy_len * std::mem::size_of::<T>()) as u64,
|
||||
);
|
||||
for m in &self.moves {
|
||||
encoder.copy_buffer_to_buffer(
|
||||
&self.buffer,
|
||||
(m.source * std::mem::size_of::<T>()) as BufferAddress,
|
||||
&new,
|
||||
(m.dest * std::mem::size_of::<T>()) as BufferAddress,
|
||||
(m.size * std::mem::size_of::<T>()) as BufferAddress,
|
||||
);
|
||||
}
|
||||
resized = true;
|
||||
self.moves.clear();
|
||||
self.len = size;
|
||||
self.buffer = new;
|
||||
}
|
||||
if self.len == 0 {
|
||||
return resized;
|
||||
}
|
||||
for update in updates {
|
||||
let mut view = belt.write_buffer(
|
||||
encoder,
|
||||
&self.buffer,
|
||||
(update.offset * std::mem::size_of::<T>()) as BufferAddress,
|
||||
unsafe {
|
||||
std::num::NonZeroU64::new_unchecked(
|
||||
(update.data.len() * std::mem::size_of::<T>()) as u64,
|
||||
)
|
||||
},
|
||||
device,
|
||||
);
|
||||
view.copy_from_slice(bytemuck::cast_slice(&update.data));
|
||||
}
|
||||
resized
|
||||
}
|
||||
|
||||
pub fn init(device: &wgpu::Device, label: &str, usage: BufferUsages) -> Self {
|
||||
let label = &(label.to_owned() + " Buffer");
|
||||
Self {
|
||||
len: 0,
|
||||
buffer: Self::init_buf(device, label, 0, usage),
|
||||
label: label.to_string(),
|
||||
typ: PhantomData,
|
||||
usage,
|
||||
moves: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn init_buf(
|
||||
device: &wgpu::Device,
|
||||
label: &str,
|
||||
mut size: usize,
|
||||
usage: BufferUsages,
|
||||
) -> wgpu::Buffer {
|
||||
if usage.contains(BufferUsages::STORAGE) && size == 0 {
|
||||
size = 1;
|
||||
}
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
usage: usage | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
|
||||
size: (size * std::mem::size_of::<T>()) as u64,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn buffer(&self) -> &wgpu::Buffer {
|
||||
&self.buffer
|
||||
}
|
||||
|
||||
pub fn mov(&mut self, mov: BufMove) {
|
||||
self.moves.push(mov);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ArrBufUpdate<T> {
|
||||
pub offset: usize,
|
||||
pub data: Vec<T>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct BufMove {
|
||||
pub source: usize,
|
||||
pub dest: usize,
|
||||
pub size: usize,
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use wgpu::{BufferUsages, VertexAttribute};
|
||||
|
||||
use super::buf::{ArrBuf, ArrBufUpdate, BufMove};
|
||||
|
||||
pub struct Instances<T: bytemuck::Pod> {
|
||||
buf: ArrBuf<T>,
|
||||
location: u32,
|
||||
attrs: [VertexAttribute; 1],
|
||||
}
|
||||
|
||||
impl<T: bytemuck::Pod> Instances<T> {
|
||||
pub fn update(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
size: usize,
|
||||
updates: &[ArrBufUpdate<T>],
|
||||
) -> bool {
|
||||
self.buf.update(device, encoder, belt, size, updates)
|
||||
}
|
||||
|
||||
pub fn init(
|
||||
device: &wgpu::Device,
|
||||
label: &str,
|
||||
location: u32,
|
||||
format: wgpu::VertexFormat,
|
||||
) -> Self {
|
||||
Self {
|
||||
buf: ArrBuf::init(
|
||||
device,
|
||||
&(label.to_owned() + " Instance"),
|
||||
BufferUsages::VERTEX,
|
||||
),
|
||||
location,
|
||||
attrs: [wgpu::VertexAttribute {
|
||||
format,
|
||||
offset: 0,
|
||||
shader_location: location,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_in<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
|
||||
render_pass.set_vertex_buffer(self.location, self.buf.buffer().slice(..));
|
||||
}
|
||||
|
||||
pub fn desc(&self) -> wgpu::VertexBufferLayout {
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<T>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &self.attrs,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mov(&mut self, mov: BufMove) {
|
||||
self.buf.mov(mov);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
mod buf;
|
||||
mod instance;
|
||||
mod renderer;
|
||||
mod storage;
|
||||
pub mod voxel;
|
||||
mod uniform;
|
||||
|
||||
pub use renderer::*;
|
||||
@@ -0,0 +1,171 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::voxel::VoxelPipeline;
|
||||
use crate::client::{rsc::CLEAR_COLOR, ClientState};
|
||||
use winit::{
|
||||
dpi::PhysicalSize,
|
||||
window::{Fullscreen, Window},
|
||||
};
|
||||
|
||||
pub struct Renderer<'a> {
|
||||
size: PhysicalSize<u32>,
|
||||
surface: wgpu::Surface<'a>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
adapter: wgpu::Adapter,
|
||||
encoder: Option<wgpu::CommandEncoder>,
|
||||
staging_belt: wgpu::util::StagingBelt,
|
||||
voxel_pipeline: VoxelPipeline,
|
||||
}
|
||||
|
||||
impl<'a> Renderer<'a> {
|
||||
pub fn new(window: Arc<Window>, fullscreen: bool) -> Self {
|
||||
if fullscreen {
|
||||
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||
}
|
||||
|
||||
let size = window.inner_size();
|
||||
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::PRIMARY,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let surface = instance
|
||||
.create_surface(window)
|
||||
.expect("Could not create window surface!");
|
||||
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::default(),
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
}))
|
||||
.expect("Could not get adapter!");
|
||||
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: None,
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
},
|
||||
None, // Trace path
|
||||
))
|
||||
.expect("Could not get device!");
|
||||
|
||||
// TODO: use a logger
|
||||
let info = adapter.get_info();
|
||||
println!("Adapter: {}", info.name);
|
||||
println!("Backend: {:?}", info.backend);
|
||||
|
||||
let surface_caps = surface.get_capabilities(&adapter);
|
||||
// Set surface format to srbg
|
||||
let surface_format = surface_caps
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|f| f.is_srgb())
|
||||
.unwrap_or(surface_caps.formats[0]);
|
||||
|
||||
// create surface config
|
||||
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);
|
||||
// not exactly sure what this number should be,
|
||||
// doesn't affect performance much and depends on "normal" zoom
|
||||
let staging_belt = wgpu::util::StagingBelt::new(4096 * 4);
|
||||
|
||||
Self {
|
||||
size,
|
||||
voxel_pipeline: VoxelPipeline::new(&device, &config.format),
|
||||
encoder: None,
|
||||
staging_belt,
|
||||
surface,
|
||||
device,
|
||||
adapter,
|
||||
config,
|
||||
queue,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_encoder(&mut self) -> wgpu::CommandEncoder {
|
||||
self.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Render Encoder"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn draw(&mut self) {
|
||||
let output = self.surface.get_current_texture().unwrap();
|
||||
let view = output
|
||||
.texture
|
||||
.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let mut encoder = self.encoder.take().unwrap_or(self.create_encoder());
|
||||
{
|
||||
let render_pass = &mut 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(CLEAR_COLOR),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
self.voxel_pipeline.draw(render_pass);
|
||||
}
|
||||
|
||||
self.staging_belt.finish();
|
||||
self.queue.submit(std::iter::once(encoder.finish()));
|
||||
output.present();
|
||||
self.staging_belt.recall();
|
||||
}
|
||||
|
||||
pub fn update(&mut self, state: &ClientState) {
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Render Encoder"),
|
||||
});
|
||||
self.voxel_pipeline.update(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&mut self.staging_belt,
|
||||
&mut self.queue,
|
||||
&RenderUpdateData {
|
||||
state,
|
||||
size: &self.size,
|
||||
},
|
||||
);
|
||||
self.encoder = Some(encoder);
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, size: PhysicalSize<u32>) {
|
||||
self.size = size;
|
||||
self.config.width = size.width;
|
||||
self.config.height = size.height;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
}
|
||||
|
||||
pub fn size(&self) -> &PhysicalSize<u32> {
|
||||
&self.size
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RenderUpdateData<'a> {
|
||||
pub state: &'a ClientState,
|
||||
pub size: &'a PhysicalSize<u32>,
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use super::buf::{ArrBuf, ArrBufUpdate, BufMove};
|
||||
use wgpu::BufferUsages;
|
||||
|
||||
pub struct Storage<T: bytemuck::Pod + PartialEq> {
|
||||
binding: u32,
|
||||
buf: ArrBuf<T>,
|
||||
}
|
||||
|
||||
impl<T: PartialEq + bytemuck::Pod> Storage<T> {
|
||||
pub fn init(device: &wgpu::Device, label: &str, binding: u32) -> Self {
|
||||
Self {
|
||||
buf: ArrBuf::init(
|
||||
device,
|
||||
&(label.to_owned() + " Storage"),
|
||||
BufferUsages::STORAGE,
|
||||
),
|
||||
binding,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq + bytemuck::Pod> Storage<T> {
|
||||
pub fn bind_group_layout_entry(&self) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: self.binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}
|
||||
}
|
||||
pub fn bind_group_entry(&self) -> wgpu::BindGroupEntry {
|
||||
return wgpu::BindGroupEntry {
|
||||
binding: self.binding,
|
||||
resource: self.buf.buffer().as_entire_binding(),
|
||||
};
|
||||
}
|
||||
pub fn update(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
size: usize,
|
||||
updates: &[ArrBufUpdate<T>],
|
||||
) -> bool {
|
||||
self.buf.update(device, encoder, belt, size, updates)
|
||||
}
|
||||
|
||||
pub fn mov(&mut self, mov: BufMove) {
|
||||
self.buf.mov(mov);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use super::RenderUpdateData;
|
||||
|
||||
pub trait UniformData {
|
||||
fn update(&mut self, data: &RenderUpdateData) -> bool;
|
||||
}
|
||||
|
||||
pub struct Uniform<T: bytemuck::Pod + PartialEq + UniformData> {
|
||||
data: T,
|
||||
buffer: wgpu::Buffer,
|
||||
binding: u32,
|
||||
}
|
||||
|
||||
impl<T: Default + PartialEq + bytemuck::Pod + UniformData> Uniform<T> {
|
||||
pub fn init(device: &wgpu::Device, name: &str, binding: u32) -> Self {
|
||||
let data = T::default();
|
||||
Self {
|
||||
data,
|
||||
buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some(&(name.to_owned() + " Uniform Buf")),
|
||||
contents: bytemuck::cast_slice(&[data]),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
}),
|
||||
binding,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq + bytemuck::Pod + UniformData> Uniform<T> {
|
||||
pub fn bind_group_layout_entry(&self) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: self.binding,
|
||||
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}
|
||||
}
|
||||
pub fn bind_group_entry(&self) -> wgpu::BindGroupEntry {
|
||||
return wgpu::BindGroupEntry {
|
||||
binding: self.binding,
|
||||
resource: self.buffer.as_entire_binding(),
|
||||
};
|
||||
}
|
||||
pub fn update(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
update_data: &RenderUpdateData,
|
||||
) {
|
||||
if self.data.update(update_data) {
|
||||
let slice = &[self.data];
|
||||
let mut view = belt.write_buffer(
|
||||
encoder,
|
||||
&self.buffer,
|
||||
0,
|
||||
unsafe {
|
||||
std::num::NonZeroU64::new_unchecked(
|
||||
(slice.len() * std::mem::size_of::<T>()) as u64,
|
||||
)
|
||||
},
|
||||
device,
|
||||
);
|
||||
view.copy_from_slice(bytemuck::cast_slice(slice));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Zeroable, bytemuck::Pod)]
|
||||
pub struct VoxelColor {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
pub a: u8,
|
||||
}
|
||||
|
||||
impl VoxelColor {
|
||||
pub fn none() -> Self {
|
||||
Self {
|
||||
r: 0,
|
||||
g: 0,
|
||||
b: 0,
|
||||
a: 0,
|
||||
}
|
||||
}
|
||||
pub fn black() -> Self {
|
||||
Self {
|
||||
r: 0,
|
||||
g: 0,
|
||||
b: 0,
|
||||
a: 255,
|
||||
}
|
||||
}
|
||||
pub fn white() -> Self {
|
||||
Self {
|
||||
r: 255,
|
||||
g: 255,
|
||||
b: 255,
|
||||
a: 255,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use nalgebra::Matrix4x3;
|
||||
|
||||
// this has cost me more than a couple of hours trying to figure out alignment :skull:
|
||||
// putting transform at the beginning so I don't have to deal with its alignment
|
||||
// I should probably look into encase (crate)
|
||||
#[repr(C, align(16))]
|
||||
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||
pub struct GridInfo {
|
||||
pub transform: Matrix4x3<f32>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
unsafe impl bytemuck::Pod for GridInfo {}
|
||||
|
||||
impl Default for GridInfo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
transform: Matrix4x3::identity(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
mod grid;
|
||||
mod view;
|
||||
mod pipeline;
|
||||
mod color;
|
||||
|
||||
pub use pipeline::*;
|
||||
@@ -0,0 +1,208 @@
|
||||
use super::{color::VoxelColor, view::View};
|
||||
use crate::client::render::{
|
||||
buf::ArrBufUpdate, storage::Storage, uniform::Uniform, RenderUpdateData,
|
||||
};
|
||||
|
||||
pub struct VoxelPipeline {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
view: Uniform<View>,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
texture: wgpu::Texture,
|
||||
voxels: Storage<VoxelColor>,
|
||||
arst: bool,
|
||||
}
|
||||
|
||||
const WIDTH: u32 = 300;
|
||||
const HEIGHT: u32 = 300;
|
||||
|
||||
impl VoxelPipeline {
|
||||
pub fn new(device: &wgpu::Device, format: &wgpu::TextureFormat) -> Self {
|
||||
// shaders
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Tile Shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
|
||||
});
|
||||
|
||||
let view = Uniform::<View>::init(device, "View", 0);
|
||||
let texture_size = wgpu::Extent3d {
|
||||
width: WIDTH,
|
||||
height: HEIGHT,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
size: texture_size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
label: Some("diffuse_texture"),
|
||||
view_formats: &[],
|
||||
});
|
||||
let voxels = Storage::init(device, "voxels", 3);
|
||||
|
||||
let diffuse_texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let diffuse_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()
|
||||
});
|
||||
|
||||
// bind groups
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
entries: &[
|
||||
view.bind_group_layout_entry(),
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
voxels.bind_group_layout_entry(),
|
||||
],
|
||||
label: Some("tile_bind_group_layout"),
|
||||
});
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &bind_group_layout,
|
||||
entries: &[
|
||||
view.bind_group_entry(),
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
|
||||
},
|
||||
voxels.bind_group_entry(),
|
||||
],
|
||||
label: Some("tile_bind_group"),
|
||||
});
|
||||
|
||||
// pipeline
|
||||
let render_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Tile Pipeline Layout"),
|
||||
bind_group_layouts: &[&bind_group_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Voxel Pipeline"),
|
||||
layout: Some(&render_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
buffers: &[],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: *format,
|
||||
blend: Some(wgpu::BlendState::REPLACE),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleStrip,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: None,
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: true,
|
||||
},
|
||||
multiview: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
pipeline: render_pipeline,
|
||||
view,
|
||||
bind_group,
|
||||
bind_group_layout,
|
||||
texture,
|
||||
voxels,
|
||||
arst: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
queue: &mut wgpu::Queue,
|
||||
update_data: &RenderUpdateData,
|
||||
) {
|
||||
let texture_size = wgpu::Extent3d {
|
||||
width: WIDTH,
|
||||
height: HEIGHT,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
if !self.arst {
|
||||
queue.write_texture(
|
||||
// Tells wgpu where to copy the pixel data
|
||||
wgpu::ImageCopyTexture {
|
||||
texture: &self.texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
// The actual pixel data
|
||||
&[0xff, 0x00, 0xff, 0xff].repeat((WIDTH * HEIGHT) as usize),
|
||||
// The layout of the texture
|
||||
wgpu::ImageDataLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(4 * WIDTH),
|
||||
rows_per_image: Some(HEIGHT),
|
||||
},
|
||||
texture_size,
|
||||
);
|
||||
let l = 10;
|
||||
let size = l * l * l;
|
||||
let mut data: Vec<_> = vec![VoxelColor::none(); size];
|
||||
data[0] = VoxelColor::white();
|
||||
data[size - 1] = VoxelColor::white();
|
||||
self.voxels.update(
|
||||
device,
|
||||
encoder,
|
||||
belt,
|
||||
data.len(),
|
||||
&[ArrBufUpdate { offset: 0, data }],
|
||||
);
|
||||
self.arst = true;
|
||||
}
|
||||
self.view.update(device, encoder, belt, update_data);
|
||||
}
|
||||
|
||||
pub fn draw<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &self.bind_group, &[]);
|
||||
render_pass.draw(0..4, 0..1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Vertex shader
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) tex_coords: vec2<f32>,
|
||||
};
|
||||
|
||||
struct View {
|
||||
width: u32,
|
||||
height: u32,
|
||||
zoom: f32,
|
||||
padding: u32,
|
||||
transform: mat4x4<f32>,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> view: View;
|
||||
@group(0) @binding(1)
|
||||
var t_diffuse: texture_2d<f32>;
|
||||
@group(0) @binding(2)
|
||||
var s_diffuse: sampler;
|
||||
@group(0) @binding(3)
|
||||
var<storage, read> voxels: array<u32>;
|
||||
|
||||
@vertex
|
||||
fn vs_main(
|
||||
@builtin(vertex_index) vi: u32,
|
||||
@builtin(instance_index) ii: u32,
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
|
||||
var pos = vec2<f32>(
|
||||
f32(vi % 2u) * 2.0 - 1.0,
|
||||
f32(vi / 2u) * 2.0 - 1.0,
|
||||
);
|
||||
out.clip_position = vec4<f32>(pos.x, pos.y, 0.0, 1.0);
|
||||
out.tex_coords = pos;
|
||||
return out;
|
||||
}
|
||||
|
||||
// Fragment shader
|
||||
|
||||
@fragment
|
||||
fn fs_main(
|
||||
in: VertexOutput,
|
||||
) -> @location(0) vec4<f32> {
|
||||
let aspect = f32(view.height) / f32(view.width);
|
||||
var pixel_pos = vec3<f32>(in.clip_position.x / f32(view.width), 1.0 - in.clip_position.y / f32(view.height), 1.0);
|
||||
pixel_pos.x -= 0.5;
|
||||
pixel_pos.y -= 0.5;
|
||||
pixel_pos.x *= 2.0;
|
||||
pixel_pos.y *= 2.0;
|
||||
pixel_pos.y *= aspect;
|
||||
|
||||
pixel_pos = (view.transform * vec4<f32>(pixel_pos, 1.0)).xyz;
|
||||
let origin = (view.transform * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
|
||||
let dir = normalize(pixel_pos - origin);
|
||||
|
||||
|
||||
|
||||
let voxel_pos = vec3<f32>(-5.0, -5.0, 30.0);
|
||||
var t = 0;
|
||||
for(t = 0; t < 1000; t += 1) {
|
||||
let pos = pixel_pos + f32(t) * 0.1 * dir - voxel_pos;
|
||||
let rel_coords = vec3<i32>(pos.xyz);
|
||||
if rel_coords.x < 0 || rel_coords.y < 0 || rel_coords.z < 0 || rel_coords.x > 10 || rel_coords.y > 10 || rel_coords.z > 10 {
|
||||
continue;
|
||||
} else {
|
||||
let i = rel_coords.x + rel_coords.y * 10 + rel_coords.z * 100;
|
||||
let color = unpack4x8unorm(voxels[i]);
|
||||
if voxels[i] != 0 {
|
||||
return vec4<f32>(1.0);
|
||||
} else {
|
||||
let pos = vec3<f32>(rel_coords);
|
||||
return vec4<f32>(pos.x / 10.0, pos.y / 10.0, pos.z / 10.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use nalgebra::{Transform3, Translation3};
|
||||
|
||||
use crate::client::render::uniform::UniformData;
|
||||
|
||||
#[repr(C, align(16))]
|
||||
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||
pub struct View {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub zoom: f32,
|
||||
pub padding: u32,
|
||||
pub transform: Transform3<f32>,
|
||||
}
|
||||
|
||||
unsafe impl bytemuck::Pod for View {}
|
||||
|
||||
impl Default for View {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: 1,
|
||||
height: 1,
|
||||
zoom: 1.0,
|
||||
padding: 0,
|
||||
transform: Transform3::identity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UniformData for View {
|
||||
fn update(&mut self, data: &crate::client::render::RenderUpdateData) -> bool {
|
||||
let camera = data.state.camera;
|
||||
let new = Transform3::identity() * Translation3::from(camera.pos) * camera.orientation;
|
||||
if new == self.transform
|
||||
&& data.size.width == self.width
|
||||
&& data.size.height == self.height
|
||||
&& camera.scale == self.zoom
|
||||
{
|
||||
false
|
||||
} else {
|
||||
*self = Self {
|
||||
width: data.size.width,
|
||||
height: data.size.height,
|
||||
zoom: camera.scale,
|
||||
padding: 0,
|
||||
transform: new,
|
||||
};
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user