Compare commits

...

10 Commits

Author SHA1 Message Date
Aaron Fenyes
5e9c5db231 Ray-caster: switch from draw effect to animation loop
This wastes a lot of CPU time, as explained on lines 253--258 of
`main.rs`, but it's better than the previous version, which could block
graphics updates system-wide for seconds on end.
2024-08-26 16:06:37 -07:00
Aaron Fenyes
bf140efaf7 Ray-caster: remove hard-coded test construction 2024-08-26 13:51:01 -07:00
Aaron Fenyes
cbec31f5df Ray-caster: pass colors in through uniforms 2024-08-26 13:41:34 -07:00
Aaron Fenyes
b9370ceb41 Ray-caster: label controls 2024-08-26 01:47:53 -07:00
Aaron Fenyes
85db7b9be0 Ray-caster: pass the sphere count as a uniform
In the process, start exploring array size limits of various kinds.
2024-08-26 00:58:20 -07:00
Aaron Fenyes
c5fe725b1b Ray-caster: automate getting uniform array locations 2024-08-25 22:22:14 -07:00
Aaron Fenyes
5bf23fa789 Ray-caster: pass spheres in through uniforms
Keep the hard-coded spheres for comparison.
2024-08-25 21:40:59 -07:00
Aaron Fenyes
206a2df480 Ray-caster: add a third test sphere
This helps confirm that the generalized depth-sorting is working.
2024-08-25 16:41:31 -07:00
Aaron Fenyes
c18cac642b Ray-caster: generalize depth sorting
Switch from a hard-coded sorting network for four fragments to an
insertion sort, which should work for any number of fragments.
2024-08-25 00:47:36 -07:00
Aaron Fenyes
8798683d25 Ray-caster: store sphere data in arrays
This is a first step toward general depth sorting.
2024-08-25 00:00:28 -07:00
5 changed files with 269 additions and 107 deletions

View File

@ -9,6 +9,7 @@ default = ["console_error_panic_hook"]
[dependencies] [dependencies]
js-sys = "0.3.70" js-sys = "0.3.70"
nalgebra = "0.33.0"
sycamore = "0.9.0-beta.2" sycamore = "0.9.0-beta.2"
# The `console_error_panic_hook` crate provides better debugging of panics by # The `console_error_panic_hook` crate provides better debugging of panics by

View File

@ -18,6 +18,16 @@ canvas {
margin-top: 5px; margin-top: 5px;
} }
input { .control {
margin-top: 5px; display: flex;
flex-direction: row;
width: 600px;
}
label {
width: 150px;
}
input {
flex-grow: 1;
} }

View File

@ -0,0 +1,12 @@
use nalgebra::DVector;
pub fn sphere(center_x: f64, center_y: f64, center_z: f64, radius: f64) -> DVector<f64> {
let center_norm_sq = center_x * center_x + center_y * center_y + center_z * center_z;
DVector::from_column_slice(&[
center_x / radius,
center_y / radius,
center_z / radius,
0.5 / radius,
0.5 * (center_norm_sq / radius - radius)
])
}

View File

@ -4,6 +4,32 @@ precision highp float;
out vec4 outColor; out vec4 outColor;
// --- inversive geometry ---
struct vecInv {
vec3 sp;
vec2 lt;
};
vecInv sphere(vec3 center, float radius) {
return vecInv(
center / radius,
vec2(
0.5 / radius,
0.5 * (dot(center, center) / radius - radius)
)
);
}
// --- uniforms ---
// construction. the SPHERE_MAX array size seems to affect frame rate a lot,
// even though we should only be using the first few elements of each array
const int SPHERE_MAX = 12;
uniform int sphere_cnt;
uniform vecInv sphere_list[SPHERE_MAX];
uniform vec3 color_list[SPHERE_MAX];
// view // view
uniform vec2 resolution; uniform vec2 resolution;
uniform float shortdim; uniform float shortdim;
@ -14,6 +40,7 @@ uniform vec2 radius;
uniform float opacity; uniform float opacity;
uniform float highlight; uniform float highlight;
uniform int layer_threshold; uniform int layer_threshold;
uniform bool test_mode;
// light and camera // light and camera
const float focal_slope = 0.3; const float focal_slope = 0.3;
@ -46,23 +73,6 @@ vec3 sRGB(vec3 color) {
return vec3(sRGB(color.r), sRGB(color.g), sRGB(color.b)); return vec3(sRGB(color.r), sRGB(color.g), sRGB(color.b));
} }
// --- inversive geometry ---
struct vecInv {
vec3 sp;
vec2 lt;
};
vecInv sphere(vec3 center, float radius) {
return vecInv(
center / radius,
vec2(
0.5 / radius,
0.5 * (dot(center, center) / radius - radius)
)
);
}
// --- shading --- // --- shading ---
struct taggedFrag { struct taggedFrag {
@ -124,40 +134,40 @@ void main() {
vec2 scr = (2.*gl_FragCoord.xy - resolution) / shortdim; vec2 scr = (2.*gl_FragCoord.xy - resolution) / shortdim;
vec3 dir = vec3(focal_slope * scr, -1.); vec3 dir = vec3(focal_slope * scr, -1.);
// initialize two spheres
vecInv v [2];
v[0] = sphere(vec3(0.5, 0.5, -5. + ctrl.x), radius.x);
v[1] = sphere(vec3(-0.5, -0.5, -5. + ctrl.y), radius.y);
vec3 color0 = vec3(1., 0.214, 0.);
vec3 color1 = vec3(0., 0.214, 1.);
// cast rays through the spheres // cast rays through the spheres
vec2 u0 = sphere_cast(v[0], dir); vec2 depth_pairs [SPHERE_MAX];
vec2 u1 = sphere_cast(v[1], dir); taggedFrag frags [2*SPHERE_MAX];
int frag_cnt = 0;
for (int i = 0; i < sphere_cnt; ++i) {
vec2 hit_depths = sphere_cast(sphere_list[i], dir);
if (!isnan(hit_depths[0])) {
frags[frag_cnt] = sphere_shading(sphere_list[i], hit_depths[0] * dir, color_list[i], i);
++frag_cnt;
}
if (!isnan(hit_depths[1])) {
frags[frag_cnt] = sphere_shading(sphere_list[i], hit_depths[1] * dir, color_list[i], i);
++frag_cnt;
}
}
// shade and depth-sort the impact points // sort the fragments by depth, using an insertion sort
taggedFrag front_hits[2] = sort( for (int take = 1; take < frag_cnt; ++take) {
sphere_shading(v[0], u0[0] * dir, color0, 0), taggedFrag pulled = frags[take];
sphere_shading(v[1], u1[0] * dir, color1, 1) for (int put = take; put >= 0; --put) {
); if (put < 1 || frags[put-1].pt.z >= pulled.pt.z) {
taggedFrag back_hits[2] = sort( frags[put] = pulled;
sphere_shading(v[0], u0[1] * dir, color0, 0), break;
sphere_shading(v[1], u1[1] * dir, color1, 1) } else {
); frags[put] = frags[put-1];
taggedFrag middle_frags[2] = sort(front_hits[1], back_hits[0]); }
}
// finish depth sorting }
taggedFrag frags_by_depth[4];
frags_by_depth[0] = front_hits[0];
frags_by_depth[1] = middle_frags[0];
frags_by_depth[2] = middle_frags[1];
frags_by_depth[3] = back_hits[1];
// highlight intersections and cusps // highlight intersections and cusps
for (int i = 3; i >= 1; --i) { for (int i = frag_cnt-1; i >= 1; --i) {
// intersections // intersections
taggedFrag frag0 = frags_by_depth[i]; taggedFrag frag0 = frags[i];
taggedFrag frag1 = frags_by_depth[i-1]; taggedFrag frag1 = frags[i-1];
float ixn_sin = length(cross(frag0.normal, frag1.normal)); float ixn_sin = length(cross(frag0.normal, frag1.normal));
vec3 disp = frag0.pt - frag1.pt; vec3 disp = frag0.pt - frag1.pt;
float ixn_dist = max( float ixn_dist = max(
@ -165,21 +175,21 @@ void main() {
abs(dot(frag0.normal, disp)) abs(dot(frag0.normal, disp))
) / ixn_sin; ) / ixn_sin;
float ixn_highlight = 0.5 * highlight * (1. - smoothstep(2./3.*ixn_threshold, 1.5*ixn_threshold, ixn_dist)); float ixn_highlight = 0.5 * highlight * (1. - smoothstep(2./3.*ixn_threshold, 1.5*ixn_threshold, ixn_dist));
frags_by_depth[i].color = mix(frags_by_depth[i].color, vec4(1.), ixn_highlight); frags[i].color = mix(frags[i].color, vec4(1.), ixn_highlight);
frags_by_depth[i-1].color = mix(frags_by_depth[i-1].color, vec4(1.), ixn_highlight); frags[i-1].color = mix(frags[i-1].color, vec4(1.), ixn_highlight);
// cusps // cusps
float cusp_cos = abs(dot(dir, frag0.normal)); float cusp_cos = abs(dot(dir, frag0.normal));
float cusp_threshold = 2.*sqrt(ixn_threshold * v[frag0.id].lt.s); float cusp_threshold = 2.*sqrt(ixn_threshold * sphere_list[frag0.id].lt.s);
float cusp_highlight = highlight * (1. - smoothstep(2./3.*cusp_threshold, 1.5*cusp_threshold, cusp_cos)); float cusp_highlight = highlight * (1. - smoothstep(2./3.*cusp_threshold, 1.5*cusp_threshold, cusp_cos));
frags_by_depth[i].color = mix(frags_by_depth[i].color, vec4(1.), cusp_highlight); frags[i].color = mix(frags[i].color, vec4(1.), cusp_highlight);
} }
// composite the sphere fragments // composite the sphere fragments
vec3 color = vec3(0.); vec3 color = vec3(0.);
for (int i = 3; i >= layer_threshold; --i) { for (int i = frag_cnt-1; i >= layer_threshold; --i) {
if (frags_by_depth[i].pt.z < 0.) { if (frags[i].pt.z < 0.) {
vec4 frag_color = frags_by_depth[i].color; vec4 frag_color = frags[i].color;
color = mix(color, frag_color.rgb, frag_color.a); color = mix(color, frag_color.rgb, frag_color.a);
} }
} }

View File

@ -8,8 +8,12 @@
// //
extern crate js_sys; extern crate js_sys;
use sycamore::{prelude::*, rt::{JsCast, JsValue}}; use core::array;
use web_sys::{console, WebGl2RenderingContext, WebGlShader}; use nalgebra::DVector;
use sycamore::{prelude::*, motion::create_raf, rt::{JsCast, JsValue}};
use web_sys::{console, WebGl2RenderingContext, WebGlProgram, WebGlShader, WebGlUniformLocation};
mod engine;
fn compile_shader( fn compile_shader(
context: &WebGl2RenderingContext, context: &WebGl2RenderingContext,
@ -22,6 +26,21 @@ fn compile_shader(
shader shader
} }
fn get_uniform_array_locations<const N: usize>(
context: &WebGl2RenderingContext,
program: &WebGlProgram,
var_name: &str,
member_name_opt: Option<&str>
) -> [Option<WebGlUniformLocation>; N] {
array::from_fn(|n| {
let name = match member_name_opt {
Some(member_name) => format!("{var_name}[{n}].{member_name}"),
None => format!("{var_name}[{n}]")
};
context.get_uniform_location(&program, name.as_str())
})
}
// load the given data into the vertex input of the given name // load the given data into the vertex input of the given name
fn bind_vertex_attrib( fn bind_vertex_attrib(
context: &WebGl2RenderingContext, context: &WebGl2RenderingContext,
@ -70,6 +89,7 @@ fn main() {
console_error_panic_hook::set_once(); console_error_panic_hook::set_once();
sycamore::render(|| { sycamore::render(|| {
// controls
let ctrl_x = create_signal(0.0); let ctrl_x = create_signal(0.0);
let ctrl_y = create_signal(0.0); let ctrl_y = create_signal(0.0);
let radius_x = create_signal(1.0); let radius_x = create_signal(1.0);
@ -77,9 +97,21 @@ fn main() {
let opacity = create_signal(0.5); let opacity = create_signal(0.5);
let highlight = create_signal(0.2); let highlight = create_signal(0.2);
let layer_threshold = create_signal(0.0); let layer_threshold = create_signal(0.0);
let debug_mode = create_signal(false);
// display
let display = create_node_ref(); let display = create_node_ref();
on_mount(move || { on_mount(move || {
// list construction elements
const SPHERE_MAX: usize = 12;
let mut sphere_vec = Vec::<DVector<f64>>::new();
let color_vec = vec![
[1.00_f32, 0.25_f32, 0.00_f32],
[0.00_f32, 0.25_f32, 1.00_f32],
[0.25_f32, 0.00_f32, 1.00_f32]
];
// get the display canvas // get the display canvas
let canvas = display let canvas = display
.get::<DomNode>() .get::<DomNode>()
@ -118,15 +150,43 @@ fn main() {
console::log_1(&JsValue::from(link_msg)); console::log_1(&JsValue::from(link_msg));
ctx.use_program(Some(&program)); ctx.use_program(Some(&program));
/* DEBUG */
// print the maximum number of vectors that can be passed as
// uniforms to a fragment shader. the OpenGL ES 3.0 standard
// requires this maximum to be at least 224, as discussed in the
// documentation of the GL_MAX_FRAGMENT_UNIFORM_VECTORS parameter
// here:
//
// https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml
//
// there are also other size limits. for example, on Aaron's
// machine, the the length of a float or genType array seems to be
// capped at 1024 elements
console::log_2(
&ctx.get_parameter(WebGl2RenderingContext::MAX_FRAGMENT_UNIFORM_VECTORS).unwrap(),
&JsValue::from("uniform vectors available")
);
// find indices of vertex attributes and uniforms // find indices of vertex attributes and uniforms
let position_index = ctx.get_attrib_location(&program, "position") as u32; let position_index = ctx.get_attrib_location(&program, "position") as u32;
let sphere_cnt_loc = ctx.get_uniform_location(&program, "sphere_cnt");
let sphere_sp_locs = get_uniform_array_locations::<SPHERE_MAX>(
&ctx, &program, "sphere_list", Some("sp")
);
let sphere_lt_locs = get_uniform_array_locations::<SPHERE_MAX>(
&ctx, &program, "sphere_list", Some("lt")
);
let color_locs = get_uniform_array_locations::<SPHERE_MAX>(
&ctx, &program, "color_list", None
);
let resolution_loc = ctx.get_uniform_location(&program, "resolution"); let resolution_loc = ctx.get_uniform_location(&program, "resolution");
let shortdim_loc = ctx.get_uniform_location(&program, "shortdim"); let shortdim_loc = ctx.get_uniform_location(&program, "shortdim");
let ctrl_loc = ctx.get_uniform_location(&program, "ctrl"); let ctrl_loc = ctx.get_uniform_location(&program, "ctrl"); /* DEBUG */
let radius_loc = ctx.get_uniform_location(&program, "radius"); let radius_loc = ctx.get_uniform_location(&program, "radius"); /* DEBUG */
let opacity_loc = ctx.get_uniform_location(&program, "opacity"); let opacity_loc = ctx.get_uniform_location(&program, "opacity");
let highlight_loc = ctx.get_uniform_location(&program, "highlight"); let highlight_loc = ctx.get_uniform_location(&program, "highlight");
let layer_threshold_loc = ctx.get_uniform_location(&program, "layer_threshold"); let layer_threshold_loc = ctx.get_uniform_location(&program, "layer_threshold");
let debug_mode_loc = ctx.get_uniform_location(&program, "debug_mode");
// create a vertex array and bind it to the graphics context // create a vertex array and bind it to the graphics context
let vertex_array = ctx.create_vertex_array().unwrap(); let vertex_array = ctx.create_vertex_array().unwrap();
@ -147,74 +207,143 @@ fn main() {
bind_vertex_attrib(&ctx, position_index, 3, &positions); bind_vertex_attrib(&ctx, position_index, 3, &positions);
// set up a repainting routine // set up a repainting routine
create_effect(move || { let (_, start_updating_display, _) = create_raf(move || {
// update the construction
sphere_vec.clear();
sphere_vec.push(engine::sphere(0.5, 0.5, -5.0 + ctrl_x.get(), radius_x.get()));
sphere_vec.push(engine::sphere(-0.5, -0.5, -5.0 + ctrl_y.get(), radius_y.get()));
sphere_vec.push(engine::sphere(-0.5, 0.5, -5.0, 0.75));
// set the resolution // set the resolution
let width = canvas.width() as f32; let width = canvas.width() as f32;
let height = canvas.height() as f32; let height = canvas.height() as f32;
ctx.uniform2f(resolution_loc.as_ref(), width, height); ctx.uniform2f(resolution_loc.as_ref(), width, height);
ctx.uniform1f(shortdim_loc.as_ref(), width.min(height)); ctx.uniform1f(shortdim_loc.as_ref(), width.min(height));
// pass the construction
ctx.uniform1i(sphere_cnt_loc.as_ref(), sphere_vec.len() as i32);
for n in 0..sphere_vec.len() {
let v = &sphere_vec[n];
ctx.uniform3f(
sphere_sp_locs[n].as_ref(),
v[0] as f32, v[1] as f32, v[2] as f32
);
ctx.uniform2f(
sphere_lt_locs[n].as_ref(),
v[3] as f32, v[4] as f32
);
ctx.uniform3fv_with_f32_array(
color_locs[n].as_ref(),
&color_vec[n]
);
}
// pass the control parameters // pass the control parameters
ctx.uniform2f(ctrl_loc.as_ref(), ctrl_x.get() as f32, ctrl_y.get() as f32); ctx.uniform2f(ctrl_loc.as_ref(), ctrl_x.get() as f32, ctrl_y.get() as f32); /* DEBUG */
ctx.uniform2f(radius_loc.as_ref(), radius_x.get() as f32, radius_y.get() as f32); ctx.uniform2f(radius_loc.as_ref(), radius_x.get() as f32, radius_y.get() as f32); /* DEBUG */
ctx.uniform1f(opacity_loc.as_ref(), opacity.get() as f32); ctx.uniform1f(opacity_loc.as_ref(), opacity.get() as f32);
ctx.uniform1f(highlight_loc.as_ref(), highlight.get() as f32); ctx.uniform1f(highlight_loc.as_ref(), highlight.get() as f32);
ctx.uniform1i(layer_threshold_loc.as_ref(), layer_threshold.get() as i32); ctx.uniform1i(layer_threshold_loc.as_ref(), layer_threshold.get() as i32);
ctx.uniform1i(debug_mode_loc.as_ref(), debug_mode.get() as i32);
// draw the scene // draw the scene
ctx.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, VERTEX_CNT as i32); ctx.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, VERTEX_CNT as i32);
}); });
/*
this wastes CPU time by running an animation loop, which updates the
display even when nothing has changed. there should be a way to make
Sycamore do single-frame updates in response to changes, but i
haven't found it yet
*/
start_updating_display();
}); });
view! { view! {
div(id="app") { div(id="app") {
canvas(ref=display, width="600", height="600") canvas(ref=display, width="600", height="600")
input( div(class="control") {
type="range", label(for="ctrl-x") { "Sphere 0 depth" }
min=-1.0, input(
max=1.0, type="range",
step=0.001, id="ctrl-x",
bind:valueAsNumber=ctrl_x min=-1.0,
) max=1.0,
input( step=0.001,
type="range", bind:valueAsNumber=ctrl_x
min=-1.0, )
max=1.0, }
step=0.001, div(class="control") {
bind:valueAsNumber=ctrl_y label(for="ctrl-y") { "Sphere 1 depth" }
) input(
input( type="range",
type="range", id="ctrl-y",
min=0.5, min=-1.0,
max=1.5, max=1.0,
step=0.001, step=0.001,
bind:valueAsNumber=radius_x bind:valueAsNumber=ctrl_y
) )
input( }
type="range", div(class="control") {
min=0.5, label(for="radius-x") { "Sphere 0 radius" }
max=1.5, input(
step=0.001, type="range",
bind:valueAsNumber=radius_y id="radius-x",
) min=0.5,
input( max=1.5,
type="range", step=0.001,
max=1.0, bind:valueAsNumber=radius_x
step=0.001, )
bind:valueAsNumber=opacity }
) div(class="control") {
input( label(for="radius-y") { "Sphere 1 radius" }
type="range", input(
max=1.0, type="range",
step=0.001, id="radius-y",
bind:valueAsNumber=highlight min=0.5,
) max=1.5,
input( step=0.001,
type="range", bind:valueAsNumber=radius_y
max=3.0, )
step=1.0, }
bind:valueAsNumber=layer_threshold div(class="control") {
) label(for="opacity") { "Opacity" }
input(
type="range",
id="opacity",
max=1.0,
step=0.001,
bind:valueAsNumber=opacity
)
}
div(class="control") {
label(for="highlight") { "Highlight" }
input(
type="range",
id="highlight",
max=1.0,
step=0.001,
bind:valueAsNumber=highlight
)
}
div(class="control") {
label(for="layer-threshold") { "Layer threshold" }
input(
type="range",
id="layer-threshold",
max=5.0,
step=1.0,
bind:valueAsNumber=layer_threshold
)
}
div(class="control") {
label(for="debug-mode") { "Debug mode" }
input(
type="checkbox",
id="debug-mode",
bind:checked=debug_mode
)
}
} }
} }
}); });