80d0cc9c43
build / mod (push) Failing after 1m21s
Stage 1 of #125: prove or disprove real hardware ray-tracing support without touching the client renderer. The probe pins the same wgpu 30.0.1 stack as the engine, including its vendored third_party/wgpu-hal patch, builds one BLAS/TLAS and traces a 16x16 ray-query compute frame, checking every ray against a CPU point-in-triangle expectation. Verified on macOS aarch64, Apple M5 / Metal: BLAS/TLAS and the ray-query pipeline build, 32 hits and 224 misses all match, exit 0. RT_PROBE_BACKEND=gl reports no RT adapter and exits 2; RT_PROBE_NO_OPTIN=1 shows request_device rejects EXPERIMENTAL_RAY_QUERY without the experimental opt-in and exits 2. tools/rt-probe/target/ is ignored; the probe is a standalone workspace and is not wired into the game build. Co-Authored-By: Kimi Code <noreply@moonshot.ai>
444 lines
16 KiB
Rust
444 lines
16 KiB
Rust
//! Native ray-tracing capability probe for AirDef issue #125, stage 1.
|
|
//!
|
|
//! Reports the real OS/backend/adapter/driver/features of the pinned wgpu
|
|
//! (=30.0.1 plus the engine's vendored `third_party/wgpu-hal` patch), builds one
|
|
//! BLAS/TLAS and traces a 16x16 ray-query frame, checking every ray against a
|
|
//! CPU point-in-triangle expectation. GPU branding is never trusted: each stage
|
|
//! is attempted and its real result printed, and an unsupported adapter or
|
|
//! backend exits with the reason instead of a promise.
|
|
//!
|
|
//! Run from the repo root (needs the `horizon` submodule populated for the
|
|
//! wgpu-hal patch): `cargo run --manifest-path tools/rt-probe/Cargo.toml`
|
|
//! `RT_PROBE_BACKEND=gl|vulkan|dx12|metal` restricts the backend set, e.g. to
|
|
//! exercise the unsupported fallback on a machine whose main backend has RT.
|
|
//! `RT_PROBE_NO_OPTIN=1` requests the RT feature without the experimental
|
|
//! opt-in, proving the device gate rejects it.
|
|
//!
|
|
//! Exit codes: 0 = ray query verified, 2 = unsupported at some stage (reason
|
|
//! printed), 1 = wrong ray results or a GPU wait failure.
|
|
|
|
use std::{
|
|
env,
|
|
sync::{Arc, Mutex},
|
|
time::Duration,
|
|
};
|
|
use wgpu::util::DeviceExt;
|
|
|
|
const SIDE: u32 = 16;
|
|
const TRI: [[f32; 3]; 3] = [[-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0]];
|
|
const CUSTOM: u32 = 42;
|
|
const WAIT: Duration = Duration::from_secs(30);
|
|
|
|
const SHADER: &str = r#"
|
|
enable wgpu_ray_query;
|
|
|
|
@group(0) @binding(0) var scene: acceleration_structure;
|
|
@group(0) @binding(1) var<storage, read_write> results: array<vec4<f32>>;
|
|
|
|
const SIDE: u32 = 16u;
|
|
|
|
@compute @workgroup_size(8, 8)
|
|
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
let idx = gid.y * SIDE + gid.x;
|
|
if (idx >= SIDE * SIDE) { return; }
|
|
let uv = (vec2<f32>(f32(gid.x) + 0.5, f32(gid.y) + 0.5) / f32(SIDE)) * 2.0 - 1.0;
|
|
var rq: ray_query;
|
|
let ray = RayDesc(
|
|
RAY_FLAG_NONE, 0xFFu, 0.0, 100.0,
|
|
vec3<f32>(uv.x, uv.y, -1.0),
|
|
vec3<f32>(0.0, 0.0, 1.0),
|
|
);
|
|
rayQueryInitialize(&rq, scene, ray);
|
|
loop {
|
|
if (!rayQueryProceed(&rq)) { break; }
|
|
}
|
|
let hit = rayQueryGetCommittedIntersection(&rq);
|
|
results[idx] = vec4<f32>(f32(hit.kind), hit.t, f32(hit.instance_custom_data), f32(hit.primitive_index));
|
|
}
|
|
"#;
|
|
|
|
#[derive(Clone, Default)]
|
|
struct ErrLog(Arc<Mutex<Vec<String>>>);
|
|
|
|
impl ErrLog {
|
|
fn drain(&self) -> Vec<String> {
|
|
std::mem::take(&mut self.0.lock().unwrap())
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
std::process::exit(run());
|
|
}
|
|
|
|
fn unsupported(stage: &str, why: &str) -> i32 {
|
|
println!("RESULT: UNSUPPORTED - {stage}: {why}");
|
|
2
|
|
}
|
|
|
|
fn run() -> i32 {
|
|
println!(
|
|
"airdef-rt-probe: issue #125 stage 1, wgpu =30.0.1 + engine third_party/wgpu-hal patch"
|
|
);
|
|
println!("os: {} {}", env::consts::OS, env::consts::ARCH);
|
|
|
|
// RT_PROBE_BACKEND restricts the backend set, e.g. `gl` to exercise the
|
|
// unsupported-adapter fallback on a machine whose primary backend has RT.
|
|
let backends = match env::var("RT_PROBE_BACKEND").as_deref() {
|
|
Ok("metal") => wgpu::Backends::METAL,
|
|
Ok("vulkan") => wgpu::Backends::VULKAN,
|
|
Ok("dx12") => wgpu::Backends::DX12,
|
|
Ok("gl") => wgpu::Backends::GL,
|
|
_ => wgpu::Backends::all(),
|
|
};
|
|
println!("probing backends: {backends:?}");
|
|
let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
|
instance_desc.backends = backends;
|
|
instance_desc.flags =
|
|
wgpu::InstanceFlags::from_build_config() | wgpu::InstanceFlags::VALIDATION;
|
|
let instance = wgpu::Instance::new(instance_desc);
|
|
let adapters = pollster::block_on(instance.enumerate_adapters(backends));
|
|
if adapters.is_empty() {
|
|
return unsupported("adapter", "no native adapter exposed on this OS");
|
|
}
|
|
let mut chosen = None;
|
|
for (i, adapter) in adapters.iter().enumerate() {
|
|
let info = adapter.get_info();
|
|
let features = adapter.features();
|
|
println!(
|
|
"adapter[{i}]: backend={:?} name={:?} vendor={:#06x} device={:#06x} type={:?} driver={:?} driver_info={:?}",
|
|
info.backend,
|
|
info.name,
|
|
info.vendor,
|
|
info.device,
|
|
info.device_type,
|
|
info.driver,
|
|
info.driver_info
|
|
);
|
|
println!(
|
|
" EXPERIMENTAL_RAY_QUERY={} features={:?}",
|
|
features.contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY),
|
|
features
|
|
);
|
|
if chosen.is_none() && features.contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) {
|
|
chosen = Some(i);
|
|
}
|
|
}
|
|
let Some(idx) = chosen else {
|
|
return unsupported(
|
|
"adapter",
|
|
"no adapter exposes Features::EXPERIMENTAL_RAY_QUERY on this OS/backend set",
|
|
);
|
|
};
|
|
let adapter = &adapters[idx];
|
|
let info = adapter.get_info();
|
|
println!(
|
|
"selected adapter[{idx}]: backend={:?} name={:?}",
|
|
info.backend, info.name
|
|
);
|
|
|
|
let (device, queue) =
|
|
match pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
|
label: Some("rt-probe"),
|
|
required_features: wgpu::Features::EXPERIMENTAL_RAY_QUERY,
|
|
// Default limits keep max_blas_geometry_count/max_tlas_instance_count at 0;
|
|
// ask for the adapter's real limits so RT resources can be created.
|
|
required_limits: adapter.limits(),
|
|
// SAFETY: deliberate experimental opt-in, confined to this probe; the
|
|
// game itself never requests experimental features (issue #125).
|
|
// RT_PROBE_NO_OPTIN=1 keeps the opt-in disabled to prove a normal
|
|
// launch cannot get RT even on a capable adapter.
|
|
experimental_features: if env::var("RT_PROBE_NO_OPTIN").is_ok() {
|
|
println!("experimental opt-in: disabled (RT_PROBE_NO_OPTIN)");
|
|
wgpu::ExperimentalFeatures::disabled()
|
|
} else {
|
|
unsafe { wgpu::ExperimentalFeatures::enabled() }
|
|
},
|
|
..Default::default()
|
|
})) {
|
|
Ok(pair) => pair,
|
|
Err(e) => {
|
|
return unsupported(
|
|
"device",
|
|
&format!("request_device with EXPERIMENTAL_RAY_QUERY failed: {e}"),
|
|
);
|
|
}
|
|
};
|
|
let errors = ErrLog::default();
|
|
let sink = errors.clone();
|
|
device.on_uncaptured_error(Arc::new(move |e| {
|
|
eprintln!("uncaptured device error: {e}");
|
|
sink.0.lock().unwrap().push(format!("{e}"));
|
|
}));
|
|
println!("device features: {:?}", device.features());
|
|
println!(
|
|
"allowed BLAS vertex formats: {:?}",
|
|
device.features().allowed_vertex_formats_for_blas()
|
|
);
|
|
|
|
let vertices: Vec<f32> = TRI.iter().flatten().copied().collect();
|
|
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
|
label: Some("probe-triangle"),
|
|
contents: bytemuck_bytes(&vertices),
|
|
usage: wgpu::BufferUsages::VERTEX
|
|
| wgpu::BufferUsages::BLAS_INPUT
|
|
| wgpu::BufferUsages::COPY_DST,
|
|
});
|
|
let size = wgpu::BlasTriangleGeometrySizeDescriptor {
|
|
vertex_format: wgpu::VertexFormat::Float32x3,
|
|
vertex_count: 3,
|
|
index_format: None,
|
|
index_count: None,
|
|
flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
|
|
};
|
|
let blas = device.create_blas(
|
|
&wgpu::CreateBlasDescriptor {
|
|
label: Some("probe-blas"),
|
|
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
|
|
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
|
|
},
|
|
wgpu::BlasGeometrySizeDescriptors::Triangles {
|
|
descriptors: vec![size.clone()],
|
|
},
|
|
);
|
|
let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor {
|
|
label: Some("probe-tlas"),
|
|
max_instances: 1,
|
|
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
|
|
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
|
|
});
|
|
tlas[0] = Some(wgpu::TlasInstance::new(
|
|
&blas,
|
|
[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
|
|
CUSTOM,
|
|
0xFF,
|
|
));
|
|
let problems = errors.drain();
|
|
if !problems.is_empty() {
|
|
return unsupported("blas/tlas", &problems.join("; "));
|
|
}
|
|
println!("stage blas/tlas: created (1 triangle, 1 instance)");
|
|
|
|
let mut encoder = device.create_command_encoder(&Default::default());
|
|
encoder.build_acceleration_structures(
|
|
&[wgpu::BlasBuildEntry {
|
|
blas: &blas,
|
|
geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {
|
|
size: &size,
|
|
vertex_buffer: &vertex_buffer,
|
|
first_vertex: 0,
|
|
vertex_stride: 12,
|
|
index_buffer: None,
|
|
first_index: None,
|
|
transform_buffer: None,
|
|
transform_buffer_offset: None,
|
|
}]),
|
|
}],
|
|
[&tlas],
|
|
);
|
|
if let Err(code) = submit_checked(&device, &queue, encoder, &errors, "as-build") {
|
|
return code;
|
|
}
|
|
println!("stage as-build: ok");
|
|
|
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
|
label: Some("probe-ray-query"),
|
|
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
|
|
});
|
|
let compilation = pollster::block_on(shader.get_compilation_info());
|
|
let shader_errors: Vec<String> = compilation
|
|
.messages
|
|
.iter()
|
|
.filter(|m| m.message_type == wgpu::CompilationMessageType::Error)
|
|
.map(|m| m.message.clone())
|
|
.collect();
|
|
let mut stage_errors = errors.drain();
|
|
stage_errors.extend(shader_errors);
|
|
if !stage_errors.is_empty() {
|
|
return unsupported("ray-query shader", &stage_errors.join("; "));
|
|
}
|
|
println!("stage ray-query shader: compiled");
|
|
|
|
let results = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: Some("probe-results"),
|
|
size: (SIDE * SIDE * 16) as u64,
|
|
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
|
mapped_at_creation: false,
|
|
});
|
|
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
label: Some("probe-bgl"),
|
|
entries: &[
|
|
wgpu::BindGroupLayoutEntry {
|
|
binding: 0,
|
|
visibility: wgpu::ShaderStages::COMPUTE,
|
|
ty: wgpu::BindingType::AccelerationStructure {
|
|
vertex_return: false,
|
|
},
|
|
count: None,
|
|
},
|
|
wgpu::BindGroupLayoutEntry {
|
|
binding: 1,
|
|
visibility: wgpu::ShaderStages::COMPUTE,
|
|
ty: wgpu::BindingType::Buffer {
|
|
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
|
has_dynamic_offset: false,
|
|
min_binding_size: None,
|
|
},
|
|
count: None,
|
|
},
|
|
],
|
|
});
|
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
label: Some("probe-bg"),
|
|
layout: &bind_group_layout,
|
|
entries: &[
|
|
wgpu::BindGroupEntry {
|
|
binding: 0,
|
|
resource: tlas.as_binding(),
|
|
},
|
|
wgpu::BindGroupEntry {
|
|
binding: 1,
|
|
resource: results.as_entire_binding(),
|
|
},
|
|
],
|
|
});
|
|
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
|
label: Some("probe-pl"),
|
|
bind_group_layouts: &[Some(&bind_group_layout)],
|
|
immediate_size: 0,
|
|
});
|
|
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
|
label: Some("probe-pipeline"),
|
|
layout: Some(&pipeline_layout),
|
|
module: &shader,
|
|
entry_point: Some("main"),
|
|
compilation_options: Default::default(),
|
|
cache: None,
|
|
});
|
|
let readback = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: Some("probe-readback"),
|
|
size: results.size(),
|
|
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
|
mapped_at_creation: false,
|
|
});
|
|
let mut encoder = device.create_command_encoder(&Default::default());
|
|
{
|
|
let mut pass = encoder.begin_compute_pass(&Default::default());
|
|
pass.set_pipeline(&pipeline);
|
|
pass.set_bind_group(0, &bind_group, &[]);
|
|
pass.dispatch_workgroups(SIDE / 8, SIDE / 8, 1);
|
|
}
|
|
encoder.copy_buffer_to_buffer(&results, 0, &readback, 0, results.size());
|
|
if let Err(code) = submit_checked(&device, &queue, encoder, &errors, "ray-query frame") {
|
|
return code;
|
|
}
|
|
|
|
let slice = readback.slice(..);
|
|
slice.map_async(wgpu::MapMode::Read, |_| {});
|
|
if let Err(e) = device.poll(wgpu::PollType::Wait {
|
|
submission_index: None,
|
|
timeout: Some(WAIT),
|
|
}) {
|
|
println!("RESULT: FAIL - readback poll: {e}");
|
|
return 1;
|
|
}
|
|
let data = match slice.get_mapped_range() {
|
|
Ok(view) => view,
|
|
Err(e) => {
|
|
println!("RESULT: FAIL - readback map: {e}");
|
|
return 1;
|
|
}
|
|
};
|
|
let ray = |i: usize| -> [f32; 4] {
|
|
let b = &data[i * 16..i * 16 + 16];
|
|
std::array::from_fn(|k| f32::from_le_bytes(b[k * 4..k * 4 + 4].try_into().unwrap()))
|
|
};
|
|
|
|
let mut hits = 0u32;
|
|
let mut misses = 0u32;
|
|
let mut wrong = 0u32;
|
|
let mut max_t_err = 0.0f32;
|
|
println!("ray-query frame ({SIDE}x{SIDE}, '#'=hit, '.'=miss):");
|
|
for y in 0..SIDE {
|
|
let mut row = String::new();
|
|
for x in 0..SIDE {
|
|
let i = (y * SIDE + x) as usize;
|
|
let [kind, t, custom, prim] = ray(i);
|
|
let uv = [
|
|
(x as f32 + 0.5) / SIDE as f32 * 2.0 - 1.0,
|
|
(y as f32 + 0.5) / SIDE as f32 * 2.0 - 1.0,
|
|
];
|
|
let expect_hit = inside_triangle(uv);
|
|
let ok = if expect_hit {
|
|
hits += 1;
|
|
max_t_err = max_t_err.max((t - 1.0).abs());
|
|
kind == 1.0 && (t - 1.0).abs() <= 1e-3 && custom == CUSTOM as f32 && prim == 0.0
|
|
} else {
|
|
misses += 1;
|
|
kind == 0.0
|
|
};
|
|
if !ok {
|
|
wrong += 1;
|
|
eprintln!(
|
|
"ray {i} uv={uv:?}: got kind={kind} t={t} custom={custom} prim={prim}, expected hit={expect_hit}"
|
|
);
|
|
}
|
|
row.push(if kind == 1.0 { '#' } else { '.' });
|
|
}
|
|
println!("{row}");
|
|
}
|
|
println!("hits={hits} misses={misses} wrong={wrong} max_t_err={max_t_err:.6}");
|
|
if wrong != 0 {
|
|
println!("RESULT: FAIL - ray results disagree with CPU expectation");
|
|
return 1;
|
|
}
|
|
println!(
|
|
"RESULT: OK - BLAS/TLAS build and ray query verified on backend={:?} name={:?} ({} hits, {} misses, all match CPU expectation)",
|
|
info.backend, info.name, hits, misses
|
|
);
|
|
0
|
|
}
|
|
|
|
fn submit_checked(
|
|
device: &wgpu::Device,
|
|
queue: &wgpu::Queue,
|
|
encoder: wgpu::CommandEncoder,
|
|
errors: &ErrLog,
|
|
stage: &str,
|
|
) -> Result<(), i32> {
|
|
let guard = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
|
let index = queue.submit([encoder.finish()]);
|
|
let poll = device.poll(wgpu::PollType::Wait {
|
|
submission_index: Some(index),
|
|
timeout: Some(WAIT),
|
|
});
|
|
let scoped = pollster::block_on(guard.pop());
|
|
let mut problems = errors.drain();
|
|
problems.extend(scoped.map(|e| format!("{e}")));
|
|
if !problems.is_empty() {
|
|
return Err(unsupported(stage, &problems.join("; ")));
|
|
}
|
|
if let Err(e) = poll {
|
|
println!("RESULT: FAIL - {stage} poll: {e}");
|
|
return Err(1);
|
|
}
|
|
println!("stage {stage}: submitted and waited");
|
|
Ok(())
|
|
}
|
|
|
|
fn inside_triangle(p: [f32; 2]) -> bool {
|
|
let cross = |o: [f32; 3], u: [f32; 3], v: [f32; 3]| {
|
|
(u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0])
|
|
};
|
|
let p3 = [p[0], p[1], 0.0];
|
|
let d1 = cross(TRI[0], TRI[1], p3);
|
|
let d2 = cross(TRI[1], TRI[2], p3);
|
|
let d3 = cross(TRI[2], TRI[0], p3);
|
|
let has_neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
|
|
let has_pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
|
|
!(has_neg && has_pos)
|
|
}
|
|
|
|
fn bytemuck_bytes(values: &[f32]) -> &[u8] {
|
|
unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), std::mem::size_of_val(values)) }
|
|
}
|