-
-
Notifications
You must be signed in to change notification settings - Fork 112
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improved picking #494
Improved picking #494
Changes from 4 commits
57d711d
a849d30
99e04f0
1fcf79c
439261b
e390c6a
9b75340
0b574b4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -588,7 +588,7 @@ pub fn pick( | |
camera: &Camera, | ||
pixel: impl Into<PhysicalPoint> + Copy, | ||
geometries: impl IntoIterator<Item = impl Geometry>, | ||
) -> Option<Vec3> { | ||
) -> Option<IntersectionResult> { | ||
let pos = camera.position_at_pixel(pixel); | ||
let dir = camera.view_direction_at_pixel(pixel); | ||
ray_intersect( | ||
|
@@ -600,6 +600,17 @@ pub fn pick( | |
) | ||
} | ||
|
||
/// Result from an intersection test | ||
#[derive(Debug, Clone, Copy)] | ||
pub struct IntersectionResult { | ||
/// The position of the intersection | ||
pub position: Vec3, | ||
/// The index of the intersected geometry in the list of geometries | ||
pub geometry_id: u32, | ||
/// The index of the intersected instance in the list of instances or 0 if the intersection did not hit an instanced geometry | ||
pub instance_id: u32, | ||
} | ||
|
||
/// | ||
/// Finds the closest intersection between a ray starting at the given position in the given direction and the given geometries. | ||
/// Returns ```None``` if no geometry was hit before the given maximum depth. | ||
|
@@ -610,7 +621,7 @@ pub fn ray_intersect( | |
direction: Vec3, | ||
max_depth: f32, | ||
geometries: impl IntoIterator<Item = impl Geometry>, | ||
) -> Option<Vec3> { | ||
) -> Option<IntersectionResult> { | ||
use crate::core::*; | ||
let viewport = Viewport::new_at_origo(1, 1); | ||
let up = if direction.dot(vec3(1.0, 0.0, 0.0)).abs() > 0.99 { | ||
|
@@ -627,7 +638,7 @@ pub fn ray_intersect( | |
0.0, | ||
max_depth, | ||
); | ||
let mut texture = Texture2D::new_empty::<f32>( | ||
let mut texture = Texture2D::new_empty::<[f32; 4]>( | ||
context, | ||
viewport.width, | ||
viewport.height, | ||
|
@@ -644,31 +655,30 @@ pub fn ray_intersect( | |
Wrapping::ClampToEdge, | ||
Wrapping::ClampToEdge, | ||
); | ||
let depth_material = DepthMaterial { | ||
render_states: RenderStates { | ||
write_mask: WriteMask { | ||
red: true, | ||
..WriteMask::DEPTH | ||
}, | ||
..Default::default() | ||
}, | ||
let mut material = IntersectionMaterial { | ||
..Default::default() | ||
}; | ||
let depth = RenderTarget::new( | ||
let result = RenderTarget::new( | ||
texture.as_color_target(None), | ||
depth_texture.as_depth_target(), | ||
) | ||
.clear(ClearState::color_and_depth(1.0, 1.0, 1.0, 1.0, 1.0)) | ||
.write::<RendererError>(|| { | ||
for geometry in geometries { | ||
render_with_material(context, &camera, &geometry, &depth_material, &[]); | ||
for (id, geometry) in geometries.into_iter().enumerate() { | ||
material.geometry_id = id as i32; | ||
render_with_material(context, &camera, &geometry, &material, &[]); | ||
} | ||
Ok(()) | ||
}) | ||
.unwrap() | ||
.read_color::<[f32; 4]>()[0][0]; | ||
.read_color::<[f32; 4]>()[0]; | ||
let depth = result[0]; | ||
if depth < 1.0 { | ||
Some(position + direction * depth * max_depth) | ||
Some(IntersectionResult { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The IDs here are limited by the maximum safe integer a f32 can hold (approximately 24 bits). However, use cases where the IDs ever get that high are probably extremely rare, so it probably isn't worth the additional complexity that fixing that issue would incur (what's currently done in #479). Maybe this limitation should be added to the documentation somewhere? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, I was thinking 24 bit integer would be enough (16,777,215 instances is probably rare 🙂), but if we also have to output primitive ids, it's probably better to support the whole u32/i32 range. I fixed that in 439261b |
||
position: position + direction * depth * max_depth, | ||
geometry_id: result[1] as u32, | ||
instance_id: result[2] as u32, | ||
}) | ||
} else { | ||
None | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
use crate::core::*; | ||
use crate::renderer::*; | ||
|
||
/// | ||
/// Used for intersection tests, see [pick] and [ray_intersect]. | ||
/// When rendering with this material, the output in each pixel is: | ||
/// Red channel: The depth (same as [DepthMaterial]) | ||
/// Green channel: The [IntersectionMaterial::geometry_id] | ||
/// Blue channel: The instance ID or 0, if this is not an instanced geometry | ||
/// | ||
/// Note: The geometry needs to pass the instance ID to the fragment shader, see [Geometry] for more information. | ||
/// | ||
#[derive(Default, Clone)] | ||
pub struct IntersectionMaterial { | ||
/// The minimum distance from the camera to any object. If None, then the near plane of the camera is used. | ||
pub min_distance: Option<f32>, | ||
/// The maximum distance from the camera to any object. If None, then the far plane of the camera is used. | ||
pub max_distance: Option<f32>, | ||
/// Render states. | ||
pub render_states: RenderStates, | ||
/// A geometry ID for the currently rendered geometry. The result is outputted in the green color channel. | ||
pub geometry_id: i32, | ||
} | ||
|
||
impl FromCpuMaterial for IntersectionMaterial { | ||
fn from_cpu_material(_context: &Context, _cpu_material: &CpuMaterial) -> Self { | ||
Self::default() | ||
} | ||
} | ||
|
||
impl Material for IntersectionMaterial { | ||
fn id(&self) -> EffectMaterialId { | ||
EffectMaterialId::IntersectionMaterial | ||
} | ||
|
||
fn fragment_shader_source(&self, _lights: &[&dyn Light]) -> String { | ||
include_str!("shaders/intersection_material.frag").to_string() | ||
} | ||
|
||
fn fragment_attributes(&self) -> FragmentAttributes { | ||
FragmentAttributes { | ||
position: true, | ||
..FragmentAttributes::NONE | ||
} | ||
} | ||
|
||
fn use_uniforms(&self, program: &Program, camera: &Camera, _lights: &[&dyn Light]) { | ||
program.use_uniform( | ||
"minDistance", | ||
self.min_distance.unwrap_or_else(|| camera.z_near()), | ||
); | ||
program.use_uniform( | ||
"maxDistance", | ||
self.max_distance.unwrap_or_else(|| camera.z_far()), | ||
); | ||
program.use_uniform("eye", camera.position()); | ||
program.use_uniform("geometryId", self.geometry_id); | ||
} | ||
|
||
fn render_states(&self) -> RenderStates { | ||
self.render_states | ||
} | ||
|
||
fn material_type(&self) -> MaterialType { | ||
MaterialType::Opaque | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
|
||
uniform vec3 eye; | ||
uniform float minDistance; | ||
uniform float maxDistance; | ||
uniform int geometryId; | ||
|
||
in vec3 pos; | ||
flat in int instance_id; | ||
|
||
layout (location = 0) out vec4 outColor; | ||
|
||
void main() | ||
{ | ||
float dist = (distance(pos, eye) - minDistance) / (maxDistance - minDistance); | ||
outColor = vec4(dist, geometryId, instance_id, 1.0); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I recently noticed other 3D rendering libraries that provide this functionality also include the face index in their return result, which would take up the last alpha color slot. I believe this can be obtained from
gl_PrimitiveID
in theIntersectionMaterial
fragment shader. This isn't needed for my use case, but could be beneficial in this hypothetical use case: a button panel, where all the buttons are part of the same model; it is known which triangles make up the buttons, so the face index is used to identify which button was clicked.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's a good point! No reason not to add that to the intersection result as well. Fixed in e390c6a
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Turns out
gl_PrimitiveID
is not supported on web, so I'm removing it again.