Added primitive renderer, world with tree hierarchy supporting lights and objects with GLTF loading. Builds and runs with broken rendering and tree.

This commit is contained in:
paladin 2026-09-03 12:08:00 +01:00
parent f1d4534063
commit efe98454d9
17 changed files with 1968 additions and 1221 deletions

312
src/app.rs Normal file
View file

@ -0,0 +1,312 @@
use std::collections::HashMap;
// Credit of most code to https://sotrh.github.io/learn-wgpu/ since I'm not familiar with wgpu
use std::sync::Arc;
use glam::{Vec2, Affine3A, Vec3, Vec4, Mat4, EulerRot, Quat};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use winit::dpi::PhysicalPosition;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::EventLoopExtWebSys;
use winit::{
application::ApplicationHandler,
event::*,
event_loop::{ActiveEventLoop, EventLoop},
keyboard::{KeyCode, PhysicalKey},
window::Window,
};
use crate::render;
use crate::render::{Renderer, SimpleTexture};
use crate::world::{SimpleObject, World};
struct Controller {
buttons: HashMap<MouseButton,bool>,
keys: HashMap<KeyCode,bool>,
mouse: Vec2,
}
impl Controller {
fn new() -> Controller {
Controller {
buttons: Default::default(),
keys: HashMap::new(),
mouse: Vec2::new(0.0,0.0),
}
}
}
pub struct AppState {
world: World,
controller: Controller,
window: Arc<Window>,
clients: Vec<SimpleObject>,
}
const BLOCKS: i32 = 50;
impl AppState {
// We don't need this to be async right now,
// but we will in the next tutorial
pub async fn new(window: Arc<Window>) -> Result<AppState,Box<dyn std::error::Error>> {
let size = window.inner_size();
let mut world = World::new();
world.add_renderer(Renderer::new(&window).await?);
let mut clients = Vec::new();
{
let file = world.renderer.as_mut().unwrap().load_from_gltf( include_bytes!("assets/cube.glb"));
let block = file.first_object().unwrap();
//let color = &renderer.load_texture_from_bytes(include_bytes!("assets/plank/color.png"));
//let normal = &renderer.load_texture_from_bytes(include_bytes!("assets/plank/normal.png"));
//let roughness = &renderer.load_texture_from_bytes(include_bytes!("assets/plank/roughness.png"));
//let mat = renderer.new_material(color,normal,roughness);
for x in -BLOCKS..BLOCKS {
for y in -BLOCKS..BLOCKS {
let block = block.hard_clone();
world.add_object(block.clone());
{
let mut model = block.0.borrow_mut();
model.model.as_mut().unwrap().instance.transform = Mat4::from_translation(Vec3::new(-x as f32 * 3.0,0.0,-y as f32 * 3.0))
* Mat4::from_rotation_z((x * y) as f32 / 1.23);
model.model.as_mut().unwrap().instance.color = Vec4::new(0.3,(x + BLOCKS) as f32 / BLOCKS as f32,(y + BLOCKS) as f32 / BLOCKS as f32,1.0);
}
clients.push(block)
}
}
}
Ok(Self {
world,
clients,
controller: Controller::new(),
window,
})
}
pub fn bounds(&self) -> (u32,u32) {
let size = self.window.inner_size();
(size.width,size.height)
}
pub fn resize(&mut self, width: u32, height: u32) {
if width > 0 && height > 0 {
let max = 2048;
self.world.renderer.as_mut().unwrap().resize(width,height);
}
}
fn update(&mut self) {
// ...
}
fn handle_key(&mut self, event_loop: &ActiveEventLoop, code: KeyCode, is_pressed: bool) {
match (code, is_pressed) {
(KeyCode::Escape, true) => event_loop.exit(),
(KeyCode::Space, true) => {},
(KeyCode::KeyR, true) => {
self.world.renderer.as_mut().unwrap().eye.frame = Affine3A::IDENTITY
}
_ => {}
}
self.controller.keys.insert(code, is_pressed);
}
fn handle_mouse_moved(&mut self, position: PhysicalPosition<f64>) {
if let Some(true) = self.controller.buttons.get(&MouseButton::Right) {
self.world.renderer.as_mut().unwrap().eye.rotate(position.x as f32 - self.controller.mouse.x, position.y as f32 - self.controller.mouse.y);
}
self.controller.mouse = Vec2::new(position.x as f32, position.y as f32);
}
fn handle_mouse_button(&mut self, button: MouseButton, state: ElementState ) {
self.controller.buttons.insert(button,state.is_pressed());
}
}
pub struct App {
#[cfg(target_arch = "wasm32")]
proxy: Option<winit::event_loop::EventLoopProxy<AppState>>,
state: Option<AppState>,
}
impl App {
pub fn new(#[cfg(target_arch = "wasm32")] event_loop: &EventLoop<AppState>) -> Self {
#[cfg(target_arch = "wasm32")]
let proxy = Some(event_loop.create_proxy());
Self {
state: None,
#[cfg(target_arch = "wasm32")]
proxy,
}
}
}
impl ApplicationHandler<AppState> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes();
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
const CANVAS_ID: &str = "canvas";
let window = wgpu::web_sys::window().unwrap_throw();
let document = window.document().unwrap_throw();
let canvas = document.get_element_by_id(CANVAS_ID).unwrap_throw();
let html_canvas_element = canvas.unchecked_into();
window_attributes = window_attributes.with_canvas(Some(html_canvas_element));
}
let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
#[cfg(not(target_arch = "wasm32"))]
{
// If we are not on web we can use pollster to
// await the window creation
self.state = Some(pollster::block_on(AppState::new(window)).unwrap());
}
#[cfg(target_arch = "wasm32")]
{
// Run the future asynchronously and use the
// proxy to send the results to the event loop
if let Some(proxy) = self.proxy.take() {
wasm_bindgen_futures::spawn_local(async move {
assert!(
proxy
.send_event(
AppState::new(window)
.await
.expect("Unable to create canvas!!!")
)
.is_ok()
)
});
}
}
}
#[allow(unused_mut)]
fn user_event(&mut self, _event_loop: &ActiveEventLoop, mut event: AppState) {
// This is where proxy.send_event() ends up
#[cfg(target_arch = "wasm32")]
{
event.window.request_redraw();
event.resize(
event.window.inner_size().width,
event.window.inner_size().height,
);
}
self.state = Some(event);
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let state = match &mut self.state {
Some(canvas) => canvas,
None => return,
};
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => state.resize(size.width, size.height),
WindowEvent::RedrawRequested => {
state.update();
let mut movement = Vec3::new(0.0,0.0,0.0);
let pressed = |keycode: KeyCode| {
if let Some(true) = state.controller.keys.get(&keycode) {
true
} else {
false
}
};
if pressed(KeyCode::KeyA) {
movement.x -= 1.0;
}
if pressed(KeyCode::KeyD) {
movement.x += 1.0;
}
if pressed(KeyCode::KeyW) {
movement.z += 1.0;
}
if pressed(KeyCode::KeyS) {
movement.z -= 1.0;
}
if pressed(KeyCode::KeyE) {
movement.y += 1.0;
}
if pressed(KeyCode::KeyQ) {
movement.y -= 1.0;
}
state.world.renderer.as_mut().unwrap().eye.control(movement * 0.1);
match state.world.renderer.as_mut().unwrap().render(&state.window) {
Ok(_) => {}
Err(e) => {
// Log the error and exit gracefully
log::error!("{e}");
event_loop.exit();
}
}
for object in state.clients.iter() {
object.0.borrow_mut().model.as_mut().unwrap().instance.transform *= Mat4::from_rotation_translation(
Quat::from_euler(EulerRot::XYZ,0.001,-0.001,0.001),
Vec3::new(0.0,0.0,0.0)
);
}
}
WindowEvent::MouseInput { button, state: element, .. } => state.handle_mouse_button(button,element),
WindowEvent::CursorMoved { position: pos, .. } => state.handle_mouse_moved(pos),
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
state: key_state,
..
},
..
} => state.handle_key(event_loop, code, key_state.is_pressed()),
_ => {}
}
}
}
pub fn run() -> anyhow::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
}
#[cfg(target_arch = "wasm32")]
{
console_log::init_with_level(log::Level::Info).unwrap_throw();
}
let event_loop = EventLoop::with_user_event().build()?;
#[cfg(not(target_arch = "wasm32"))]
{
let mut app = App::new();
event_loop.run_app(&mut app)?;
}
#[cfg(target_arch = "wasm32")]
{
let app = App::new(&event_loop);
event_loop.spawn_app(app);
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
run().unwrap_throw();
Ok(())
}

View file

@ -0,0 +1,97 @@
struct Environment {
ambient: vec4<f32>,
light: vec4<f32>,
dir: vec4<f32>,
}
struct View {
view: mat4x4<f32>,
frame: mat4x4<f32>,
}
// Vertex shader
@group(0) @binding(0)
var<uniform> view: View;
@group(0) @binding(1)
var<uniform> environment: Environment;
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) tex_coords: vec2<f32>,
}
struct InstanceInput {
@location(4) model_matrix_0: vec4<f32>,
@location(5) model_matrix_1: vec4<f32>,
@location(6) model_matrix_2: vec4<f32>,
@location(7) model_matrix_3: vec4<f32>,
@location(8) model_color: vec4<f32>,
}
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) tex_coords: vec2<f32>,
@location(1) color: vec4<f32>,
@location(2) world_normal: vec3<f32>,
@location(3) world_position: vec3<f32>,
}
@vertex
fn vs_main(
model: VertexInput,
instance: InstanceInput,
) -> VertexOutput {
var out: VertexOutput;
let model_matrix = mat4x4<f32>(
instance.model_matrix_0,
instance.model_matrix_1,
instance.model_matrix_2,
instance.model_matrix_3,
);
let model_rot_matrix = mat3x3<f32>(
instance.model_matrix_0.xyz,
instance.model_matrix_1.xyz,
instance.model_matrix_2.xyz,
);
out.tex_coords = model.tex_coords;
out.color = instance.model_color;
out.world_normal = model_rot_matrix * model.normal;
var world_position: vec4<f32> = model_matrix * vec4<f32>(model.position, 1.0);
out.world_position = world_position.xyz;
out.clip_position = view.view * world_position;
return out;
}
// Fragment shader
@group(1) @binding(0)
var s_diffuse: sampler;
@group(1) @binding(1)
var t_diffuse: texture_2d<f32>;
@group(1) @binding(2)
var t_normal: texture_2d<f32>;
@group(1) @binding(3)
var t_rough: texture_2d<f32>;
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let object_color: vec4<f32> = textureSample(t_diffuse, s_diffuse, in.tex_coords);
let object_normal: vec4<f32> = textureSample(t_normal, s_diffuse, in.tex_coords);
let tangent_normal = object_normal.xyz * 2.0 - 1.0;
let light_dir = normalize(environment.dir.xyz);
let view_dir = normalize(view.frame[3].xyz - in.world_position);
let half_dir = normalize(view_dir + light_dir);
let diffuse_strength = max(dot(tangent_normal, light_dir), 0.0);
let diffuse_color = environment.light.xyz * diffuse_strength;
let specular_strength = pow(max(dot(tangent_normal, half_dir), 0.0), 32.0);
let specular_color = specular_strength * environment.light.xyz;
let result = (environment.ambient.xyz + diffuse_color.xyz + specular_color.xyz) * object_color.xyz;
return vec4<f32>(result.xyz,object_color.a);
}

BIN
src/assets/plank/color.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

BIN
src/assets/plank/normal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 499 KiB

View file

@ -1,35 +0,0 @@
// Vertex shader
@group(1) @binding(0)
var<uniform> view: mat4x4<f32>;
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) tex_coords: vec2<f32>,
}
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) tex_coords: vec2<f32>,
}
@vertex
fn vs_main(
model: VertexInput,
) -> VertexOutput {
var out: VertexOutput;
out.tex_coords = model.tex_coords;
out.clip_position = view * vec4<f32>(model.position, 1.0);
return out;
}
// Fragment shader
@group(0) @binding(0)
var t_diffuse: texture_2d<f32>;
@group(0) @binding(1)
var s_diffuse: sampler;
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return textureSample(t_diffuse, s_diffuse, in.tex_coords);
}

View file

@ -1,21 +0,0 @@
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) color: vec4<f32>
};
@vertex
fn vs_main(
@builtin(vertex_index) in_vertex_index: u32,
) -> VertexOutput {
var out: VertexOutput;
let x = f32(1 - i32(in_vertex_index)) * 0.5;
let y = f32(i32(in_vertex_index & 1u) * 2 - 1) * 0.5;
out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
out.color = vec4<f32>(0.3,x,y,1.0);
return out;
}
@fragment
fn fs_main(@location(0) col: vec4<f32>) -> @location(0) vec4<f32> {
return col;
}

View file

@ -1,807 +0,0 @@
use std::collections::HashMap;
// Credit of most code to https://sotrh.github.io/learn-wgpu/ since I'm not familiar with wgpu
use std::sync::Arc;
use glam::camera::lh::proj::directx::perspective;
use wgpu::util::DeviceExt;
use glam::prelude::*;
struct Controller {
buttons: HashMap<MouseButton,bool>,
keys: HashMap<KeyCode,bool>,
mouse: Vec2,
}
impl Controller {
fn new() -> Controller {
Controller {
buttons: Default::default(),
keys: HashMap::new(),
mouse: Vec2::new(0.0,0.0),
}
}
}
struct Camera {
frame: Affine3A,
aspect_ratio: f32,
z_near: f32,
z_far: f32,
fov_y: f32,
}
impl Camera {
fn view(&self) -> Mat4 {
let projection = perspective(self.fov_y, self.aspect_ratio, self.z_near, self.z_far);
projection * self.frame.inverse()
}
fn new(window: &Arc<Window>) -> Camera {
Camera {
aspect_ratio: window.inner_size().width as f32 / window.inner_size().height as f32,
frame: Affine3A::IDENTITY,
fov_y: 90.0,
z_near: 0.1,
z_far: 1000.0
}
}
fn resize(&mut self, window: &Arc<Window>) {
self.aspect_ratio = window.inner_size().width as f32 / window.inner_size().height as f32
}
fn control(&mut self, delta: Vec3) {
self.frame = self.frame * Affine3A::from_translation(delta);
}
fn rotate(&mut self, yaw: f32, pitch: f32) {
let (mut y,mut x,z) = self.frame.matrix3.to_euler(EulerRot::YXZ);
x = (x + pitch * 0.005).clamp(-1.4,1.4);
y = y + yaw * 0.005;
self.frame.matrix3 = Mat3A::from_euler(EulerRot::YXZ,y,x,z);
}
}
const VERTICES: &[Vertex] = &[
// Changed
Vertex { position: [-0.5,-0.5,-0.5], tex_coords: [0,0]}
];
const INDICES: &[u16] = &[
0, 1, 4,
1, 2, 4,
2, 3, 4,
];
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use winit::dpi::PhysicalPosition;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::EventLoopExtWebSys;
use winit::{
application::ApplicationHandler,
event::*,
event_loop::{ActiveEventLoop, EventLoop},
keyboard::{KeyCode, PhysicalKey},
window::Window,
};
type Kt<K,V> = HashMap<K,Vec<V>>;
struct Renderer {
surface: (wgpu::Surface<'static>,bool),
config: wgpu::SurfaceConfiguration,
device: wgpu::Device,
queue: wgpu::Queue,
camera: Camera,
clear_color: wgpu::Color,
}
struct UniformPlan {
bind_group: wgpu::BindGroup,
buffer: wgpu::Buffer,
}
struct TexturePlan {
bind_group: wgpu::BindGroup,
texture: wgpu::Texture,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct SimpleVertex {
pos: [f32; 3],
uv: [f32; 2],
norm: [f32; 3],
}
impl SimpleVertex {
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<SimpleVertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 5]>() as wgpu::BufferAddress,
shader_location: 2,
format: wgpu::VertexFormat::Float32x3,
}
]
}
}
}
struct SimpleMesh {
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
indices_count: u32,
}
struct SimpleMaterial {
albedo: TexturePlan,
normal: Option<TexturePlan>,
specular: Option<TexturePlan>,
}
struct SimpleModel {
affine: Affine3A,
material: mars::gc::Gc<SimpleMaterial>,
}
struct SimpleRenderPlan {
pipeline: wgpu::RenderPipeline,
// todo: clients: Kt<SimpleMesh,Kt<SimpleMaterial,Vec<Affine3A>>>
clients: Vec<SimpleModel>
}
struct FluidRigidBody {
}
pub struct State {
renderer: Renderer,
controller: Controller,
window: Arc<Window>,
diffuse_bind_group: wgpu::BindGroup,
sky: wgpu::Color,
}
impl State {
// We don't need this to be async right now,
// but we will in the next tutorial
pub async fn new(window: Arc<Window>) -> anyhow::Result<Self> {
let size = window.inner_size();
// The instance is a handle to our GPU
// BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
#[cfg(not(target_arch = "wasm32"))]
backends: wgpu::Backends::PRIMARY,
#[cfg(target_arch = "wasm32")]
backends: wgpu::Backends::GL,
flags: Default::default(),
memory_budget_thresholds: Default::default(),
backend_options: Default::default(),
display: None,
});
let surface = instance.create_surface(window.clone())?;
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
experimental_features: wgpu::ExperimentalFeatures::disabled(),
// WebGL doesn't support all of wgpu's features, so if
// we're building for the web we'll have to disable some.
required_limits: if cfg!(target_arch = "wasm32") {
wgpu::Limits::downlevel_webgl2_defaults()
} else {
wgpu::Limits::default()
},
memory_hints: Default::default(),
trace: wgpu::Trace::Off,
})
.await?;
let surface_caps = surface.get_capabilities(&adapter);
// Shader code in this tutorial assumes an sRGB surface texture. Using a different
// one will result in all the colors coming out darker. If you want to support non
// sRGB surfaces, you'll need to account for that when drawing to the frame.
let surface_format = surface_caps
.formats
.iter()
.find(|f| f.is_srgb())
.copied()
.unwrap_or(surface_caps.formats[0]);
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,
};
let diffuse_bytes = include_bytes!("assets/test.png");
let diffuse_image = image::load_from_memory(diffuse_bytes)?;
let diffuse_rgba = diffuse_image.to_rgba8();
use image::GenericImageView;
let dimensions = diffuse_image.dimensions();
println!("{:?}",dimensions);
let texture_size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
// All textures are stored as 3D, we represent our 2D texture
// by setting depth to 1.
depth_or_array_layers: 1,
};
let diffuse_texture = device.create_texture(
&wgpu::TextureDescriptor {
size: texture_size,
mip_level_count: 1, // We'll talk about this a little later
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
// Most images are stored using sRGB, so we need to reflect that here.
format: wgpu::TextureFormat::Rgba8UnormSrgb,
// TEXTURE_BINDING tells wgpu that we want to use this texture in shaders
// COPY_DST means that we want to copy data to this texture
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some("diffuse_texture"),
// This is the same as with the SurfaceConfig. It
// specifies what texture formats can be used to
// create TextureViews for this texture. The base
// texture format (Rgba8UnormSrgb in this case) is
// always supported. Note that using a different
// texture format is not supported on the WebGL2
// backend.
view_formats: &[],
}
);
queue.write_texture(
// Tells wgpu where to copy the pixel data
wgpu::TexelCopyTextureInfo {
texture: &diffuse_texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
// The actual pixel data
&diffuse_rgba,
// The layout of the texture
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * dimensions.0),
rows_per_image: Some(dimensions.1),
},
texture_size,
);
let diffuse_texture_view = diffuse_texture.create_view(&wgpu::TextureViewDescriptor::default());
let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
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: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
// This should match the filterable field of the
// corresponding Texture entry above.
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
label: Some("texture_bind_group_layout"),
});
let diffuse_bind_group = device.create_bind_group(
&wgpu::BindGroupDescriptor {
layout: &texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
}
],
label: Some("diffuse_bind_group"),
}
);
let camera = Camera::new(&window);
let camera_buffer = device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Camera Buffer"),
contents: bytemuck::cast_slice(&[camera.view()]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
}
);
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
],
label: Some("camera_bind_group_layout"),
});
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &camera_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: camera_buffer.as_entire_binding(),
}
],
label: Some("camera_bind_group"),
});
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(INDICES),
usage: wgpu::BufferUsages::INDEX,
}
);
let num_indices = INDICES.len() as u32;
let shader1 = device.create_shader_module(wgpu::include_wgsl!("assets/shader.wgsl"));
let render_pipeline_layout1 =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[
Some(&texture_bind_group_layout),
Some(&camera_bind_group_layout),
],
immediate_size: 0,
});
/*let water_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Water Pipeline"),
layout: Some(&water_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader1,
entry_point: Some("vs_main"),
buffers: &[
],
compilation_options: wgpu::PipelineCompilationOptions::default();
}
});*/
let render_pipeline1 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout1),
vertex: wgpu::VertexState {
module: &shader1,
entry_point: Some("vs_main"),
buffers: &[
Vertex::desc(),
],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
// 3.
module: &shader1,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
// 4.
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList, // 1.
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw, // 2.
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLIP_CONTROL
unclipped_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},
depth_stencil: None, // 1.
multisample: wgpu::MultisampleState {
count: 1, // 2.
mask: !0, // 3.
alpha_to_coverage_enabled: false, // 4.
},
multiview_mask: None, // 5.
cache: None, // 6.
});
Ok(Self {
surface,
camera_buffer,
camera_bind_group,
diffuse_bind_group,
index_buffer,
vertex_buffer,
controller: Controller::new(),
device,
queue,
config,
is_surface_configured: false,
window,
num_indices,
render_pipeline: render_pipeline1,
sky: wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
},
camera,
})
}
pub fn resize(&mut self, width: u32, height: u32) {
if width > 0 && height > 0 {
let max = 2048;
self.config.width = width.min(max);
self.config.height = height.min(max);
self.surface.configure(&self.device, &self.config);
self.camera.resize(&self.window);
self.is_surface_configured = true;
}
}
fn update(&mut self) {
// ...
}
fn render(&mut self) -> anyhow::Result<()> {
self.window.request_redraw();
// We can't render unless the surface is configured
if !self.is_surface_configured {
return Ok(());
}
let output = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(surface_texture) => surface_texture,
wgpu::CurrentSurfaceTexture::Suboptimal(surface_texture) => {
self.surface.configure(&self.device, &self.config);
surface_texture
}
wgpu::CurrentSurfaceTexture::Timeout
| wgpu::CurrentSurfaceTexture::Occluded
| wgpu::CurrentSurfaceTexture::Validation => {
// Skip this frame
return Ok(());
}
wgpu::CurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.device, &self.config);
return Ok(());
}
wgpu::CurrentSurfaceTexture::Lost => {
// You could recreate the devices and all resources
// created with it here, but we'll just bail
anyhow::bail!("Lost device");
}
};
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(self.sky),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
multiview_mask: None,
});
let mut movement = Vec3::new(0.0,0.0,0.0);
let pressed = |keycode: KeyCode| {
if let Some(true) = self.controller.keys.get(&keycode) {
true
} else {
false
}
};
if pressed(KeyCode::KeyA) {
movement.x -= 1.0;
}
if pressed(KeyCode::KeyD) {
movement.x += 1.0;
}
if pressed(KeyCode::KeyW) {
movement.z += 1.0;
}
if pressed(KeyCode::KeyS) {
movement.z -= 1.0;
}
if pressed(KeyCode::KeyE) {
movement.y += 1.0;
}
if pressed(KeyCode::KeyQ) {
movement.y -= 1.0;
}
println!("{:?} {:?} {:?}",movement,self.camera.frame.translation,self.camera.frame.matrix3.to_euler(EulerRot::YXZ));
self.camera.control(movement * 0.1);
self.queue.write_buffer(&self.camera_buffer,0,bytemuck::cast_slice(&[self.camera.view()]));
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(1, &self.camera_bind_group, &[]);
render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
}
// submit will accept anything that implements IntoIter
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}
fn handle_key(&mut self, event_loop: &ActiveEventLoop, code: KeyCode, is_pressed: bool) {
match (code, is_pressed) {
(KeyCode::Escape, true) => event_loop.exit(),
(KeyCode::Space, true) => {},
(KeyCode::KeyR, true) => {
self.camera.frame = Affine3A::IDENTITY
}
_ => {}
}
self.controller.keys.insert(code, is_pressed);
}
fn handle_mouse_moved(&mut self, position: PhysicalPosition<f64>) {
self.sky = wgpu::Color {
r: 0.3,
g: position.x / 1000.0,
b: position.y / 1000.0,
a: 1.0,
};
if let Some(true) = self.controller.buttons.get(&MouseButton::Right) {
self.camera.rotate(position.x as f32 - self.controller.mouse.x, position.y as f32 - self.controller.mouse.y);
}
self.controller.mouse = Vec2::new(position.x as f32, position.y as f32);
}
fn handle_mouse_button(&mut self, button: MouseButton, state: ElementState ) {
self.controller.buttons.insert(button,state.is_pressed());
}
}
pub struct App {
#[cfg(target_arch = "wasm32")]
proxy: Option<winit::event_loop::EventLoopProxy<State>>,
state: Option<State>,
}
impl App {
pub fn new(#[cfg(target_arch = "wasm32")] event_loop: &EventLoop<State>) -> Self {
#[cfg(target_arch = "wasm32")]
let proxy = Some(event_loop.create_proxy());
Self {
state: None,
#[cfg(target_arch = "wasm32")]
proxy,
}
}
}
impl ApplicationHandler<State> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes();
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
use winit::platform::web::WindowAttributesExtWebSys;
const CANVAS_ID: &str = "canvas";
let window = wgpu::web_sys::window().unwrap_throw();
let document = window.document().unwrap_throw();
let canvas = document.get_element_by_id(CANVAS_ID).unwrap_throw();
let html_canvas_element = canvas.unchecked_into();
window_attributes = window_attributes.with_canvas(Some(html_canvas_element));
}
let window = Arc::new(event_loop.create_window(window_attributes).unwrap());
#[cfg(not(target_arch = "wasm32"))]
{
// If we are not on web we can use pollster to
// await the window creation
self.state = Some(pollster::block_on(State::new(window)).unwrap());
}
#[cfg(target_arch = "wasm32")]
{
// Run the future asynchronously and use the
// proxy to send the results to the event loop
if let Some(proxy) = self.proxy.take() {
wasm_bindgen_futures::spawn_local(async move {
assert!(
proxy
.send_event(
State::new(window)
.await
.expect("Unable to create canvas!!!")
)
.is_ok()
)
});
}
}
}
#[allow(unused_mut)]
fn user_event(&mut self, _event_loop: &ActiveEventLoop, mut event: State) {
// This is where proxy.send_event() ends up
#[cfg(target_arch = "wasm32")]
{
event.window.request_redraw();
event.resize(
event.window.inner_size().width,
event.window.inner_size().height,
);
}
self.state = Some(event);
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let state = match &mut self.state {
Some(canvas) => canvas,
None => return,
};
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => state.resize(size.width, size.height),
WindowEvent::RedrawRequested => {
state.update();
match state.render() {
Ok(_) => {}
Err(e) => {
// Log the error and exit gracefully
log::error!("{e}");
event_loop.exit();
}
}
}
WindowEvent::MouseInput { button, state: element, .. } => state.handle_mouse_button(button,element),
WindowEvent::CursorMoved { position: pos, .. } => state.handle_mouse_moved(pos),
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
state: key_state,
..
},
..
} => state.handle_key(event_loop, code, key_state.is_pressed()),
_ => {}
}
}
}
pub fn run() -> anyhow::Result<()> {
#[cfg(not(target_arch = "wasm32"))]
{
env_logger::init();
}
#[cfg(target_arch = "wasm32")]
{
console_log::init_with_level(log::Level::Info).unwrap_throw();
}
let event_loop = EventLoop::with_user_event().build()?;
#[cfg(not(target_arch = "wasm32"))]
{
let mut app = App::new();
event_loop.run_app(&mut app)?;
}
#[cfg(target_arch = "wasm32")]
{
let app = App::new(&event_loop);
event_loop.spawn_app(app);
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
run().unwrap_throw();
Ok(())
}

View file

@ -1,2 +1,5 @@
#![recursion_limit = "256"]
pub mod engine;
pub mod app;
pub mod render;
pub mod web;
pub mod world;

View file

@ -1,7 +1,6 @@
#![recursion_limit = "256"]
use game::*;
fn main() {
engine::run().unwrap();
app::run().unwrap();
}

View file

@ -1,353 +0,0 @@
// Macro for expanding syntax form into a struct
macro_rules! definition {
{@build ($n:ident structure) ($($t:tt)*) null () } => {
#[allow(unused)]
#[derive(Debug)]
struct $n ($($t)*);
};
{@build ($n:ident enumeration new ($($f:tt)*) ($m:ident($($mt:tt)*)$($r:tt)*)) () null ()} => {
definition!{@build ($n enumeration ($($f)*) ($m($($mt)*)$($r)*)) () null () $($mt)*}
};
{@build ($n:ident enumeration ($($f:tt)*) ($m:ident($($mt:tt)*)$($r:tt)*)) ($($t:tt)*) null ()} => {
definition!{@build ($n enumeration new ($($f)*$m($($t)*)) ($($r)*)) () null () }
};
{@build ($n:ident enumeration new ($($m:ident($($mt:tt)*))*) ()) () null () } => {
definition!{@build ($n enumeration filter () ($($m($($mt)*))*))}
};
{@build ($n:ident enumeration filter ($($e:tt)*) ($m:ident($($mt:tt)+)$($t:tt)*))} => {
definition!{@build ($n enumeration filter ($($e)*$m($($mt)*),) ($($t)*))}
};
{@build ($n:ident enumeration filter ($($e:tt)*) ($m:ident()$($t:tt)*))} => {
definition!{@build ($n enumeration filter ($($e)*$m,) ($($t)*))}
};
{@build ($n:ident enumeration filter ($($e:tt)*) ())} => {
#[allow(unused)]
#[derive(Debug)]
enum $n {
$($e)*
}
};
{@build $m:tt ($($t:tt)*) null () $l:literal $($r:tt)*} => {
definition!{@build $m ($($t)*) null () $($r)*}
};
{@build $m:tt ($($t:tt)*) null () $i:ident $($r:tt)*} => {
definition!{@build $m ($($t)*Box<$i>,) null () $($r)*}
};
{@build $m:tt ($($t:tt)*) option ($a:tt) () $($r:tt)*} => {
definition!{@build $m ($($t)*Option<$a>,) null () $($r)*}
};
{@build $m:tt ($($t:tt)*) vector ($a:tt) () $($r:tt)*} => {
definition!{@build $m ($($t)*Vec<$a>,) null () $($r)*}
};
{@build $m:tt ($($t:tt)*) option ($($a:tt)*) () $($r:tt)*} => {
definition!{@build $m ($($t)*Option<($($a),*)>,) null () $($r)*}
};
{@build $m:tt ($($t:tt)*) vector ($($a:tt)*) () $($r:tt)*} => {
definition!{@build $m ($($t)*Vec<($($a),*)>,) null () $($r)*}
};
{@build $m:tt ($($t:tt)*) null () [$($b:tt)*] $($r:tt)*} => {
definition!{@build $m ($($t)*) option () ($($b)*) $($r)*}
};
{@build $m:tt ($($t:tt)*) null () {$($b:tt)*} $($r:tt)*} => {
definition!{@build $m ($($t)*) vector () ($($b)*) $($r)*}
};
{@build $m:tt ($($t:tt)*) $i:ident ($($a:tt)*) ($l:literal $($b:tt)*) $($r:tt)*} => {
definition!{@build $m ($($t)*) $i ($($a)*) ($($b)*) $($r)*}
};
{@build $m:tt ($($t:tt)*) $i:ident ($($a:tt)*) ($n:ident $($b:tt)*) $($r:tt)*} => {
definition!{@build $m ($($t)*) $i ($($a)*$n) ($($b)*) $($r)*}
};
}
macro_rules! implement {
{@begin $n:ident structure $($t:tt)*} => {
implement!{@build (state result) (structure $n) {} {} $($t)*}
};
{@begin $n:ident enumeration ($m:ident ($($t2:tt)*)$($t:tt)*)} => {
implement!{@build (state result) (enumeration $m {} ($($t)*) $n) {} {} $($t2)*}
};
{@build ($st:ident $r:ident) $m:tt $f:tt {$($f2:tt)*} $s:literal $($t:tt)*} => {
implement!{@build ($st $r) $m $f {
$($f2)*
$st = $st.trim_start();
if $st.starts_with($s) {
$st = &$st[$s.len()..]
} else {
return Err("error".to_string())
}
} $($t)*}
};
{@build ($s:ident $r:ident) $m:tt {$($f:tt)*} {$($f2:tt)*} $i:ident $($t:tt)*} => {
implement!{@build ($s $r) $m {$($f)*{$($f2)*}} {
let $r;
match $i::consume($s) {
Ok((r,s)) => {
$s = s;
$r = r;
}
Err(error) => {
return Err(error);
}
}
} $($t)*}
};
{@build $va:tt ($($m:tt)*) {$($f:tt)*} {$($f2:tt)*} {$($r:tt)*} $($t:tt)*} => {
implement!{@build $va (vector {$($f)*{$($f2)*}} ($($t)*) $($m)*) {} {} $($r)*}
};
{@build $va:tt ($($m:tt)*) {$($f:tt)*} {$($f2:tt)*} [$($r:tt)*] $($t:tt)*} => {
implement!{@build $va (option {$($f)*{$($f2)*}} ($($t)*) $($m)*) {} {} $($r)*}
};
{@finish ($s:ident $re:ident) (option {$($l:tt)*} ($($t:tt)*) $($m:tt)*) {{$($f:tt)*}$({$($r:tt)*})*} } => {
implement!{@build ($s $re) ($($m)*) {$($l)*} {
let mut $re;
let taker = move |_state| {
let mut $s: &str = _state;
$($f)*
Ok(((
$({$($r)*$re}),*
),$s))
};
match taker($s) {
Ok((r,s)) => {
$s = s;
$re = Some(r);
}
Err(_) => {
$re = None;
}
}
} $($t)*}
};
{@finish ($s:ident $re:ident) (vector {$($l:tt)*} ($($t:tt)*) $($m:tt)*) {{$($f:tt)*}$({$($r:tt)*})*} } => {
implement!{@build ($s $re) ($($m)*) {$($l)*} {
let mut $re = Vec::new();
let taker = move |_state| {
let mut $s: &str = _state;
$($f)*
Ok(((
$({$($r)*$re}),*
),$s))
};
while !$s.is_empty() {
match taker($s) {
Ok((r,s)) => {
$s = s;
$re.push(r);
}
Err(error) => {
break;
}
};
}
} $($t)*}
};
{@build $va:tt $m:tt {$($r:tt)*} $r2:tt} => {
implement!{@finish $va $m {$($r)*$r2}}
};
{@finish ($s:ident $re:ident) (structure $n:ident) {{$($f:tt)*}$({$($r:tt)*})*} } => {
#[allow(unused)]
impl Parse for $n {
fn consume(_state: &str) -> Result<(Self, &str), Error> where Self: Sized {
let mut $s: &str = _state;
$($f)*
Ok((
$n($({$($r)*$re.into()}),*),$s
))
}
}
};
{@finish ($s:ident $re:ident) (enumeration $m2:ident {$($l:tt)*} ($m:ident ($($t2:tt)*)$($t:tt)*) $n:ident) {$f:tt$({$($r:tt)*})+} } => {
implement!{@build ($s $re) (enumeration $m {$($l)*{
$f
Ok((
$n::$m2($({$($r)*$re.into()}),+),$s
))
}} ($($t)*) $n) {} {} $($t2)*}
};
{@finish ($s:ident $re:ident) (enumeration $m3:ident {$($l:tt)*} ($m:ident ($($t2:tt)*)$($t:tt)*) $n:ident) {$f:tt} } => {
implement!{@build ($s $re) (enumeration $m {$($l)*{
$f
Ok((
$n::$m3,$s
))
}} ($($t)*) $n) {} {} $($t2)*}
};
{@finish ($s:ident $re:ident) (enumeration $m2:ident {$($l:tt)*} () $n:ident) {$f:tt$({$($r:tt)*})+}} => {
implement!{@finish ($s $re) (enumeration {$($l)*{
$f
Ok((
$n::$m2($({$($r)*$re.into()}),+),$s
))
}} () $n)} // straight to below
};
{@finish ($s:ident $re:ident) (enumeration $m2:ident {$($l:tt)*} () $n:ident) {$f:tt}} => {
implement!{@finish ($s $re) (enumeration {$($l)*{
$f
Ok((
$n::$m2,$s
))
}} () $n)} // straight to below
};
{@finish ($s:ident $re:ident) (enumeration {$({$($f:tt)*})*} () $n:ident)} => {
#[allow(unused)]
impl Parse for $n {
fn consume(_state: &str) -> Result<(Self, &str), Error> where Self: Sized {
let mut $s: &str = _state;
$(
let case = (||{
let mut state: &str = _state;
$($f)*
})(); // put it into a closure and run it (makes returning easier)
if case.is_ok() {
return case;
}
)*
Err("error".into())
}
}
};
}
macro_rules! class {
($i:ident($($t:tt)*)) => {
definition!{@build ($i structure) () null () $($t)*}
implement!{@begin $i structure $($t)*}
//display!{@begin $i structure $($t)*}
};
($i:ident{$($n:ident($($t:tt)*)),*}) => {
definition!{@build ($i enumeration new () ($($n($($t)*))*)) () null ()}
implement!{@begin $i enumeration ($($n($($t)*))*)}
//display!{@begin $i enumeration ($($n($($t)*))*)}
}
}
macro_rules! parser {
() => {};
($i:ident$t:tt;$($tail:tt)*) => {
class!($i$t);
parser!($($tail)*);
};
}
// todo: reimplement attrib here
// https://www.lua.org/manual/5.5/manual.html#9
parser!{
// LiteralString -> "..."
// LiteralNumber -> 0x... 123.456
Chunk ( Block );
Block ( {Statement} [Return] );
Statement {
Semicolon (";"),
Assignment (Variables "=" Expressions),
Call (RootAtom CallChain),
Label (Label),
Break ("break"),
Goto ("goto" Name),
Do ("do" Block "end"),
While ("while" Expression "do" Block "end"),
Repeat ("repeat" Block "until" Expression),
If ("if" Expression "then" Block {"elseif" Expression "then" Block} ["else" Block] "end"),
ForRange ("for" Name "=" Expression "," Expression ["," Expression] "do" Block "end"),
ForIn ("for" Names "in" Expressions "do" Block "end"),
Function ("function" FunctionName FunctionBody),
LocalFunction ("local" "function" Name FunctionBody),
GlobalFunction ("global" "function" Name FunctionBody),
Declaration ("local" Names ["=" Expressions]),
Global ("global" Names)
};
Return( "return" [Expressions] [";"] );
Label( "::" Name "::" );
FunctionName( Name {"." Name} [":" Name] );
Variables( Variable {"," Variable} );
Names( Name {"," Name} );
Expressions( Expression {"," Expression} );
// DEVIATION: This parser is greedy, so the manual's syntax breaks it.
RootAtom {
Variable (Name),
Expression ("(" Expression ")")
};
IndexAtom {
Dot ("." Name),
Index ("[" Expression "]")
};
CallAtom {
Normal (Arguments),
Method (":" Name Arguments)
};
PrefixAtom {
Call (CallAtom),
Index (IndexAtom)
};
VariableChain {
Link (PrefixAtom VariableChain),
Finish (IndexAtom)
};
CallChain {
Link (PrefixAtom CallChain),
Finish (CallAtom)
};
Variable (RootAtom VariableChain);
Expression {
Nil ("nil"),
False ("false"),
True ("true"),
VarArg ("..."),
Number (Number),
String (String),
FunctionDef (FunctionDef),
Prefix (RootAtom {PrefixAtom}),
Table (Table),
Binary (Expression BinaryOp Expression), // todo: .
Unary (UnaryOp Expression)
};
// -----------------------
Arguments {
Expressions ("(" [Expressions] ")"),
Table (Table),
String (String)
};
FunctionDef( "function" FunctionBody );
FunctionBody( "(" [Parameters] ")" Block "end" );
Parameters {
Names (Names ["," VarArg]),
VarArg (VarArg)
};
VarArg( "..." [Name] );
Table( "{" [Fields] "}" );
Fields( Field {FieldSep Field} [FieldSep] );
Field {
ExpressionIndex ("[" Expression "]" "=" Expression),
Name (Name "=" Expression),
Expression (Expression)
};
FieldSep {
Comma (","),
Semicolon (";")
};
BinaryOp {
Plus ("+"),
Minus ("-"),
Mul ("*"),
Divide ("/"),
DivFloor ("//"),
Caret ("^"),
Modulo ("%"),
Ampersand ("&"),
Tilde ("~"),
Pipe ("|"),
ShiftRight (">>"),
ShiftLeft ("<<"),
Concat (".."),
Less ("<"),
LessEqual ("<="),
Greater (">"),
GreatEqual (">="),
Equivalent ("=="),
NotEqual ("~="),
And ("and"),
Or ("or")
};
UnaryOp {
Negate ("-"),
Not ("not"),
Ampersand ("#"),
Tilde ("~")
};
}

131
src/render/eye.rs Normal file
View file

@ -0,0 +1,131 @@
use bytemuck::{Pod, Zeroable};
use env_logger::Env;
use glam::{Affine3A, EulerRot, Mat3A, Mat4, Vec3, Vec4};
use glam::camera::lh::proj::directx::perspective;
use wgpu::{Device, Queue};
use wgpu::util::DeviceExt;
pub(crate) struct Eye {
pub(crate) frame: Affine3A,
pub(crate) environment: Environment,
aspect_ratio: f32,
z_near: f32,
z_far: f32,
fov_y: f32,
pub(crate) environment_buffer: wgpu::Buffer,
pub(crate) buffer: wgpu::Buffer,
pub(crate) layout: wgpu::BindGroupLayout,
pub(crate) group: wgpu::BindGroup,
}
#[repr(C)]
#[derive(Pod, Copy, Clone, Zeroable)]
struct Environment {
ambient: Vec4,
light: Vec4,
dir: Vec4,
}
impl Eye {
pub(crate) fn view(&self) -> Mat4 {
let projection = perspective(self.fov_y, self.aspect_ratio, self.z_near, self.z_far);
projection * self.frame.inverse()
}
pub(crate) fn write(&mut self, queue: &Queue) {
queue.write_buffer(&self.buffer,0,bytemuck::cast_slice(&[
self.view(),
Mat4::from_mat3_translation(self.frame.matrix3.into(), Vec3::from(self.frame.translation))
]));
queue.write_buffer(&self.environment_buffer,0,bytemuck::cast_slice(&[self.environment]));
}
pub(crate) fn new(device: &Device, width: u32, height: u32) -> Eye {
let buffer = device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Camera Buffer"),
contents: bytemuck::cast_slice(&[Mat4::from_translation(Vec3::new(0.0,2.0,-8.0)),Mat4::IDENTITY]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
}
);
let dir = Vec3::new(1.0,0.5,1.0).normalize();
let environment = Environment {
ambient: Vec4::new(0.15,0.15,0.15, 0.0),
light: Vec4::new(1.0,1.0,1.0, 0.0),
dir: Vec4::new(dir.x,dir.y,dir.z,0.0),
};
let environment_buffer = device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some(""),
contents: bytemuck::cast_slice(&[environment]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
}
);
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
],
label: Some("eye_bind_group_layout"),
});
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: environment_buffer.as_entire_binding(),
}
],
label: Some("eye_bind_group"),
});
Eye {
aspect_ratio: width as f32 / height as f32,
frame: Affine3A::IDENTITY,
fov_y: 90.0,
z_near: 0.1,
z_far: 1000.0,
buffer,
group,
layout,
environment,
environment_buffer,
}
}
pub(crate) fn resize(&mut self, width: u32, height: u32) {
self.aspect_ratio = width as f32 / height as f32
}
pub(crate) fn control(&mut self, delta: Vec3) {
self.frame *= Affine3A::from_translation(delta);
}
pub(crate) fn rotate(&mut self, yaw: f32, pitch: f32) {
let (mut y,mut x,z) = self.frame.matrix3.to_euler(EulerRot::YXZ);
x = (x + pitch * 0.005).clamp(-1.4,1.4);
y += yaw * 0.005;
self.frame.matrix3 = Mat3A::from_euler(EulerRot::YXZ,y,x,z);
}
}

1043
src/render/mod.rs Normal file

File diff suppressed because it is too large Load diff

0
src/web.rs Normal file
View file

223
src/world/mod.rs Normal file
View file

@ -0,0 +1,223 @@
use std::cell::RefCell;
use std::hash::{BuildHasherDefault, Hash, Hasher};
use std::ops::{Div, Mul};
use std::rc::Rc;
use glam::{DVec3, IVec3, Mat4, UVec3, Vec3, Vec4Swizzles};
use wgpu::naga::{FastHashMap, FastHashSet};
use crate::render::{SimpleModelData, SimpleLightData, Renderer};
#[derive(Clone)]
pub enum Shape {
Block(Vec3),
Sphere(f32),
None,
}
#[derive(Clone)]
pub struct SimpleColliderData {
pub transform: Mat4,
pub shape: Shape,
pub radius: f32,
}
#[derive(Clone)]
pub struct SimpleObjectData {
pub model: Option<SimpleModelData>,
pub collider: SimpleColliderData,
}
#[derive(Clone)]
pub struct SimpleLight(pub Rc<RefCell<SimpleLightData>>);
impl PartialEq for SimpleLight {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for SimpleLight {}
impl Hash for SimpleLight {
fn hash<H: Hasher>(&self, state: &mut H) {
(self.0.as_ptr() as *const RefCell<SimpleLight>).hash(state)
}
}
#[derive(Clone)]
pub struct SimpleObject(pub Rc<RefCell<SimpleObjectData>>);
impl SimpleObject {
pub(crate) fn hard_clone(&self) -> SimpleObject {
SimpleObject {
0: Rc::new(RefCell::new(SimpleObjectData {
model: self.0.borrow().model.clone(),
collider: self.0.borrow().collider.clone(),
})),
}
}
}
impl PartialEq for SimpleObject {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0,&other.0)
}
}
impl Eq for SimpleObject {}
impl Hash for SimpleObject {
fn hash<H: Hasher>(&self, state: &mut H) {
(self.0.as_ptr() as *const RefCell<SimpleModelData>).hash(state);
}
}
#[derive(Eq, Hash, PartialEq, Clone)]
enum Interest {
Light(SimpleLight),
Object(SimpleObject),
}
struct Block {
debug: Option<SimpleObject>,
volume: u8,
velocity: Vec3,
material: u8,
interests: FastHashSet<Interest>,
blocks: [Option<Box<Block>>;64],
}
const TREE_ATTACK: usize = 4;
const TREE_FLOOR: usize = 4;
impl Block {
fn new() -> Block {
Block {
debug: None,
volume: 0,
velocity: Vec3::ZERO,
material: 0,
interests: FastHashSet::with_hasher(BuildHasherDefault::default()),
blocks: [const { None }; const { TREE_ATTACK * TREE_ATTACK * TREE_ATTACK }],
}
}
fn place_pos(&mut self, interest: Interest, pos: Vec3, rad: f32, block_size: f32) {
let cs = block_size / const { TREE_ATTACK as f32 };
if rad < cs || block_size >= TREE_FLOOR as f32 {
let rel = ((pos + block_size / 2.0) / cs).round().as_uvec3();
let new_pos = pos - (rel.as_vec3() + cs / 2.0);
let index = (rel.x + rel.y * 4 + rel.z * 16) as usize;
match self.blocks[index] {
Some(ref mut block) => {
block.place_pos(interest,new_pos,rad,cs);
},
None => {
let mut block = Box::new(Block::new());
block.place_pos(interest,new_pos,rad,cs);
self.blocks[index] = Some(block);
}
}
} else {
self.interests.insert(interest);
}
}
fn debug_step(&mut self, value: bool) {
match self.debug {
Some(ref mut debug) => {
if value {
} else {
}
},
None => {
if value {
} else {
}
}
}
}
}
pub struct World {
chunk_size: u32,
map: FastHashMap<IVec3,Block>,
pub renderer: Option<Renderer>,
debug_world_map: bool,
debug_world_map_object: Option<SimpleObject>,
}
impl World {
pub fn new() -> World {
World {
chunk_size: 512,
map: FastHashMap::with_hasher(BuildHasherDefault::default()),
renderer: None,
debug_world_map: false,
debug_world_map_object: None,
}
}
pub fn add_renderer(&mut self, renderer: Renderer) {
self.renderer = Some(renderer);
self.debug_world_map_object = self.renderer.as_mut().unwrap().load_from_gltf(include_bytes!("../assets/debug.glb")).first_object()
}
pub fn add_object(&mut self, object: SimpleObject) {
self.place(Interest::Object(object.clone()));
if let Some(ref mut renderer) = self.renderer {
renderer.instances.add_object(object)
}
}
pub fn set_debug(&mut self, value: bool) {
self.debug_world_map = value;
}
pub fn light_step(&mut self) {
}
pub fn object_step(&mut self) {
}
pub fn debug_step(&mut self) {
self.light_step();
self.object_step();
for (index, item) in self.map.iter_mut() {
item.debug_step(self.debug_world_map);
}
}
fn place_pos(&mut self, interest: Interest, pos: Vec3, rad: f32) {
let cs = self.chunk_size as f32;
let c_rad = ((cs / 2.0) * (cs / 2.0)) * 3.0;
for x in (pos.x - rad).div(cs) as i32..=(pos.x + rad).div(cs).ceil() as i32 {
for y in (pos.y - rad).div(cs) as i32..=(pos.y + rad).div(cs).ceil() as i32 {
for z in (pos.z - rad).div(cs) as i32..=(pos.z + rad).div(cs).ceil() as i32 {
let block_pos = IVec3::new(x,y,z);
let block_pos_f32 = block_pos.as_vec3();
if block_pos_f32.distance_squared(pos) < rad + c_rad {
self.map.entry(block_pos).or_insert_with(|| {
let mut block = Block::new();
block.place_pos(
interest.clone(),
pos - block_pos_f32,
rad,
self.chunk_size as f32,
);
block
});
}
}
}
}
}
fn place(&mut self, interest: Interest) {
let (pos,rad) = match &interest {
Interest::Light(light) => {
let light = light.0.borrow();
(light.instance.location.xyz(),light.instance.color.length())
},
Interest::Object(object) => {
let collider = &object.0.borrow().collider;
(collider.transform.to_scale_rotation_translation().2,collider.radius)
},
};
self.place_pos(interest,pos,rad);
}
}