Working version of original project

This commit is contained in:
John Hunter
2025-01-01 23:55:53 +00:00
parent b6b252c69d
commit 041d876fe5
8 changed files with 368 additions and 502 deletions
+1
View File
@@ -1 +1,2 @@
/target /target
pipeline_cache.bin
Generated
+17 -10
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 4
[[package]] [[package]]
name = "ab_glyph" name = "ab_glyph"
@@ -546,6 +546,17 @@ dependencies = [
"winit", "winit",
] ]
[[package]]
name = "egui_plot"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c226cae80a6ee10c4d3aaf9e33bd9e9b2f1c0116b6036bdc2a1cfc9d2d0dcc10"
dependencies = [
"ahash",
"egui",
"emath",
]
[[package]] [[package]]
name = "egui_winit_vulkano" name = "egui_winit_vulkano"
version = "0.27.0" version = "0.27.0"
@@ -621,6 +632,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"egui", "egui",
"egui_plot",
"egui_winit_vulkano", "egui_winit_vulkano",
"foldhash", "foldhash",
"glam", "glam",
@@ -2083,9 +2095,9 @@ checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.93" version = "2.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c786062daee0d6db1132800e623df74274a0a87322d8e183338e01b3d98d058" checksum = "987bc0be1cdea8b10216bd06e2ca407d40b9543468fafd3ddfb02f36e77f71f3"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -2897,9 +2909,9 @@ dependencies = [
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "0.6.20" version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" checksum = "e6f5bb5257f2407a5425c6e749bfd9692192a73e70a6060516ac04f889087d68"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]
@@ -3101,8 +3113,3 @@ dependencies = [
name = "vulkano-taskgraph" name = "vulkano-taskgraph"
version = "0.34.0" version = "0.34.0"
source = "git+https://github.com/vulkano-rs/vulkano#ea30f65280360b1e1bc907cd42d4eb355fed3c9d" source = "git+https://github.com/vulkano-rs/vulkano#ea30f65280360b1e1bc907cd42d4eb355fed3c9d"
[[patch.unused]]
name = "vulkano-win"
version = "0.34.0"
source = "git+https://github.com/vulkano-rs/vulkano#ea30f65280360b1e1bc907cd42d4eb355fed3c9d"
+1 -1
View File
@@ -22,6 +22,7 @@ glam = "0.29"
egui = "0.30" egui = "0.30"
egui_winit_vulkano = "0.27" egui_winit_vulkano = "0.27"
egui_plot = "0.30.0"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
@@ -40,5 +41,4 @@ vulkano-macros = { git = "https://github.com/vulkano-rs/vulkano" }
vulkano-shaders = { git = "https://github.com/vulkano-rs/vulkano" } vulkano-shaders = { git = "https://github.com/vulkano-rs/vulkano" }
vulkano-taskgraph = { git = "https://github.com/vulkano-rs/vulkano" } vulkano-taskgraph = { git = "https://github.com/vulkano-rs/vulkano" }
vulkano-util = { git = "https://github.com/vulkano-rs/vulkano" } vulkano-util = { git = "https://github.com/vulkano-rs/vulkano" }
vulkano-win = { git = "https://github.com/vulkano-rs/vulkano" }
egui_winit_vulkano = { git = "https://github.com/Molive-0/egui_winit_vulkano" } egui_winit_vulkano = { git = "https://github.com/Molive-0/egui_winit_vulkano" }
+9 -14
View File
@@ -1,10 +1,8 @@
use egui::{ use egui::{Color32, Frame, Id};
plot::{Line, Plot, PlotPoints}, use egui_plot::{Line, Plot, PlotPoints};
Color32, Frame, Id,
};
use egui_winit_vulkano::Gui; use egui_winit_vulkano::Gui;
use crate::objects::{Light, Mesh, CSG}; use crate::objects::{CSG, Light, Mesh};
fn sized_text(ui: &mut egui::Ui, text: impl Into<String>, size: f32) { fn sized_text(ui: &mut egui::Ui, text: impl Into<String>, size: f32) {
ui.label(egui::RichText::new(text).size(size)); ui.label(egui::RichText::new(text).size(size));
@@ -94,16 +92,13 @@ pub(crate) fn gui_up(gui: &mut Gui, state: &mut GState) {
.text("Position.z"), .text("Position.z"),
); );
ui.add( ui.add(
egui::Slider::new(&mut mesh.rot.x.0, 0.0..=360.0) egui::Slider::new(&mut mesh.rot.x, 0.0..=360.0).text("Rotation.x"),
.text("Rotation.x"),
); );
ui.add( ui.add(
egui::Slider::new(&mut mesh.rot.y.0, 0.0..=360.0) egui::Slider::new(&mut mesh.rot.y, 0.0..=360.0).text("Rotation.y"),
.text("Rotation.y"),
); );
ui.add( ui.add(
egui::Slider::new(&mut mesh.rot.z.0, 0.0..=360.0) egui::Slider::new(&mut mesh.rot.z, 0.0..=360.0).text("Rotation.z"),
.text("Rotation.z"),
); );
ui.add(egui::Slider::new(&mut mesh.scale.x, 0.0..=2.0).text("Scale.x")); ui.add(egui::Slider::new(&mut mesh.scale.x, 0.0..=2.0).text("Scale.x"));
ui.add(egui::Slider::new(&mut mesh.scale.y, 0.0..=2.0).text("Scale.y")); ui.add(egui::Slider::new(&mut mesh.scale.y, 0.0..=2.0).text("Scale.y"));
@@ -134,13 +129,13 @@ pub(crate) fn gui_up(gui: &mut Gui, state: &mut GState) {
.text("Position.z"), .text("Position.z"),
); );
ui.add( ui.add(
egui::Slider::new(&mut csg.rot.x.0, 0.0..=360.0).text("Rotation.x"), egui::Slider::new(&mut csg.rot.x, 0.0..=360.0).text("Rotation.x"),
); );
ui.add( ui.add(
egui::Slider::new(&mut csg.rot.y.0, 0.0..=360.0).text("Rotation.y"), egui::Slider::new(&mut csg.rot.y, 0.0..=360.0).text("Rotation.y"),
); );
ui.add( ui.add(
egui::Slider::new(&mut csg.rot.z.0, 0.0..=360.0).text("Rotation.z"), egui::Slider::new(&mut csg.rot.z, 0.0..=360.0).text("Rotation.z"),
); );
ui.add(egui::Slider::new(&mut csg.scale.x, 0.0..=2.0).text("Scale.x")); ui.add(egui::Slider::new(&mut csg.scale.x, 0.0..=2.0).text("Scale.x"));
ui.add(egui::Slider::new(&mut csg.scale.y, 0.0..=2.0).text("Scale.y")); ui.add(egui::Slider::new(&mut csg.scale.y, 0.0..=2.0).text("Scale.y"));
+36 -120
View File
@@ -1,9 +1,6 @@
use cgmath::{Array, ElementWise, InnerSpace, MetricSpace, VectorSpace}; use glam::{self, FloatExt, Mat2, Mat3, Mat4, Vec2, Vec3, Vec4};
use crate::{ use crate::{CSG, Float, instruction_set::InstructionSet::*, objects::Inputs};
instruction_set::InstructionSet::*, objects::Inputs, Float, Mat2, Mat3, Mat4, Vec2, Vec3, Vec4,
CSG,
};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub(crate) struct Interpreter<'csg> { pub(crate) struct Interpreter<'csg> {
@@ -169,85 +166,61 @@ impl<'csg> Interpreter<'csg> {
} }
macro_rules! mul { macro_rules! mul {
($self:ident, $instruction:ident, $type1:ty,Float) => {
let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1 * in2);
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.mul_element_wise(in2)); $self.push(in1 * in2);
}; };
} }
macro_rules! div { macro_rules! div {
($self:ident, $instruction:ident, $type1:ty,Float) => {
let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1 / in2);
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.div_element_wise(in2)); $self.push(in1 / in2);
}; };
} }
macro_rules! add { macro_rules! add {
($self:ident, $instruction:ident,Float,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1 + in2);
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.add_element_wise(in2)); $self.push(in1 + in2);
}; };
} }
macro_rules! sub { macro_rules! sub {
($self:ident, $instruction:ident,Float,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1 - in2);
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.sub_element_wise(in2)); $self.push(in1 - in2);
}; };
} }
macro_rules! modulo { macro_rules! modulo {
($self:ident, $instruction:ident,Float,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1 % in2);
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.rem_element_wise(in2)); $self.push(in1 % in2);
}; };
} }
macro_rules! pow { macro_rules! pow {
($self:ident, $instruction:ident,Float,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1.powf(in2));
};
($self:ident, $instruction:ident, $type1:ty,Float) => { ($self:ident, $instruction:ident, $type1:ty,Float) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]); let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1.map(|x| x.powf(in2))); $self.push(in1.powf(in2));
}; };
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.zip(in2, Float::powf)); $self.push(<$type1>::from_slice(
&in1.to_array()
.iter()
.zip(in2.to_array().iter())
.map(|(x, y)| x.powf(*y))
.collect::<Vec<_>>(),
));
}; };
} }
@@ -284,17 +257,11 @@ macro_rules! clamp {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
let in3: $type3 = $self.pull($instruction.constants[2]); let in3: $type3 = $self.pull($instruction.constants[2]);
$self.push(in1.zip(in2, Float::max).zip(in3, Float::min)); $self.push(in1.clamp(in2, in3));
}; };
} }
macro_rules! mix { macro_rules! mix {
($self:ident, $instruction:ident,Float,Float,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
let in3: Float = $self.pull($instruction.constants[2]);
$self.push((in1 * ((1 as Float) - in3)) + (in2 * in3));
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty,Float) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty,Float) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
@@ -305,54 +272,37 @@ macro_rules! mix {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
let in3: $type3 = $self.pull($instruction.constants[2]); let in3: $type3 = $self.pull($instruction.constants[2]);
$self.push( $self.push((in1 * (<$type3>::splat(1 as Float) - in3)) + (in2 * in3));
(in1.mul_element_wise(<$type3>::from_value(1 as Float).sub_element_wise(in3)))
+ (in2.mul_element_wise(in3)),
);
}; };
} }
macro_rules! fma { macro_rules! fma {
($self:ident, $instruction:ident,Float,Float,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
let in3: Float = $self.pull($instruction.constants[2]);
$self.push(in1.mul_add(in2, in3));
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty, $type3:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty, $type3:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type1 = $self.pull($instruction.constants[1]); let in2: $type1 = $self.pull($instruction.constants[1]);
let in3: $type3 = $self.pull($instruction.constants[2]); let in3: $type3 = $self.pull($instruction.constants[2]);
$self.push((in1.mul_element_wise(in2)) + in3); $self.push(in1.mul_add(in2, in3));
}; };
} }
macro_rules! square { macro_rules! square {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1 * in1);
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.mul_element_wise(in1)); $self.push(in1 * in1);
}; };
} }
macro_rules! cube { macro_rules! cube {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1 * in1 * in1);
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.mul_element_wise(in1).mul_element_wise(in1)); $self.push(in1 * in1 * in1);
}; };
} }
macro_rules! len { macro_rules! len {
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.magnitude()); $self.push(in1.length());
}; };
} }
@@ -378,13 +328,9 @@ macro_rules! matinvert {
} }
macro_rules! absolute { macro_rules! absolute {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.abs());
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::abs)); $self.push(in1.abs());
}; };
} }
@@ -405,35 +351,27 @@ macro_rules! sign {
} }
macro_rules! floor { macro_rules! floor {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.floor());
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::floor)); $self.push(in1.floor());
}; };
} }
macro_rules! ceiling { macro_rules! ceiling {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.ceil());
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::ceil)); $self.push(in1.ceil());
}; };
} }
macro_rules! fract { macro_rules! fract {
($self:ident, $instruction:ident,Float) => { ($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]); let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.fract()); $self.push(in1 - in1.floor());
}; };
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::fract)); $self.push(in1.fract_gl());
}; };
} }
@@ -451,22 +389,18 @@ macro_rules! squareroot {
macro_rules! inversesquareroot { macro_rules! inversesquareroot {
($self:ident, $instruction:ident,Float) => { ($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]); let in1: Float = $self.pull($instruction.constants[0]);
$self.push((1 as Float) / in1.sqrt()); $self.push(in1.sqrt().recip());
}; };
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(|x| (1 as Float) / x.sqrt())); $self.push(in1.map(|x| x.sqrt().recip()));
}; };
} }
macro_rules! exponent { macro_rules! exponent {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.exp());
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::exp)); $self.push(in1.exp());
}; };
} }
@@ -636,50 +570,32 @@ macro_rules! hyperbolicarctangent {
} }
macro_rules! min { macro_rules! min {
($self:ident, $instruction:ident, $type1:ty,Float) => {
let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1.min(in2));
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.zip(in2, Float::min)); $self.push(in1.min(in2));
}; };
} }
macro_rules! max { macro_rules! max {
($self:ident, $instruction:ident, $type1:ty,Float) => {
let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: Float = $self.pull($instruction.constants[1]);
$self.push(in1.max(in2));
};
($self:ident, $instruction:ident, $type1:ty, $type2:ty) => { ($self:ident, $instruction:ident, $type1:ty, $type2:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
let in2: $type2 = $self.pull($instruction.constants[1]); let in2: $type2 = $self.pull($instruction.constants[1]);
$self.push(in1.zip(in2, Float::max)); $self.push(in1.max(in2));
}; };
} }
macro_rules! round { macro_rules! round {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.round());
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::round)); $self.push(in1.round());
}; };
} }
macro_rules! trunc { macro_rules! trunc {
($self:ident, $instruction:ident,Float) => {
let in1: Float = $self.pull($instruction.constants[0]);
$self.push(in1.trunc());
};
($self:ident, $instruction:ident, $type1:ty) => { ($self:ident, $instruction:ident, $type1:ty) => {
let in1: $type1 = $self.pull($instruction.constants[0]); let in1: $type1 = $self.pull($instruction.constants[0]);
$self.push(in1.map(Float::trunc)); $self.push(in1.trunc());
}; };
} }
@@ -1649,7 +1565,7 @@ impl<'csg> Interpreter<'csg> {
OPSDFSphere => { OPSDFSphere => {
let r: Float = self.pull(instruction.constants[0]); let r: Float = self.pull(instruction.constants[0]);
let p: Vec3 = self.pull(instruction.constants[1]); let p: Vec3 = self.pull(instruction.constants[1]);
self.push(p.magnitude() - r); self.push(p.length() - r);
}, },
OPSDFBox => { OPSDFBox => {
@@ -1657,7 +1573,7 @@ impl<'csg> Interpreter<'csg> {
let p: Vec3 = self.pull(instruction.constants[1]); let p: Vec3 = self.pull(instruction.constants[1]);
let q = p.map(Float::abs) - r; let q = p.map(Float::abs) - r;
self.push( self.push(
(q.map(|x| x.max(0 as Float))).magnitude() + q.x.max(q.y.max(q.z)).min(0.), (q.map(|x| x.max(0 as Float))).length() + q.x.max(q.y.max(q.z)).min(0.),
); );
}, },
@@ -1665,7 +1581,7 @@ impl<'csg> Interpreter<'csg> {
let t: Vec2 = self.pull(instruction.constants[0]); let t: Vec2 = self.pull(instruction.constants[0]);
let p: Vec3 = self.pull(instruction.constants[1]); let p: Vec3 = self.pull(instruction.constants[1]);
let q = Vec2::new(((p.x * p.x) + (p.z * p.z)).sqrt() - t.x, p.y); let q = Vec2::new(((p.x * p.x) + (p.z * p.z)).sqrt() - t.x, p.y);
self.push(q.magnitude() - t.y); self.push(q.length() - t.y);
}, },
OPNop => {}, OPNop => {},
+228 -284
View File
@@ -1,8 +1,7 @@
#![feature(variant_count)] #![feature(variant_count)]
use std::{ use std::{
default,
error::Error, error::Error,
fs::{remove_file, rename, File}, fs::{File, remove_file, rename},
io::{Cursor, Read, Write}, io::{Cursor, Read, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
@@ -12,39 +11,40 @@ use std::{
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use egui_winit_vulkano::{Gui, GuiConfig}; use egui_winit_vulkano::{Gui, GuiConfig};
use foldhash::{HashMap, HashMapExt}; use foldhash::{HashMap, HashMapExt};
use glam::{self, vec3, EulerRot, Mat3, Mat4, Vec3}; use glam::{self, EulerRot, Mat3, Mat4, Vec3, vec3};
use instruction_set::InputTypes; use instruction_set::InputTypes;
use rayon::prelude::*; use rayon::prelude::*;
use vulkano::{ use vulkano::{
Validated, Version, VulkanError, VulkanLibrary,
buffer::{ buffer::{
allocator::{SubbufferAllocator, SubbufferAllocatorCreateInfo},
Buffer, BufferCreateInfo, BufferUsage, Subbuffer, Buffer, BufferCreateInfo, BufferUsage, Subbuffer,
allocator::{SubbufferAllocator, SubbufferAllocatorCreateInfo},
}, },
command_buffer::{ command_buffer::{
allocator::StandardCommandBufferAllocator, AutoCommandBufferBuilder, CommandBufferUsage, AutoCommandBufferBuilder, CommandBufferUsage, CopyBufferInfo, PrimaryCommandBufferAbstract,
CopyBufferInfo, PrimaryCommandBufferAbstract, RenderPassBeginInfo, SubpassBeginInfo, RenderPassBeginInfo, SubpassBeginInfo, SubpassContents,
SubpassContents, allocator::StandardCommandBufferAllocator,
}, },
descriptor_set::{ descriptor_set::{
allocator::StandardDescriptorSetAllocator, DescriptorSet, WriteDescriptorSet, DescriptorSet, WriteDescriptorSet, allocator::StandardDescriptorSetAllocator,
}, },
device::{ device::{
physical::PhysicalDeviceType, Device, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Device, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, DeviceOwned, Queue,
DeviceOwned, Queue, QueueCreateInfo, QueueFlags, QueueCreateInfo, QueueFlags, physical::PhysicalDeviceType,
}, },
format::Format, format::Format,
image::{ image::{Image, ImageCreateInfo, ImageType, ImageUsage, SampleCount, view::ImageView},
view::{ImageView, ImageViewCreateInfo},
Image, ImageCreateInfo, ImageType, ImageUsage, SampleCount,
},
instance::{Instance, InstanceCreateInfo, InstanceExtensions}, instance::{Instance, InstanceCreateInfo, InstanceExtensions},
memory::allocator::{ memory::allocator::{
AllocationCreateInfo, MemoryAllocatePreference, MemoryTypeFilter, StandardMemoryAllocator, AllocationCreateInfo, MemoryAllocatePreference, MemoryTypeFilter, StandardMemoryAllocator,
}, },
pipeline::{ pipeline::{
ComputePipeline, GraphicsPipeline, Pipeline, PipelineBindPoint, PipelineLayout,
PipelineShaderStageCreateInfo,
cache::{PipelineCache, PipelineCacheCreateInfo}, cache::{PipelineCache, PipelineCacheCreateInfo},
compute::ComputePipelineCreateInfo, compute::ComputePipelineCreateInfo,
graphics::{ graphics::{
GraphicsPipelineCreateInfo,
color_blend::{ColorBlendAttachmentState, ColorBlendState}, color_blend::{ColorBlendAttachmentState, ColorBlendState},
depth_stencil::{DepthState, DepthStencilState}, depth_stencil::{DepthState, DepthStencilState},
input_assembly::InputAssemblyState, input_assembly::InputAssemblyState,
@@ -52,28 +52,24 @@ use vulkano::{
rasterization::{CullMode, FrontFace::Clockwise, RasterizationState}, rasterization::{CullMode, FrontFace::Clockwise, RasterizationState},
vertex_input::{Vertex, VertexDefinition}, vertex_input::{Vertex, VertexDefinition},
viewport::{Viewport, ViewportState}, viewport::{Viewport, ViewportState},
GraphicsPipelineCreateInfo,
}, },
layout::PipelineDescriptorSetLayoutCreateInfo, layout::PipelineDescriptorSetLayoutCreateInfo,
ComputePipeline, GraphicsPipeline, Pipeline, PipelineBindPoint, PipelineLayout,
PipelineShaderStageCreateInfo,
}, },
render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass, Subpass}, render_pass::{Framebuffer, FramebufferCreateInfo, RenderPass, Subpass},
shader::{EntryPoint, ShaderModule, SpecializationConstant}, shader::{ShaderModule, SpecializationConstant},
swapchain::{ swapchain::{
acquire_next_image, PresentMode, Surface, Swapchain, SwapchainCreateInfo, PresentMode, Surface, Swapchain, SwapchainCreateInfo, SwapchainPresentInfo,
SwapchainPresentInfo, acquire_next_image,
}, },
sync::{self, GpuFuture}, sync::{self, GpuFuture},
Validated, Version, VulkanError, VulkanLibrary,
}; };
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
dpi::PhysicalSize, dpi::PhysicalSize,
event::{DeviceEvent, ElementState, Event, MouseButton, WindowEvent}, event::{DeviceEvent, ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, event_loop::{ActiveEventLoop, EventLoop},
keyboard::{KeyCode, PhysicalKey}, keyboard::{KeyCode, PhysicalKey},
window::{Window, WindowAttributes}, window::Window,
}; };
mod gui; mod gui;
@@ -152,25 +148,16 @@ struct ShaderModules {
compute_shader: Arc<ShaderModule>, compute_shader: Arc<ShaderModule>,
} }
struct ShaderEntryPoints {
mesh_vs: EntryPoint,
mesh_fs: EntryPoint,
implicit_ts: EntryPoint,
implicit_ms: EntryPoint,
implicit_fs: EntryPoint,
}
struct RenderContext { struct RenderContext {
window: Arc<Window>, window: Arc<Window>,
swapchain: Arc<Swapchain>, swapchain: Arc<Swapchain>,
render_pass: Arc<RenderPass>, render_pass: Arc<RenderPass>,
framebuffers: Vec<Arc<Framebuffer>>, framebuffers: Vec<Arc<Framebuffer>>,
shader_entrypoints: ShaderEntryPoints,
shader_modules: ShaderModules, shader_modules: ShaderModules,
pipeline_layout: Arc<PipelineLayout>,
compute_pipeline: Arc<ComputePipeline>, compute_pipeline: Arc<ComputePipeline>,
mesh_pipeline: Arc<GraphicsPipeline>, mesh_pipeline: Arc<GraphicsPipeline>,
implicit_pipeline: Arc<GraphicsPipeline>, implicit_pipeline: Arc<GraphicsPipeline>,
viewport: Viewport,
recreate_swapchain: bool, recreate_swapchain: bool,
previous_frame_end: Option<Box<dyn GpuFuture>>, previous_frame_end: Option<Box<dyn GpuFuture>>,
gui: Gui, gui: Gui,
@@ -191,9 +178,7 @@ impl App {
let library = VulkanLibrary::new().expect("Vulkan is not installed???"); let library = VulkanLibrary::new().expect("Vulkan is not installed???");
let required_extensions = Surface::required_extensions(event_loop).unwrap(); let required_extensions = Surface::required_extensions(event_loop).unwrap();
let instance = Instance::new( let instance = Instance::new(library, InstanceCreateInfo {
library,
InstanceCreateInfo {
enabled_extensions: InstanceExtensions { enabled_extensions: InstanceExtensions {
..required_extensions ..required_extensions
}, },
@@ -202,8 +187,7 @@ impl App {
application_name: Some(env!("CARGO_PKG_NAME").to_owned()), application_name: Some(env!("CARGO_PKG_NAME").to_owned()),
application_version: app_version(), application_version: app_version(),
..Default::default() ..Default::default()
}, })
)
.unwrap(); .unwrap();
let device_extensions = DeviceExtensions { let device_extensions = DeviceExtensions {
@@ -265,9 +249,7 @@ impl App {
physical_device.properties().device_type, physical_device.properties().device_type,
); );
let (device, mut queues) = Device::new( let (device, mut queues) = Device::new(physical_device, DeviceCreateInfo {
physical_device,
DeviceCreateInfo {
enabled_extensions: device_extensions, enabled_extensions: device_extensions,
queue_create_infos: vec![ queue_create_infos: vec![
QueueCreateInfo { QueueCreateInfo {
@@ -289,11 +271,11 @@ impl App {
storage_buffer8_bit_access: true, storage_buffer8_bit_access: true,
geometry_shader: true, geometry_shader: true,
primitive_fragment_shading_rate: true, primitive_fragment_shading_rate: true,
maintenance4: true,
..DeviceFeatures::empty() ..DeviceFeatures::empty()
}, },
..Default::default() ..Default::default()
}, })
)
.expect("Unable to initialize device"); .expect("Unable to initialize device");
let graphics_queue = queues.next().expect("Unable to retrieve queues"); let graphics_queue = queues.next().expect("Unable to retrieve queues");
@@ -309,15 +291,13 @@ impl App {
Default::default(), Default::default(),
)); ));
let uniform_buffer_allocator = SubbufferAllocator::new( let uniform_buffer_allocator =
memory_allocator.clone(), SubbufferAllocator::new(memory_allocator.clone(), SubbufferAllocatorCreateInfo {
SubbufferAllocatorCreateInfo {
buffer_usage: BufferUsage::UNIFORM_BUFFER | BufferUsage::STORAGE_BUFFER, buffer_usage: BufferUsage::UNIFORM_BUFFER | BufferUsage::STORAGE_BUFFER,
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE memory_type_filter: MemoryTypeFilter::PREFER_DEVICE
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE, | MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
..Default::default() ..Default::default()
}, });
);
let pipeline_cache = get_pipeline_cache(device.clone()); let pipeline_cache = get_pipeline_cache(device.clone());
@@ -433,10 +413,7 @@ impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) { fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = Arc::new( let window = Arc::new(
event_loop event_loop
.create_window(WindowAttributes { .create_window(Window::default_attributes().with_title("Implicit Surfaces"))
title: "Implicit Surfaces".to_owned(),
..Window::default_attributes()
})
.unwrap(), .unwrap(),
); );
let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap(); let surface = Surface::from_window(self.instance.clone(), window.clone()).unwrap();
@@ -455,10 +432,7 @@ impl ApplicationHandler for App {
.surface_formats(&surface, Default::default()) .surface_formats(&surface, Default::default())
.unwrap()[0]; .unwrap()[0];
Swapchain::new( Swapchain::new(self.device.clone(), surface.clone(), SwapchainCreateInfo {
self.device.clone(),
surface.clone(),
SwapchainCreateInfo {
min_image_count: 3 min_image_count: 3
.max(surface_capabilities.min_image_count) .max(surface_capabilities.min_image_count)
.min(surface_capabilities.max_image_count.unwrap_or(u32::MAX)), .min(surface_capabilities.max_image_count.unwrap_or(u32::MAX)),
@@ -466,7 +440,7 @@ impl ApplicationHandler for App {
image_format, image_format,
image_extent: window_size.into(), image_extent: window_size.into(),
image_usage: ImageUsage::COLOR_ATTACHMENT, image_usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::TRANSFER_DST,
composite_alpha: surface_capabilities composite_alpha: surface_capabilities
.supported_composite_alpha .supported_composite_alpha
@@ -477,8 +451,7 @@ impl ApplicationHandler for App {
present_mode: PresentMode::Fifo, present_mode: PresentMode::Fifo,
..Default::default() ..Default::default()
}, })
)
.unwrap() .unwrap()
}; };
@@ -556,32 +529,11 @@ impl ApplicationHandler for App {
shader_modules.compute_shader.entry_point("main").unwrap(), shader_modules.compute_shader.entry_point("main").unwrap(),
); );
let mesh_vs_stage =
PipelineShaderStageCreateInfo::new(shader_modules.mesh_vs.entry_point("main").unwrap());
let mesh_fs_stage =
PipelineShaderStageCreateInfo::new(shader_modules.mesh_fs.entry_point("main").unwrap());
let implicit_ms_stage = PipelineShaderStageCreateInfo::new(
shader_modules.implicit_ms.entry_point("main").unwrap(),
);
let implicit_ts_stage = PipelineShaderStageCreateInfo::new(
shader_modules.implicit_ts.entry_point("main").unwrap(),
);
let implicit_fs_stage = PipelineShaderStageCreateInfo::new(
shader_modules.implicit_fs.entry_point("main").unwrap(),
);
use vulkano::pipeline::ComputePipeline; use vulkano::pipeline::ComputePipeline;
let pipeline_layout = PipelineLayout::new( let compute_pipeline_layout = PipelineLayout::new(
self.device.clone(), self.device.clone(),
PipelineDescriptorSetLayoutCreateInfo::from_stages([ PipelineDescriptorSetLayoutCreateInfo::from_stages([&compute_stage])
&mesh_vs_stage,
&mesh_fs_stage,
&implicit_ms_stage,
&implicit_ts_stage,
&implicit_fs_stage,
&compute_stage,
])
.into_pipeline_layout_create_info(self.device.clone()) .into_pipeline_layout_create_info(self.device.clone())
.unwrap(), .unwrap(),
) )
@@ -590,7 +542,7 @@ impl ApplicationHandler for App {
let compute_pipeline = ComputePipeline::new( let compute_pipeline = ComputePipeline::new(
self.device.clone(), self.device.clone(),
None, None,
ComputePipelineCreateInfo::stage_layout(compute_stage, pipeline_layout.clone()), ComputePipelineCreateInfo::stage_layout(compute_stage, compute_pipeline_layout.clone()),
) )
.expect("failed to create compute pipeline"); .expect("failed to create compute pipeline");
@@ -630,13 +582,11 @@ impl ApplicationHandler for App {
.unwrap(); .unwrap();
//let [RES_X, RES_Y] = images[0].dimensions().width_height(); //let [RES_X, RES_Y] = images[0].dimensions().width_height();
let ([mesh_pipeline, implicit_pipeline], framebuffers, shader_entrypoints) = let ([mesh_pipeline, implicit_pipeline], framebuffers) = window_size_dependent_setup(
window_size_dependent_setup(
window_size, window_size,
&images, &images,
&render_pass, &render_pass,
&self.memory_allocator, &self.memory_allocator,
&pipeline_layout,
&self.pipeline_cache, &self.pipeline_cache,
&shader_modules, &shader_modules,
&self.gstate.debug, &self.gstate.debug,
@@ -667,17 +617,22 @@ impl ApplicationHandler for App {
false, false,
); );
let viewport = Viewport {
offset: [0.0, 0.0],
extent: window_size.into(),
depth_range: 0.0..=1.0,
};
self.rcx = Some(RenderContext { self.rcx = Some(RenderContext {
window, window,
swapchain, swapchain,
render_pass, render_pass,
framebuffers, framebuffers,
shader_entrypoints,
shader_modules, shader_modules,
pipeline_layout,
compute_pipeline, compute_pipeline,
mesh_pipeline, mesh_pipeline,
implicit_pipeline, implicit_pipeline,
viewport,
recreate_swapchain: false, recreate_swapchain: false,
previous_frame_end, previous_frame_end,
gui, gui,
@@ -757,13 +712,17 @@ impl ApplicationHandler for App {
_ => {}, _ => {},
}, },
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => {
drop(rcx);
self.redraw(); self.redraw();
}, },
_ => {}, _ => {},
} }
} }
} }
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
let rcx = self.rcx.as_mut().unwrap();
rcx.window.request_redraw();
}
} }
impl App { impl App {
@@ -801,20 +760,17 @@ impl App {
.expect("Failed to recreate swapchain"); .expect("Failed to recreate swapchain");
rcx.swapchain = new_swapchain; rcx.swapchain = new_swapchain;
( ([rcx.mesh_pipeline, rcx.implicit_pipeline], rcx.framebuffers) =
[rcx.mesh_pipeline, rcx.implicit_pipeline], window_size_dependent_setup(
rcx.framebuffers,
rcx.shader_entrypoints,
) = window_size_dependent_setup(
window_size, window_size,
&new_images, &new_images,
&rcx.render_pass, &rcx.render_pass,
&self.memory_allocator, &self.memory_allocator,
&rcx.pipeline_layout,
&self.pipeline_cache, &self.pipeline_cache,
&rcx.shader_modules, &rcx.shader_modules,
&self.gstate.debug, &self.gstate.debug,
); );
rcx.viewport.extent = window_size.into();
rcx.recreate_swapchain = false; rcx.recreate_swapchain = false;
} }
@@ -963,19 +919,19 @@ impl App {
fake_csg.push(CSG { fake_csg.push(CSG {
name: format!("fuzz_{i}"), name: format!("fuzz_{i}"),
parts: vec![ parts: vec![
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPMulVec3Float, vec![
InstructionSet::OPMulVec3Float, Inputs::Variable,
vec![Inputs::Variable, Inputs::Float(0.9)], Inputs::Float(0.9),
), ]),
CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]), CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![
InstructionSet::OPAddVec3Vec3, Inputs::Variable,
vec![Inputs::Variable, Inputs::Vec3(vec3(-0.7, i as f32, -0.7))], Inputs::Vec3(vec3(-0.7, i as f32, -0.7)),
), ]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPSDFSphere, vec![
InstructionSet::OPSDFSphere, Inputs::Float(0.5),
vec![Inputs::Float(0.5), Inputs::Variable], Inputs::Variable,
), ]),
//CSGPart::opcode(InstructionSet::OPNop,vec![]), //CSGPart::opcode(InstructionSet::OPNop,vec![]),
//CSGPart::opcode(InstructionSet::OPDupVec3, //CSGPart::opcode(InstructionSet::OPDupVec3,
// vec![Inputs::Variable]), // vec![Inputs::Variable]),
@@ -985,21 +941,21 @@ impl App {
// CSGPart::opcode(InstructionSet::OPAddVec3Vec3, // CSGPart::opcode(InstructionSet::OPAddVec3Vec3,
// vec![Inputs::Variable, Inputs::Vec3([-0.0, -0.0, // vec![Inputs::Variable, Inputs::Vec3([-0.0, -0.0,
// -0.0].into())]), // -0.0].into())]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPSDFSphere, vec![
InstructionSet::OPSDFSphere, Inputs::Float(1.2),
vec![Inputs::Float(1.2), Inputs::Variable], Inputs::Variable,
), ]),
//CSGPart::opcode(InstructionSet::OPSDFBox, //CSGPart::opcode(InstructionSet::OPSDFBox,
// vec![Inputs::Variable, // vec![Inputs::Variable,
// Inputs::Vec3([0.7, 0.7, 0.7].into())]), // Inputs::Vec3([0.7, 0.7, 0.7].into())]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPMinFloat, vec![
InstructionSet::OPMinFloat, Inputs::Variable,
vec![Inputs::Variable, Inputs::Variable], Inputs::Variable,
), ]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPDivFloatFloat, vec![
InstructionSet::OPDivFloatFloat, Inputs::Variable,
vec![Inputs::Variable, Inputs::Float(0.9)], Inputs::Float(0.9),
), ]),
CSGPart::opcode(InstructionSet::OPStop, vec![Inputs::Variable]), CSGPart::opcode(InstructionSet::OPStop, vec![Inputs::Variable]),
], ],
pos: Vec3::ZERO, pos: Vec3::ZERO,
@@ -1022,7 +978,7 @@ impl App {
.allocate_slice((fake_csg.len() + 1) as u64) .allocate_slice((fake_csg.len() + 1) as u64)
.unwrap(); .unwrap();
let compute_layout = rcx.compute_pipeline.layout().set_layouts()[0]; let compute_layout = &rcx.compute_pipeline.layout().set_layouts()[0];
let compute_set = DescriptorSet::new( let compute_set = DescriptorSet::new(
self.descriptor_set_allocator.clone(), self.descriptor_set_allocator.clone(),
compute_layout.clone(), compute_layout.clone(),
@@ -1090,97 +1046,109 @@ impl App {
} }
let (image_index, suboptimal, acquire_future) = let (image_index, suboptimal, acquire_future) =
match acquire_next_image(swapchain.clone(), None) { match acquire_next_image(rcx.swapchain.clone(), None).map_err(Validated::unwrap) {
Ok(r) => r, Ok(r) => r,
Err(AcquireError::OutOfDate) => { Err(VulkanError::OutOfDate) => {
recreate_swapchain = true; rcx.recreate_swapchain = true;
return; return;
}, },
Err(e) => panic!("Failed to acquire next image: {e:?}"), Err(e) => panic!("Failed to acquire next image: {e}"),
}; };
if suboptimal { if suboptimal {
recreate_swapchain = true; rcx.recreate_swapchain = true;
} }
gui_up(&mut gui, &mut gstate); gui_up(&mut rcx.gui, &mut self.gstate);
let mut builder = AutoCommandBufferBuilder::primary( let mut builder = AutoCommandBufferBuilder::primary(
&command_buffer_allocator, self.command_buffer_allocator.clone(),
queue.queue_family_index(), self.graphics_queue.queue_family_index(),
CommandBufferUsage::OneTimeSubmit, CommandBufferUsage::OneTimeSubmit,
) )
.unwrap(); .unwrap();
let guicb = gui.draw_on_subpass_image(dimensions.into()); let guicb = rcx.gui.draw_on_subpass_image(window_size.into());
builder builder
.begin_render_pass( .begin_render_pass(
RenderPassBeginInfo { RenderPassBeginInfo {
clear_values: vec![Some([0.12, 0.1, 0.1, 1.0].into()), None, Some(1.0.into())], clear_values: vec![Some([0.12, 0.1, 0.1, 1.0].into()), None, Some(1.0.into())],
..RenderPassBeginInfo::framebuffer(framebuffers[image_index as usize].clone()) ..RenderPassBeginInfo::framebuffer(
rcx.framebuffers[image_index as usize].clone(),
)
}, },
SubpassBeginInfo { SubpassBeginInfo {
contents: SubpassContents::Inline, contents: SubpassContents::Inline,
..default::Default() ..Default::default()
}, },
) )
.unwrap() .unwrap()
.set_viewport(0, [viewport.clone()]) .set_viewport(0, [rcx.viewport.clone()].into_iter().collect())
.bind_pipeline_graphics(mesh_pipeline.clone()) .unwrap()
.bind_pipeline_graphics(rcx.mesh_pipeline.clone())
.unwrap()
.bind_descriptor_sets( .bind_descriptor_sets(
PipelineBindPoint::Graphics, PipelineBindPoint::Graphics,
mesh_pipeline.layout().clone(), rcx.mesh_pipeline.layout().clone(),
0, 0,
mesh_set, mesh_set,
); )
.unwrap();
for object in &gstate.meshes { for object in &self.gstate.meshes {
push_constants.world = push_constants.world = (Mat4::from_translation(object.pos * 0.01)
(Matrix4::from_translation(object.pos * 0.01 - Point3::origin()) * Mat4::from_euler(
* Matrix4::from(object.rot) EulerRot::XYZ,
* Matrix4::from_nonuniform_scale( object.rot.x.to_radians(),
object.scale.x, object.rot.y.to_radians(),
object.scale.y, object.rot.z.to_radians(),
object.scale.z, )
)) * Mat4::from_scale(object.scale))
.into(); .to_cols_array_2d();
builder builder
.bind_vertex_buffers(0, object.vertices.clone()) .bind_vertex_buffers(0, object.vertices.clone())
.unwrap()
.bind_index_buffer(object.indices.clone()) .bind_index_buffer(object.indices.clone())
.push_constants(mesh_pipeline.layout().clone(), 0, push_constants) .unwrap()
.draw_indexed(object.indices.len() as u32, 1, 0, 0, 0) .push_constants(rcx.mesh_pipeline.layout().clone(), 0, push_constants)
.unwrap(); .unwrap();
unsafe { builder.draw_indexed(object.indices.len() as u32, 1, 0, 0, 0) }.unwrap();
} }
builder builder
.bind_pipeline_graphics(implicit_pipeline.clone()) .bind_pipeline_graphics(rcx.implicit_pipeline.clone())
.unwrap()
.bind_descriptor_sets( .bind_descriptor_sets(
PipelineBindPoint::Graphics, PipelineBindPoint::Graphics,
implicit_pipeline.layout().clone(), rcx.implicit_pipeline.layout().clone(),
0, 0,
implicit_set, implicit_set,
); )
for csg in &gstate.csg {
push_constants.world = (Matrix4::from_translation(csg.pos * 0.01 - Point3::origin())
* Matrix4::from(csg.rot)
* Matrix4::from_nonuniform_scale(csg.scale.x, csg.scale.y, csg.scale.z))
.into();
builder
.push_constants(implicit_pipeline.layout().clone(), 0, push_constants)
.draw_mesh([1, 1, 2])
.unwrap(); .unwrap();
for csg in &self.gstate.csg {
push_constants.world = (Mat4::from_translation(csg.pos * 0.01)
* Mat4::from_euler(
EulerRot::XYZ,
csg.rot.x.to_radians(),
csg.rot.y.to_radians(),
csg.rot.z.to_radians(),
)
* Mat4::from_scale(csg.scale))
.to_cols_array_2d();
builder
.push_constants(rcx.implicit_pipeline.layout().clone(), 0, push_constants)
.unwrap();
unsafe { builder.draw_mesh_tasks([1, 1, 2]) }.unwrap();
} }
builder builder
.next_subpass( .next_subpass(Default::default(), SubpassBeginInfo {
Default::default(),
SubpassBeginInfo {
contents: SubpassContents::SecondaryCommandBuffers, contents: SubpassContents::SecondaryCommandBuffers,
..default::Default() ..Default::default()
}, })
)
.unwrap() .unwrap()
.execute_commands(guicb) .execute_commands(guicb)
.unwrap() .unwrap()
@@ -1189,29 +1157,30 @@ impl App {
let command_buffer = builder.build().unwrap(); let command_buffer = builder.build().unwrap();
let future = previous_frame_end let future = rcx
.previous_frame_end
.take() .take()
.unwrap() .unwrap()
.join(acquire_future) .join(acquire_future)
.then_execute(queue.clone(), command_buffer) .then_execute(self.graphics_queue.clone(), command_buffer)
.unwrap() .unwrap()
.then_swapchain_present( .then_swapchain_present(
queue.clone(), self.graphics_queue.clone(),
SwapchainPresentInfo::swapchain_image_index(swapchain.clone(), image_index), SwapchainPresentInfo::swapchain_image_index(rcx.swapchain.clone(), image_index),
) )
.then_signal_fence_and_flush(); .then_signal_fence_and_flush();
match future { match future.map_err(Validated::unwrap) {
Ok(future) => { Ok(future) => {
previous_frame_end = Some(future.boxed()); rcx.previous_frame_end = Some(future.boxed());
}, },
Err(FlushError::OutOfDate) => { Err(VulkanError::OutOfDate) => {
recreate_swapchain = true; rcx.recreate_swapchain = true;
previous_frame_end = Some(sync::now(device.clone()).boxed()); rcx.previous_frame_end = Some(sync::now(self.device.clone()).boxed());
}, },
Err(e) => { Err(e) => {
println!("Failed to flush future: {e:?}"); println!("Failed to flush future: {e:?}");
previous_frame_end = Some(sync::now(device.clone()).boxed()); rcx.previous_frame_end = Some(sync::now(self.device.clone()).boxed());
}, },
} }
} }
@@ -1224,15 +1193,10 @@ fn window_size_dependent_setup(
images: &[Arc<Image>], images: &[Arc<Image>],
render_pass: &Arc<RenderPass>, render_pass: &Arc<RenderPass>,
allocator: &Arc<StandardMemoryAllocator>, allocator: &Arc<StandardMemoryAllocator>,
layout: &Arc<PipelineLayout>,
cache: &Arc<PipelineCache>, cache: &Arc<PipelineCache>,
shader_modules: &ShaderModules, shader_modules: &ShaderModules,
debug: &PreviousDebug, debug: &PreviousDebug,
) -> ( ) -> ([Arc<GraphicsPipeline>; 2], Vec<Arc<Framebuffer>>) {
[Arc<GraphicsPipeline>; 2],
Vec<Arc<Framebuffer>>,
ShaderEntryPoints,
) {
let device = allocator.device(); let device = allocator.device();
let depth_buffer = ImageView::new_default( let depth_buffer = ImageView::new_default(
@@ -1272,21 +1236,12 @@ fn window_size_dependent_setup(
let framebuffers = images let framebuffers = images
.iter() .iter()
.map(|image| { .map(|image| {
let view = ImageView::new( let view = ImageView::new_default(image.clone()).unwrap();
image.clone(),
ImageViewCreateInfo { Framebuffer::new(render_pass.clone(), FramebufferCreateInfo {
usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::TRANSFER_DST,
..ImageViewCreateInfo::from_image(&image)
},
)
.unwrap();
Framebuffer::new(
render_pass.clone(),
FramebufferCreateInfo {
attachments: vec![intermediary.clone(), view, depth_buffer.clone()], attachments: vec![intermediary.clone(), view, depth_buffer.clone()],
..Default::default() ..Default::default()
}, })
)
.unwrap() .unwrap()
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -1326,50 +1281,65 @@ fn window_size_dependent_setup(
let specs = spec_constants; let specs = spec_constants;
let shader_entrypoints = ShaderEntryPoints { let mesh_vs_entry = shader_modules
mesh_vs: shader_modules
.mesh_vs .mesh_vs
.specialize(specs.clone()) .specialize(specs.clone())
.unwrap() .unwrap()
.single_entry_point() .single_entry_point()
.unwrap(), .unwrap();
mesh_fs: shader_modules
let vertex_input_state = [OVertex::per_vertex()].definition(&mesh_vs_entry).unwrap();
let mesh_vs_info = PipelineShaderStageCreateInfo::new(mesh_vs_entry);
let mesh_fs_info = PipelineShaderStageCreateInfo::new(
shader_modules
.mesh_fs .mesh_fs
.specialize(specs.clone()) .specialize(specs.clone())
.unwrap() .unwrap()
.single_entry_point() .single_entry_point()
.unwrap(), .unwrap(),
implicit_ts: shader_modules );
let implicit_ts_info = PipelineShaderStageCreateInfo::new(
shader_modules
.implicit_ts .implicit_ts
.specialize(specs.clone()) .specialize(specs.clone())
.unwrap() .unwrap()
.single_entry_point() .single_entry_point()
.unwrap(), .unwrap(),
implicit_ms: shader_modules );
let implicit_ms_info = PipelineShaderStageCreateInfo::new(
shader_modules
.implicit_ms .implicit_ms
.specialize(specs.clone()) .specialize(specs.clone())
.unwrap() .unwrap()
.single_entry_point() .single_entry_point()
.unwrap(), .unwrap(),
implicit_fs: shader_modules );
let implicit_fs_info = PipelineShaderStageCreateInfo::new(
shader_modules
.implicit_fs .implicit_fs
.specialize(specs.clone()) .specialize(specs.clone())
.unwrap() .unwrap()
.single_entry_point() .single_entry_point()
.unwrap(), .unwrap(),
}; );
let mesh_pipeline = { let layout = PipelineLayout::new(
let vertex_input_state = [OVertex::per_vertex()] device.clone(),
.definition(&shader_entrypoints.mesh_vs) PipelineDescriptorSetLayoutCreateInfo::from_stages([
&mesh_vs_info,
&mesh_fs_info,
&implicit_ts_info,
&implicit_ms_info,
&implicit_fs_info,
])
.into_pipeline_layout_create_info(device.clone())
.unwrap(),
)
.unwrap(); .unwrap();
let stages = [ let mesh_pipeline = {
PipelineShaderStageCreateInfo::new(shader_entrypoints.mesh_vs.clone()), let stages = [mesh_vs_info, mesh_fs_info].into_iter().collect();
PipelineShaderStageCreateInfo::new(shader_entrypoints.mesh_fs.clone()),
]
.into_iter()
.collect();
let subpass = Subpass::from(render_pass.clone(), 0).unwrap(); let subpass = Subpass::from(render_pass.clone(), 0).unwrap();
@@ -1418,18 +1388,9 @@ fn window_size_dependent_setup(
let implicit_pipeline = { let implicit_pipeline = {
let stages = if debug.brute_force { let stages = if debug.brute_force {
[ [implicit_ms_info, implicit_fs_info].into_iter().collect()
PipelineShaderStageCreateInfo::new(shader_entrypoints.implicit_ms.clone()),
PipelineShaderStageCreateInfo::new(shader_entrypoints.implicit_fs.clone()),
]
.into_iter()
.collect()
} else { } else {
[ [implicit_ts_info, implicit_ms_info, implicit_fs_info]
PipelineShaderStageCreateInfo::new(shader_entrypoints.implicit_ts.clone()),
PipelineShaderStageCreateInfo::new(shader_entrypoints.implicit_ms.clone()),
PipelineShaderStageCreateInfo::new(shader_entrypoints.implicit_fs.clone()),
]
.into_iter() .into_iter()
.collect() .collect()
}; };
@@ -1442,7 +1403,7 @@ fn window_size_dependent_setup(
GraphicsPipelineCreateInfo { GraphicsPipelineCreateInfo {
stages, stages,
vertex_input_state: None, vertex_input_state: None,
input_assembly_state: Some(InputAssemblyState::default()), input_assembly_state: None,
viewport_state: Some(ViewportState { viewport_state: Some(ViewportState {
viewports: [Viewport { viewports: [Viewport {
offset: [0.0, 0.0], offset: [0.0, 0.0],
@@ -1482,11 +1443,7 @@ fn window_size_dependent_setup(
dump_pipeline_cache(cache.clone()); dump_pipeline_cache(cache.clone());
( ([mesh_pipeline, implicit_pipeline], framebuffers)
[mesh_pipeline, implicit_pipeline],
framebuffers,
shader_entrypoints,
)
} }
#[repr(C)] #[repr(C)]
@@ -1576,16 +1533,6 @@ where
buffer buffer
} }
fn f64tof32<const A: usize>(input: [[f64; A]; A]) -> [[f32; A]; A] {
let mut out = [[0_f32; A]; A];
for x in 0..input.len() {
for y in 0..input.len() {
out[x][y] = input[x][y] as f32;
}
}
out
}
fn object_size_dependent_setup( fn object_size_dependent_setup(
allocator: Arc<StandardMemoryAllocator>, allocator: Arc<StandardMemoryAllocator>,
state: &Vec<CSG>, state: &Vec<CSG>,
@@ -1621,19 +1568,19 @@ fn object_size_dependent_setup(
]; ];
let example = vec![ let example = vec![
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPMulVec3Float, vec![
InstructionSet::OPMulVec3Float, Inputs::Variable,
vec![Inputs::Variable, Inputs::Float(0.9)], Inputs::Float(0.9),
), ]),
CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]), CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![
InstructionSet::OPAddVec3Vec3, Inputs::Variable,
vec![Inputs::Variable, Inputs::Vec3([-0.7, -1.2, -0.7].into())], Inputs::Vec3([-0.7, -1.2, -0.7].into()),
), ]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPSDFSphere, vec![
InstructionSet::OPSDFSphere, Inputs::Float(0.5),
vec![Inputs::Float(0.5), Inputs::Variable], Inputs::Variable,
), ]),
//CSGPart::opcode(InstructionSet::OPNop,vec![]), //CSGPart::opcode(InstructionSet::OPNop,vec![]),
//CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]), //CSGPart::opcode(InstructionSet::OPDupVec3, vec![Inputs::Variable]),
//CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable, //CSGPart::opcode(InstructionSet::OPAddVec3Vec3, vec![Inputs::Variable,
@@ -1642,20 +1589,20 @@ fn object_size_dependent_setup(
// Inputs::Vec3([-0.0, -0.0, -0.0].into())]), // Inputs::Vec3([-0.0, -0.0, -0.0].into())]),
// CSGPart::opcode(InstructionSet::OPSDFSphere,vec![Inputs::Float(1.2), // CSGPart::opcode(InstructionSet::OPSDFSphere,vec![Inputs::Float(1.2),
// Inputs::Variable]), // Inputs::Variable]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPSDFTorus, vec![
InstructionSet::OPSDFTorus, Inputs::Vec2([0.7, 0.4].into()),
vec![Inputs::Vec2([0.7, 0.4].into()), Inputs::Variable], Inputs::Variable,
), ]),
//CSGPart::opcode(InstructionSet::OPSDFBox, vec![Inputs::Vec3([0.7, 0.4, 0.7].into()), //CSGPart::opcode(InstructionSet::OPSDFBox, vec![Inputs::Vec3([0.7, 0.4, 0.7].into()),
// Inputs::Variable]), // Inputs::Variable]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPMinFloat, vec![
InstructionSet::OPMinFloat, Inputs::Variable,
vec![Inputs::Variable, Inputs::Variable], Inputs::Variable,
), ]),
CSGPart::opcode( CSGPart::opcode(InstructionSet::OPDivFloatFloat, vec![
InstructionSet::OPDivFloatFloat, Inputs::Variable,
vec![Inputs::Variable, Inputs::Float(0.9)], Inputs::Float(0.9),
), ]),
CSGPart::opcode(InstructionSet::OPStop, vec![Inputs::Variable]), CSGPart::opcode(InstructionSet::OPStop, vec![Inputs::Variable]),
]; ];
@@ -1786,9 +1733,9 @@ fn object_size_dependent_setup(
Inputs::Vec2(f) => vec2s.push(f.map(|x| x as f32).into()), Inputs::Vec2(f) => vec2s.push(f.map(|x| x as f32).into()),
Inputs::Vec3(f) => vec4s.push(f.map(|x| x as f32).extend(1.).into()), Inputs::Vec3(f) => vec4s.push(f.map(|x| x as f32).extend(1.).into()),
Inputs::Vec4(f) => vec4s.push(f.map(|x| x as f32).into()), Inputs::Vec4(f) => vec4s.push(f.map(|x| x as f32).into()),
Inputs::Mat2(f) => mat2s.push(f64tof32(f.into())), Inputs::Mat2(f) => mat2s.push(f.to_cols_array_2d()),
Inputs::Mat3(f) => mat3s.push(f64tof32(f.into())), Inputs::Mat3(f) => mat3s.push(f.to_cols_array_2d()),
Inputs::Mat4(f) => mat4s.push(f64tof32(f.into())), Inputs::Mat4(f) => mat4s.push(f.to_cols_array_2d()),
Inputs::Variable => unreachable!(), Inputs::Variable => unreachable!(),
} }
} }
@@ -1833,25 +1780,21 @@ fn object_size_dependent_setup(
let temp_csg = &CSG { let temp_csg = &CSG {
name: "test".to_string(), name: "test".to_string(),
parts: parts.to_vec(), parts: parts.to_vec(),
pos: Point3::origin(), pos: Vec3::ZERO,
rot: Euler::new(Deg(0.), Deg(0.), Deg(0.)), rot: Vec3::ZERO,
scale: Vector3 { scale: Vec3::ONE,
x: 1.,
y: 1.,
z: 1.,
},
}; };
let mut interpreter = interpreter::Interpreter::new(temp_csg); let mut interpreter = interpreter::Interpreter::new(temp_csg);
const CLIPCHECK: Float = 65536.; const CLIPCHECK: Float = 65536.;
let bounds = set_bound.unwrap_or([ let bounds = set_bound.unwrap_or([
((CLIPCHECK - interpreter.scene(Vector3::new(CLIPCHECK, 0., 0.))) * 1.00001) as f32, ((CLIPCHECK - interpreter.scene(vec3(CLIPCHECK, 0., 0.))) * 1.00001) as f32,
((CLIPCHECK - interpreter.scene(Vector3::new(0., CLIPCHECK, 0.))) * 1.00001) as f32, ((CLIPCHECK - interpreter.scene(vec3(0., CLIPCHECK, 0.))) * 1.00001) as f32,
((CLIPCHECK - interpreter.scene(Vector3::new(0., 0., CLIPCHECK))) * 1.00001) as f32, ((CLIPCHECK - interpreter.scene(vec3(0., 0., CLIPCHECK))) * 1.00001) as f32,
((-CLIPCHECK + interpreter.scene(Vector3::new(-CLIPCHECK, 0., 0.))) * 1.00001) as f32, ((-CLIPCHECK + interpreter.scene(vec3(-CLIPCHECK, 0., 0.))) * 1.00001) as f32,
((-CLIPCHECK + interpreter.scene(Vector3::new(0., -CLIPCHECK, 0.))) * 1.00001) as f32, ((-CLIPCHECK + interpreter.scene(vec3(0., -CLIPCHECK, 0.))) * 1.00001) as f32,
((-CLIPCHECK + interpreter.scene(Vector3::new(0., 0., -CLIPCHECK))) * 1.00001) as f32, ((-CLIPCHECK + interpreter.scene(vec3(0., 0., -CLIPCHECK))) * 1.00001) as f32,
]); ]);
//println!("bounds: {:?}",bounds); //println!("bounds: {:?}",bounds);
@@ -1993,15 +1936,18 @@ fn object_size_dependent_setup(
fn dump_pipeline_cache(cache: Arc<PipelineCache>) { fn dump_pipeline_cache(cache: Arc<PipelineCache>) {
if let Ok(data) = cache.get_data() { if let Ok(data) = cache.get_data() {
println!("Dumping pipeline cache...");
let tmp_path = relpath("pipeline_cache.bin.tmp"); let tmp_path = relpath("pipeline_cache.bin.tmp");
if let Ok(mut file) = File::create(&tmp_path) { if let Ok(mut file) = File::create(&tmp_path) {
if file.write_all(&data).is_ok() { if file.write_all(&data).is_ok() {
let _ = rename(&tmp_path, relpath("pipeline_cache.bin")); let _ = rename(&tmp_path, relpath("pipeline_cache.bin"));
println!("Pipeline cache dump success");
} else { } else {
let _ = remove_file(&tmp_path); let _ = remove_file(&tmp_path);
} }
} }
println!("Pipeline cache dump exit");
} }
} }
@@ -2010,6 +1956,7 @@ fn get_pipeline_cache(device: Arc<Device>) -> Arc<PipelineCache> {
if let Ok(mut file) = File::open(relpath("pipeline_cache.bin")) { if let Ok(mut file) = File::open(relpath("pipeline_cache.bin")) {
let mut data = Vec::new(); let mut data = Vec::new();
if file.read_to_end(&mut data).is_ok() { if file.read_to_end(&mut data).is_ok() {
println!("Successfuly retrieved pipeline cache");
data data
} else { } else {
Vec::new() Vec::new()
@@ -2020,13 +1967,10 @@ fn get_pipeline_cache(device: Arc<Device>) -> Arc<PipelineCache> {
}; };
unsafe { unsafe {
PipelineCache::new( PipelineCache::new(device, PipelineCacheCreateInfo {
device,
PipelineCacheCreateInfo {
initial_data, initial_data,
..Default::default() ..Default::default()
}, })
)
} }
.unwrap() .unwrap()
} }
+2 -1
View File
@@ -5,11 +5,12 @@ use std::{
}; };
use serde::{ use serde::{
Deserialize,
de::{ de::{
self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess,
Visitor, Visitor,
}, },
forward_to_deserialize_any, Deserialize, forward_to_deserialize_any,
}; };
use utf8::BufReadDecoder; use utf8::BufReadDecoder;
+4 -2
View File
@@ -155,7 +155,8 @@ pub(crate) fn load_obj(
..Default::default() ..Default::default()
}, },
AllocationCreateInfo { AllocationCreateInfo {
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE, memory_type_filter: MemoryTypeFilter::PREFER_HOST
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
allocate_preference: MemoryAllocatePreference::AlwaysAllocate, allocate_preference: MemoryAllocatePreference::AlwaysAllocate,
..Default::default() ..Default::default()
}, },
@@ -170,7 +171,8 @@ pub(crate) fn load_obj(
..Default::default() ..Default::default()
}, },
AllocationCreateInfo { AllocationCreateInfo {
memory_type_filter: MemoryTypeFilter::PREFER_DEVICE, memory_type_filter: MemoryTypeFilter::PREFER_HOST
| MemoryTypeFilter::HOST_SEQUENTIAL_WRITE,
allocate_preference: MemoryAllocatePreference::AlwaysAllocate, allocate_preference: MemoryAllocatePreference::AlwaysAllocate,
..Default::default() ..Default::default()
}, },