Reorganize project to workspace

This commit is contained in:
Tony Klink 2024-04-01 20:51:39 -06:00
parent 92c0278ef0
commit 960e2f8a37
Signed by: klink
GPG key ID: 85175567C4D19231
39 changed files with 4420 additions and 1189 deletions

View file

@ -0,0 +1,16 @@
[package]
name = "khors-config"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
khors-core = { path = "../../khors-core", version = "0.1.0" }
anyhow = "1.0.80"
notify = "6.1.1"
notify-debouncer-mini = "0.4.1"
flax = { version = "0.6.2", features = ["derive", "serde", "tokio", "tracing"] }
serde = { version = "1.0.197", features = ["derive"] }
serde-lexpr = "0.1.3"

View file

@ -0,0 +1,9 @@
use flax::component;
use super::Config;
component! {
pub config: Config,
pub notify_file_event: notify::Event,
pub resources,
}

View file

@ -0,0 +1,53 @@
use flax::{Schedule, World};
use khors_core::module::Module;
use serde::{Deserialize, Serialize};
use self::systems::first_read_config_system;
pub mod components;
pub mod systems;
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct Config {
pub asset_path: String,
}
#[allow(dead_code)]
pub struct ConfigModule {
// watcher: INotifyWatcher,
// watcher_rx: std::sync::mpsc::Receiver<Result<notify::Event, notify::Error>>,
}
impl ConfigModule {
pub fn new(
schedule: &mut Schedule,
_world: &mut World,
_events: &mut khors_core::events::Events,
) -> Self {
let schedule_r = Schedule::builder()
// .with_system(read_config_system())
.with_system(first_read_config_system())
.build();
schedule.append(schedule_r);
Self {
// schedule,
// watcher,
// watcher_rx: rx,
}
}
}
impl Module for ConfigModule {
fn on_update(
&mut self,
_world: &mut World,
_events: &mut khors_core::events::Events,
_frame_time: std::time::Duration,
) -> anyhow::Result<()> {
// println!("ConfigModule on_update");
Ok(())
}
}

View file

@ -0,0 +1,53 @@
use std::{fs, path::Path};
use flax::{BoxedSystem, CommandBuffer, EntityBorrow, Query, System};
use serde_lexpr::from_str;
use super::{components::{config, notify_file_event, resources}, Config};
#[allow(dead_code)]
pub fn read_config_system() -> BoxedSystem {
let query = Query::new(notify_file_event()).entity(resources());
System::builder()
.with_name("read_config")
.with_cmd_mut()
.with_query(query)
.build(|cmd: &mut CommandBuffer, mut _q: EntityBorrow<_>| {
// if let Ok(n_event) = q.get() {
// println!("here");
// if (n_event as &notify::Event).kind.is_modify() {
// println!("file modified: {:?}", (n_event as &notify::Event).paths);
cmd.set(resources(), config(), read_engine_config());
// }
// }
})
.boxed()
}
fn read_engine_config() -> Config {
let config_path = Path::new("engine_config.scm");
let config_file = fs::read_to_string(config_path).unwrap();
let config: Config = from_str::<Config>(&config_file).expect("Failed to parse config file");
config
}
pub fn first_read_config_system() -> BoxedSystem {
let query = Query::new(config().as_mut()).entity(resources());
System::builder()
.with_name("first_read_config")
.with_cmd_mut()
.with_query(query)
.build(|cmd: &mut CommandBuffer, mut q: EntityBorrow<_>| {
if let Ok(_config) = q.get() {
return;
} else {
println!("read_notify_events_system: config read");
cmd.set(resources(), config(), read_engine_config());
}
std::thread::sleep(std::time::Duration::from_secs(3));
})
.boxed()
}

View file

@ -0,0 +1,24 @@
[package]
name = "khors-graphics"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
khors-core = { path = "../../khors-core", version = "0.1.0" }
egui-vulkano = { path = "../../vendor/egui-vulkano", version = "0.1.0" }
anyhow = "1.0.80"
egui = "0.27.1"
glam = "0.27.0"
winit = { version = "0.29.15",features = ["rwh_05"] }
vulkano = { git = "https://github.com/vulkano-rs/vulkano.git", branch = "master" }
vulkano-shaders = { git = "https://github.com/vulkano-rs/vulkano.git", branch = "master" }
vulkano-util = { git = "https://github.com/vulkano-rs/vulkano.git", branch = "master" }
flax = { version = "0.6.2", features = ["derive", "serde", "tokio", "tracing"] }
flume = "0.11.0"
parking_lot = "0.12.1"
downcast-rs = "1.2.0"
serde = { version = "1.0.197", features = ["derive"] }
serde-lexpr = "0.1.3"

View file

@ -0,0 +1,7 @@
#[derive(Debug, Clone, Copy, PartialEq)]
#[allow(dead_code)]
pub enum GraphicsEvent {
/// Signifies that the swapchain was recreated. This requires images that
/// reference the old swapchain to be recreated.
SwapchainRecreation,
}

View file

@ -0,0 +1,14 @@
#version 450
layout(location = 0) in vec3 v_normal;
layout(location = 0) out vec4 f_color;
const vec3 LIGHT = vec3(0.0, 0.0, 1.0);
void main() {
float brightness = dot(normalize(v_normal), normalize(LIGHT));
vec3 dark_color = vec3(0.6, 0.0, 0.0);
vec3 regular_color = vec3(1.0, 0.0, 0.0);
f_color = vec4(mix(dark_color, regular_color, brightness), 1.0);
}

View file

@ -0,0 +1,551 @@
use flax::{entity_ids, BoxedSystem, Query, QueryBorrow, Schedule, System, World};
use glam::{
f32::{Mat3, Vec3},
Mat4,
};
use std::sync::Arc;
use vulkano::{
buffer::{
allocator::{SubbufferAllocator, SubbufferAllocatorCreateInfo},
Buffer, BufferCreateInfo, BufferUsage,
},
command_buffer::{
allocator::{CommandBufferAllocator, StandardCommandBufferAllocator},
CommandBufferBeginInfo, CommandBufferLevel, CommandBufferUsage, RecordingCommandBuffer,
RenderPassBeginInfo,
},
descriptor_set::{
allocator::StandardDescriptorSetAllocator, DescriptorSet, WriteDescriptorSet,
},
device::DeviceOwned,
format::Format,
image::{view::ImageView, Image, ImageCreateInfo, ImageType, ImageUsage},
memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, StandardMemoryAllocator},
pipeline::{
graphics::{
color_blend::{ColorBlendAttachmentState, ColorBlendState},
depth_stencil::{DepthState, DepthStencilState},
input_assembly::InputAssemblyState,
multisample::MultisampleState,
rasterization::RasterizationState,
vertex_input::{Vertex, VertexDefinition},
viewport::{Viewport, ViewportState},
GraphicsPipelineCreateInfo,
},
layout::PipelineDescriptorSetLayoutCreateInfo,
GraphicsPipeline, Pipeline, PipelineBindPoint, PipelineLayout,
PipelineShaderStageCreateInfo,
},
render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass, Subpass},
shader::EntryPoint,
sync::GpuFuture,
};
use vulkano_util::{
context::VulkanoContext, renderer::VulkanoWindowRenderer, window::VulkanoWindows,
};
use egui_vulkano::Gui;
use khors_core::{debug_gui::DebugGuiStack, module::RenderModule as ThreadLocalModule};
use self::{
model::{INDICES, NORMALS, POSITIONS},
vulkan::vertex::{Normal, Position},
};
pub mod events;
mod model;
mod test_pipeline;
mod vulkan;
pub struct RenderModule {
schedule: Schedule,
memory_allocator: Arc<StandardMemoryAllocator>,
descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
command_buffer_allocator: Arc<dyn CommandBufferAllocator>,
viewport: Viewport,
rotation_start: std::time::Instant,
}
impl RenderModule {
pub fn new(
vk_context: &mut VulkanoContext,
_vk_windows: &mut VulkanoWindows,
_schedule: &mut Schedule,
_world: &mut World,
_events: &mut khors_core::events::Events,
) -> Self {
let schedule = Schedule::builder()
.with_system(add_distance_system())
.build();
let memory_allocator = Arc::new(StandardMemoryAllocator::new_default(
vk_context.device().clone(),
));
let descriptor_set_allocator = Arc::new(StandardDescriptorSetAllocator::new(
vk_context.device().clone(),
Default::default(),
));
let command_buffer_allocator = Arc::new(StandardCommandBufferAllocator::new(
vk_context.device().clone(),
Default::default(),
));
let viewport = Viewport {
offset: [0.0, 0.0],
extent: [0.0, 0.0],
depth_range: 0.0..=1.0,
};
let rotation_start = std::time::Instant::now();
Self {
schedule,
memory_allocator,
descriptor_set_allocator,
command_buffer_allocator,
viewport,
rotation_start,
}
}
}
impl ThreadLocalModule for RenderModule {
fn on_update(
&mut self,
gui_stack: &mut DebugGuiStack,
vk_context: &mut VulkanoContext,
vk_windows: &mut vulkano_util::window::VulkanoWindows,
world: &mut World,
_events: &mut khors_core::events::Events,
_frame_time: std::time::Duration,
) -> anyhow::Result<()> {
self.schedule.execute_seq(world).unwrap();
let viewport = &mut self.viewport;
for (window_id, renderer) in vk_windows.iter_mut() {
let gui = gui_stack.get_mut(*window_id).unwrap();
draw(
vk_context.device().clone(),
self.memory_allocator.clone(),
self.descriptor_set_allocator.clone(),
self.command_buffer_allocator.clone(),
viewport,
vk_context,
renderer,
gui,
self.rotation_start,
);
}
Ok(())
}
}
pub fn add_distance_system() -> BoxedSystem {
let query = Query::new(entity_ids());
System::builder()
.with_query(query)
.build(|mut query: QueryBorrow<'_, flax::EntityIds, _>| {
for _id in &mut query {
// println!("----------: {}", _id.index());
}
})
.boxed()
}
fn draw(
device: Arc<vulkano::device::Device>,
memory_allocator: Arc<StandardMemoryAllocator>,
descriptor_set_allocator: Arc<StandardDescriptorSetAllocator>,
command_buffer_allocator: Arc<dyn CommandBufferAllocator>,
_viewport: &mut Viewport,
context: &mut VulkanoContext,
renderer: &mut VulkanoWindowRenderer,
gui: &mut Gui,
rotation_start: std::time::Instant,
) {
let vertex_buffer = Buffer::from_iter(
memory_allocator.clone(),
BufferCreateInfo {
usage: BufferUsage::VERTEX_BUFFER,
..Default::default()
},
AllocationCreateInfo {
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
..Default::default()
},
POSITIONS,
)
.unwrap();
let normals_buffer = Buffer::from_iter(
memory_allocator.clone(),
BufferCreateInfo {
usage: BufferUsage::VERTEX_BUFFER,
..Default::default()
},
AllocationCreateInfo {
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
..Default::default()
},
NORMALS,
)
.unwrap();
let index_buffer = Buffer::from_iter(
memory_allocator.clone(),
BufferCreateInfo {
usage: BufferUsage::INDEX_BUFFER,
..Default::default()
},
AllocationCreateInfo {
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
..Default::default()
},
INDICES,
)
.unwrap();
let uniform_buffer = SubbufferAllocator::new(
memory_allocator.clone(),
SubbufferAllocatorCreateInfo {
buffer_usage: BufferUsage::UNIFORM_BUFFER,
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
..Default::default()
},
);
let render_pass = vulkano::single_pass_renderpass!(
device.clone(),
attachments: {
color: {
format: renderer.swapchain_format(),
samples: 1,
load_op: Clear,
store_op: Store,
},
depth_stencil: {
format: Format::D16_UNORM,
samples: 1,
load_op: Clear,
store_op: DontCare,
},
},
pass: {
color: [color],
depth_stencil: {depth_stencil},
},
)
.unwrap();
let vs = vs::load(device.clone())
.unwrap()
.entry_point("main")
.unwrap();
let fs = fs::load(device.clone())
.unwrap()
.entry_point("main")
.unwrap();
let (mut pipeline, mut framebuffers) = window_size_dependent_setup(
memory_allocator.clone(),
vs.clone(),
fs.clone(),
renderer.swapchain_image_views(),
render_pass.clone(),
);
// Do not draw the frame when the screen size is zero. On Windows, this can
// occur when minimizing the application.
let image_extent: [u32; 2] = renderer.window().inner_size().into();
if image_extent.contains(&0) {
return;
}
// Begin rendering by acquiring the gpu future from the window renderer.
let previous_frame_end = renderer
.acquire(None, |swapchain_images| {
// Whenever the window resizes we need to recreate everything dependent
// on the window size. In this example that
// includes the swapchain, the framebuffers
// and the dynamic state viewport.
let (new_pipeline, new_framebuffers) = window_size_dependent_setup(
memory_allocator.clone(),
vs.clone(),
fs.clone(),
swapchain_images,
render_pass.clone(),
);
pipeline = new_pipeline;
framebuffers = new_framebuffers;
})
.unwrap();
let uniform_buffer_subbuffer = {
let elapsed = rotation_start.elapsed();
let rotation = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 / 1_000_000_000.0;
let rotation = Mat3::from_rotation_y(rotation as f32);
// NOTE: This teapot was meant for OpenGL where the origin is at the lower left
// instead the origin is at the upper left in Vulkan, so we reverse the Y axis.
let aspect_ratio = renderer.aspect_ratio();
let proj = Mat4::perspective_rh_gl(std::f32::consts::FRAC_PI_2, aspect_ratio, 0.01, 100.0);
let view = Mat4::look_at_rh(
Vec3::new(0.4, 0.3, 1.0),
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(0.0, -1.0, 0.0),
);
let scale = Mat4::from_scale(Vec3::splat(0.01));
let uniform_data = vs::Data {
world: Mat4::from_mat3(rotation).to_cols_array_2d(),
view: (view * scale).to_cols_array_2d(),
proj: proj.to_cols_array_2d(),
};
let subbuffer = uniform_buffer.allocate_sized().unwrap();
*subbuffer.write().unwrap() = uniform_data;
subbuffer
};
let mut builder = RecordingCommandBuffer::new(
command_buffer_allocator.clone(),
context.graphics_queue().queue_family_index(),
CommandBufferLevel::Primary,
CommandBufferBeginInfo {
usage: CommandBufferUsage::OneTimeSubmit,
..Default::default()
},
)
.unwrap();
let layout = &pipeline.layout().set_layouts()[0];
let set = DescriptorSet::new(
descriptor_set_allocator.clone(),
layout.clone(),
[WriteDescriptorSet::buffer(0, uniform_buffer_subbuffer)],
[],
)
.unwrap();
builder
.begin_render_pass(
RenderPassBeginInfo {
clear_values: vec![Some([0.0, 0.0, 1.0, 1.0].into()), Some(1f32.into())],
..RenderPassBeginInfo::framebuffer(
framebuffers[renderer.image_index() as usize].clone(),
)
},
Default::default(),
)
.unwrap()
.bind_pipeline_graphics(pipeline.clone())
.unwrap()
.bind_descriptor_sets(
PipelineBindPoint::Graphics,
pipeline.layout().clone(),
0,
set,
)
.unwrap()
.bind_vertex_buffers(0, (vertex_buffer.clone(), normals_buffer.clone()))
.unwrap()
.bind_index_buffer(index_buffer.clone())
.unwrap();
unsafe {
builder
.draw_indexed(index_buffer.len() as u32, 1, 0, 0, 0)
.unwrap();
}
builder.end_render_pass(Default::default()).unwrap();
// Finish recording the command buffer by calling `end`.
let command_buffer = builder.end().unwrap();
draw_gui(gui);
let before_future = previous_frame_end
.then_execute(context.graphics_queue().clone(), command_buffer)
.unwrap()
.boxed();
let after_future = gui
.draw_on_image(before_future, renderer.swapchain_image_view())
.boxed();
// The color output is now expected to contain our triangle. But in order to
// show it on the screen, we have to *present* the image by calling
// `present` on the window renderer.
//
// This function does not actually present the image immediately. Instead it
// submits a present command at the end of the queue. This means that it will
// only be presented once the GPU has finished executing the command buffer
// that draws the triangle.
renderer.present(after_future, true);
}
fn draw_gui(gui: &mut Gui) {
let mut code = CODE.to_owned();
gui.immediate_ui(|gui| {
let ctx = gui.context();
egui::Window::new("Colors").vscroll(true).show(&ctx, |ui| {
ui.vertical_centered(|ui| {
ui.add(egui::widgets::Label::new("Hi there!"));
sized_text(ui, "Rich Text", 32.0);
});
ui.separator();
ui.columns(2, |columns| {
egui::ScrollArea::vertical()
.id_source("source")
.show(&mut columns[0], |ui| {
ui.add(
egui::TextEdit::multiline(&mut code).font(egui::TextStyle::Monospace),
);
});
egui::ScrollArea::vertical()
.id_source("rendered")
.show(&mut columns[1], |ui| {
ui.add(egui::widgets::Label::new("Good day!"));
});
});
});
});
}
fn sized_text(ui: &mut egui::Ui, text: impl Into<String>, size: f32) {
ui.label(
egui::RichText::new(text)
.size(size)
.family(egui::FontFamily::Monospace),
);
}
const CODE: &str = r"
# Some markup
```
let mut gui = Gui::new(&event_loop, renderer.surface(), None, renderer.queue(), SampleCount::Sample1);
```
";
fn window_size_dependent_setup(
memory_allocator: Arc<StandardMemoryAllocator>,
vs: EntryPoint,
fs: EntryPoint,
image_views: &[Arc<ImageView>],
render_pass: Arc<RenderPass>,
) -> (Arc<GraphicsPipeline>, Vec<Arc<Framebuffer>>) {
let device = memory_allocator.device().clone();
let extent = image_views[0].image().extent();
let depth_buffer = ImageView::new_default(
Image::new(
memory_allocator,
ImageCreateInfo {
image_type: ImageType::Dim2d,
format: Format::D16_UNORM,
extent,
usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT | ImageUsage::TRANSIENT_ATTACHMENT,
..Default::default()
},
AllocationCreateInfo::default(),
)
.unwrap(),
)
.unwrap();
let framebuffers = image_views
.iter()
.map(|image_view| {
Framebuffer::new(
render_pass.clone(),
FramebufferCreateInfo {
attachments: vec![image_view.clone(), depth_buffer.clone()],
..Default::default()
},
)
.unwrap()
})
.collect::<Vec<_>>();
// In the triangle example we use a dynamic viewport, as its a simple example. However in the
// teapot example, we recreate the pipelines with a hardcoded viewport instead. This allows the
// driver to optimize things, at the cost of slower window resizes.
// https://computergraphics.stackexchange.com/questions/5742/vulkan-best-way-of-updating-pipeline-viewport
let pipeline = {
let vertex_input_state = [Position::per_vertex(), Normal::per_vertex()]
.definition(&vs)
.unwrap();
let stages = [
PipelineShaderStageCreateInfo::new(vs),
PipelineShaderStageCreateInfo::new(fs),
];
let layout = PipelineLayout::new(
device.clone(),
PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
.into_pipeline_layout_create_info(device.clone())
.unwrap(),
)
.unwrap();
let subpass = Subpass::from(render_pass, 0).unwrap();
GraphicsPipeline::new(
device,
None,
GraphicsPipelineCreateInfo {
stages: stages.into_iter().collect(),
vertex_input_state: Some(vertex_input_state),
input_assembly_state: Some(InputAssemblyState::default()),
viewport_state: Some(ViewportState {
viewports: [Viewport {
offset: [0.0, 0.0],
extent: [extent[0] as f32, extent[1] as f32],
depth_range: 0.0..=1.0,
}]
.into_iter()
.collect(),
..Default::default()
}),
rasterization_state: Some(RasterizationState::default()),
depth_stencil_state: Some(DepthStencilState {
depth: Some(DepthState::simple()),
..Default::default()
}),
multisample_state: Some(MultisampleState::default()),
color_blend_state: Some(ColorBlendState::with_attachment_states(
subpass.num_color_attachments(),
ColorBlendAttachmentState::default(),
)),
subpass: Some(subpass.into()),
..GraphicsPipelineCreateInfo::layout(layout)
},
)
.unwrap()
};
(pipeline, framebuffers)
}
mod vs {
vulkano_shaders::shader! {
ty: "vertex",
path: "src/vert.glsl",
}
}
mod fs {
vulkano_shaders::shader! {
ty: "fragment",
path: "src/frag.glsl",
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,198 @@
use std::sync::Arc;
use vulkano::{
buffer::{Buffer, BufferContents, BufferCreateInfo, BufferUsage, Subbuffer},
device::Device,
format::Format,
memory::allocator::{AllocationCreateInfo, MemoryAllocator, MemoryTypeFilter},
pipeline::{
graphics::{
color_blend::{ColorBlendAttachmentState, ColorBlendState},
input_assembly::InputAssemblyState,
multisample::MultisampleState,
rasterization::RasterizationState,
subpass::PipelineRenderingCreateInfo,
vertex_input::{Vertex, VertexDefinition},
viewport::ViewportState,
GraphicsPipelineCreateInfo,
},
layout::PipelineDescriptorSetLayoutCreateInfo,
DynamicState, GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo,
},
};
#[allow(dead_code)]
pub fn test_pipeline(
device: Arc<Device>,
memory_allocator: Arc<dyn MemoryAllocator>,
image_format: Format,
) -> (Subbuffer<[MyVertex]>, Arc<GraphicsPipeline>) {
let vertices = [
MyVertex {
position: [-0.5, -0.25],
},
MyVertex {
position: [0.0, 0.5],
},
MyVertex {
position: [0.25, -0.1],
},
];
let vertex_buffer = Buffer::from_iter(
memory_allocator,
BufferCreateInfo {
usage: BufferUsage::VERTEX_BUFFER,
..Default::default()
},
AllocationCreateInfo {
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
..Default::default()
},
vertices,
)
.unwrap();
let pipeline = {
// First, we load the shaders that the pipeline will use:
// the vertex shader and the fragment shader.
//
// A Vulkan shader can in theory contain multiple entry points, so we have to specify which
// one.
let vs = vs::load(device.clone())
.unwrap()
.entry_point("main")
.unwrap();
let fs = fs::load(device.clone())
.unwrap()
.entry_point("main")
.unwrap();
// Automatically generate a vertex input state from the vertex shader's input interface,
// that takes a single vertex buffer containing `Vertex` structs.
let vertex_input_state = MyVertex::per_vertex().definition(&vs).unwrap();
// Make a list of the shader stages that the pipeline will have.
let stages = [
PipelineShaderStageCreateInfo::new(vs),
PipelineShaderStageCreateInfo::new(fs),
];
// We must now create a **pipeline layout** object, which describes the locations and types
// of descriptor sets and push constants used by the shaders in the pipeline.
//
// Multiple pipelines can share a common layout object, which is more efficient.
// The shaders in a pipeline must use a subset of the resources described in its pipeline
// layout, but the pipeline layout is allowed to contain resources that are not present in
// the shaders; they can be used by shaders in other pipelines that share the same
// layout. Thus, it is a good idea to design shaders so that many pipelines have
// common resource locations, which allows them to share pipeline layouts.
let layout = PipelineLayout::new(
device.clone(),
// Since we only have one pipeline in this example, and thus one pipeline layout,
// we automatically generate the creation info for it from the resources used in the
// shaders. In a real application, you would specify this information manually so that
// you can re-use one layout in multiple pipelines.
PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
.into_pipeline_layout_create_info(device.clone())
.unwrap(),
)
.unwrap();
// We describe the formats of attachment images where the colors, depth and/or stencil
// information will be written. The pipeline will only be usable with this particular
// configuration of the attachment images.
let subpass = PipelineRenderingCreateInfo {
// We specify a single color attachment that will be rendered to. When we begin
// rendering, we will specify a swapchain image to be used as this attachment, so here
// we set its format to be the same format as the swapchain.
color_attachment_formats: vec![Some(image_format)],
..Default::default()
};
// Finally, create the pipeline.
GraphicsPipeline::new(
device.clone(),
None,
GraphicsPipelineCreateInfo {
stages: stages.into_iter().collect(),
// How vertex data is read from the vertex buffers into the vertex shader.
vertex_input_state: Some(vertex_input_state),
// How vertices are arranged into primitive shapes.
// The default primitive shape is a triangle.
input_assembly_state: Some(InputAssemblyState::default()),
// How primitives are transformed and clipped to fit the framebuffer.
// We use a resizable viewport, set to draw over the entire window.
viewport_state: Some(ViewportState::default()),
// How polygons are culled and converted into a raster of pixels.
// The default value does not perform any culling.
rasterization_state: Some(RasterizationState::default()),
// How multiple fragment shader samples are converted to a single pixel value.
// The default value does not perform any multisampling.
multisample_state: Some(MultisampleState::default()),
// How pixel values are combined with the values already present in the framebuffer.
// The default value overwrites the old value with the new one, without any
// blending.
color_blend_state: Some(ColorBlendState::with_attachment_states(
subpass.color_attachment_formats.len() as u32,
ColorBlendAttachmentState::default(),
)),
// Dynamic states allows us to specify parts of the pipeline settings when
// recording the command buffer, before we perform drawing.
// Here, we specify that the viewport should be dynamic.
dynamic_state: [DynamicState::Viewport].into_iter().collect(),
subpass: Some(subpass.into()),
..GraphicsPipelineCreateInfo::layout(layout)
},
)
.unwrap()
};
(vertex_buffer, pipeline)
}
#[derive(BufferContents, Vertex)]
#[repr(C)]
pub struct MyVertex {
#[format(R32G32_SFLOAT)]
position: [f32; 2],
}
mod vs {
vulkano_shaders::shader! {
ty: "vertex",
src: r"
#version 450
layout(location = 0) in vec2 position;
layout(location = 0) out vec3 fragColor;
vec3 colors[3] = vec3[](vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
void main() {
gl_Position = vec4(position, 0.0, 1.0);
fragColor = colors[gl_VertexIndex];
}
",
}
}
mod fs {
vulkano_shaders::shader! {
ty: "fragment",
src: r"
#version 450
layout(location = 0) in vec3 fragColor;
layout(location = 0) out vec4 f_color;
void main() {
f_color = vec4(fragColor, 1.0);
}
",
}
}

View file

@ -0,0 +1,18 @@
#version 450
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
layout(location = 0) out vec3 v_normal;
layout(set = 0, binding = 0) uniform Data {
mat4 world;
mat4 view;
mat4 proj;
} uniforms;
void main() {
mat4 worldview = uniforms.view * uniforms.world;
v_normal = transpose(inverse(mat3(worldview))) * normal;
gl_Position = uniforms.proj * worldview * vec4(position, 1.0);
}

View file

@ -0,0 +1,2 @@
// pub mod pipeline;
pub mod vertex;

View file

@ -0,0 +1,108 @@
use std::sync::Arc;
use vulkano::{
device::Device,
pipeline::{
graphics::{
color_blend::{ColorBlendAttachmentState, ColorBlendState},
depth_stencil::{DepthState, DepthStencilState},
input_assembly::InputAssemblyState,
multisample::MultisampleState,
rasterization::RasterizationState,
vertex_input::{Vertex, VertexDefinition},
viewport::{Viewport, ViewportState},
GraphicsPipelineCreateInfo,
},
layout::PipelineDescriptorSetLayoutCreateInfo,
GraphicsPipeline, PipelineLayout, PipelineShaderStageCreateInfo,
},
render_pass::{RenderPass, Subpass},
shader::ShaderModule,
};
use super::vertex::{Normal, Position};
pub struct PipelineInfo {
pub vs: Arc<ShaderModule>,
pub fs: Arc<ShaderModule>,
}
pub fn make_pipeline(
device: Arc<Device>,
pipeline_info: &PipelineInfo,
pass_info: &PassInfo,
) -> Arc<GraphicsPipeline> {
let vs = pipeline_info.vs.entry_point("main").unwrap();
let fs = pipeline_info.fs.entry_point("main").unwrap();
let vertex_input_state = [Position::per_vertex(), Normal::per_vertex()]
.definition(&vs)
.unwrap();
let stages = [
PipelineShaderStageCreateInfo::new(vs),
PipelineShaderStageCreateInfo::new(fs),
];
let layout = PipelineLayout::new(
device.clone(),
PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
.into_pipeline_layout_create_info(device.clone())
.unwrap(),
)
.unwrap();
let subpass = pass_info.subpass().unwrap();
let extent = pass_info.extent;
GraphicsPipeline::new(
device,
None,
GraphicsPipelineCreateInfo {
stages: stages.into_iter().collect(),
vertex_input_state: Some(vertex_input_state),
input_assembly_state: Some(InputAssemblyState::default()),
viewport_state: Some(ViewportState {
viewports: [Viewport {
offset: [0.0, 0.0],
extent: [extent[0] as f32, extent[1] as f32],
depth_range: 0.0..=1.0,
}]
.into_iter()
.collect(),
..Default::default()
}),
rasterization_state: Some(RasterizationState::default()),
depth_stencil_state: Some(DepthStencilState {
depth: Some(DepthState::simple()),
..Default::default()
}),
multisample_state: Some(MultisampleState::default()),
color_blend_state: Some(ColorBlendState::with_attachment_states(
subpass.num_color_attachments(),
ColorBlendAttachmentState::default(),
)),
subpass: Some(subpass.into()),
..GraphicsPipelineCreateInfo::layout(layout)
},
)
.unwrap()
}
pub struct PassInfo {
pub render_pass: Arc<RenderPass>,
pub subpass_id: u32,
pub extent: [u32; 3],
}
impl PassInfo {
pub fn new(render_pass: Arc<RenderPass>, subpass_id: u32, extent: [u32; 3]) -> Self {
Self {
render_pass: render_pass.clone(),
subpass_id,
extent,
}
}
pub fn subpass(&self) -> Option<Subpass> {
Subpass::from(self.render_pass.clone(), self.subpass_id)
}
}

View file

@ -0,0 +1,15 @@
use vulkano::{buffer::BufferContents, pipeline::graphics::vertex_input::Vertex};
#[derive(BufferContents, Vertex)]
#[repr(C)]
pub struct Position {
#[format(R32G32B32_SFLOAT)]
pub position: [f32; 3],
}
#[derive(BufferContents, Vertex)]
#[repr(C)]
pub struct Normal {
#[format(R32G32B32_SFLOAT)]
pub normal: [f32; 3],
}

View file

@ -0,0 +1,17 @@
[package]
name = "khors-steel"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
khors-core = { path = "../../khors-core", version = "0.1.0" }
anyhow = "1.0.80"
flax = { version = "0.6.2", features = ["derive", "serde", "tokio", "tracing"] }
flume = "0.11.0"
notify = "6.1.1"
notify-debouncer-mini = "0.4.1"
steel-core = { git="https://github.com/mattwparas/steel.git", branch = "master" }
steel-derive = { git="https://github.com/mattwparas/steel.git", branch = "master" }

View file

@ -0,0 +1,102 @@
extern crate khors_core;
use flax::{component, BoxedSystem, EntityBorrow, Query, QueryBorrow, Schedule, System, World};
use khors_core::module::Module;
use steel::steel_vm::engine::Engine;
use steel_derive::Steel;
component! {
steel_script: String,
steel_event_tx: flume::Sender<SteelEvent>,
resources,
}
pub fn execute_script_system() -> BoxedSystem {
let tx_query = Query::new(steel_event_tx()).entity(resources());
let script_query = Query::new(steel_script());
System::builder()
.with_query(tx_query)
.with_query(script_query)
.build(|mut tx_query: EntityBorrow<'_, flax::Component<flume::Sender<SteelEvent>>>, mut script_query: QueryBorrow<flax::Component<String>>| {
if let Ok(tx) = tx_query.get() {
for script in &mut script_query {
println!("Got script and tx");
tx.send(SteelEvent::Execute(script.into())).unwrap();
}
}
})
.boxed()
}
#[derive(Debug, Steel)]
enum SteelEvent {
Execute(String),
}
#[allow(dead_code)]
#[derive(Steel, Clone)]
pub struct SteelModule {
engine: Engine,
// schedule: Schedule,
rx: flume::Receiver<SteelEvent>,
}
impl SteelModule {
pub fn new(
schedule: &mut Schedule,
world: &mut World,
_events: &mut khors_core::events::Events,
) -> Self {
let engine = Engine::new();
let (tx, rx) = flume::unbounded::<SteelEvent>();
let schedule_r = Schedule::builder()
.with_system(execute_script_system())
.build();
schedule.append(schedule_r);
world.set(resources(), steel_event_tx(), tx).unwrap();
// Some testing
let entity = world.spawn();
world.set(entity, steel_script(), r#"
(require-builtin steel/time)
(display "Hello ")
(time/sleep-ms 5000)
(display "World!")"#.into()).unwrap();
Self {
engine,
// schedule,
rx,
}
}
}
impl Module for SteelModule {
fn on_update(
&mut self,
_world: &mut World,
_events: &mut khors_core::events::Events,
_frame_time: std::time::Duration,
) -> anyhow::Result<()> {
// self.schedule.execute_par(world).unwrap();
if let Ok(event) = self.rx.recv() {
match event {
SteelEvent::Execute(script) => {
let _handle = std::thread::spawn(|| {
let mut engine = Engine::new();
let val = engine.run(script).unwrap();
println!("Steel val: {:?}", val);
});
}
}
}
Ok(())
}
}

View file

@ -0,0 +1,12 @@
[package]
name = "khors-window"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
khors-core = { path = "../../khors-core", version = "0.1.0" }
anyhow = "1.0.80"
flax = { version = "0.6.2", features = ["derive", "serde", "tokio", "tracing"] }

View file

@ -0,0 +1,34 @@
use flax::{Schedule, World};
use khors_core::module::Module;
pub struct WindowModule {
}
impl WindowModule {
pub fn new(
schedule: &mut Schedule,
_world: &mut World,
_events: &mut khors_core::events::Events,
) -> Self {
let schedule_r = Schedule::builder()
.build();
schedule.append(schedule_r);
Self {
}
}
}
impl Module for WindowModule {
fn on_update(
&mut self,
_world: &mut World,
_events: &mut khors_core::events::Events,
_frame_time: std::time::Duration,
) -> anyhow::Result<()> {
// println!("WindowModule on_update");
Ok(())
}
}