[msl] Make ray queries safer (#9442)

Co-authored-by: Connor Fitzgerald <connorwadefitzgerald@gmail.com>
This commit is contained in:
VecvecandConnor Fitzgerald authored and GitHub committed 2026-06-29 22:27:03 +00:00
1 parent cf2dbfd40f
commit a03be8d223
13 files changed
+627 -194

No files matched your search

+1
View File
@@ -245,6 +245,7 @@ By @stuartparmenter in [#9658](https://github.com/gfx-rs/wgpu/pull/9658).
#### naga
- Switched from using an `intersector` to using an `intersection_query` on metal so AABBs and non-opaque triangles can be handled. By @Vecvec in [#9304](https://github.com/gfx-rs/wgpu/pull/9304).
- Guard against invalid calls to ray query functions on Metal. By @Vecvec in [#9442](https://github.com/gfx-rs/wgpu/pull/9442).
### Bug Fixes
+43 -31
View File
@@ -145,6 +145,11 @@ development. Naming is mostly taken from vulkan.
```wgsl
// - Initializes the `ray_query` to check where (if anywhere) the ray defined by `ray_desc` hits in `acceleration_structure`
// - If `ray_desc` is "invalid" (see definition on struct) then either:
// 1. the call is discarded (see behaviour of other calls if the ray query is uninitialized)
// 2. the call behaves *as if* the minimum number of fields were changed to make `ray_desc` valid
// - A ray query is "initialized" if this function has been called *and* was not discarded. If the call was discarded,
// the ray query may either be treated as if it were uninitialized or left in its previous state.
rayQueryInitialize(rq: ptr<function, ray_query>, acceleration_structure: acceleration_structure, ray_desc: RayDesc)
// Overload.
rayQueryInitialize(rq: ptr<function, ray_query<vertex_return>>, acceleration_structure: acceleration_structure<vertex_return>, ray_desc: RayDesc)
@@ -160,18 +165,31 @@ rayQueryInitialize(rq: ptr<function, ray_query<vertex_return>>, acceleration_str
// the closest hit a `Committed` intersection should be used.
// - Calling this function multiple times will cause the ray traversal to continue if it was interrupted by a `Candidate`
// intersection.
// - If `rq` was not previously initialized, the call is discarded.
// - If the previous proceed returned false (and no initialize was performed in between), the call is discarded.
rayQueryProceed(rq: ptr<function, ray_query>) -> bool
// Overload.
rayQueryProceed(rq: ptr<function, ray_query<vertex_return>>) -> bool
// - Generates a hit from procedural geometry at a particular distance.
rayQueryGenerateIntersection(hit_t: f32)
// - If `rq` was not previously initialized, the call is discarded.
// - If the previous proceed returned false (and no initialize was performed in between), the call is discarded.
// - If `hit_t` is not between the `ray_desc.tmin` provided to the previous initialize and the `t` value of the
// latest committed hit (or the last `ray_desc.tmax` if there are no committed hits), the call is discarded.
rayQueryGenerateIntersection(rq: ptr<function, ray_query>, hit_t: f32)
// - Commits a hit from triangular non-opaque geometry.
rayQueryConfirmIntersection()
// - If `rq` was not previously initialized, the call is discarded.
// - If the previous proceed returned false (and no initialize was performed in between), the call is discarded.
rayQueryConfirmIntersection(rq: ptr<function, ray_query>)
// Aborts the query which is in progress, that is, the next `rayQueryProceed` is guaranteed to return `false`
// and any call to `rayQueryGetCommittedIntersection` will return the closest committed result so far.
// and any call to `rayQueryGetCommittedIntersection` after the `rayQueryProceed` will return the closest
// committed result so far. (`rayQueryProceed` must be called for `rayQueryGetCommittedIntersection` to return
// a non zeroed value).
//
// - If `rq` was not previously initialized, the call is discarded.
// - If the previous proceed returned false (and no initialize was performed in between), the call is discarded.
rayQueryTerminate(rq: ptr<function, ray_query>)
// - Returns intersection details about a hit considered `Committed`.
@@ -190,6 +208,9 @@ rayQueryTerminate(rq: ptr<function, ray_query>)
// - The following fields are populated if the closest hit is was a triangle.
// - barycentrics
// - front_face
// If `rq` was not previously initialized, the call is discarded.
// If the previous proceed returned true or there were no previous proceed calls since the last initialize, a
// zero-initialized `RayIntersection` is returned.
rayQueryGetCommittedIntersection(rq: ptr<function, ray_query>) -> RayIntersection
// Overload.
rayQueryGetCommittedIntersection(rq: ptr<function, ray_query<vertex_return>>) -> RayIntersection
@@ -213,44 +234,35 @@ rayQueryGetCommittedIntersection(rq: ptr<function, ray_query<vertex_return>>) ->
//
// Note that `t` is *only* returned for a candidate triangle intersection. This is because
// `RAY_QUERY_INTERSECTION_AABB` is an AABB which has a volume.
// If `rq` was not previously initialized, the call is discarded.
// If the previous proceed returned false or there were no previous proceed calls since the last initialize, a
// zero-initialized `RayIntersection` is returned.
rayQueryGetCandidateIntersection(rq: ptr<function, ray_query>) -> RayIntersection
// Overload.
rayQueryGetCandidateIntersection(rq: ptr<function, ray_query<vertex_return>>) -> RayIntersection
// - Returns the vertices of the hit triangle considered `Committed`.
// - If `rq` was not previously initialized, the call is discarded.
// - If the previous proceed returned true or there were no previous proceed calls since the last initialize, a
// zero-initialized `array` is returned.
// - If the last hit was not a triangle, a zero-initialized `array` is returned.
getCommittedHitVertexPositions(rq: ptr<function, ray_query<vertex_return>>) -> array<vec3<f32>, 3>
// - Returns the vertices of the hit triangle considered `Candidate`.
// - If `rq` was not previously initialized, the call is discarded.
// - If the previous proceed returned true or there were no previous proceed calls since the last initialize, a
// zero-initialized `array` is returned.
// - If the last hit was not a triangle, a zero-initialized `array` is returned.
getCandidateHitVertexPositions(rq: ptr<function, ray_query<vertex_return>>) -> array<vec3<f32>, 3>
```
> [!CAUTION]
>
> #### ⚠️Undefined behavior ⚠️:
>
> - Calling `rayQueryGetCommittedIntersection` or `rayQueryGetCandidateIntersection` when `rayQueryProceed` has not been
> called on this ray query since it was initialized (or if the ray query has not been previously initialized).
> - Calling `rayQueryGetCommittedIntersection` when `rayQueryProceed`'s latest return on this ray query is considered
> `Candidate`.
> - Calling `rayQueryGetCandidateIntersection` when `rayQueryProceed`'s latest return on this ray query is considered
> `Committed`.
> - Calling `getCommittedHitVertexPositions` when `rayQueryProceed`'s latest return on this ray query is considered
> `Candidate`.
> - Calling `getCandidateHitVertexPositions` when `rayQueryProceed`'s latest return on this ray query is considered
> `Committed`.
> - Calling `get*HitVertexPositions` when the last `rayQueryProceed` did not hit a triangle
> - Calling `rayQueryProceed` when `rayQueryInitialize` has not previously been called on this ray query
> - Calling `rayQueryGenerateIntersection` on a query with last intersection kind not being
> `RAY_QUERY_INTERSECTION_AABB`,
> - Calling `rayQueryGenerateIntersection` with `hit_t` outside of `RayDesc::t_min .. RayDesc::t_max` range.
> or when `rayQueryProceed`'s latest return on this ray query is not considered `Candidate`.
> - Calling `rayQueryConfirmIntersection` on a query with last intersection kind not being
> `RAY_QUERY_INTERSECTION_TRIANGLE`,
> or when `rayQueryProceed`'s latest return on this ray query is not considered `Candidate`.
>
> \*this is only known undefined behaviour, and will be worked around in the future.
```wgsl
// A `RayDesc` is invalid if:
// - `ray_desc.flags` contains more than one of `SKIP_TRIANGLES` and `SKIP_AABBS`
// - `ray_desc.flags` contains more than one of `SKIP_TRIANGLES`, `CULL_BACK_FACING` and `CULL_FRONT_FACING`
// - `ray_desc.flags` contains more than one of `FORCE_OPAQUE`, `FORCE_NO_OPAQUE`, `CULL_OPAQUE`, `CULL_NO_OPAQUE`
// - `ray_desc.t_min` is less than `0.0`, or is not finite (`NaN` or `Inf`).
// - `ray_desc.t_max` is less than `0.0`, less than `ray_desc.t_min` (the first rule is implied by the second).
// - Any component of `ray_desc.origin` or `ray_desc.dir` is not finite (`NaN` or `Inf`)
// - `ray_desc.dir`'s length is zero (this implies `ray_desc.dir`)
struct RayDesc {
// Contains flags to use for this ray (e.g. consider all `Blas`es opaque)
flags: u32,
+3
View File
@@ -324,6 +324,8 @@ pub struct Options {
/// overflow. Set to false to emit raw division for faster compute shaders
/// where the developer guarantees non-zero divisors.
pub emit_int_div_checks: bool,
/// Whether to validate ray query calls
pub ray_query_initialization_tracking: bool,
}
impl Default for Options {
@@ -339,6 +341,7 @@ impl Default for Options {
force_loop_bounding: true,
task_dispatch_limits: None,
mesh_shader_primitive_indices_clamp: true,
ray_query_initialization_tracking: true,
emit_int_div_checks: true,
}
}
+308 -44
View File
@@ -8,10 +8,10 @@ use crate::{
back::{
self,
msl::{
writer::{StatementContext, TypeContext, WrappedFunction},
BackendResult, Error, Writer,
writer::{NameKeyExt, StatementContext, TypeContext, WrappedFunction},
BackendResult, Error, Writer, NAMESPACE,
},
Baked,
Baked, INDENT,
},
Handle,
};
@@ -24,8 +24,29 @@ pub(super) fn metal_intersector_ty() -> String {
}
pub(super) const INTERSECTION_FUNCTION_NAME: &str = "ray_query_get_intersection";
pub(crate) const RAY_QUERY_TRACKER_VARIABLE_PREFIX: &str = "naga_query_init_tracker_for_";
pub(crate) const RAY_QUERY_T_MAX_TRACKER_VARIABLE_PREFIX: &str = "naga_query_tmax_tracker_for_";
impl<W: Write> Writer<W> {
fn write_not_finite(&mut self, expr: &str) -> BackendResult {
self.write_contains_flags(&format!("as_type<uint>({expr})"), 0x7f800000)
}
/// Checks whether `expr` does not have the bitpattern of IEEE f32 `NaN`.
///
/// Note that this evaluates `expr` in the written code multiple times.
fn write_is_nan(&mut self, expr: &str) -> BackendResult {
write!(self.out, "(")?;
self.write_not_finite(expr)?;
write!(self.out, " && ((as_type<uint>({expr}) & 0x7fffff) != 0))")?;
Ok(())
}
fn write_contains_flags(&mut self, expr: &str, flags: u32) -> BackendResult {
write!(self.out, "(({expr} & {flags}) == {flags})")?;
Ok(())
}
/// Writes a function to get the current intersection from the ray query
///
/// Like other backends, this is needed to have a single branch for constructing
@@ -35,6 +56,7 @@ impl<W: Write> Writer<W> {
&mut self,
module: &crate::Module,
committed: bool,
options: &super::Options,
) -> BackendResult {
let wrapped = WrappedFunction::RayQueryGetIntersection { committed };
if !self.wrapped_functions.insert(wrapped) {
@@ -52,90 +74,122 @@ impl<W: Write> Writer<W> {
access: crate::StorageAccess::empty(),
first_time: false,
};
let level = back::Level(1);
let mut base_level = back::Level(1);
writeln!(
self.out,
"{intersection} {INTERSECTION_FUNCTION_NAME}_{committed}({} intersector) {{",
"{intersection} {INTERSECTION_FUNCTION_NAME}_{committed}({} intersector",
metal_intersector_ty()
)?;
if options.ray_query_initialization_tracking {
writeln!(self.out, ", uint intersector_tracker")?;
}
writeln!(self.out, ") {{")?;
// Initialize the intersection to its default values (which should be zero).
writeln!(
self.out,
"{level}{intersection} intersection = {intersection} {{}};"
"{base_level}{intersection} intersection = {intersection} {{}};"
)?;
writeln!(self.out, "{level}{RT_NAMESPACE}::intersection_type ty = intersector.get_{ty}_intersection_type();")?;
if options.ray_query_initialization_tracking {
write!(self.out, "{base_level}if (")?;
if committed {
self.write_contains_flags(
"intersector_tracker",
back::RayQueryPoint::FINISHED_TRAVERSAL.bits(),
)?;
} else {
self.write_contains_flags(
"intersector_tracker",
back::RayQueryPoint::PROCEED.bits(),
)?;
write!(self.out, " && !")?;
self.write_contains_flags(
"intersector_tracker",
back::RayQueryPoint::FINISHED_TRAVERSAL.bits(),
)?;
}
writeln!(self.out, ") {{")?;
base_level = base_level.next();
}
writeln!(self.out, "{base_level}{RT_NAMESPACE}::intersection_type ty = intersector.get_{ty}_intersection_type();")?;
// If the ray hit a triangle, call all methods that require that and set the intersection type.
writeln!(
self.out,
"{level}if (ty == {RT_NAMESPACE}::intersection_type::triangle) {{"
"{base_level}if (ty == {RT_NAMESPACE}::intersection_type::triangle) {{"
)?;
writeln!(
self.out,
"{level}{level}intersection.kind = {};",
"{base_level}{INDENT}intersection.kind = {};",
crate::RayQueryIntersection::Triangle as u32
)?;
if !committed {
writeln!(
self.out,
"{level}{level}intersection.t = intersector.get_candidate_triangle_distance();"
"{base_level}{INDENT}intersection.t = intersector.get_candidate_triangle_distance();"
)?;
}
writeln!(self.out, "{level}{level}intersection.barycentrics = intersector.get_{ty}_triangle_barycentric_coord();")?;
writeln!(self.out, "{base_level}{INDENT}intersection.barycentrics = intersector.get_{ty}_triangle_barycentric_coord();")?;
writeln!(
self.out,
"{level}{level}intersection.front_face = intersector.is_{ty}_triangle_front_facing();"
"{base_level}{INDENT}intersection.front_face = intersector.is_{ty}_triangle_front_facing();"
)?;
// Otherwise, if the ray hit an AABB (called a bounding box in metal) set the intersection type
// (which depends on whether this is a committed or candidate intersection).
writeln!(
self.out,
"{level}}} else if (ty == {RT_NAMESPACE}::intersection_type::bounding_box) {{"
"{base_level}}} else if (ty == {RT_NAMESPACE}::intersection_type::bounding_box) {{"
)?;
if committed {
writeln!(
self.out,
"{level}{level}intersection.kind = {};",
"{base_level}{INDENT}intersection.kind = {};",
crate::RayQueryIntersection::Generated as u32
)?;
} else {
writeln!(
self.out,
"{level}{level}intersection.kind = {};",
"{base_level}{INDENT}intersection.kind = {};",
crate::RayQueryIntersection::Aabb as u32
)?;
}
writeln!(self.out, "{level}}}")?;
writeln!(self.out, "{base_level}}}")?;
// If the ray hit anything at all, call all methods that require that.
writeln!(
self.out,
"{level}if (ty != {RT_NAMESPACE}::intersection_type::none) {{"
"{base_level}if (ty != {RT_NAMESPACE}::intersection_type::none) {{"
)?;
if committed {
writeln!(
self.out,
"{level}{level}intersection.t = intersector.get_committed_distance();"
"{base_level}{INDENT}intersection.t = intersector.get_committed_distance();"
)?;
}
writeln!(self.out, "{level}{level}intersection.instance_custom_data = intersector.get_{ty}_user_instance_id();")?;
writeln!(self.out, "{base_level}{INDENT}intersection.instance_custom_data = intersector.get_{ty}_user_instance_id();")?;
writeln!(
self.out,
"{level}{level}intersection.instance_index = intersector.get_{ty}_instance_id();"
"{base_level}{INDENT}intersection.instance_index = intersector.get_{ty}_instance_id();"
)?;
// Metal does not appear to support obtaining the intersection offset from a ray query.
//writeln!(self.out, "{level}{level}intersection.sbt_record_offset = intersector.get_{ty}_user_instance_id();")?;
writeln!(
self.out,
"{level}{level}intersection.geometry_index = intersector.get_{ty}_geometry_id();"
"{base_level}{INDENT}intersection.geometry_index = intersector.get_{ty}_geometry_id();"
)?;
writeln!(
self.out,
"{level}{level}intersection.primitive_index = intersector.get_{ty}_primitive_id();"
"{base_level}{INDENT}intersection.primitive_index = intersector.get_{ty}_primitive_id();"
)?;
writeln!(self.out, "{level}{level}intersection.object_to_world = intersector.get_{ty}_object_to_world_transform();")?;
writeln!(self.out, "{level}{level}intersection.world_to_object = intersector.get_{ty}_world_to_object_transform();")?;
writeln!(self.out, "{level}}}")?;
writeln!(self.out, "{level}return intersection;")?;
writeln!(self.out, "{base_level}{INDENT}intersection.object_to_world = intersector.get_{ty}_object_to_world_transform();")?;
writeln!(self.out, "{base_level}{INDENT}intersection.world_to_object = intersector.get_{ty}_world_to_object_transform();")?;
writeln!(self.out, "{base_level}}}")?;
if options.ray_query_initialization_tracking {
writeln!(self.out, "{INDENT}}}")?;
}
writeln!(self.out, "{INDENT}return intersection;")?;
writeln!(self.out, "}}")?;
Ok(())
@@ -152,6 +206,33 @@ impl<W: Write> Writer<W> {
return Err(Error::UnsupportedRayTracing);
}
// There are three possibilities for a ptr to be:
// 1. A variable
// 2. A function argument
// 3. part of a struct
//
// 2 and 3 are not possible, a ray query (in naga IR)
// is not allowed to be passed into a function, and
// all languages disallow it in a struct (you get fun results if
// you try it :) ).
//
// Therefore, the ray query expression must be a variable.
let crate::Expression::LocalVariable(query_var) =
context.expression.function.expressions[query]
else {
unreachable!()
};
let tracker_expr_name = format!(
"{RAY_QUERY_TRACKER_VARIABLE_PREFIX}{}",
self.names[&crate::proc::NameKey::local(context.expression.origin, query_var)]
);
let tmax_tracker_expr_name = format!(
"{RAY_QUERY_T_MAX_TRACKER_VARIABLE_PREFIX}{}",
self.names[&crate::proc::NameKey::local(context.expression.origin, query_var)]
);
// TODO: check for misuse.
match *fun {
crate::RayQueryFunction::Initialize {
@@ -193,24 +274,37 @@ impl<W: Write> Writer<W> {
// Determine whether or not to cull opaque/non-opaques
let f_opaque = back::RayFlag::CULL_OPAQUE.bits();
let f_no_opaque = back::RayFlag::CULL_NO_OPAQUE.bits();
writeln!(self.out, "{inner_level}{RT_NAMESPACE}::opacity_cull_mode cull_mode =
{inner_level}{INDENT}(desc.flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::opaque : (
{inner_level}{INDENT}{INDENT}(desc.flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::non_opaque : {RT_NAMESPACE}::opacity_cull_mode::none
{inner_level}{INDENT});")?;
writeln!(
self.out,
"{inner_level}params.set_opacity_cull_mode(
{inner_level} (desc.flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::opaque : (
{inner_level} (desc.flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::opacity_cull_mode::non_opaque : {RT_NAMESPACE}::opacity_cull_mode::none
{inner_level} )
{inner_level});"
"{inner_level}params.set_opacity_cull_mode(cull_mode);"
)?;
if context.expression.ray_query_initialization_tracking {
writeln!(self.out, "{inner_level}bool force_opacity = cull_mode == {RT_NAMESPACE}::opacity_cull_mode::none;")?;
}
}
{
let mut current_level = inner_level;
if context.expression.ray_query_initialization_tracking {
writeln!(self.out, "{inner_level}if (force_opacity) {{")?;
current_level = current_level.next();
}
// Determine whether to force a particular opacity
let f_opaque = back::RayFlag::OPAQUE.bits();
let f_no_opaque = back::RayFlag::NO_OPAQUE.bits();
writeln!(self.out, "{inner_level}params.force_opacity(
{inner_level} (desc.flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::opaque : (
{inner_level} (desc.flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::non_opaque : {RT_NAMESPACE}::forced_opacity::none
{inner_level} )
{inner_level});")?;
writeln!(self.out, "{current_level}params.force_opacity(
{current_level} (desc.flags & {f_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::opaque : (
{current_level} (desc.flags & {f_no_opaque}) != 0 ? {RT_NAMESPACE}::forced_opacity::non_opaque : {RT_NAMESPACE}::forced_opacity::none
{current_level} )
{current_level});")?;
if context.expression.ray_query_initialization_tracking {
writeln!(self.out, "{inner_level}}}")?;
}
}
{
let flag = back::RayFlag::TERMINATE_ON_FIRST_HIT.bits();
@@ -225,7 +319,46 @@ impl<W: Write> Writer<W> {
"{inner_level}{RT_NAMESPACE}::ray ray = {RT_NAMESPACE}::ray(desc.origin, desc.dir, desc.tmin, desc.tmax);"
)?;
write!(self.out, "{inner_level}")?;
let mut init_level = inner_level;
// The `reset` function is virtually undocumented (many of the Metal ray tracing functions lack it), so to be safe,
// this assumes an invalid ray is UB (NOTE: invalid ray behaviour is defined for intersectors).
if context.expression.ray_query_initialization_tracking {
write!(self.out, "{inner_level}bool invalid_nan_infs = ")?;
// tmax needs special handling because it can be INF
for (idx, &field_access) in [
"origin.x", "origin.y", "origin.z", "dir.x", "dir.y", "dir.z", "tmin",
]
.iter()
.enumerate()
{
if idx != 0 {
write!(self.out, " || ")?;
}
self.write_not_finite(&format!("desc.{field_access}"))?;
}
write!(self.out, " || ")?;
self.write_is_nan("desc.tmax")?;
writeln!(self.out, ";")?;
// Metal also requires that tmax >= 0.0, but if tmax >= tmin and tmin >= 0.0, tmax must be >= 0.0
writeln!(self.out, "{inner_level}bool invalid_t = (desc.tmin > desc.tmax) || (desc.tmin < 0.0);")?;
// Metal requires that the length of the direction is not 0.0. This is the case only when all the
// components are zero.
//
// Use absolute to cover signed zero.
writeln!(self.out, "{inner_level}bool invalid_dir = {NAMESPACE}::all({NAMESPACE}::abs(desc.dir) == 0.0);")?;
writeln!(
self.out,
"{inner_level}if (!(invalid_dir || invalid_t || invalid_nan_infs)) {{"
)?;
init_level = init_level.next();
}
write!(self.out, "{init_level}")?;
// A ray query can by initialized in metal by either using a "non-default constructor"
// or by calling reset. Ray queries cannot be assigned to in metal, so reset needs to
// be called.
@@ -233,34 +366,165 @@ impl<W: Write> Writer<W> {
write!(self.out, ".reset(ray,")?;
self.put_expression(acceleration_structure, &context.expression, true)?;
writeln!(self.out, ", desc.cull_mask, params);")?;
if context.expression.ray_query_initialization_tracking {
// We don't set the initialization tracker to zero (uninitialized)
// if the call fails. Resetting to uninitialized might be useful
// for debugging, but for everything else it is just extra code.
writeln!(
self.out,
"{init_level}{tracker_expr_name} = {};",
back::RayQueryPoint::INITIALIZED.bits()
)?;
writeln!(
self.out,
"{init_level}{tmax_tracker_expr_name} = desc.tmax;"
)?;
writeln!(self.out, "{inner_level}}}")?;
}
writeln!(self.out, "{level}}}")?;
}
crate::RayQueryFunction::Proceed { result } => {
write!(self.out, "{level}")?;
let mut current_level = level;
write!(self.out, "{current_level}")?;
let name = Baked(result).to_string();
self.start_baking_expression(result, &context.expression, &name)?;
self.named_expressions.insert(result, name);
self.named_expressions.insert(result, name.clone());
writeln!(self.out, "false;")?;
if context.expression.ray_query_initialization_tracking {
write!(self.out, "{level}if (")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::INITIALIZED.bits(),
)?;
write!(self.out, " && !")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::FINISHED_TRAVERSAL.bits(),
)?;
write!(self.out, ")")?;
writeln!(self.out, " {{")?;
current_level = current_level.next();
}
write!(self.out, "{current_level}{name} = ")?;
self.put_expression(query, &context.expression, true)?;
writeln!(self.out, ".next();")?;
if context.expression.ray_query_initialization_tracking {
writeln!(self.out, "{current_level}{tracker_expr_name} = {tracker_expr_name} | ({name} ? {}: {});", back::RayQueryPoint::PROCEED.bits(), (back::RayQueryPoint::PROCEED | back::RayQueryPoint::FINISHED_TRAVERSAL).bits())?;
writeln!(self.out, "{level}}}")?;
}
}
crate::RayQueryFunction::GenerateIntersection { hit_t } => {
write!(self.out, "{level}")?;
self.put_expression(query, &context.expression, true)?;
write!(self.out, ".commit_bounding_box_intersection(")?;
let mut current_level = level;
if context.expression.ray_query_initialization_tracking {
write!(self.out, "{level}if (")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::PROCEED.bits(),
)?;
write!(self.out, " && !")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::FINISHED_TRAVERSAL.bits(),
)?;
write!(self.out, ")")?;
} else {
// For readability
write!(self.out, "{level}")?;
}
writeln!(self.out, "{{")?;
current_level = current_level.next();
write!(self.out, "{current_level}float t = ")?;
self.put_expression(hit_t, &context.expression, true)?;
writeln!(self.out, ");")?;
writeln!(self.out, ";")?;
if context.expression.ray_query_initialization_tracking {
write!(
self.out,
"{current_level}float current_max_t = {tmax_tracker_expr_name};
{current_level}if ("
)?;
self.put_expression(query, &context.expression, true)?;
write!(self.out, ".get_committed_intersection_type() != {RT_NAMESPACE}::intersection_type::none) {{
{current_level}{INDENT}current_max_t = ")?;
self.put_expression(query, &context.expression, true)?;
write!(
self.out,
".get_committed_distance();
{current_level}}}
{current_level}if ("
)?;
self.put_expression(query, &context.expression, true)?;
write!(self.out, ".get_candidate_intersection_type() == {RT_NAMESPACE}::intersection_type::bounding_box && (")?;
self.put_expression(query, &context.expression, true)?;
write!(self.out, ".get_ray_min_distance()")?;
writeln!(self.out, " <= t) && (t <= current_max_t)) {{")?;
current_level = current_level.next();
}
write!(self.out, "{current_level}")?;
self.put_expression(query, &context.expression, true)?;
writeln!(self.out, ".commit_bounding_box_intersection(t);")?;
if context.expression.ray_query_initialization_tracking {
writeln!(self.out, "{level}{INDENT}}}")?;
}
writeln!(self.out, "{level}}}")?;
}
crate::RayQueryFunction::ConfirmIntersection => {
let mut current_level = level;
if context.expression.ray_query_initialization_tracking {
write!(self.out, "{level}if (")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::PROCEED.bits(),
)?;
write!(self.out, " && !")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::FINISHED_TRAVERSAL.bits(),
)?;
writeln!(self.out, ") {{")?;
current_level = current_level.next();
write!(self.out, "{current_level}if (")?;
self.put_expression(query, &context.expression, true)?;
writeln!(self.out, ".get_candidate_intersection_type() == {RT_NAMESPACE}::intersection_type::triangle) {{")?;
}
write!(self.out, "{level}")?;
self.put_expression(query, &context.expression, true)?;
writeln!(self.out, ".commit_triangle_intersection();")?;
if context.expression.ray_query_initialization_tracking {
writeln!(
self.out,
"{level}{INDENT}}}
{level}}}"
)?;
}
}
crate::RayQueryFunction::Terminate => {
write!(self.out, "{level}")?;
let mut current_level = level;
if context.expression.ray_query_initialization_tracking {
write!(self.out, "{level}if (")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::PROCEED.bits(),
)?;
write!(self.out, " && !")?;
self.write_contains_flags(
&tracker_expr_name,
back::RayQueryPoint::FINISHED_TRAVERSAL.bits(),
)?;
writeln!(self.out, ") {{")?;
current_level = current_level.next();
}
write!(self.out, "{current_level}")?;
self.put_expression(query, &context.expression, true)?;
// Terminate appears to map to abort in spirv-cross, but metal only documents
// the existence of this method, not what it does.
writeln!(self.out, ".abort();")?;
// To get the committed intersection, an extra proceed must occur as specified in
// the API docs.
if context.expression.ray_query_initialization_tracking {
writeln!(self.out, "{level}}}")?;
}
}
}
+49 -6
View File
@@ -719,12 +719,12 @@ impl crate::Type {
}
#[derive(Clone, Copy)]
enum FunctionOrigin {
pub(super) enum FunctionOrigin {
Handle(Handle<crate::Function>),
EntryPoint(proc::EntryPointIndex),
}
trait NameKeyExt {
pub(super) trait NameKeyExt {
fn local(origin: FunctionOrigin, local_handle: Handle<crate::LocalVariable>) -> NameKey {
match origin {
FunctionOrigin::Handle(handle) => NameKey::FunctionLocal(handle, local_handle),
@@ -779,7 +779,7 @@ struct TexelAddress {
pub(super) struct ExpressionContext<'a> {
pub(super) function: &'a crate::Function,
origin: FunctionOrigin,
pub(super) origin: FunctionOrigin,
pub(super) info: &'a valid::FunctionInfo,
pub(super) module: &'a crate::Module,
pub(super) mod_info: &'a valid::ModuleInfo,
@@ -795,6 +795,7 @@ pub(super) struct ExpressionContext<'a> {
pub(super) force_loop_bounding: bool,
/// Whether to emit safety checks for integer division/modulo.
emit_int_div_checks: bool,
pub(super) ray_query_initialization_tracking: bool,
}
impl<'a> ExpressionContext<'a> {
@@ -1171,6 +1172,27 @@ impl<W: Write> Writer<W> {
}
};
writeln!(self.out, ";")?;
// If this variable is a ray query, put in an initialization tracker.
if context.ray_query_initialization_tracking {
if let crate::TypeInner::RayQuery { .. } = context.module.types[ty].inner {
writeln!(
self.out,
"{}uint {}{} = 0u;",
back::INDENT,
super::ray::RAY_QUERY_TRACKER_VARIABLE_PREFIX,
self.names[&name_key]
)?;
writeln!(
self.out,
"{}float {}{} = 0.0;",
back::INDENT,
super::ray::RAY_QUERY_T_MAX_TRACKER_VARIABLE_PREFIX,
self.names[&name_key]
)?;
}
}
}
Ok(())
}
@@ -3033,12 +3055,28 @@ impl<W: Write> Writer<W> {
return Err(Error::UnsupportedRayTracing);
}
// See comment in `write_ray_query_stmt` for why this is valid
let crate::Expression::LocalVariable(query_var) =
context.function.expressions[query]
else {
unreachable!()
};
let tracker_expr_name = format!(
"{}{}",
super::ray::RAY_QUERY_TRACKER_VARIABLE_PREFIX,
self.names[&NameKey::local(context.origin, query_var)]
);
write!(
self.out,
"{}_{committed}(",
super::ray::INTERSECTION_FUNCTION_NAME
)?;
self.put_expression(query, context, true)?;
if context.ray_query_initialization_tracking {
write!(self.out, ", {tracker_expr_name}")?;
}
write!(self.out, ")")?;
}
crate::Expression::CooperativeLoad { ref data, .. } => {
@@ -4517,6 +4555,8 @@ impl<W: Write> Writer<W> {
&[
CLAMPED_LOD_LOAD_PREFIX,
super::ray::INTERSECTION_FUNCTION_NAME,
super::ray::RAY_QUERY_TRACKER_VARIABLE_PREFIX,
super::ray::RAY_QUERY_T_MAX_TRACKER_VARIABLE_PREFIX,
],
&mut self.names,
);
@@ -6683,6 +6723,7 @@ template <typename A>
&mut self,
module: &crate::Module,
func_ctx: &back::FunctionCtx,
options: &Options,
) -> BackendResult {
for (expr_handle, expr) in func_ctx.expressions.iter() {
match *expr {
@@ -6772,7 +6813,7 @@ template <typename A>
self.write_wrapped_cooperative_multiply_add(module, func_ctx, space, a, b, c)?;
}
crate::Expression::RayQueryGetIntersection { committed, .. } => {
self.write_rq_get_intersection_function(module, committed)?;
self.write_rq_get_intersection_function(module, committed, options)?;
}
_ => {}
}
@@ -6908,7 +6949,7 @@ template <typename A>
};
writeln!(self.out)?;
self.write_wrapped_functions(module, &ctx)?;
self.write_wrapped_functions(module, &ctx, options)?;
let fun_info = &mod_info[fun_handle];
pass_through_globals.clear();
@@ -7006,6 +7047,7 @@ template <typename A>
pipeline_options,
force_loop_bounding: options.force_loop_bounding,
emit_int_div_checks: options.emit_int_div_checks,
ray_query_initialization_tracking: options.ray_query_initialization_tracking,
},
result_struct: None,
};
@@ -7049,7 +7091,7 @@ template <typename A>
named_expressions: &fun.named_expressions,
};
self.write_wrapped_functions(module, &ctx)?;
self.write_wrapped_functions(module, &ctx, options)?;
let (em_str, in_mode, out_mode, can_vertex_pull) = match ep.stage {
crate::ShaderStage::Vertex => (
@@ -8229,6 +8271,7 @@ template <typename A>
pipeline_options,
force_loop_bounding: options.force_loop_bounding,
emit_int_div_checks: options.emit_int_div_checks,
ray_query_initialization_tracking: options.ray_query_initialization_tracking,
},
result_struct: if ep.stage == crate::ShaderStage::Task {
None
@@ -6,6 +6,7 @@ fake_missing_bindings = true
lang_version = [2, 4]
spirv_cross_compatibility = false
zero_initialize_workgroup_memory = false
ray_query_initialization_tracking = false
[hlsl]
shader_model = "V6_5"
+60 -29
View File
@@ -26,24 +26,28 @@ struct RayIntersection {
metal::float4x3 object_to_world;
metal::float4x3 world_to_object;
};
RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector) {
RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector
, uint intersector_tracker
) {
RayIntersection intersection = RayIntersection {};
metal::raytracing::intersection_type ty = intersector.get_candidate_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
intersection.kind = 1;
intersection.t = intersector.get_candidate_triangle_distance();
intersection.barycentrics = intersector.get_candidate_triangle_barycentric_coord();
intersection.front_face = intersector.is_candidate_triangle_front_facing();
} else if (ty == metal::raytracing::intersection_type::bounding_box) {
intersection.kind = 3;
}
if (ty != metal::raytracing::intersection_type::none) {
intersection.instance_custom_data = intersector.get_candidate_user_instance_id();
intersection.instance_index = intersector.get_candidate_instance_id();
intersection.geometry_index = intersector.get_candidate_geometry_id();
intersection.primitive_index = intersector.get_candidate_primitive_id();
intersection.object_to_world = intersector.get_candidate_object_to_world_transform();
intersection.world_to_object = intersector.get_candidate_world_to_object_transform();
if (((intersector_tracker & 2) == 2) && !((intersector_tracker & 4) == 4)) {
metal::raytracing::intersection_type ty = intersector.get_candidate_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
intersection.kind = 1;
intersection.t = intersector.get_candidate_triangle_distance();
intersection.barycentrics = intersector.get_candidate_triangle_barycentric_coord();
intersection.front_face = intersector.is_candidate_triangle_front_facing();
} else if (ty == metal::raytracing::intersection_type::bounding_box) {
intersection.kind = 3;
}
if (ty != metal::raytracing::intersection_type::none) {
intersection.instance_custom_data = intersector.get_candidate_user_instance_id();
intersection.instance_index = intersector.get_candidate_instance_id();
intersection.geometry_index = intersector.get_candidate_geometry_id();
intersection.primitive_index = intersector.get_candidate_primitive_id();
intersection.object_to_world = intersector.get_candidate_object_to_world_transform();
intersection.world_to_object = intersector.get_candidate_world_to_object_transform();
}
}
return intersection;
}
@@ -52,36 +56,63 @@ RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection
metal::raytracing::instance_acceleration_structure acc_struct [[user(fake0)]]
) {
metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> rq_1 = {};
uint naga_query_init_tracker_for_rq_1 = 0u;
float naga_query_tmax_tracker_for_rq_1 = 0.0;
metal::float3 pos = metal::float3(0.0);
metal::float3 dir = metal::float3(0.0, 1.0, 0.0);
RayDesc _e12 = RayDesc {4u, 255u, 0.1, 100.0, pos, dir};
{
RayDesc desc = _e12;
metal::raytracing::intersection_params params;
params.set_opacity_cull_mode(
metal::raytracing::opacity_cull_mode cull_mode =
(desc.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (
(desc.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none
)
);
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
);
params.set_opacity_cull_mode(cull_mode);
bool force_opacity = cull_mode == metal::raytracing::opacity_cull_mode::none;
if (force_opacity) {
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
}
params.accept_any_intersection((desc.flags & 4) != 0);
metal::raytracing::ray ray = metal::raytracing::ray(desc.origin, desc.dir, desc.tmin, desc.tmax);
rq_1.reset(ray,acc_struct, desc.cull_mask, params);
bool invalid_nan_infs = ((as_type<uint>(desc.origin.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.tmin) & 2139095040) == 2139095040) || (((as_type<uint>(desc.tmax) & 2139095040) == 2139095040) && ((as_type<uint>(desc.tmax) & 0x7fffff) != 0));
bool invalid_t = (desc.tmin > desc.tmax) || (desc.tmin < 0.0);
bool invalid_dir = metal::all(metal::abs(desc.dir) == 0.0);
if (!(invalid_dir || invalid_t || invalid_nan_infs)) {
rq_1.reset(ray,acc_struct, desc.cull_mask, params);
naga_query_init_tracker_for_rq_1 = 1;
naga_query_tmax_tracker_for_rq_1 = desc.tmax;
}
}
RayIntersection intersection = ray_query_get_intersection_false(rq_1);
RayIntersection intersection = ray_query_get_intersection_false(rq_1, naga_query_init_tracker_for_rq_1);
if (intersection.kind == 3u) {
rq_1.commit_bounding_box_intersection(10.0);
if (((naga_query_init_tracker_for_rq_1 & 2) == 2) && !((naga_query_init_tracker_for_rq_1 & 4) == 4)){
float t = 10.0;
float current_max_t = naga_query_tmax_tracker_for_rq_1;
if (rq_1.get_committed_intersection_type() != metal::raytracing::intersection_type::none) {
current_max_t = rq_1.get_committed_distance();
}
if (rq_1.get_candidate_intersection_type() == metal::raytracing::intersection_type::bounding_box && (rq_1.get_ray_min_distance() <= t) && (t <= current_max_t)) {
rq_1.commit_bounding_box_intersection(t);
}
}
return;
} else {
if (intersection.kind == 1u) {
if (((naga_query_init_tracker_for_rq_1 & 2) == 2) && !((naga_query_init_tracker_for_rq_1 & 4) == 4)) {
if (rq_1.get_candidate_intersection_type() == metal::raytracing::intersection_type::triangle) {
rq_1.commit_triangle_intersection();
}
}
return;
} else {
rq_1.abort();
if (((naga_query_init_tracker_for_rq_1 & 2) == 2) && !((naga_query_init_tracker_for_rq_1 & 4) == 4)) {
rq_1.abort();
}
return;
}
}
@@ -18,29 +18,45 @@ constant float o = 2.0;
metal::raytracing::instance_acceleration_structure acc_struct [[user(fake0)]]
) {
metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> rq = {};
uint naga_query_init_tracker_for_rq = 0u;
float naga_query_tmax_tracker_for_rq = 0.0;
RayDesc desc = RayDesc {4u, 255u, 34.0, 38.0, metal::float3(46.0), metal::float3(58.0, 62.0, 74.0)};
{
RayDesc desc = desc;
metal::raytracing::intersection_params params;
params.set_opacity_cull_mode(
metal::raytracing::opacity_cull_mode cull_mode =
(desc.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (
(desc.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none
)
);
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
);
params.set_opacity_cull_mode(cull_mode);
bool force_opacity = cull_mode == metal::raytracing::opacity_cull_mode::none;
if (force_opacity) {
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
}
params.accept_any_intersection((desc.flags & 4) != 0);
metal::raytracing::ray ray = metal::raytracing::ray(desc.origin, desc.dir, desc.tmin, desc.tmax);
rq.reset(ray,acc_struct, desc.cull_mask, params);
bool invalid_nan_infs = ((as_type<uint>(desc.origin.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.tmin) & 2139095040) == 2139095040) || (((as_type<uint>(desc.tmax) & 2139095040) == 2139095040) && ((as_type<uint>(desc.tmax) & 0x7fffff) != 0));
bool invalid_t = (desc.tmin > desc.tmax) || (desc.tmin < 0.0);
bool invalid_dir = metal::all(metal::abs(desc.dir) == 0.0);
if (!(invalid_dir || invalid_t || invalid_nan_infs)) {
rq.reset(ray,acc_struct, desc.cull_mask, params);
naga_query_init_tracker_for_rq = 1;
naga_query_tmax_tracker_for_rq = desc.tmax;
}
}
uint2 loop_bound = uint2(4294967295u);
while(true) {
if (metal::all(loop_bound == uint2(0u))) { break; }
loop_bound -= uint2(loop_bound.y == 0u, 1u);
bool _e31 = rq.next();
bool _e31 = false;
if (((naga_query_init_tracker_for_rq & 1) == 1) && !((naga_query_init_tracker_for_rq & 4) == 4)) {
_e31 = rq.next();
naga_query_init_tracker_for_rq = naga_query_init_tracker_for_rq | (_e31 ? 2: 6);
}
if (_e31) {
} else {
break;
@@ -32,7 +32,8 @@ struct Output {
metal::float3 normal;
};
RayIntersection ray_query_get_intersection_true(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector) {
RayIntersection ray_query_get_intersection_true(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector
) {
RayIntersection intersection = RayIntersection {};
metal::raytracing::intersection_type ty = intersector.get_committed_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
@@ -63,11 +64,11 @@ RayIntersection query_loop(
{
RayDesc desc = _e8;
metal::raytracing::intersection_params params;
params.set_opacity_cull_mode(
metal::raytracing::opacity_cull_mode cull_mode =
(desc.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (
(desc.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none
)
);
);
params.set_opacity_cull_mode(cull_mode);
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
@@ -81,7 +82,8 @@ RayIntersection query_loop(
while(true) {
if (metal::all(loop_bound == uint2(0u))) { break; }
loop_bound -= uint2(loop_bound.y == 0u, 1u);
bool _e9 = rq_1.next();
bool _e9 = false;
_e9 = rq_1.next();
if (_e9) {
} else {
break;
@@ -113,7 +115,8 @@ metal::float3 get_torus_normal(
return;
}
RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector) {
RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector
) {
RayIntersection intersection = RayIntersection {};
metal::raytracing::intersection_type ty = intersector.get_candidate_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
@@ -145,11 +148,11 @@ RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection
{
RayDesc desc = _e12;
metal::raytracing::intersection_params params;
params.set_opacity_cull_mode(
metal::raytracing::opacity_cull_mode cull_mode =
(desc.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (
(desc.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none
)
);
);
params.set_opacity_cull_mode(cull_mode);
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
@@ -161,7 +164,10 @@ RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection
}
RayIntersection intersection_1 = ray_query_get_intersection_false(rq);
if (intersection_1.kind == 3u) {
rq.commit_bounding_box_intersection(10.0);
{
float t = 10.0;
rq.commit_bounding_box_intersection(t);
}
return;
} else {
if (intersection_1.kind == 1u) {
+108 -57
View File
@@ -32,24 +32,28 @@ struct Output {
metal::float3 normal;
};
RayIntersection ray_query_get_intersection_true(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector) {
RayIntersection ray_query_get_intersection_true(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector
, uint intersector_tracker
) {
RayIntersection intersection = RayIntersection {};
metal::raytracing::intersection_type ty = intersector.get_committed_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
intersection.kind = 1;
intersection.barycentrics = intersector.get_committed_triangle_barycentric_coord();
intersection.front_face = intersector.is_committed_triangle_front_facing();
} else if (ty == metal::raytracing::intersection_type::bounding_box) {
intersection.kind = 2;
}
if (ty != metal::raytracing::intersection_type::none) {
intersection.t = intersector.get_committed_distance();
intersection.instance_custom_data = intersector.get_committed_user_instance_id();
intersection.instance_index = intersector.get_committed_instance_id();
intersection.geometry_index = intersector.get_committed_geometry_id();
intersection.primitive_index = intersector.get_committed_primitive_id();
intersection.object_to_world = intersector.get_committed_object_to_world_transform();
intersection.world_to_object = intersector.get_committed_world_to_object_transform();
if (((intersector_tracker & 4) == 4)) {
metal::raytracing::intersection_type ty = intersector.get_committed_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
intersection.kind = 1;
intersection.barycentrics = intersector.get_committed_triangle_barycentric_coord();
intersection.front_face = intersector.is_committed_triangle_front_facing();
} else if (ty == metal::raytracing::intersection_type::bounding_box) {
intersection.kind = 2;
}
if (ty != metal::raytracing::intersection_type::none) {
intersection.t = intersector.get_committed_distance();
intersection.instance_custom_data = intersector.get_committed_user_instance_id();
intersection.instance_index = intersector.get_committed_instance_id();
intersection.geometry_index = intersector.get_committed_geometry_id();
intersection.primitive_index = intersector.get_committed_primitive_id();
intersection.object_to_world = intersector.get_committed_object_to_world_transform();
intersection.world_to_object = intersector.get_committed_world_to_object_transform();
}
}
return intersection;
}
@@ -59,35 +63,51 @@ RayIntersection query_loop(
metal::raytracing::instance_acceleration_structure acs
) {
metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> rq_1 = {};
uint naga_query_init_tracker_for_rq_1 = 0u;
float naga_query_tmax_tracker_for_rq_1 = 0.0;
RayDesc _e8 = RayDesc {4u, 255u, 0.1, 100.0, pos, dir};
{
RayDesc desc = _e8;
metal::raytracing::intersection_params params;
params.set_opacity_cull_mode(
metal::raytracing::opacity_cull_mode cull_mode =
(desc.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (
(desc.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none
)
);
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
);
params.set_opacity_cull_mode(cull_mode);
bool force_opacity = cull_mode == metal::raytracing::opacity_cull_mode::none;
if (force_opacity) {
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
}
params.accept_any_intersection((desc.flags & 4) != 0);
metal::raytracing::ray ray = metal::raytracing::ray(desc.origin, desc.dir, desc.tmin, desc.tmax);
rq_1.reset(ray,acs, desc.cull_mask, params);
bool invalid_nan_infs = ((as_type<uint>(desc.origin.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.tmin) & 2139095040) == 2139095040) || (((as_type<uint>(desc.tmax) & 2139095040) == 2139095040) && ((as_type<uint>(desc.tmax) & 0x7fffff) != 0));
bool invalid_t = (desc.tmin > desc.tmax) || (desc.tmin < 0.0);
bool invalid_dir = metal::all(metal::abs(desc.dir) == 0.0);
if (!(invalid_dir || invalid_t || invalid_nan_infs)) {
rq_1.reset(ray,acs, desc.cull_mask, params);
naga_query_init_tracker_for_rq_1 = 1;
naga_query_tmax_tracker_for_rq_1 = desc.tmax;
}
}
uint2 loop_bound = uint2(4294967295u);
while(true) {
if (metal::all(loop_bound == uint2(0u))) { break; }
loop_bound -= uint2(loop_bound.y == 0u, 1u);
bool _e9 = rq_1.next();
bool _e9 = false;
if (((naga_query_init_tracker_for_rq_1 & 1) == 1) && !((naga_query_init_tracker_for_rq_1 & 4) == 4)) {
_e9 = rq_1.next();
naga_query_init_tracker_for_rq_1 = naga_query_init_tracker_for_rq_1 | (_e9 ? 2: 6);
}
if (_e9) {
} else {
break;
}
}
return ray_query_get_intersection_true(rq_1);
return ray_query_get_intersection_true(rq_1, naga_query_init_tracker_for_rq_1);
}
metal::float3 get_torus_normal(
@@ -113,24 +133,28 @@ metal::float3 get_torus_normal(
return;
}
RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector) {
RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> intersector
, uint intersector_tracker
) {
RayIntersection intersection = RayIntersection {};
metal::raytracing::intersection_type ty = intersector.get_candidate_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
intersection.kind = 1;
intersection.t = intersector.get_candidate_triangle_distance();
intersection.barycentrics = intersector.get_candidate_triangle_barycentric_coord();
intersection.front_face = intersector.is_candidate_triangle_front_facing();
} else if (ty == metal::raytracing::intersection_type::bounding_box) {
intersection.kind = 3;
}
if (ty != metal::raytracing::intersection_type::none) {
intersection.instance_custom_data = intersector.get_candidate_user_instance_id();
intersection.instance_index = intersector.get_candidate_instance_id();
intersection.geometry_index = intersector.get_candidate_geometry_id();
intersection.primitive_index = intersector.get_candidate_primitive_id();
intersection.object_to_world = intersector.get_candidate_object_to_world_transform();
intersection.world_to_object = intersector.get_candidate_world_to_object_transform();
if (((intersector_tracker & 2) == 2) && !((intersector_tracker & 4) == 4)) {
metal::raytracing::intersection_type ty = intersector.get_candidate_intersection_type();
if (ty == metal::raytracing::intersection_type::triangle) {
intersection.kind = 1;
intersection.t = intersector.get_candidate_triangle_distance();
intersection.barycentrics = intersector.get_candidate_triangle_barycentric_coord();
intersection.front_face = intersector.is_candidate_triangle_front_facing();
} else if (ty == metal::raytracing::intersection_type::bounding_box) {
intersection.kind = 3;
}
if (ty != metal::raytracing::intersection_type::none) {
intersection.instance_custom_data = intersector.get_candidate_user_instance_id();
intersection.instance_index = intersector.get_candidate_instance_id();
intersection.geometry_index = intersector.get_candidate_geometry_id();
intersection.primitive_index = intersector.get_candidate_primitive_id();
intersection.object_to_world = intersector.get_candidate_object_to_world_transform();
intersection.world_to_object = intersector.get_candidate_world_to_object_transform();
}
}
return intersection;
}
@@ -139,36 +163,63 @@ RayIntersection ray_query_get_intersection_false(metal::raytracing::intersection
metal::raytracing::instance_acceleration_structure acc_struct [[user(fake0)]]
) {
metal::raytracing::intersection_query<metal::raytracing::instancing, metal::raytracing::triangle_data> rq = {};
uint naga_query_init_tracker_for_rq = 0u;
float naga_query_tmax_tracker_for_rq = 0.0;
metal::float3 pos_2 = metal::float3(0.0);
metal::float3 dir_2 = metal::float3(0.0, 1.0, 0.0);
RayDesc _e12 = RayDesc {4u, 255u, 0.1, 100.0, pos_2, dir_2};
{
RayDesc desc = _e12;
metal::raytracing::intersection_params params;
params.set_opacity_cull_mode(
metal::raytracing::opacity_cull_mode cull_mode =
(desc.flags & 64) != 0 ? metal::raytracing::opacity_cull_mode::opaque : (
(desc.flags & 128) != 0 ? metal::raytracing::opacity_cull_mode::non_opaque : metal::raytracing::opacity_cull_mode::none
)
);
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
);
params.set_opacity_cull_mode(cull_mode);
bool force_opacity = cull_mode == metal::raytracing::opacity_cull_mode::none;
if (force_opacity) {
params.force_opacity(
(desc.flags & 1) != 0 ? metal::raytracing::forced_opacity::opaque : (
(desc.flags & 2) != 0 ? metal::raytracing::forced_opacity::non_opaque : metal::raytracing::forced_opacity::none
)
);
}
params.accept_any_intersection((desc.flags & 4) != 0);
metal::raytracing::ray ray = metal::raytracing::ray(desc.origin, desc.dir, desc.tmin, desc.tmax);
rq.reset(ray,acc_struct, desc.cull_mask, params);
bool invalid_nan_infs = ((as_type<uint>(desc.origin.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.origin.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.x) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.y) & 2139095040) == 2139095040) || ((as_type<uint>(desc.dir.z) & 2139095040) == 2139095040) || ((as_type<uint>(desc.tmin) & 2139095040) == 2139095040) || (((as_type<uint>(desc.tmax) & 2139095040) == 2139095040) && ((as_type<uint>(desc.tmax) & 0x7fffff) != 0));
bool invalid_t = (desc.tmin > desc.tmax) || (desc.tmin < 0.0);
bool invalid_dir = metal::all(metal::abs(desc.dir) == 0.0);
if (!(invalid_dir || invalid_t || invalid_nan_infs)) {
rq.reset(ray,acc_struct, desc.cull_mask, params);
naga_query_init_tracker_for_rq = 1;
naga_query_tmax_tracker_for_rq = desc.tmax;
}
}
RayIntersection intersection_1 = ray_query_get_intersection_false(rq);
RayIntersection intersection_1 = ray_query_get_intersection_false(rq, naga_query_init_tracker_for_rq);
if (intersection_1.kind == 3u) {
rq.commit_bounding_box_intersection(10.0);
if (((naga_query_init_tracker_for_rq & 2) == 2) && !((naga_query_init_tracker_for_rq & 4) == 4)){
float t = 10.0;
float current_max_t = naga_query_tmax_tracker_for_rq;
if (rq.get_committed_intersection_type() != metal::raytracing::intersection_type::none) {
current_max_t = rq.get_committed_distance();
}
if (rq.get_candidate_intersection_type() == metal::raytracing::intersection_type::bounding_box && (rq.get_ray_min_distance() <= t) && (t <= current_max_t)) {
rq.commit_bounding_box_intersection(t);
}
}
return;
} else {
if (intersection_1.kind == 1u) {
if (((naga_query_init_tracker_for_rq & 2) == 2) && !((naga_query_init_tracker_for_rq & 4) == 4)) {
if (rq.get_candidate_intersection_type() == metal::raytracing::intersection_type::triangle) {
rq.commit_triangle_intersection();
}
}
return;
} else {
rq.abort();
if (((naga_query_init_tracker_for_rq & 2) == 2) && !((naga_query_init_tracker_for_rq & 4) == 4)) {
rq.abort();
}
return;
}
}
+6 -5
View File
@@ -1,12 +1,12 @@
use crate::ray_tracing::{acceleration_structure_limits, AsBuildContext};
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use wgpu::{
include_wgsl, Backends, BindGroupDescriptor, BindGroupEntry, BindingResource, BufferDescriptor,
include_wgsl, BindGroupDescriptor, BindGroupEntry, BindingResource, BufferDescriptor,
CommandEncoderDescriptor, ComputePassDescriptor, ComputePipelineDescriptor, InstanceFlags,
};
use wgpu::{AccelerationStructureFlags, BufferUsages};
use wgpu_macros::gpu_test;
use wgpu_test::{FailureCase, GpuTestInitializer};
use wgpu_test::GpuTestInitializer;
use wgpu_test::{GpuTestConfiguration, TestParameters, TestingContext};
const STRUCT_SIZE: wgpu::BufferAddress = 176;
@@ -109,14 +109,15 @@ fn access_all_struct_members(ctx: TestingContext) {
#[gpu_test]
static PREVENT_INVALID_RAY_QUERY_CALLS: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(
// Don't disable metal shader validation in `TestParameters` because
// the shader validation is important here and the results from the
// ray query don't matter.
TestParameters::default()
.test_features_limits()
.limits(acceleration_structure_limits())
.features(wgpu::Features::EXPERIMENTAL_RAY_QUERY)
// Otherwise, mistakes in the generated code won't be caught.
.instance_flags(InstanceFlags::GPU_BASED_VALIDATION)
// not yet implemented in metal
.skip(FailureCase::backend(Backends::METAL)),
.instance_flags(InstanceFlags::GPU_BASED_VALIDATION),
)
.run_sync(prevent_invalid_ray_query_calls);
+4
View File
@@ -237,6 +237,10 @@ impl super::Device {
.runtime_checks
.mesh_shader_primitive_indices_clamp,
emit_int_div_checks: stage.module.runtime_checks.int_div_checks,
ray_query_initialization_tracking: stage
.module
.runtime_checks
.ray_query_initialization_tracking,
};
let pipeline_options = naga::back::msl::PipelineOptions {
+2 -2
View File
@@ -40,8 +40,8 @@ pub struct ShaderRuntimeChecks {
/// `getCandidateHitVertexPositions` or `rayQueryGetCandidateIntersection` is called
/// - `rayQueryProceed` must have been called and have returned false before `rayQueryGetCommittedIntersection`
/// or `getCommittedHitVertexPositions` are called
///
/// It is the aim that these cases will not cause UB if this is set to true, but currently this will still happen on DX12 and Metal.
/// - when calling `rayQueryInitialize`, the ray desc argument must not contain NaNs in any floating point
/// values and must not contain Infs in any component of `dir`, `origin`, `tmin`
pub ray_query_initialization_tracking: bool,
/// If false, task shaders will not validate that the mesh shader grid they dispatch is within legal limits.