Skip to content
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

Ray3d::from_screenspace() implementation from Camera.viewport_to_world() #76

Closed
wants to merge 1 commit into from

Conversation

rosingrind
Copy link

Summary

bevyengine/bevy#8306 introduces consistent coordinates for every entity without .y flipping. The changes are not rolled out yet, but current main of bevy_mod_raycast is not working well with bevy's main. In attempt to fix this, I found a simple but questionable solution:

pub fn from_screenspace(
cursor_pos_screen: Vec2,
camera: &Camera,
camera_transform: &GlobalTransform,
) -> Option<Self> {
let view = camera_transform.compute_matrix();
let (viewport_min, viewport_max) = camera.logical_viewport_rect()?;
let screen_size = camera.logical_target_size()?;
let viewport_size = viewport_max - viewport_min;
let adj_cursor_pos =
cursor_pos_screen - Vec2::new(viewport_min.x, screen_size.y - viewport_max.y);
let projection = camera.projection_matrix();
let far_ndc = projection.project_point3(Vec3::NEG_Z).z;
let near_ndc = projection.project_point3(Vec3::Z).z;
let cursor_ndc = (adj_cursor_pos / viewport_size) * 2.0 - Vec2::ONE;
let ndc_to_world: Mat4 = view * projection.inverse();
let near = ndc_to_world.project_point3(cursor_ndc.extend(near_ndc));
let far = ndc_to_world.project_point3(cursor_ndc.extend(far_ndc));
let ray_direction = far - near;
Some(Ray3d::new(near, ray_direction))
}

is equal to

https://github.com/bevyengine/bevy/blob/585baf0a66b855cef1f0568a4af44b666cfee076/crates/bevy_render/src/camera/camera.rs#L250-L270

Solution

It seems that there's no reason not to utilize Camera::viewport_to_world() as it's available since bevyengine/bevy@37860a0 from v0.9.0. I propose to utilize Camera.viewport_to_world() under the hood of Ray3d::from_screenspace() as their purposes seems identical. Changes doesn't seem to break any examples functionality on my end

@rosingrind
Copy link
Author

Closing this in favor of #78 and #83

@rosingrind rosingrind closed this Jul 1, 2023
@yyogo yyogo mentioned this pull request Jul 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant