RAY CASTED OCT TREE RENDERING
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
client::camera::Camera,
|
||||
common::component::{ChunkMesh, ChunkPos},
|
||||
common::component::{ChunkMesh, ChunkPos}, util::oct_tree::OctTree,
|
||||
};
|
||||
|
||||
use super::{voxel::VoxelColor, Renderer};
|
||||
@@ -32,6 +32,7 @@ pub struct AddChunk {
|
||||
pub id: Entity,
|
||||
pub pos: ChunkPos,
|
||||
pub mesh: ChunkMesh,
|
||||
pub tree: OctTree,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
mod poly;
|
||||
// mod ray;
|
||||
pub use poly::*;
|
||||
// mod poly; pub use poly::*;
|
||||
// mod ray; pub use ray::*;
|
||||
mod ray_oct; pub use ray_oct::*;
|
||||
|
||||
@@ -249,7 +249,7 @@ impl VoxelPipeline {
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
AddChunk { id, pos, mesh }: AddChunk,
|
||||
AddChunk { id, pos, mesh, .. }: AddChunk,
|
||||
) {
|
||||
if mesh.faces.iter().all(|f| f.is_empty()) {
|
||||
return;
|
||||
|
||||
53
src/client/render/voxel/ray_oct/color.rs
Normal file
53
src/client/render/voxel/ray_oct/color.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use rand::distributions::{Distribution, Standard};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||
pub struct VoxelColor {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
pub a: u8,
|
||||
}
|
||||
|
||||
unsafe impl bytemuck::Pod for VoxelColor {}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
pub fn random() -> Self {
|
||||
rand::random()
|
||||
}
|
||||
}
|
||||
|
||||
impl Distribution<VoxelColor> for Standard {
|
||||
fn sample<R: rand::prelude::Rng + ?Sized>(&self, rng: &mut R) -> VoxelColor {
|
||||
VoxelColor {
|
||||
r: rng.gen(),
|
||||
g: rng.gen(),
|
||||
b: rng.gen(),
|
||||
a: rng.gen(),
|
||||
}
|
||||
}
|
||||
}
|
||||
24
src/client/render/voxel/ray_oct/grid.rs
Normal file
24
src/client/render/voxel/ray_oct/grid.rs
Normal file
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
12
src/client/render/voxel/ray_oct/group.rs
Normal file
12
src/client/render/voxel/ray_oct/group.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
use nalgebra::{Projective3, Vector3};
|
||||
|
||||
#[repr(C, align(16))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||
pub struct VoxelGroup {
|
||||
pub transform: Projective3<f32>,
|
||||
pub transform_inv: Projective3<f32>,
|
||||
pub dimensions: Vector3<u32>,
|
||||
pub offset: u32,
|
||||
}
|
||||
|
||||
unsafe impl bytemuck::Pod for VoxelGroup {}
|
||||
9
src/client/render/voxel/ray_oct/light.rs
Normal file
9
src/client/render/voxel/ray_oct/light.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use nalgebra::Vector3;
|
||||
|
||||
#[repr(C, align(16))]
|
||||
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||
pub struct GlobalLight {
|
||||
pub direction: Vector3<f32>,
|
||||
}
|
||||
|
||||
unsafe impl bytemuck::Pod for GlobalLight {}
|
||||
297
src/client/render/voxel/ray_oct/mod.rs
Normal file
297
src/client/render/voxel/ray_oct/mod.rs
Normal file
@@ -0,0 +1,297 @@
|
||||
mod color;
|
||||
mod grid;
|
||||
mod group;
|
||||
mod light;
|
||||
mod view;
|
||||
|
||||
pub use color::*;
|
||||
|
||||
use super::super::UpdateGridTransform;
|
||||
use crate::{client::{
|
||||
camera::Camera,
|
||||
render::{
|
||||
util::{ArrBufUpdate, Storage, Texture, Uniform},
|
||||
AddChunk, CreateVoxelGrid,
|
||||
},
|
||||
}, common::component::chunk, util::oct_tree::OctNode};
|
||||
use bevy_ecs::entity::Entity;
|
||||
use light::GlobalLight;
|
||||
use nalgebra::{Projective3, Transform3, Translation3, Vector2, Vector3};
|
||||
use std::{collections::HashMap, ops::Deref};
|
||||
|
||||
use {group::VoxelGroup, view::View};
|
||||
|
||||
pub struct VoxelPipeline {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
view: Uniform<View>,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
bind_group: wgpu::BindGroup,
|
||||
voxel_groups: Storage<VoxelGroup>,
|
||||
voxels: Storage<OctNode>,
|
||||
global_lights: Storage<GlobalLight>,
|
||||
id_map: HashMap<Entity, (usize, VoxelGroup)>,
|
||||
}
|
||||
|
||||
impl VoxelPipeline {
|
||||
pub fn new(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> 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::init(device, "view", 0);
|
||||
let voxels = Storage::init(device, "voxels", 1);
|
||||
let voxel_groups = Storage::init(device, "voxel groups", 2);
|
||||
let global_lights = Storage::init_with(
|
||||
device,
|
||||
"global lights",
|
||||
3,
|
||||
&[GlobalLight {
|
||||
direction: Vector3::new(-0.5, -4.0, 2.0).normalize(),
|
||||
}],
|
||||
);
|
||||
|
||||
// bind groups
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
entries: &[
|
||||
view.bind_group_layout_entry(),
|
||||
voxels.bind_group_layout_entry(),
|
||||
voxel_groups.bind_group_layout_entry(),
|
||||
global_lights.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(),
|
||||
voxels.bind_group_entry(),
|
||||
voxel_groups.bind_group_entry(),
|
||||
global_lights.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: config.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: Some(wgpu::DepthStencilState {
|
||||
format: Texture::DEPTH_FORMAT,
|
||||
depth_write_enabled: true,
|
||||
depth_compare: wgpu::CompareFunction::Less,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: true,
|
||||
},
|
||||
multiview: None,
|
||||
});
|
||||
|
||||
Self {
|
||||
pipeline: render_pipeline,
|
||||
view,
|
||||
bind_group,
|
||||
bind_group_layout,
|
||||
voxels,
|
||||
voxel_groups,
|
||||
global_lights,
|
||||
id_map: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_group(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
CreateVoxelGrid {
|
||||
id,
|
||||
pos,
|
||||
orientation,
|
||||
dimensions,
|
||||
grid,
|
||||
}: CreateVoxelGrid,
|
||||
) {
|
||||
// let offset = self.voxels.len();
|
||||
//
|
||||
// let updates = [ArrBufUpdate {
|
||||
// offset,
|
||||
// data: &grid.as_slice().unwrap(),
|
||||
// }];
|
||||
// let size = offset + grid.len();
|
||||
// self.voxels.update(device, encoder, belt, size, &updates);
|
||||
//
|
||||
// let proj = Projective3::identity()
|
||||
// * Translation3::from(pos)
|
||||
// * orientation
|
||||
// * Translation3::from(-dimensions.cast() / 2.0);
|
||||
// let group = VoxelGroup {
|
||||
// transform: proj,
|
||||
// transform_inv: proj.inverse(),
|
||||
// dimensions: dimensions.cast(),
|
||||
// offset: offset as u32,
|
||||
// };
|
||||
// let updates = [ArrBufUpdate {
|
||||
// offset: self.voxel_groups.len(),
|
||||
// data: &[group],
|
||||
// }];
|
||||
// let i = self.voxel_groups.len();
|
||||
// let size = i + 1;
|
||||
// self.voxel_groups
|
||||
// .update(device, encoder, belt, size, &updates);
|
||||
//
|
||||
// self.id_map.insert(id, (i, group));
|
||||
//
|
||||
// self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
// layout: &self.bind_group_layout,
|
||||
// entries: &[
|
||||
// self.view.bind_group_entry(),
|
||||
// self.voxels.bind_group_entry(),
|
||||
// self.voxel_groups.bind_group_entry(),
|
||||
// self.global_lights.bind_group_entry(),
|
||||
// ],
|
||||
// label: Some("tile_bind_group"),
|
||||
// });
|
||||
}
|
||||
|
||||
pub fn add_chunk(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
AddChunk {
|
||||
id,
|
||||
pos,
|
||||
tree,
|
||||
..
|
||||
}: AddChunk,
|
||||
) {
|
||||
let offset = self.voxels.len();
|
||||
|
||||
let data = tree.raw();
|
||||
let updates = [ArrBufUpdate {
|
||||
offset,
|
||||
data,
|
||||
}];
|
||||
let size = offset + data.len();
|
||||
self.voxels.update(device, encoder, belt, size, &updates);
|
||||
|
||||
let proj = Projective3::identity()
|
||||
* Translation3::from((pos.deref() * chunk::SIDE_LENGTH as i32).cast())
|
||||
* Translation3::from(-chunk::DIMENSIONS.cast() / 2.0);
|
||||
let group = VoxelGroup {
|
||||
transform: proj,
|
||||
transform_inv: proj.inverse(),
|
||||
dimensions: chunk::DIMENSIONS.cast(),
|
||||
offset: offset as u32,
|
||||
};
|
||||
let updates = [ArrBufUpdate {
|
||||
offset: self.voxel_groups.len(),
|
||||
data: &[group],
|
||||
}];
|
||||
let i = self.voxel_groups.len();
|
||||
let size = i + 1;
|
||||
self.voxel_groups
|
||||
.update(device, encoder, belt, size, &updates);
|
||||
|
||||
self.id_map.insert(id, (i, group));
|
||||
|
||||
self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
self.view.bind_group_entry(),
|
||||
self.voxels.bind_group_entry(),
|
||||
self.voxel_groups.bind_group_entry(),
|
||||
self.global_lights.bind_group_entry(),
|
||||
],
|
||||
label: Some("tile_bind_group"),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn update_transform(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
update: UpdateGridTransform,
|
||||
) {
|
||||
if let Some((i, group)) = self.id_map.get_mut(&update.id) {
|
||||
let proj = Projective3::identity()
|
||||
* Translation3::from(update.pos)
|
||||
* update.orientation
|
||||
* Translation3::from(-group.dimensions.cast() / 2.0);
|
||||
group.transform = proj;
|
||||
group.transform_inv = proj.inverse();
|
||||
let updates = [ArrBufUpdate {
|
||||
offset: *i,
|
||||
data: &[*group],
|
||||
}];
|
||||
let size = self.voxel_groups.len();
|
||||
self.voxel_groups
|
||||
.update(device, encoder, belt, size, &updates);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_view(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
belt: &mut wgpu::util::StagingBelt,
|
||||
size: Vector2<u32>,
|
||||
camera: &Camera,
|
||||
) {
|
||||
let transform =
|
||||
Transform3::identity() * Translation3::from(camera.pos) * camera.orientation;
|
||||
let data = View {
|
||||
width: size.x,
|
||||
height: size.y,
|
||||
zoom: camera.scale,
|
||||
transform,
|
||||
};
|
||||
self.view.update(device, encoder, belt, 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);
|
||||
}
|
||||
}
|
||||
284
src/client/render/voxel/ray_oct/shader.wgsl
Normal file
284
src/client/render/voxel/ray_oct/shader.wgsl
Normal file
@@ -0,0 +1,284 @@
|
||||
// Vertex shader
|
||||
|
||||
struct GlobalLight {
|
||||
dir: vec3<f32>,
|
||||
};
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
};
|
||||
|
||||
struct View {
|
||||
transform: mat4x4<f32>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
zoom: f32,
|
||||
};
|
||||
|
||||
struct VoxelGroup {
|
||||
transform: mat4x4<f32>,
|
||||
transform_inv: mat4x4<f32>,
|
||||
dimensions: vec3<u32>,
|
||||
offset: u32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> view: View;
|
||||
@group(0) @binding(1)
|
||||
var<storage, read> voxels: array<u32>;
|
||||
@group(0) @binding(2)
|
||||
var<storage, read> voxel_groups: array<VoxelGroup>;
|
||||
@group(0) @binding(3)
|
||||
var<storage, read> global_lights: array<GlobalLight>;
|
||||
|
||||
@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);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Fragment shader
|
||||
|
||||
@fragment
|
||||
fn fs_main(
|
||||
in: VertexOutput,
|
||||
) -> @location(0) vec4<f32> {
|
||||
// get position of the pixel; eye at origin, pixel on plane z = 1
|
||||
let win_dim = vec2<f32>(f32(view.width), f32(view.height));
|
||||
let aspect = win_dim.y / win_dim.x;
|
||||
let pixel_pos = vec3<f32>(
|
||||
(in.clip_position.xy / win_dim - vec2<f32>(0.5)) * vec2<f32>(2.0, -2.0 * aspect),
|
||||
1.0
|
||||
);
|
||||
|
||||
// move to position in world
|
||||
let pos = view.transform * vec4<f32>(pixel_pos, 1.0);
|
||||
let dir = view.transform * vec4<f32>(normalize(pixel_pos), 0.0);
|
||||
|
||||
var color = trace_full(pos, dir);
|
||||
let light_mult = clamp((-dot(dir.xyz, global_lights[0].dir) - 0.99) * 200.0, 0.0, 1.0);
|
||||
let sky_color = light_mult * vec3<f32>(1.0, 1.0, 1.0);
|
||||
color += vec4<f32>(sky_color * (1.0 - color.a), 1.0 - color.a);
|
||||
color.a = 1.0;
|
||||
return color;
|
||||
}
|
||||
|
||||
const ZERO3F = vec3<f32>(0.0);
|
||||
const ZERO2F = vec2<f32>(0.0);
|
||||
const DEPTH = 16u;
|
||||
const FULL_ALPHA = 0.9999;
|
||||
|
||||
fn trace_full(pos_view: vec4<f32>, dir_view: vec4<f32>) -> vec4<f32> {
|
||||
let gi = 0;
|
||||
let group = voxel_groups[gi];
|
||||
if group.dimensions.x == 0 {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
let dim_f = vec3<f32>(group.dimensions);
|
||||
let dim_i = vec3<i32>(group.dimensions);
|
||||
|
||||
// transform so that group is at 0,0
|
||||
let pos_start = (group.transform_inv * pos_view).xyz;
|
||||
let dir = (group.transform_inv * dir_view).xyz;
|
||||
|
||||
let dir_if = sign(dir);
|
||||
|
||||
|
||||
|
||||
// calculate normals
|
||||
var normals = mat3x3<f32>(
|
||||
(group.transform * vec4<f32>(dir_if.x, 0.0, 0.0, 0.0)).xyz,
|
||||
(group.transform * vec4<f32>(0.0, dir_if.y, 0.0, 0.0)).xyz,
|
||||
(group.transform * vec4<f32>(0.0, 0.0, dir_if.z, 0.0)).xyz,
|
||||
);
|
||||
var next_normal = vec3<f32>(0.0, 0.0, 0.0);
|
||||
|
||||
// find where ray intersects with group
|
||||
let plane_point = (vec3<f32>(1.0) - dir_if) / 2.0 * dim_f;
|
||||
var pos = pos_start;
|
||||
var t = 0.0;
|
||||
if outside3f(pos, ZERO3F, dim_f) {
|
||||
// time of intersection; x = td + p, solve for t
|
||||
let t_i = (plane_point - pos) / dir;
|
||||
// points of intersection
|
||||
let px = pos + t_i.x * dir;
|
||||
let py = pos + t_i.y * dir;
|
||||
let pz = pos + t_i.z * dir;
|
||||
|
||||
// check if point is in bounds
|
||||
let hit = vec3<bool>(
|
||||
inside2f(px.yz, ZERO2F, dim_f.yz),
|
||||
inside2f(py.xz, ZERO2F, dim_f.xz),
|
||||
inside2f(pz.xy, ZERO2F, dim_f.xy),
|
||||
) && (t_i > ZERO3F);
|
||||
if !any(hit) {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
pos = select(select(pz, py, hit.y), px, hit.x);
|
||||
t = select(select(t_i.z, t_i.y, hit.y), t_i.x, hit.x);
|
||||
next_normal = select(select(normals[2], normals[1], hit.y), normals[0], hit.x);
|
||||
}
|
||||
var vox_pos = clamp(vec3<i32>(pos), vec3<i32>(0), dim_i - vec3<i32>(1));
|
||||
|
||||
|
||||
|
||||
let dir_i = vec3<i32>(dir_if);
|
||||
let dir_u = ((dir_i + vec3<i32>(1)) / 2);
|
||||
let dir_bits = u32(dir_u.x * 4 + dir_u.y * 2 + dir_u.z);
|
||||
// time to move 1 unit using dir
|
||||
let inc_t = abs(1.0 / dir);
|
||||
var side_len = 256;
|
||||
// "unsigned" minimum cube coords of current tree
|
||||
var low_corner = vec3<i32>(0);
|
||||
// time of next 1 unit plane hit in each direction
|
||||
var color = vec4<f32>(0.0);
|
||||
var data_start = 1u;
|
||||
var i = 0u;
|
||||
var axis = 0;
|
||||
var hits = 0;
|
||||
for (var safety = 0; safety < 1000; safety += 1) {
|
||||
let node = voxels[group.offset + i];
|
||||
if node >= LEAF_BIT {
|
||||
hits += 1;
|
||||
let vcolor = get_color(node & LEAF_MASK);
|
||||
if vcolor.a > 0.0 {
|
||||
let diffuse = max(dot(global_lights[0].dir, next_normal) + 0.1, 0.0);
|
||||
let ambient = 0.2;
|
||||
let lighting = max(diffuse, ambient);
|
||||
let new_color = min(vcolor.xyz * lighting, vec3<f32>(1.0));
|
||||
color += vec4<f32>(new_color.xyz * vcolor.a, vcolor.a) * (1.0 - color.a);
|
||||
if color.a > .999 {
|
||||
return color;
|
||||
}
|
||||
}
|
||||
|
||||
// move to next face of cube
|
||||
let half_len = f32(side_len) / 2.0;
|
||||
let corner = vec3<f32>(low_corner) + vec3<f32>(half_len) + dir_if * half_len;
|
||||
let next_t = inc_t * abs(corner - pos_start);
|
||||
axis = select(select(2, 1, next_t.y < next_t.z), 0, next_t.x < next_t.y && next_t.x < next_t.z);
|
||||
t = next_t[axis];
|
||||
next_normal = normals[axis];
|
||||
pos = pos_start + t * dir;
|
||||
let old = vox_pos[axis];
|
||||
vox_pos = vec3<i32>(pos) - low_corner;
|
||||
vox_pos[axis] += select(0, dir_i[axis], vox_pos[axis] == 0 || vox_pos[axis] == side_len - 1);
|
||||
// if hits == 1 {
|
||||
// // var axis_c = vec3<f32>(0.0);
|
||||
// // axis_c[axis] = 1.0;
|
||||
// // return vec4<f32>(axis_c, 1.0);
|
||||
// return vec4<f32>(vec3<f32>(vox_pos), 1.0);
|
||||
// }
|
||||
} else if inside3i(vox_pos, vec3<i32>(0), vec3<i32>(side_len - 1)) {
|
||||
let node_pos = data_start + node;
|
||||
side_len /= 2;
|
||||
let vcorner = vox_pos / side_len;
|
||||
vox_pos -= vcorner * side_len;
|
||||
let j = u32(vcorner.x * 4 + vcorner.y * 2 + vcorner.z);
|
||||
i = node_pos + j;
|
||||
data_start = node_pos + 9;
|
||||
|
||||
low_corner += vec3<i32>(dir_to_vec(j)) * i32(side_len);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// idrk what to put here tbh but this prolly works; don't zoom out if max
|
||||
if side_len == 256 {
|
||||
return color;
|
||||
}
|
||||
|
||||
// get parent info and reset "pointers" to parent
|
||||
let parent_info_i = data_start - 1;
|
||||
let parent_info = voxels[group.offset + parent_info_i];
|
||||
let parent_root = parent_info_i - (parent_info >> 3);
|
||||
let parent_loc = parent_info & 7;
|
||||
let loc = 8 - (data_start - 1 - i);
|
||||
// let test = (parent_root + 9 + voxels[group.offset + parent_root + parent_loc] + loc) == i;
|
||||
i = parent_root + parent_loc;
|
||||
data_start = parent_root + 9;
|
||||
|
||||
// adjust corner back to parent
|
||||
let low_corner_adj = vec3<i32>(dir_to_vec(loc)) * i32(side_len);
|
||||
low_corner -= low_corner_adj;
|
||||
|
||||
// update vox pos to be relative to parent
|
||||
vox_pos += low_corner_adj;
|
||||
|
||||
side_len *= 2;
|
||||
// return vec4<f32>(vec3<f32>(dir_to_vec(parent_loc)) * f32(loc) / 8.0, 1.0);
|
||||
// return vec4<f32>(vec3<f32>(f32(test)), 1.0);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
const LEAF_BIT = 1u << 31u;
|
||||
const LEAF_MASK = ~LEAF_BIT;
|
||||
|
||||
// there's no way this is efficient, mod is faster for all I know
|
||||
fn dir_to_vec(bits: u32) -> vec3<u32> {
|
||||
return vec3<u32>(extractBits(bits, 2u, 1u), extractBits(bits, 1u, 1u), extractBits(bits, 0u, 1u));
|
||||
}
|
||||
|
||||
fn get_voxel(offset: u32, pos_: vec3<u32>) -> u32 {
|
||||
var data_start = 1u;
|
||||
var i = 0u;
|
||||
var pos = pos_;
|
||||
var side_len: u32 = 256;
|
||||
var safety = 0;
|
||||
while voxels[offset + i] < LEAF_BIT {
|
||||
let node_pos = data_start + voxels[offset + i];
|
||||
side_len /= 2u;
|
||||
let corner = pos / side_len;
|
||||
pos -= corner * side_len;
|
||||
let j = corner.x * 4 + corner.y * 2 + corner.z;
|
||||
i = node_pos + j;
|
||||
data_start = node_pos + 8;
|
||||
if safety == 10 {
|
||||
return 10u;
|
||||
}
|
||||
safety += 1;
|
||||
}
|
||||
return voxels[offset + i] & LEAF_MASK;
|
||||
}
|
||||
|
||||
fn get_color(id: u32) -> vec4<f32> {
|
||||
switch id {
|
||||
case 0u: {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
case 1u: {
|
||||
return vec4<f32>(0.5, 0.5, 0.5, 1.0);
|
||||
}
|
||||
case 2u: {
|
||||
return vec4<f32>(0.5, 1.0, 0.5, 1.0);
|
||||
}
|
||||
case 3u: {
|
||||
return vec4<f32>(0.5, 0.5, 1.0, 0.5);
|
||||
}
|
||||
default: {
|
||||
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn outside3f(v: vec3<f32>, low: vec3<f32>, high: vec3<f32>) -> bool {
|
||||
return any(v < low) || any(v > high);
|
||||
}
|
||||
|
||||
fn inside2f(v: vec2<f32>, low: vec2<f32>, high: vec2<f32>) -> bool {
|
||||
return all(v >= low) && all(v <= high);
|
||||
}
|
||||
|
||||
fn inside3i(v: vec3<i32>, low: vec3<i32>, high: vec3<i32>) -> bool {
|
||||
return all(v >= low) && all(v <= high);
|
||||
}
|
||||
277
src/client/render/voxel/ray_oct/shader_broken.wgsl
Normal file
277
src/client/render/voxel/ray_oct/shader_broken.wgsl
Normal file
@@ -0,0 +1,277 @@
|
||||
// Vertex shader
|
||||
|
||||
struct GlobalLight {
|
||||
dir: vec3<f32>,
|
||||
};
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
};
|
||||
|
||||
struct View {
|
||||
transform: mat4x4<f32>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
zoom: f32,
|
||||
};
|
||||
|
||||
struct VoxelGroup {
|
||||
transform: mat4x4<f32>,
|
||||
transform_inv: mat4x4<f32>,
|
||||
dimensions: vec3<u32>,
|
||||
offset: u32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> view: View;
|
||||
@group(0) @binding(1)
|
||||
var<storage, read> voxels: array<u32>;
|
||||
@group(0) @binding(2)
|
||||
var<storage, read> voxel_groups: array<VoxelGroup>;
|
||||
@group(0) @binding(3)
|
||||
var<storage, read> global_lights: array<GlobalLight>;
|
||||
|
||||
@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);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Fragment shader
|
||||
|
||||
@fragment
|
||||
fn fs_main(
|
||||
in: VertexOutput,
|
||||
) -> @location(0) vec4<f32> {
|
||||
// get position of the pixel; eye at origin, pixel on plane z = 1
|
||||
let win_dim = vec2<f32>(f32(view.width), f32(view.height));
|
||||
let aspect = win_dim.y / win_dim.x;
|
||||
let pixel_pos = vec3<f32>(
|
||||
(in.clip_position.xy / win_dim - vec2<f32>(0.5)) * vec2<f32>(2.0, -2.0 * aspect),
|
||||
1.0
|
||||
);
|
||||
|
||||
// move to position in world
|
||||
let pos = view.transform * vec4<f32>(pixel_pos, 1.0);
|
||||
let dir = view.transform * vec4<f32>(normalize(pixel_pos), 0.0);
|
||||
|
||||
var color = trace_full(pos, dir);
|
||||
let light_mult = clamp((-dot(dir.xyz, global_lights[0].dir) - 0.99) * 200.0, 0.0, 1.0);
|
||||
let sky_color = light_mult * vec3<f32>(1.0, 1.0, 1.0);
|
||||
color += vec4<f32>(sky_color * (1.0 - color.a), 1.0 - color.a);
|
||||
color.a = 1.0;
|
||||
return color;
|
||||
}
|
||||
|
||||
const ZERO3F = vec3<f32>(0.0);
|
||||
const ZERO2F = vec2<f32>(0.0);
|
||||
const DEPTH = 16u;
|
||||
const FULL_ALPHA = 0.9999;
|
||||
|
||||
fn trace_full(pos_view: vec4<f32>, dir_view: vec4<f32>) -> vec4<f32> {
|
||||
let gi = 0;
|
||||
let group = voxel_groups[gi];
|
||||
if group.dimensions.x == 0 {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
let dim_f = vec3<f32>(group.dimensions);
|
||||
let dim_i = vec3<i32>(group.dimensions);
|
||||
|
||||
// transform so that group is at 0,0
|
||||
let pos_start = (group.transform_inv * pos_view).xyz;
|
||||
let dir = (group.transform_inv * dir_view).xyz;
|
||||
|
||||
let dir_if = sign(dir);
|
||||
|
||||
|
||||
|
||||
// calculate normals
|
||||
var normals = mat3x3<f32>(
|
||||
(group.transform * vec4<f32>(dir_if.x, 0.0, 0.0, 0.0)).xyz,
|
||||
(group.transform * vec4<f32>(0.0, dir_if.y, 0.0, 0.0)).xyz,
|
||||
(group.transform * vec4<f32>(0.0, 0.0, dir_if.z, 0.0)).xyz,
|
||||
);
|
||||
var next_normal = vec3<f32>(0.0, 0.0, 0.0);
|
||||
|
||||
// find where ray intersects with group
|
||||
let plane_point = (vec3<f32>(1.0) - dir_if) / 2.0 * dim_f;
|
||||
var pos = pos_start;
|
||||
var t = 0.0;
|
||||
if outside3f(pos, ZERO3F, dim_f) {
|
||||
// time of intersection; x = td + p, solve for t
|
||||
let t_i = (plane_point - pos) / dir;
|
||||
// points of intersection
|
||||
let px = pos + t_i.x * dir;
|
||||
let py = pos + t_i.y * dir;
|
||||
let pz = pos + t_i.z * dir;
|
||||
|
||||
// check if point is in bounds
|
||||
let hit = vec3<bool>(
|
||||
inside2f(px.yz, ZERO2F, dim_f.yz),
|
||||
inside2f(py.xz, ZERO2F, dim_f.xz),
|
||||
inside2f(pz.xy, ZERO2F, dim_f.xy),
|
||||
) && (t_i > ZERO3F);
|
||||
if !any(hit) {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
pos = select(select(pz, py, hit.y), px, hit.x);
|
||||
t = select(select(t_i.z, t_i.y, hit.y), t_i.x, hit.x);
|
||||
next_normal = select(select(normals[2], normals[1], hit.y), normals[0], hit.x);
|
||||
}
|
||||
var vox_pos = clamp(vec3<i32>(pos), vec3<i32>(0), dim_i - vec3<i32>(1));
|
||||
|
||||
|
||||
|
||||
let dir_i = vec3<i32>(dir_if);
|
||||
let dir_u = ((dir_i + vec3<i32>(1)) / 2);
|
||||
let dir_bits = u32(dir_u.x * 4 + dir_u.y * 2 + dir_u.z);
|
||||
// time to move 1 unit using dir
|
||||
let inc_t = abs(1.0 / dir);
|
||||
var side_len = 256;
|
||||
// "unsigned" minimum cube coords of current tree
|
||||
var low_corner = vec3<i32>(0);
|
||||
// time of next 1 unit plane hit in each direction
|
||||
var color = vec4<f32>(0.0);
|
||||
var data_start = 1u;
|
||||
var i = 0u;
|
||||
var axis = 0;
|
||||
for (var safety = 0; safety < 100; safety += 1) {
|
||||
let node = voxels[group.offset + i];
|
||||
if node >= LEAF_BIT {
|
||||
let vcolor = get_color(node & LEAF_MASK);
|
||||
if vcolor.a > 0.0 {
|
||||
let diffuse = max(dot(global_lights[0].dir, next_normal) + 0.1, 0.0);
|
||||
let ambient = 0.2;
|
||||
let lighting = max(diffuse, ambient);
|
||||
let new_color = min(vcolor.xyz * lighting, vec3<f32>(1.0));
|
||||
color += vec4<f32>(new_color.xyz * vcolor.a, vcolor.a) * (1.0 - color.a);
|
||||
if color.a > .999 {
|
||||
return color;
|
||||
}
|
||||
}
|
||||
|
||||
// move to next face of cube
|
||||
let half_len = f32(side_len) / 2.0;
|
||||
let corner = vec3<f32>(low_corner) + vec3<f32>(half_len) + dir_if * half_len;
|
||||
let next_t = inc_t * abs(corner - pos_start);
|
||||
axis = select(select(2, 1, next_t.y < next_t.z), 0, next_t.x < next_t.y && next_t.x < next_t.z);
|
||||
t = next_t[axis];
|
||||
next_normal = normals[axis];
|
||||
pos = pos_start + t * dir;
|
||||
let old = vox_pos[axis];
|
||||
vox_pos = vec3<i32>(pos) - low_corner;
|
||||
vox_pos[axis] = old + side_len * dir_i[axis];
|
||||
// var axis_c = vec3<f32>(0.0);
|
||||
// axis_c[axis] = 1.0;
|
||||
// return vec4<f32>(axis_c, 1.0);
|
||||
} else if inside3i(vox_pos, vec3<i32>(0), vec3<i32>(side_len)) {
|
||||
let node_pos = data_start + node;
|
||||
side_len /= 2;
|
||||
let vcorner = vox_pos / side_len;
|
||||
vox_pos -= vcorner * side_len;
|
||||
let j = u32(vcorner.x * 4 + vcorner.y * 2 + vcorner.z);
|
||||
i = node_pos + j;
|
||||
data_start = node_pos + 9;
|
||||
|
||||
low_corner += vec3<i32>(dir_to_vec(j)) * i32(side_len);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// get parent info and reset "pointers" to parent
|
||||
let parent_info_i = data_start - 1;
|
||||
if parent_info_i == 0 {
|
||||
return color;
|
||||
}
|
||||
let parent_info = voxels[group.offset + parent_info_i];
|
||||
let parent_root = parent_info_i - (parent_info >> 3);
|
||||
let parent_loc = parent_info & 7;
|
||||
let loc = 8 - (data_start - 1 - i);
|
||||
// let test = (parent_root + 9 + voxels[group.offset + parent_root + parent_loc] + loc) == i;
|
||||
i = parent_root + parent_loc;
|
||||
data_start = parent_root + 9;
|
||||
|
||||
// adjust corner back to parent
|
||||
let low_corner_adj = vec3<i32>(dir_to_vec(loc)) * i32(side_len);
|
||||
low_corner -= low_corner_adj;
|
||||
|
||||
// update vox pos to be relative to parent
|
||||
vox_pos += low_corner_adj;
|
||||
|
||||
side_len *= 2;
|
||||
// return vec4<f32>(vec3<f32>(dir_to_vec(parent_loc)) * f32(loc) / 8.0, 1.0);
|
||||
// return vec4<f32>(vec3<f32>(f32(test)), 1.0);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
const LEAF_BIT = 1u << 31u;
|
||||
const LEAF_MASK = ~LEAF_BIT;
|
||||
|
||||
// there's no way this is efficient, mod is faster for all I know
|
||||
fn dir_to_vec(bits: u32) -> vec3<u32> {
|
||||
return vec3<u32>(extractBits(bits, 2u, 1u), extractBits(bits, 1u, 1u), extractBits(bits, 0u, 1u));
|
||||
}
|
||||
|
||||
fn get_voxel(offset: u32, pos_: vec3<u32>) -> u32 {
|
||||
var data_start = 1u;
|
||||
var i = 0u;
|
||||
var pos = pos_;
|
||||
var side_len: u32 = 256;
|
||||
var safety = 0;
|
||||
while voxels[offset + i] < LEAF_BIT {
|
||||
let node_pos = data_start + voxels[offset + i];
|
||||
side_len /= 2u;
|
||||
let corner = pos / side_len;
|
||||
pos -= corner * side_len;
|
||||
let j = corner.x * 4 + corner.y * 2 + corner.z;
|
||||
i = node_pos + j;
|
||||
data_start = node_pos + 8;
|
||||
if safety == 10 {
|
||||
return 10u;
|
||||
}
|
||||
safety += 1;
|
||||
}
|
||||
return voxels[offset + i] & LEAF_MASK;
|
||||
}
|
||||
|
||||
fn get_color(id: u32) -> vec4<f32> {
|
||||
switch id {
|
||||
case 0u: {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
case 1u: {
|
||||
return vec4<f32>(0.5, 0.5, 0.5, 1.0);
|
||||
}
|
||||
case 2u: {
|
||||
return vec4<f32>(0.5, 1.0, 0.5, 1.0);
|
||||
}
|
||||
case 3u: {
|
||||
return vec4<f32>(0.5, 0.5, 1.0, 0.5);
|
||||
}
|
||||
default: {
|
||||
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn outside3f(v: vec3<f32>, low: vec3<f32>, high: vec3<f32>) -> bool {
|
||||
return any(v < low) || any(v > high);
|
||||
}
|
||||
|
||||
fn inside2f(v: vec2<f32>, low: vec2<f32>, high: vec2<f32>) -> bool {
|
||||
return all(v >= low) && all(v <= high);
|
||||
}
|
||||
|
||||
fn inside3i(v: vec3<i32>, low: vec3<i32>, high: vec3<i32>) -> bool {
|
||||
return all(v >= low) && all(v <= high);
|
||||
}
|
||||
23
src/client/render/voxel/ray_oct/view.rs
Normal file
23
src/client/render/voxel/ray_oct/view.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use nalgebra::Transform3;
|
||||
|
||||
#[repr(C, align(16))]
|
||||
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
|
||||
pub struct View {
|
||||
pub transform: Transform3<f32>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub zoom: f32,
|
||||
}
|
||||
|
||||
unsafe impl bytemuck::Pod for View {}
|
||||
|
||||
impl Default for View {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: 1,
|
||||
height: 1,
|
||||
zoom: 1.0,
|
||||
transform: Transform3::identity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,14 +57,15 @@ pub fn update_transform(
|
||||
}
|
||||
|
||||
pub fn add_chunk(
|
||||
query: Query<(Entity, &ChunkPos, &ChunkMesh), Or<(Added<ChunkPos>, Added<ChunkMesh>)>>,
|
||||
query: Query<(Entity, &ChunkPos, &ChunkMesh, &ChunkData), Or<(Added<ChunkPos>, Added<ChunkMesh>, Added<ChunkData>)>>,
|
||||
mut renderer: ResMut<RenderCommands>,
|
||||
) {
|
||||
for (id, pos, mesh) in query.iter() {
|
||||
for (id, pos, mesh, data) in query.iter() {
|
||||
renderer.push(RenderCommand::AddChunk(AddChunk {
|
||||
id,
|
||||
pos: *pos,
|
||||
mesh: mesh.clone()
|
||||
mesh: mesh.clone(),
|
||||
tree: data.deref().clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user