diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/main.rs | 20 | ||||
-rw-r--r-- | src/sdf.rs | 24 |
2 files changed, 36 insertions, 8 deletions
diff --git a/src/main.rs b/src/main.rs index c55d1c0..2bcdd06 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,9 +62,9 @@ impl View { fn try_main() -> Result<(), String> { use sdf::{R3ToR}; - let funciton = R3ToR::min( - R3ToR::sphere_f32(1.5), - R3ToR::cube_f32(1.0), + let funciton = R3ToR::smooth_min( + R3ToR::sphere_f32(1.2), + R3ToR::cube_f32(1.0) ); let my_sdf = sdf::Sdf::from_function(funciton); @@ -90,6 +90,7 @@ uniform float u_level_set; #define AA_X 1 #define AA_Y 1 + float sdf_adjusted(vec3 p) { return sdf(p) - u_level_set; } @@ -128,14 +129,17 @@ void main() { for (i = 0; i < ITERATIONS; i++) { float dist = sdf(p); min_dist = min(min_dist, dist); - if (dist <= 0.01) { - float L = 0.3 + max(0., dot(normal(p), normalize(vec3(.8,1,.6)))); - final_color += L * vec3(1.0, 0.0, 0.0); - break; - } if (dist > 100.0) break;//little optimization p += dist * delta; } + + float threshold = 0.02; + if (min_dist < threshold) { + float L = 0.3 + max(0., dot(normal(p), normalize(vec3(.8,1,.6)))); + final_color += L * (1.0/threshold) * (threshold-min_dist) * vec3(1.0, 0.0, 0.0); + break; + } + } } final_color *= 1.0 / (AA_X * AA_Y); @@ -81,6 +81,10 @@ impl R3ToR { pub fn min(a: Self, b: Self) -> Self { Self::Min(Box::new(a), Box::new(b)) } + + pub fn smooth_min(a: Self, b: Self) -> Self { + Self::SmoothMin(Box::new(a), Box::new(b)) + } } struct VarCounter { @@ -191,6 +195,19 @@ impl Function for R3ToR { var.next() ); }, + SmoothMin(a, b) => { + let a_output = a.to_glsl(input, code, var); + let b_output = b.to_glsl(input, code, var); + // for now we're using a fixed k value + // i don't want to make this a Constant right now, + // since most values of k (i.e. <0, >1) look bad/just like min. + let k = 0.2; + write_str!( + code, + "float v{} = smooth_min(v{a_output}, v{b_output}, {k});\n", + var.next() + ); + }, _ => todo!(), } @@ -212,6 +229,13 @@ impl Sdf { /// appends some glsl code including a function `float sdf(vec3) { ... }` pub fn to_glsl(&self, code: &mut String) { + code.push_str(" +float smooth_min(float a, float b, float k) { + k = clamp(k, 0.0, 1.0); + float h = max(k-abs(a-b), 0.0)/k; + return min(a, b) - h*h*h*k*(1.0/6.0); +} +"); code.push_str("float sdf(vec3 p) {\n"); let mut var = VarCounter::new(); write_str!(code, "vec3 v{} = p;\n", var.next()); |