diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 54fed4165f5..2faf4bc8930 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -128,7 +128,8 @@ The [architecture page](docs/architecture.md) has the layer table. The short ver - Non-test code never uses `unwrap`, `expect`, `panic!` or indexing on input-derived data. There's no `unsafe` outside `apps/solidcraft/src/open_documents.rs` (macOS file-open events), `apps/solidcraft/src/native_crash.rs` (Windows native crash capture) and - `crates/threedx-client/src/macos.rs` (the 3Dconnexion driver's client API on macOS), and the + `crates/threedx-client/src/macos.rs` (the 3Dconnexion driver's client API on macOS) and + `crates/gpu-native/src/pipeline_cache.rs` (the persistent GPU pipeline cache, #3236), and the compiler denies it. - An unsupported case returns an error ("not supported yet: …"); it never panics. - Every call into truck goes through `solidcraft_kernel::guard`. diff --git a/Cargo.lock b/Cargo.lock index 9a17497e9fb..7d713af4fbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4326,8 +4326,10 @@ dependencies = [ "robust", "serde", "serde_json", + "sha2 0.10.9", "solidcraft-engine", "solidcraft-geom", + "solidcraft-gpu-native", "solidcraft-io", "solidcraft-kernel", "solidcraft-render", @@ -4335,6 +4337,13 @@ dependencies = [ "wgpu", ] +[[package]] +name = "solidcraft-gpu-native" +version = "0.30.0" +dependencies = [ + "wgpu", +] + [[package]] name = "solidcraft-io" version = "0.30.0" diff --git a/Cargo.toml b/Cargo.toml index 29547a738e9..e3bd609c6ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ solidcraft-sketch = { path = "crates/sketch" } solidcraft-kernel = { path = "crates/kernel" } solidcraft-render = { path = "crates/render" } solidcraft-gpu = { path = "crates/gpu" } +solidcraft-gpu-native = { path = "crates/gpu-native" } solidcraft-doc = { path = "crates/doc" } solidcraft-io = { path = "crates/io" } solidcraft-engine = { path = "crates/engine" } diff --git a/crates/gpu-native/Cargo.toml b/crates/gpu-native/Cargo.toml new file mode 100644 index 00000000000..5cda72f160e --- /dev/null +++ b/crates/gpu-native/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "solidcraft-gpu-native" +description = "SolidCraft's native-only wgpu calls that wgpu marks unsafe (the persistent pipeline cache), kept out of solidcraft-gpu, which forbids unsafe code" +version.workspace = true +edition.workspace = true +license.workspace = true + +# The workspace lints, except unsafe_code: denied, not forbidden, so that src/pipeline_cache.rs can +# allow it (#3236). Keep the rest in sync with [workspace.lints]. +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +dbg_macro = "warn" +todo = "warn" +too_many_arguments = "allow" +type_complexity = "allow" +neg_cmp_op_on_partial_ord = "allow" + +[dependencies] +wgpu = { workspace = true } diff --git a/crates/gpu-native/src/lib.rs b/crates/gpu-native/src/lib.rs new file mode 100644 index 00000000000..555d7a899bf --- /dev/null +++ b/crates/gpu-native/src/lib.rs @@ -0,0 +1,9 @@ +//! wgpu calls that wgpu marks `unsafe` although SolidCraft can meet their contract, kept out of +//! `solidcraft-gpu`, which forbids unsafe code (#3236). Native only: nothing here builds for the +//! browser. Each call lives in one module that allows `unsafe_code` and states its contract. +#![deny(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod pipeline_cache; + +pub use pipeline_cache::pipeline_cache; diff --git a/crates/gpu-native/src/pipeline_cache.rs b/crates/gpu-native/src/pipeline_cache.rs new file mode 100644 index 00000000000..f8d4b935d97 --- /dev/null +++ b/crates/gpu-native/src/pipeline_cache.rs @@ -0,0 +1,22 @@ +//! A pipeline cache seeded with data from an earlier run (#3433). +//! +//! `Device::create_pipeline_cache` is `unsafe` because wgpu cannot prove that seed data came from +//! `PipelineCache::get_data`. wgpu checks its own header (format version, backend, adapter and +//! driver) and, with `fallback`, starts empty when that doesn't match; it does not check the +//! data itself. The caller (`solidcraft_gpu::shader_cache`) only passes data it wrote itself from +//! `get_data`, behind a SHA-256 of the data that it checks first, so corrupted or truncated files +//! never reach the driver. +#![allow(unsafe_code)] + +/// A pipeline cache for `device`, seeded with `data` that an earlier run's +/// [`wgpu::PipelineCache::get_data`] returned; `None` when the device lacks +/// [`wgpu::Features::PIPELINE_CACHE`]. +pub fn pipeline_cache(device: &wgpu::Device, label: &str, data: Option<&[u8]>) -> Option { + if !device.features().contains(wgpu::Features::PIPELINE_CACHE) { + return None; + } + // SAFETY: `data` is `get_data` output written by this program and verified against its + // checksum by the caller (see the module documentation); `fallback: true` makes wgpu start + // an empty cache instead of failing when the data is for another adapter, driver or format. + Some(unsafe { device.create_pipeline_cache(&wgpu::PipelineCacheDescriptor { label: Some(label), data, fallback: true }) }) +} diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index f3c8d2a3fc6..b408e85ae01 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -22,6 +22,9 @@ robust = { workspace = true } pollster = { workspace = true } # Native backends, so tests and the CLI can open a device without a window. wgpu = { workspace = true, features = ["metal", "vulkan", "dx12", "gles"] } +# The persistent pipeline cache (src/shader_cache.rs): wgpu's unsafe call, and the file checksum. +solidcraft-gpu-native = { workspace = true } +sha2 = { workspace = true } [dev-dependencies] image = { workspace = true } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 84d2588aae5..e1ccfdb1d96 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -26,6 +26,8 @@ pub mod path; mod pbr; #[cfg(not(target_arch = "wasm32"))] pub mod select; +#[cfg(not(target_arch = "wasm32"))] +pub mod shader_cache; pub mod view; /// The tessellation compute shader (WGSL). diff --git a/crates/gpu/src/path/denoise.rs b/crates/gpu/src/path/denoise.rs index 7d2f6f6ea0c..71170d4814a 100644 --- a/crates/gpu/src/path/denoise.rs +++ b/crates/gpu/src/path/denoise.rs @@ -36,7 +36,7 @@ impl Pipelines { module: &guide_shader, entry_point: Some("denoise_guides"), compilation_options: Default::default(), - cache: None, + cache: context.cache.as_ref().map(crate::shader_cache::ShaderCache::get), }); let entries: Vec<_> = (0..4) .map(|binding| wgpu::BindGroupLayoutEntry { @@ -64,11 +64,14 @@ impl Pipelines { module: &shader, entry_point: Some("atrous"), compilation_options: Default::default(), - cache: None, + cache: context.cache.as_ref().map(crate::shader_cache::ShaderCache::get), }); checked(error_scopes)?; warm_up(device, &context.queue, &guide, &placeholder_bind(device, &context.layout, 7)?, &context.healthy)?; warm_up(device, &context.queue, &filter, &placeholder_bind(device, &filter_layout, 4)?, &context.healthy)?; + if let Some(cache) = &context.cache { + cache.save(); + } Ok(Self { guide, filter, filter_layout }) } diff --git a/crates/gpu/src/path/denoise_tests.rs b/crates/gpu/src/path/denoise_tests.rs index 12bc5f2ab37..bba9bd5e80d 100644 --- a/crates/gpu/src/path/denoise_tests.rs +++ b/crates/gpu/src/path/denoise_tests.rs @@ -141,7 +141,7 @@ fn f64_atrous_preserves_body_normal_depth_and_albedo_edges() { } } fn context() -> Option> { - let (_, device, queue) = match open_headless() { + let (adapter, device, queue) = match open_headless() { Ok(v) => v, Err(e) => { // The path tracer runs on Vulkan or Metal only: where the backends in use leave both out @@ -151,7 +151,7 @@ fn context() -> Option> { return None; } }; - Some(Executor::new(device, queue).unwrap().context) + Some(Executor::new(device, queue, &adapter.get_info()).unwrap().context) } fn request(size: u32) -> ImageRequest { let mut camera = Camera { distance: 4.0, ..Default::default() }; diff --git a/crates/gpu/src/path/mod.rs b/crates/gpu/src/path/mod.rs index 3b08b462604..879fdbc9ffa 100644 --- a/crates/gpu/src/path/mod.rs +++ b/crates/gpu/src/path/mod.rs @@ -86,7 +86,7 @@ fn checked_creation(device: &wgpu::Device, create: impl FnOnce() -> Result pub fn host() -> Result { let (adapter, device, queue) = open_headless()?; log::info!("gpu-path adapter: {} ({:?})", adapter.get_info().name, adapter.get_info().device_type); - ImageHost::with_executor(Arc::new(Executor::new(device, queue)?)) + ImageHost::with_executor(Arc::new(Executor::new(device, queue, &adapter.get_info())?)) } /// Open an independent job device on the viewport's selected adapter. In particular, @@ -108,13 +108,14 @@ pub fn host_on_adapter(adapter: &wgpu::Adapter) -> Result { if !matches!(info.backend, wgpu::Backend::Vulkan | wgpu::Backend::Metal) { let (picked, _) = crate::select::pick_path(policy, |i| i.vendor == info.vendor && i.device == info.device) .ok_or_else(|| gpu(format!("{VULKAN_ONLY}; the viewport uses {:?}", info.backend)))?; + let picked_info = picked.get_info(); let (device, queue) = open_device(&picked)?; log::info!("gpu-path viewport GPU: {} through Vulkan or Metal", info.name); - return ImageHost::with_executor(Arc::new(Executor::new(device, queue)?)); + return ImageHost::with_executor(Arc::new(Executor::new(device, queue, &picked_info)?)); } let (device, queue) = open_device(adapter)?; log::info!("gpu-path viewport adapter: {} ({:?})", info.name, info.device_type); - ImageHost::with_executor(Arc::new(Executor::new(device, queue)?)) + ImageHost::with_executor(Arc::new(Executor::new(device, queue, &info)?)) } // D3D12 shader compilation is avoided; the user can select a CPU image method instead. @@ -147,7 +148,7 @@ fn open_device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue)> { let required_limits = device_limits(adapter.limits())?; pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("solidcraft progressive path"), - required_features: crate::depth_features(adapter), + required_features: crate::depth_features(adapter) | (adapter.features() & wgpu::Features::PIPELINE_CACHE), required_limits, ..Default::default() })) @@ -166,6 +167,8 @@ struct Context { device: wgpu::Device, queue: wgpu::Queue, pipeline: wgpu::ComputePipeline, + // Compiled pipelines kept between runs, where the backend has a pipeline cache (#3433). + cache: Option, // Built and warmed by the first denoised job, then shared by later ones. denoise: std::sync::OnceLock, layout: wgpu::BindGroupLayout, @@ -204,8 +207,9 @@ struct Executor { context: Arc, } impl Executor { - fn new(device: wgpu::Device, queue: wgpu::Queue) -> Result { + fn new(device: wgpu::Device, queue: wgpu::Queue, adapter: &wgpu::AdapterInfo) -> Result { device_limits(device.limits())?; + let cache = crate::shader_cache::ShaderCache::open(&device, adapter, "gpu-path"); let healthy = Arc::new(AtomicBool::new(true)); let uncaptured = healthy.clone(); device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| { @@ -248,11 +252,14 @@ impl Executor { module: &shader, entry_point: Some("main"), compilation_options: Default::default(), - cache: None, + cache: cache.as_ref().map(crate::shader_cache::ShaderCache::get), }); checked(scopes)?; warm_up(&device, &queue, &pipeline, &placeholder_bind(&device, &layout, 7)?, &healthy)?; - Ok(Self { context: Arc::new(Context { healthy, device, queue, pipeline, layout, denoise: std::sync::OnceLock::new() }) }) + if let Some(cache) = &cache { + cache.save(); + } + Ok(Self { context: Arc::new(Context { healthy, device, queue, pipeline, layout, cache, denoise: std::sync::OnceLock::new() }) }) } } diff --git a/crates/gpu/src/path/tests.rs b/crates/gpu/src/path/tests.rs index 24e838ffcaa..cd7fe9356e5 100644 --- a/crates/gpu/src/path/tests.rs +++ b/crates/gpu/src/path/tests.rs @@ -15,7 +15,7 @@ fn executor() -> Option { } }; eprintln!("gpu-path tests on {} ({:?}, {:?})", adapter.get_info().name, adapter.get_info().device_type, adapter.get_info().backend); - Some(Executor::new(device, queue).unwrap()) + Some(Executor::new(device, queue, &adapter.get_info()).unwrap()) } fn request(size: u32) -> ImageRequest { let mut camera = Camera { distance: 4.0, ..Default::default() }; diff --git a/crates/gpu/src/shader_cache.rs b/crates/gpu/src/shader_cache.rs new file mode 100644 index 00000000000..f6360fc8b3c --- /dev/null +++ b/crates/gpu/src/shader_cache.rs @@ -0,0 +1,185 @@ +//! Compiled pipelines kept between runs, as games keep their shader caches (#3433). +//! +//! A cold Vulkan driver needs minutes for the path tracer's shader. Where the backend keeps a +//! pipeline cache (Vulkan; wgpu has none for D3D12 or Metal), the cache is seeded from disk +//! before the pipelines are built and written back after. Each file holds wgpu's own data +//! (versioned and keyed by adapter and driver, so a driver update starts empty) behind a +//! SHA-256 of it; a file that fails the check is ignored, never handed to the driver. Writes +//! go to a temporary file renamed into place, so concurrent processes never see half a file. +//! Every failure here costs speed only: the pipelines are built without the cache. + +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; + +/// The file format: this tag, the SHA-256 of the data, the data. +const MAGIC: &[u8; 8] = b"SCPIPE01"; +const HEADER: usize = MAGIC.len() + 32; +/// Larger files are not read (a path tracer cache is a few megabytes). +const MAX_BYTES: u64 = 512 << 20; +/// Where the cache lives instead of the default folder, or `off`. +pub const ENV: &str = "SOLIDCRAFT_SHADER_CACHE"; + +/// A pipeline cache for one set of pipelines on one adapter, and the file it persists to. +pub(crate) struct ShaderCache { + cache: wgpu::PipelineCache, + path: PathBuf, +} + +impl ShaderCache { + /// The cache for the pipelines `name` on this device, seeded from the cache folder; `None` + /// where the backend keeps no pipeline cache or caching is off. + pub(crate) fn open(device: &wgpu::Device, info: &wgpu::AdapterInfo, name: &str) -> Option { + Self::open_in(&dir()?, device, info, name) + } + + pub(crate) fn open_in(dir: &Path, device: &wgpu::Device, info: &wgpu::AdapterInfo, name: &str) -> Option { + let key = wgpu::util::pipeline_cache_key(info)?; + let path = dir.join(format!("{key}_{name}.bin")); + let data = read(&path); + log::info!("shader cache {}: {}", path.display(), data.as_ref().map_or("empty".into(), |d| format!("{} KiB", d.len() / 1024))); + let cache = solidcraft_gpu_native::pipeline_cache(device, name, data.as_deref())?; + Some(Self { cache, path }) + } + + pub(crate) fn get(&self) -> &wgpu::PipelineCache { + &self.cache + } + + /// Write the cache back once its pipelines are built. A failure is logged, never fatal. + pub(crate) fn save(&self) { + let Some(data) = self.cache.get_data() else { return }; + match write(&self.path, &data) { + Ok(()) => log::info!("shader cache {}: saved {} KiB", self.path.display(), data.len() / 1024), + Err(e) => log::warn!("shader cache {}: not saved: {e}", self.path.display()), + } + } +} + +/// The cache folder: `SOLIDCRAFT_SHADER_CACHE` (a folder, or `off`), else the user's cache +/// folder: `%LOCALAPPDATA%\SolidCraft\cache\shaders`, `~/Library/Caches/SolidCraft/shaders` or +/// `$XDG_CACHE_HOME/solidcraft/shaders` (`~/.cache` without it). +pub fn dir() -> Option { + let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from); + if let Some(chosen) = env(ENV) { + return (chosen.as_os_str() != "off").then_some(chosen); + } + if cfg!(target_os = "windows") { + Some(env("LOCALAPPDATA")?.join("SolidCraft").join("cache").join("shaders")) + } else if cfg!(target_os = "macos") { + Some(env("HOME")?.join("Library/Caches/SolidCraft/shaders")) + } else { + Some(env("XDG_CACHE_HOME").or_else(|| env("HOME").map(|h| h.join(".cache")))?.join("solidcraft/shaders")) + } +} + +/// The data in a cache file, when the file is whole and its checksum matches. +fn read(path: &Path) -> Option> { + if std::fs::metadata(path).ok()?.len() > MAX_BYTES { + return None; + } + let bytes = std::fs::read(path).ok()?; + let (head, data) = bytes.split_at_checked(HEADER)?; + let (magic, sum) = head.split_at(MAGIC.len()); + if magic != MAGIC || sum != Sha256::digest(data).as_slice() { + log::warn!("shader cache {}: ignored (damaged or from another version)", path.display()); + return None; + } + Some(data.to_vec()) +} + +fn write(path: &Path, data: &[u8]) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut bytes = Vec::with_capacity(HEADER + data.len()); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&Sha256::digest(data)); + bytes.extend_from_slice(data); + let temporary = path.with_extension(format!("{}.tmp", std::process::id())); + std::fs::write(&temporary, &bytes)?; + std::fs::rename(&temporary, path).inspect_err(|_| { + let _ = std::fs::remove_file(&temporary); + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-shader-cache-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + #[test] + fn files_round_trip_and_damage_is_ignored() { + let dir = scratch("round-trip"); + let path = dir.join("nested").join("cache.bin"); + let data: Vec = (0..10_000u32).map(|i| (i * 7) as u8).collect(); + write(&path, &data).unwrap(); + assert_eq!(read(&path).as_deref(), Some(&data[..])); + + let mut bytes = std::fs::read(&path).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 1; + std::fs::write(&path, &bytes).unwrap(); + assert_eq!(read(&path), None, "a flipped bit"); + std::fs::write(&path, &bytes[..HEADER - 1]).unwrap(); + assert_eq!(read(&path), None, "truncated inside the header"); + let mut other = bytes.clone(); + other[0] = b'X'; + std::fs::write(&path, &other).unwrap(); + assert_eq!(read(&path), None, "another format"); + assert_eq!(read(&dir.join("missing.bin")), None); + // Nothing but the file itself is left behind. + write(&path, &data).unwrap(); + assert_eq!(std::fs::read_dir(path.parent().unwrap()).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + /// On a device with a pipeline cache, building a pipeline and saving leaves a checked file + /// that the next open reads. + #[test] + fn a_built_pipeline_is_saved_and_read_back() { + let Some((adapter, _)) = crate::select::pick(crate::select::Policy::Auto) else { return }; + let info = adapter.get_info(); + let Ok((device, _queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_features: adapter.features() & wgpu::Features::PIPELINE_CACHE, + ..Default::default() + })) else { + return; + }; + let dir = scratch("device"); + let Some(cache) = ShaderCache::open_in(&dir, &device, &info, "test") else { + assert!(wgpu::util::pipeline_cache_key(&info).is_none() || !device.features().contains(wgpu::Features::PIPELINE_CACHE)); + return; + }; + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl("@group(0) @binding(0) var v: array; @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) i: vec3) { v[i.x] = i.x * 3u; }".into()), + }); + let _pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &module, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: Some(cache.get()), + }); + cache.save(); + let saved = read(&cache.path).expect("a saved cache with a matching checksum"); + assert!(!saved.is_empty()); + assert!(ShaderCache::open_in(&dir, &device, &info, "test").is_some(), "the next run seeds from it"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn only_vulkan_keeps_a_pipeline_cache() { + let info = |backend| wgpu::AdapterInfo::new(wgpu::DeviceType::DiscreteGpu, backend); + assert!(wgpu::util::pipeline_cache_key(&info(wgpu::Backend::Vulkan)).is_some()); + for backend in [wgpu::Backend::Dx12, wgpu::Backend::Metal, wgpu::Backend::Gl] { + assert!(wgpu::util::pipeline_cache_key(&info(backend)).is_none(), "{backend:?}"); + } + } +} diff --git a/docs/render-path.md b/docs/render-path.md index d121dae265a..a01c8992006 100644 --- a/docs/render-path.md +++ b/docs/render-path.md @@ -25,6 +25,14 @@ equal per sample with DXC and about 55% slower with FXC, and it compiles the pat at every start (about 82 s with DXC, about 2 hours with FXC), where Vulkan's compiled pipelines persist between runs. +On Vulkan, compiled pipelines persist between runs in a wgpu pipeline cache (#3433), so +only the first start on a machine compiles the path shader (minutes on a cold driver; wgpu +has no pipeline cache for Metal). The cache +lives in `%LOCALAPPDATA%\SolidCraft\cache\shaders` or `$XDG_CACHE_HOME/solidcraft/shaders`; +`SOLIDCRAFT_SHADER_CACHE` names another folder, or `off` disables it. A file that fails its +checksum, or comes from another driver or wgpu version, is ignored and rewritten; deleting +the folder is always safe. + In the Render workspace, select **GPU path tracing** and samples per pixel before checking or starting an image. These controls are transient image-job intent that can also be retained in typed saved setups. Each new saved concept diff --git a/skills/solidcraft-crash-safety/SKILL.md b/skills/solidcraft-crash-safety/SKILL.md index bee78b86baf..4c63194879a 100644 --- a/skills/solidcraft-crash-safety/SKILL.md +++ b/skills/solidcraft-crash-safety/SKILL.md @@ -12,6 +12,7 @@ People trust SolidCraft with their designs. This outranks feature work. - No `unsafe` (`unsafe_code = "forbid"`). The exceptions, in the app crate and in `crates/threedx-client` (which deny it instead), have no safe API: - macOS only: `crates/threedx-client/src/macos.rs` (loads the 3Dconnexion driver's client framework at run time and calls through its function pointers), two functions in `apps/solidcraft/src/open_documents.rs` (macOS hands Finder files only to an Objective-C method), and `apps/solidcraft/src/native_crash_macos.rs` (the signal handler that records crashes inside native code, as `native_crash.rs` does on Windows) - Windows only: `apps/solidcraft/src/native_crash.rs` (the exception filter that records crashes inside native code such as graphics drivers), `apps/solidcraft/src/native_frame.rs` (the window procedure that answers the resize-border hit test of the window without OS decorations, and gives its class the icon the taskbar falls back on) and `apps/solidcraft/src/space_mouse/windows_hid.rs` (asks Plug and Play which HID interfaces are 3D mice, so no other device is sent anything) + - Native, not FFI (#3236): `crates/gpu-native/src/pipeline_cache.rs` (wgpu marks seeding a pipeline cache `unsafe`) - Errors are `Result` through the crate's error type and `?`. An unfinished feature returns an error ("not supported yet: ..."); it never panics. - Input-derived numbers are hostile (command parameters, design files, control-channel input): `get()` not `[i]`, finite checks, caps on sizes and loop counts. - Everything that calls `truck` goes through `solidcraft_kernel::guard`, which turns a panic into `KernelError::Internal`. Only `crates/kernel` may use `truck`. diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 78a832237b4..612cde40e63 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -12,6 +12,9 @@ use serde_json::Value; pub enum Class { /// Regular layered crate. Layer(u8), + /// A layered crate for native targets only: same rules as `Layer`, but not in the wasm + /// check (`cargo xtask wasm`). + Native(u8), /// Layer 0, and additionally may depend on no workspace crate at all. Standalone, /// Test tooling: may depend on anything up to L5 (it sits at L6 for rule @@ -24,7 +27,7 @@ pub enum Class { impl Class { fn layer(self) -> Option { match self { - Class::Layer(l) => Some(l), + Class::Layer(l) | Class::Native(l) => Some(l), Class::Standalone => Some(0), Class::Testkit => Some(6), Class::Exempt => None, @@ -42,6 +45,8 @@ pub const TABLE: &[(&str, Class)] = &[ ("derive", Class::Standalone), // the 3Dconnexion driver's client API on macOS (no workspace dependencies) ("3dx-client", Class::Standalone), + // native-only wgpu calls that need `unsafe` (#3236), for the GPU crate; not built for wasm + ("gpu-native", Class::Native(5)), ("sketch", Class::Layer(1)), ("kernel", Class::Layer(1)), ("render", Class::Layer(1)), @@ -61,8 +66,9 @@ pub const TABLE: &[(&str, Class)] = &[ /// Explicit orderings *within* a layer (earlier may be used by later). /// The viewport draws display plans the GPU crate evaluates and draws with its pipelines; the MCP -/// server's tests draw screenshots with them. -pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["gpu", "ui-egui"], &["gpu", "mcp"]]; +/// server's tests draw screenshots with them; the GPU crate keeps its pipeline cache through +/// `gpu-native`. +pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["gpu", "ui-egui"], &["gpu", "mcp"], &["gpu-native", "gpu"]]; fn intra_layer_allowed(from: &str, to: &str) -> bool { let (from, to) = (short_name(from), short_name(to)); @@ -226,6 +232,7 @@ pub fn from_metadata(meta: &Value) -> Result, String> { pub fn describe(class: Option) -> String { match class { Some(Class::Layer(l)) => format!("L{l}"), + Some(Class::Native(l)) => format!("L{l} native"), Some(Class::Standalone) => "L0 standalone".into(), Some(Class::Testkit) => "testkit".into(), Some(Class::Exempt) => "exempt".into(),