DirectX 12 on Windows: the fallback when Vulkan fails, and a setting (#746)

The Windows client builds wgpu's dx12 backend. With graphicsApi:auto (the
default), the renderer opens Vulkan and falls back to DirectX 12 when Vulkan
has no adapter (no Vulkan driver) or its device request fails; vulkan and dx12
pick one (horizon-graphics.txt, Video Settings > Graphics API on Windows, or
HORIZON_GRAPHICS_API; WGPU_BACKEND still overrides). Other systems keep their
one backend.

DirectX 12 keeps wgpu's indirect-draw validation: it is what passes each
draw's first instance to shaders there. Occlusion culling stays Vulkan-only and
flat draws Metal-only, as before; multi-draw and the GPU timer use DirectX 12's
own. gpu-allocator now resolves to the windows crate wgpu-hal's dx12 code
uses (0.62): with cpal's 0.54 it did not compile. A test translates every WGSL
shader to HLSL as the dx12 backend does for FXC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-19 07:34:11 +02:00
parent 70de685d2b
commit 8aacf93d8f
6 changed files with 396 additions and 100 deletions
Generated
+11
View File
@@ -1293,6 +1293,7 @@ dependencies = [
"log", "log",
"presser", "presser",
"thiserror 2.0.21", "thiserror 2.0.21",
"windows 0.62.2",
] ]
[[package]] [[package]]
@@ -3027,6 +3028,12 @@ dependencies = [
"getrandom 0.2.17", "getrandom 0.2.17",
] ]
[[package]]
name = "range-alloc"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"
[[package]] [[package]]
name = "raw-window-handle" name = "raw-window-handle"
version = "0.6.2" version = "0.6.2"
@@ -4607,6 +4614,7 @@ dependencies = [
"android_system_properties", "android_system_properties",
"arrayvec", "arrayvec",
"ash", "ash",
"bit-set 0.10.0",
"bitflags 2.13.2", "bitflags 2.13.2",
"block2 0.6.2", "block2 0.6.2",
"bytemuck", "bytemuck",
@@ -4625,11 +4633,13 @@ dependencies = [
"objc2-foundation 0.3.2", "objc2-foundation 0.3.2",
"objc2-metal 0.3.2", "objc2-metal 0.3.2",
"objc2-quartz-core 0.3.2", "objc2-quartz-core 0.3.2",
"once_cell",
"ordered-float", "ordered-float",
"parking_lot", "parking_lot",
"portable-atomic", "portable-atomic",
"portable-atomic-util", "portable-atomic-util",
"profiling", "profiling",
"range-alloc",
"raw-window-handle", "raw-window-handle",
"raw-window-metal", "raw-window-metal",
"renderdoc-sys", "renderdoc-sys",
@@ -4639,6 +4649,7 @@ dependencies = [
"wgpu-naga-bridge", "wgpu-naga-bridge",
"wgpu-types", "wgpu-types",
"windows 0.62.2", "windows 0.62.2",
"windows-core 0.62.2",
] ]
[[package]] [[package]]
+10
View File
@@ -58,6 +58,12 @@ ureq = { version = "2", default-features = false, features = ["tls"] }
# The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs). # The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs).
rustix = { version = "1", default-features = false, features = ["std", "time"] } rustix = { version = "1", default-features = false, features = ["std", "time"] }
[target.'cfg(windows)'.dependencies]
# DirectX 12, where Vulkan has no adapter or device, or by choice (`graphicsApi`, graphics.rs).
# Shaders compile with FXC (d3dcompiler_47.dll, part of Windows), or DXC when dxcompiler.dll is
# on the PATH.
wgpu = { version = "30.0.1", default-features = false, features = ["dx12"] }
[target.'cfg(windows)'.build-dependencies] [target.'cfg(windows)'.build-dependencies]
# The icon resource in the .exe (build.rs). # The icon resource in the .exe (build.rs).
winresource = "0.1" winresource = "0.1"
@@ -74,3 +80,7 @@ rng-trace = ["horizon-core/rng-trace"]
[lints] [lints]
workspace = true workspace = true
[dev-dependencies]
# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests).
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
+20 -2
View File
@@ -8285,6 +8285,7 @@ impl Game<'_> {
pack, pack,
gui, gui,
self.renderer.as_ref(), self.renderer.as_ref(),
self.settings.horizon.api,
) )
} }
fn apply_settings(&mut self) { fn apply_settings(&mut self) {
@@ -11346,6 +11347,7 @@ fn build_renderer(
pack: &PackResources, pack: &PackResources,
gui: &UiResources, gui: &UiResources,
previous: Option<&Renderer>, previous: Option<&Renderer>,
api: horizon_client::graphics::GraphicsApi,
) -> Result<Renderer> { ) -> Result<Renderer> {
let assets = &pack.render; let assets = &pack.render;
let atlas = &gui.atlas; let atlas = &gui.atlas;
@@ -11362,6 +11364,7 @@ fn build_renderer(
(&pack.forcefield.2, pack.forcefield.0), (&pack.forcefield.2, pack.forcefield.0),
&gui.panorama, &gui.panorama,
previous, previous,
api,
))?; ))?;
renderer.hud.fire_animations = atlas renderer.hud.fire_animations = atlas
.fire_animations .fire_animations
@@ -11379,6 +11382,7 @@ fn loading_renderer(
offscreen: bool, offscreen: bool,
gui: Option<&UiResources>, gui: Option<&UiResources>,
previous: Option<&Renderer>, previous: Option<&Renderer>,
api: horizon_client::graphics::GraphicsApi,
) -> Result<Renderer> { ) -> Result<Renderer> {
static FORCEFIELD: [u8; 4] = [0; 4]; static FORCEFIELD: [u8; 4] = [0; 4];
static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255]; static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255];
@@ -11405,6 +11409,7 @@ fn loading_renderer(
(&FORCEFIELD[..], 1), (&FORCEFIELD[..], 1),
panorama, panorama,
previous, previous,
api,
))?; ))?;
if let Some(atlas) = atlas { if let Some(atlas) = atlas {
renderer.hud.fire_animations = atlas renderer.hud.fire_animations = atlas
@@ -11670,7 +11675,13 @@ impl Loading {
} }
}; };
let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen); let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen);
match loading_renderer(window.clone(), offscreen, self.gui.as_ref(), None) { match loading_renderer(
window.clone(),
offscreen,
self.gui.as_ref(),
None,
self.settings.horizon.api,
) {
Ok(r) => self.renderer = Some(r), Ok(r) => self.renderer = Some(r),
Err(e) => { Err(e) => {
self.error = Some(e); self.error = Some(e);
@@ -11712,7 +11723,13 @@ impl Loading {
if let Some(renderer) = &mut self.renderer { if let Some(renderer) = &mut self.renderer {
renderer.release_surface(); renderer.release_surface();
} }
match loading_renderer(window, offscreen, self.gui.as_ref(), self.renderer.as_ref()) { match loading_renderer(
window,
offscreen,
self.gui.as_ref(),
self.renderer.as_ref(),
self.settings.horizon.api,
) {
Ok(r) => { Ok(r) => {
self.settings self.settings
.clamp_gui_scale([r.config.width as i32, r.config.height as i32]); .clamp_gui_scale([r.config.width as i32, r.config.height as i32]);
@@ -11783,6 +11800,7 @@ impl Loading {
&loaded.pack, &loaded.pack,
&gui, &gui,
self.renderer.as_ref(), self.renderer.as_ref(),
self.settings.horizon.api,
)?; )?;
log::info!( log::info!(
"Horizon: world renderer ready after {} ms", "Horizon: world renderer ready after {} ms",
+288 -95
View File
@@ -4,6 +4,7 @@
use crate::{ use crate::{
Result, Result,
environment::Sky, environment::Sky,
graphics::GraphicsApi,
hud::{HudBatch, HudRenderer}, hud::{HudBatch, HudRenderer},
mesher::{SectionMesh, TerrainVertex, Vertex}, mesher::{SectionMesh, TerrainVertex, Vertex},
sprites::SpriteAnimation, sprites::SpriteAnimation,
@@ -539,23 +540,187 @@ fn mip_chain(
/// bounds by construction: index counts within `indices`, vertices within /// bounds by construction: index counts within `indices`, vertices within
/// the section's arena range, first instances below the origins written that /// the section's arena range, first instances below the origins written that
/// frame. Debug builds keep validating them; `WGPU_VALIDATION_INDIRECT_CALL=1` /// frame. Debug builds keep validating them; `WGPU_VALIDATION_INDIRECT_CALL=1`
/// turns it back on. /// turns it back on. DirectX 12 keeps it too: there wgpu-core's validation
fn instance_descriptor() -> wgpu::InstanceDescriptor { /// pass is also what passes each draw's first instance to shaders reading
/// `instance_index`, and DirectX 12 is the fallback, where working matters
/// more than CPU time.
fn instance_descriptor(backends: wgpu::Backends) -> wgpu::InstanceDescriptor {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
if !cfg!(debug_assertions) { descriptor.backends = backends.with_env();
let dx12 = cfg!(windows) && descriptor.backends.contains(wgpu::Backends::DX12);
if !cfg!(debug_assertions) && !dx12 {
descriptor descriptor
.flags .flags
.remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL); .remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL);
} }
descriptor.with_env() descriptor.with_env()
} }
/// The backends to open a device on, each tried in turn until one gives a
/// device. `api` is the player's choice (`GraphicsApi::with_env` applied);
/// `wgpu_backend`: whether `WGPU_BACKEND` is set, which picks the backends
/// itself. Only Windows has two: Auto tries Vulkan, then DirectX 12 when
/// Vulkan has no adapter (no Vulkan driver) or no device. A native crash in
/// the driver can't be caught in the game; the launcher switches the setting
/// to DirectX 12 after one at the renderer's start (#746).
fn backend_order(api: GraphicsApi, windows: bool, wgpu_backend: bool) -> Vec<wgpu::Backends> {
if !windows || wgpu_backend {
return vec![wgpu::Backends::default()];
}
match api {
GraphicsApi::Auto => vec![wgpu::Backends::VULKAN, wgpu::Backends::DX12],
GraphicsApi::Vulkan => vec![wgpu::Backends::VULKAN],
GraphicsApi::Dx12 => vec![wgpu::Backends::DX12],
}
}
fn backends_name(backends: wgpu::Backends) -> &'static str {
match backends {
wgpu::Backends::VULKAN => "Vulkan",
wgpu::Backends::DX12 => "DirectX 12",
_ => "graphics",
}
}
/// A device and what it came from.
struct Opened {
instance: wgpu::Instance,
surface: Option<wgpu::Surface<'static>>,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
}
/// Logs the adapter and records it for telemetry and crash reports.
fn describe_adapter(adapter: &wgpu::Adapter) {
let info = adapter.get_info();
log::info!(
"Horizon renderer: {} ({:?}, {:?})",
info.name,
info.backend,
info.device_type
);
crate::telemetry::set_gpu(
&info.name,
format!("{} {}", info.driver, info.driver_info)
.trim()
.to_owned(),
format!("{:?}", info.backend),
);
crate::crash::set_detail(
"Graphics Adapter",
format!(
"{} ({:?}, {:?}), driver {} {}",
info.name, info.backend, info.device_type, info.driver, info.driver_info
),
);
}
/// Whether an adapter's texture arrays hold the block textures Horizon puts
/// in one array.
fn check_layers(limits: &wgpu::Limits, layers: u32) -> Result<()> {
let needed = layers.min(sprite_split());
if limits.max_texture_array_layers < needed {
return Err(format!(
"GPU supports {} texture layers; {needed} required",
limits.max_texture_array_layers
)
.into());
}
Ok(())
}
/// Opens a device on the first of `backend_order`'s backends that gives one.
/// Offscreen rendering needs no surface, so it can use a GPU the window's
/// display cannot present from (a headless compositor).
async fn open_device(
window: &Arc<Window>,
offscreen: bool,
api: GraphicsApi,
layers: u32,
) -> Result<Opened> {
let order = backend_order(
api.with_env(),
cfg!(windows),
std::env::var_os("WGPU_BACKEND").is_some(),
);
let mut failures = Vec::new();
for (attempt, backends) in order.iter().copied().enumerate() {
let name = backends_name(backends);
if attempt > 0 {
log::warn!("Horizon renderer: trying {name} ({})", failures.join("; "));
}
let instance = wgpu::Instance::new(instance_descriptor(backends));
let surface = if offscreen {
None
} else {
Some(instance.create_surface(window.clone())?)
};
let adapter = match instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: surface.as_ref(),
force_fallback_adapter: false,
..Default::default()
})
.await
{
Ok(adapter) => adapter,
Err(e) => {
failures.push(format!("{name}: {e}"));
continue;
}
};
describe_adapter(&adapter);
let info = adapter.get_info();
let limits = adapter.limits();
if let Err(e) = check_layers(&limits, layers) {
failures.push(format!("{name}: {e}"));
continue;
}
// Mappable primary buffers: section pages that no longer fit in
// video memory go to system memory.
let features = timing::GpuTimer::features(&adapter)
| cull::Cull::features(&adapter)
| (adapter.features()
& (wgpu::Features::INDIRECT_FIRST_INSTANCE
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS));
let driver = format!("{} {}", info.driver, info.driver_info);
startup_step(format_args!(
"requesting the device (driver {}) with features [{features}] and the adapter's \
limits (buffers up to {} bytes, storage bindings up to {} bytes, {} texture layers)",
match driver.trim() {
"" => "unnamed",
driver => driver,
},
limits.max_buffer_size,
limits.max_storage_buffer_binding_size,
limits.max_texture_array_layers,
));
match adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("Horizon device"),
required_features: features,
required_limits: limits,
..Default::default()
})
.await
{
Ok((device, queue)) => {
return Ok(Opened {
instance,
surface,
adapter,
device,
queue,
});
}
Err(e) => failures.push(format!("{name} device: {e}")),
}
}
Err(format!("{NO_GPU_DRIVER} ({})", failures.join("; ")).into())
}
/// What to tell a player whose system offers no usable graphics adapter. /// What to tell a player whose system offers no usable graphics adapter.
/// Vulkan is loaded at run time (the game links no graphics library), so a /// Vulkan is loaded at run time (the game links no graphics library), so a
/// missing driver shows here rather than as a missing-DLL dialog. /// missing driver shows here rather than as a missing-DLL dialog.
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
const NO_GPU_DRIVER: &str = "No Vulkan graphics driver found: Horizon needs a GPU driver with Vulkan \ const NO_GPU_DRIVER: &str = "No graphics driver with Vulkan or DirectX 12 found: Horizon needs a GPU \
(vulkan-1.dll comes with it). Install the latest driver for your NVIDIA, AMD or Intel GPU \ driver with one of them. Install the latest driver for your NVIDIA, AMD or Intel GPU and \
and start the game again"; start the game again";
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
const NO_GPU_DRIVER: &str = "No Metal graphics device found"; const NO_GPU_DRIVER: &str = "No Metal graphics device found";
#[cfg(not(any(target_os = "windows", target_os = "macos")))] #[cfg(not(any(target_os = "windows", target_os = "macos")))]
@@ -610,54 +775,8 @@ impl Renderer {
forcefield: (&[u8], u32), forcefield: (&[u8], u32),
panorama_faces: &panorama::Faces, panorama_faces: &panorama::Faces,
previous: Option<&Self>, previous: Option<&Self>,
api: GraphicsApi,
) -> Result<Self> { ) -> Result<Self> {
// Reload resources on the same device; replacing live Vulkan devices
// can invalidate the driver's swapchain state on the same window.
let instance = previous.map_or_else(
|| wgpu::Instance::new(instance_descriptor()),
|renderer| renderer.instance.clone(),
);
// Offscreen rendering needs no surface, so it can use a GPU the
// window's display cannot present from (a headless compositor).
let surface = if offscreen {
None
} else {
Some(instance.create_surface(window.clone())?)
};
let adapter = match previous {
Some(renderer) => renderer.adapter.clone(),
None => instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: surface.as_ref(),
force_fallback_adapter: false,
..Default::default()
})
.await
.map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?,
};
let info = adapter.get_info();
log::info!(
"Horizon renderer: {} ({:?}, {:?})",
info.name,
info.backend,
info.device_type
);
crate::telemetry::set_gpu(
&info.name,
format!("{} {}", info.driver, info.driver_info)
.trim()
.to_owned(),
format!("{:?}", info.backend),
);
crate::crash::set_detail(
"Graphics Adapter",
format!(
"{} ({:?}, {:?}), driver {} {}",
info.name, info.backend, info.device_type, info.driver, info.driver_info
),
);
let limits = adapter.limits();
let split = sprite_split(); let split = sprite_split();
if layers > split * SPRITE_ARRAYS { if layers > split * SPRITE_ARRAYS {
return Err(format!( return Err(format!(
@@ -666,46 +785,34 @@ impl Renderer {
) )
.into()); .into());
} }
if limits.max_texture_array_layers < layers.min(split) { let Opened {
return Err(format!( instance,
"GPU supports {} texture layers; {} required", surface,
limits.max_texture_array_layers, adapter,
layers.min(split) device,
) queue,
.into()); } = match previous {
} // Reload resources on the same device; replacing live Vulkan
let (device, queue) = match previous { // devices can invalidate the driver's swapchain state on the same
Some(renderer) => (renderer.device.clone(), renderer.queue.clone()), // window.
None => { Some(renderer) => {
// Mappable primary buffers: section pages that no longer fit describe_adapter(&renderer.adapter);
// in video memory go to system memory. check_layers(&renderer.adapter.limits(), layers)?;
let features = timing::GpuTimer::features(&adapter) Opened {
| cull::Cull::features(&adapter) surface: if offscreen {
| (adapter.features() None
& (wgpu::Features::INDIRECT_FIRST_INSTANCE } else {
| wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)); Some(renderer.instance.create_surface(window.clone())?)
let driver = format!("{} {}", info.driver, info.driver_info);
startup_step(format_args!(
"requesting the device (driver {}) with features [{features}] and the adapter's \
limits (buffers up to {} bytes, storage bindings up to {} bytes, {} texture layers)",
match driver.trim() {
"" => "unnamed",
driver => driver,
}, },
limits.max_buffer_size, instance: renderer.instance.clone(),
limits.max_storage_buffer_binding_size, adapter: renderer.adapter.clone(),
limits.max_texture_array_layers, device: renderer.device.clone(),
)); queue: renderer.queue.clone(),
adapter }
.request_device(&wgpu::DeviceDescriptor {
label: Some("Horizon device"),
required_features: features,
required_limits: limits.clone(),
..Default::default()
})
.await?
} }
None => open_device(&window, offscreen, api, layers).await?,
}; };
let info = adapter.get_info();
let size = window.inner_size(); let size = window.inner_size();
let (config, present_modes) = if let Some(surface) = &surface { let (config, present_modes) = if let Some(surface) = &surface {
let mut config = surface let mut config = surface
@@ -3747,6 +3854,84 @@ mod tests {
); );
} }
#[test] #[test]
fn windows_tries_vulkan_then_directx_12() {
use super::{GraphicsApi, backend_order};
use wgpu::Backends;
assert_eq!(
backend_order(GraphicsApi::Auto, true, false),
[Backends::VULKAN, Backends::DX12]
);
assert_eq!(
backend_order(GraphicsApi::Vulkan, true, false),
[Backends::VULKAN]
);
assert_eq!(
backend_order(GraphicsApi::Dx12, true, false),
[Backends::DX12]
);
// WGPU_BACKEND picks the backends itself; other systems have one.
for api in GraphicsApi::ALL {
assert_eq!(backend_order(api, true, true), [Backends::default()]);
assert_eq!(backend_order(api, false, false), [Backends::default()]);
}
}
/// Every WGSL shader file translates to HLSL as wgpu's DirectX 12 backend
/// writes it for FXC (shader model 5.1), entry point by entry point.
#[test]
fn shaders_translate_to_hlsl_for_directx_12() {
fn wgsl_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
wgsl_files(&path, out);
} else if path.extension().is_some_and(|e| e == "wgsl") {
out.push(path);
}
}
}
let mut files = Vec::new();
wgsl_files(
std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
&mut files,
);
assert!(files.len() >= 10, "{files:?}");
for path in files {
let text = std::fs::read_to_string(&path).unwrap();
// entity.wgsl comes after the overlay's constants (entity_shader).
let module = naga::front::wgsl::parse_str(&text)
.or_else(|_| {
naga::front::wgsl::parse_str(&(crate::overlay::wgsl_constants() + &text))
})
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
let info = naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap_or_else(|e| panic!("{}: {e:?}", path.display()));
for entry in &module.entry_points {
let (module, info) = naga::back::pipeline_constants::process_overrides(
&module,
&info,
Some((entry.stage, &entry.name)),
&Default::default(),
)
.unwrap();
let mut hlsl = String::new();
naga::back::hlsl::Writer::new(
&mut hlsl,
&naga::back::hlsl::Options::default(),
&naga::back::hlsl::PipelineOptions {
entry_point: Some((entry.stage, entry.name.clone())),
},
)
.write(&module, &info, None)
.unwrap_or_else(|e| panic!("{} {}: {e}", path.display(), entry.name));
assert!(!hlsl.is_empty());
}
}
}
#[test]
fn entity_shader_validates_with_its_overlay_constants() { fn entity_shader_validates_with_its_overlay_constants() {
let module = naga::front::wgsl::parse_str(&super::entity_shader()).unwrap(); let module = naga::front::wgsl::parse_str(&super::entity_shader()).unwrap();
naga::valid::Validator::new( naga::valid::Validator::new(
@@ -3806,12 +3991,20 @@ mod tests {
assert_eq!(super::outline_width(3840), 5.0); assert_eq!(super::outline_width(3840), 5.0);
} }
#[test] #[test]
fn indirect_draws_are_validated_only_in_debug_builds() { fn indirect_draws_are_validated_only_in_debug_builds_and_on_directx_12() {
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { let validated = |backends| {
let flags = super::instance_descriptor().flags; super::instance_descriptor(backends)
.flags
.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL)
};
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none()
&& std::env::var_os("WGPU_BACKEND").is_none()
{
assert_eq!(validated(wgpu::Backends::default()), cfg!(debug_assertions));
assert_eq!(validated(wgpu::Backends::VULKAN), cfg!(debug_assertions));
assert_eq!( assert_eq!(
flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL), validated(wgpu::Backends::DX12),
cfg!(debug_assertions) cfg!(debug_assertions) || cfg!(windows)
); );
} }
} }
+49 -1
View File
@@ -93,6 +93,48 @@ impl PresentMode {
} }
} }
/// The graphics API the renderer runs on. Only Windows has a choice: the
/// other systems always use their one backend (Vulkan on Linux, Metal on
/// macOS). Applies at the next start.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GraphicsApi {
/// Vulkan, and DirectX 12 when Vulkan has no adapter or device.
#[default]
Auto,
Vulkan,
Dx12,
}
impl GraphicsApi {
pub const ALL: [GraphicsApi; 3] = [GraphicsApi::Auto, GraphicsApi::Vulkan, GraphicsApi::Dx12];
pub fn name(self) -> &'static str {
match self {
GraphicsApi::Auto => "auto",
GraphicsApi::Vulkan => "vulkan",
GraphicsApi::Dx12 => "dx12",
}
}
pub fn label(self) -> &'static str {
match self {
GraphicsApi::Auto => "Auto",
GraphicsApi::Vulkan => "Vulkan",
GraphicsApi::Dx12 => "DirectX 12",
}
}
/// The API a name stands for, ignoring case; `None` for anything else.
pub fn from_name(s: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|api| api.name().eq_ignore_ascii_case(s.trim()))
}
/// `HORIZON_GRAPHICS_API` (auto, vulkan or dx12) if set, else the setting.
pub fn with_env(self) -> Self {
std::env::var("HORIZON_GRAPHICS_API")
.ok()
.and_then(|v| Self::from_name(&v))
.unwrap_or(self)
}
}
/// What the frame limiter does in the last half millisecond before a frame. /// What the frame limiter does in the last half millisecond before a frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Pacing { pub enum Pacing {
@@ -149,6 +191,8 @@ pub struct Graphics {
/// The Horizon shader pack in `shaderpacks/` (its folder name); empty: /// The Horizon shader pack in `shaderpacks/` (its folder name); empty:
/// none, the vanilla picture (docs/shader-packs.md). /// none, the vanilla picture (docs/shader-packs.md).
pub shader_pack: String, pub shader_pack: String,
/// The graphics API (Windows only; see `GraphicsApi`).
pub api: GraphicsApi,
} }
impl Default for Graphics { impl Default for Graphics {
fn default() -> Self { fn default() -> Self {
@@ -172,6 +216,7 @@ impl Default for Graphics {
advanced: false, advanced: false,
battery: false, battery: false,
shader_pack: String::new(), shader_pack: String::new(),
api: GraphicsApi::Auto,
} }
} }
} }
@@ -222,6 +267,7 @@ impl Graphics {
"level" => g.advanced = value == "advanced", "level" => g.advanced = value == "advanced",
"batteryMode" => g.battery = flag(g.battery), "batteryMode" => g.battery = flag(g.battery),
"shaderPack" => g.shader_pack = value.to_string(), "shaderPack" => g.shader_pack = value.to_string(),
"graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(),
"overlay" => { "overlay" => {
g.overlay = match value { g.overlay = match value {
"fps" => Overlay::Fps, "fps" => Overlay::Fps,
@@ -236,7 +282,7 @@ impl Graphics {
} }
pub fn serialize(&self) -> String { pub fn serialize(&self) -> String {
format!( format!(
"preset:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n", "preset:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
self.preset.name(), self.preset.name(),
bool_text(self.cave_culling), bool_text(self.cave_culling),
bool_text(self.cull_leaves), bool_text(self.cull_leaves),
@@ -263,6 +309,7 @@ impl Graphics {
if self.advanced { "advanced" } else { "simple" }, if self.advanced { "advanced" } else { "simple" },
bool_text(self.battery), bool_text(self.battery),
self.shader_pack, self.shader_pack,
self.api.name(),
) )
} }
pub fn save(&self, dir: &Path) { pub fn save(&self, dir: &Path) {
@@ -355,6 +402,7 @@ mod tests {
advanced: true, advanced: true,
battery: true, battery: true,
shader_pack: "horizon-sample".into(), shader_pack: "horizon-sample".into(),
api: GraphicsApi::Dx12,
}; };
assert_eq!(Graphics::parse(&g.serialize()), g); assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default()); assert_eq!(Graphics::parse(""), Graphics::default());
+18 -2
View File
@@ -2,7 +2,7 @@
//! they show, in what groups, with what description and cost, and their //! they show, in what groups, with what description and cost, and their
//! input. How they look comes from `graphics_style`. //! input. How they look comes from `graphics_style`.
use crate::{ use crate::{
graphics::{Overlay, Pacing, PresentMode, Preset}, graphics::{GraphicsApi, Overlay, Pacing, PresentMode, Preset},
graphics_style::{Cost, STYLE}, graphics_style::{Cost, STYLE},
hud::{HudAtlas, HudBatch}, hud::{HudAtlas, HudBatch},
options_ui::Opt, options_ui::Opt,
@@ -38,6 +38,7 @@ pub enum H {
Antialiasing, Antialiasing,
BatteryMode, BatteryMode,
ShaderPack, ShaderPack,
GraphicsApi,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -99,7 +100,7 @@ pub fn rows(level: Level) -> Vec<Row> {
None, None,
"Sets the options below together. Changing one makes it Custom.", "Sets the options below together. Changing one makes it Custom.",
); );
match level { let mut rows = match level {
Level::Simple => vec![preset, render, fov, fps, vsync, gui], Level::Simple => vec![preset, render, fov, fps, vsync, gui],
Level::Advanced => vec![ Level::Advanced => vec![
Row::Header("Rendering"), Row::Header("Rendering"),
@@ -248,6 +249,11 @@ pub fn rows(level: Level) -> Vec<Row> {
None, None,
"Threads that generate, light and mesh chunks. Next start.", "Threads that generate, light and mesh chunks. Next start.",
), ),
h(
H::GraphicsApi,
None,
"Vulkan, or DirectX 12 where Vulkan fails. Next start.",
),
h( h(
H::UploadBudget, H::UploadBudget,
Low, Low,
@@ -260,7 +266,14 @@ pub fn rows(level: Level) -> Vec<Row> {
"Frame rate and frame times over the game, with a graph.", "Frame rate and frame times over the game, with a graph.",
), ),
], ],
};
// Only Windows has more than one graphics API.
if !cfg!(windows) {
rows.retain(
|row| !matches!(row, Row::Setting(s) if s.item == Item::Horizon(H::GraphicsApi)),
);
} }
rows
} }
const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384]; const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384];
@@ -342,6 +355,7 @@ impl H {
H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)), H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)),
H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }), H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }),
H::BatteryMode => labelled("Battery Mode", on_off(g.battery)), H::BatteryMode => labelled("Battery Mode", on_off(g.battery)),
H::GraphicsApi => labelled("Graphics API", g.api.label()),
H::ShaderPack => match g.shader_pack.as_str() { H::ShaderPack => match g.shader_pack.as_str() {
"" => labelled("Shader Pack", "Off"), "" => labelled("Shader Pack", "Off"),
id => labelled("Shader Pack", id), id => labelled("Shader Pack", id),
@@ -393,6 +407,7 @@ impl H {
H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back), H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back),
H::Antialiasing => g.fxaa = !g.fxaa, H::Antialiasing => g.fxaa = !g.fxaa,
H::BatteryMode => g.battery = !g.battery, H::BatteryMode => g.battery = !g.battery,
H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back),
H::ShaderPack => { H::ShaderPack => {
// Off, then every pack in shaderpacks/ by folder name. // Off, then every pack in shaderpacks/ by folder name.
let dir = std::env::current_dir() let dir = std::env::current_dir()
@@ -497,6 +512,7 @@ impl Item {
| H::Workers | H::Workers
| H::BatteryMode | H::BatteryMode
| H::ShaderPack | H::ShaderPack
| H::GraphicsApi
) | Item::Vanilla( ) | Item::Vanilla(
Opt::GuiScale Opt::GuiScale
| Opt::Fullscreen | Opt::Fullscreen