SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Graphics: the window no longer waits for Direct3D 12 shader compiles (#4860) (#7288)
yhamil043574956d2943
diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rsindex 0b55034d9a..f7df85b553 100644--- a/crates/gpu/src/capture.rs+++ b/crates/gpu/src/capture.rs@@ -16,7 +16,7 @@ use solidcraft_render::{AnalysisMode, Camera, Rgb, SECTION_CAP, Scene};use wgpu::util::DeviceExt;use crate::view::{AccessMap, Frame, GpuScene, GpuTarget, Renderer, analysis_colors, analysis_uniform};-use crate::{GpuError, Result, popped};+use crate::{GpuError, Result, caught, error_scopes};/// The colour format pictures are drawn in: sRGB bytes as they are, like the viewport's usual/// (non-sRGB) target.@@ -460,22 +460,6 @@ fn watch_lost(device: &wgpu::Device) -> Arc<AtomicBool> {lost}-/// Error scopes catching what a picture's GPU work may raise (popped by [`caught`]).-fn error_scopes(device: &wgpu::Device) -> [wgpu::ErrorScopeGuard; 3] {- [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation].map(|f| device.push_error_scope(f))-}--/// The first error the scopes caught.-fn caught(scopes: [wgpu::ErrorScopeGuard; 3]) -> Option<String> {- let mut failed = None;- for scope in scopes.into_iter().rev() {- if let Some(e) = popped(scope.pop()) {- failed.get_or_insert(e.to_string());- }- }- failed-}-/// The background gradient: the viewport's top colour at the top, its bottom one at the bottom,/// mixed in sRGB as the window paints it.const BACKGROUND_SHADER: &str = r#"diff --git a/crates/gpu/src/concurrent.rs b/crates/gpu/src/concurrent.rsnew file mode 100644index 0000000000..94facc85c3--- /dev/null+++ b/crates/gpu/src/concurrent.rs@@ -0,0 +1,295 @@+//! Pipelines built on several threads at once (#4860).+//!+//! Direct3D 12 compiles a pipeline's shaders when the pipeline is made (wgpu writes the WGSL out+//! as HLSL and compiles that with FXC), and nothing compiled is kept between launches, so the+//! viewport's pipelines, built one after another, held the window back for seconds. Work+//! handed to [`Jobs::spawn`] runs on a thread of its own, and [`Job::join`] collects it.+//!+//! - wgpu's error scopes belong to the thread that pushed them, so a job runs under scopes of its+//! own. A job that raised an error, or whose thread panicked or could not start, runs again on+//! the calling thread when joined: its errors reach the caller's scopes and the device's handler+//! as they did when every pipeline was built there.+//! - Threads only on Vulkan, Metal and Direct3D 12 with FXC, whose devices make pipelines from any+//! thread. wgpu hands every thread one DXC compiler, which is not documented as safe to share,+//! and OpenGL works through one context. There, and in the browser, which has no threads, each+//! job runs when it is joined, one after another, as before.++#[cfg(target_arch = "wasm32")]+use std::marker::PhantomData;++/// The name of the threads jobs run on (in crash reports and debuggers).+#[cfg(not(target_arch = "wasm32"))]+const WORKER: &str = "solidcraft pipelines";++/// Jobs on `device`, collected before [`scope`] returns.+pub struct Jobs<'scope, 'env> {+ device: &'env wgpu::Device,+ /// The threads' scope; `None` where jobs run on the calling thread.+ #[cfg(not(target_arch = "wasm32"))]+ threads: Option<&'scope std::thread::Scope<'scope, 'env>>,+ #[cfg(target_arch = "wasm32")]+ threads: PhantomData<&'scope ()>,+}++/// Work handed to [`Jobs::spawn`].+pub struct Job<'scope, T, F> {+ work: F,+ #[cfg(not(target_arch = "wasm32"))]+ worker: Option<std::thread::ScopedJoinHandle<'scope, Option<T>>>,+ #[cfg(target_arch = "wasm32")]+ worker: PhantomData<(&'scope (), T)>,+}++/// Runs `f` with a [`Jobs`] on `device`; every job is joined before this returns.+pub fn scope<'env, R>(device: &'env wgpu::Device, f: impl for<'scope> FnOnce(&Jobs<'scope, 'env>) -> R) -> R {+ #[cfg(not(target_arch = "wasm32"))]+ {+ let threaded = threads_allowed(device);+ std::thread::scope(|s| f(&Jobs { device, threads: threaded.then_some(s) }))+ }+ #[cfg(target_arch = "wasm32")]+ {+ f(&Jobs { device, threads: PhantomData })+ }+}++/// `device` makes pipelines on several threads at once (see the module); the shader of the GPU+/// plan evaluation compiles on a thread of its own by the same rule (`view::TessLater`).+#[cfg(not(target_arch = "wasm32"))]+pub(crate) fn threads_allowed(device: &wgpu::Device) -> bool {+ threaded(device.adapter_info().backend, dx12_compiles_with_fxc)+}++/// Backends whose devices make pipelines on several threads at once; D3D12 when `fxc` says it+/// compiles with FXC.+#[cfg(not(target_arch = "wasm32"))]+fn threaded(backend: wgpu::Backend, fxc: impl FnOnce() -> bool) -> bool {+ match backend {+ wgpu::Backend::Vulkan | wgpu::Backend::Metal => true,+ wgpu::Backend::Dx12 => fxc(),+ _ => false,+ }+}++/// D3D12 compiles with FXC: `WGPU_DX12_COMPILER` says `fxc`, or leaves wgpu's choice (`auto`),+/// which takes DXC when it can load a `dxcompiler.dll` (#6756) and FXC otherwise. Looked up+/// once: neither changes while the app runs.+#[cfg(not(target_arch = "wasm32"))]+fn dx12_compiles_with_fxc() -> bool {+ static FXC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+ *FXC.get_or_init(|| fxc_chosen(std::env::var("WGPU_DX12_COMPILER").ok().as_deref(), dxcompiler_found))+}++/// [`dx12_compiles_with_fxc`] for the variable's value `setting`, read as wgpu reads it;+/// `dxc_found` looks for the DLL.+#[cfg(not(target_arch = "wasm32"))]+fn fxc_chosen(setting: Option<&str>, dxc_found: impl FnOnce() -> bool) -> bool {+ match setting.map(str::to_lowercase).as_deref() {+ Some("fxc") => true,+ Some("dxc" | "dynamicdxc" | "staticdxc") => false,+ // `auto`, unset, or a value wgpu does not know (it keeps `auto` then).+ _ => !dxc_found(),+ }+}++/// A `dxcompiler.dll` where Windows looks for one: beside the program, in the system folders, the+/// working folder or `PATH`. Conservative: one found there may be one Windows would not load.+#[cfg(not(target_arch = "wasm32"))]+fn dxcompiler_found() -> bool {+ let program = std::env::current_exe().ok().and_then(|p| p.parent().map(std::path::Path::to_path_buf));+ let windows = std::env::var_os("SystemRoot").map(std::path::PathBuf::from);+ let system = windows.as_ref().map(|w| w.join("System32"));+ let path = std::env::var_os("PATH");+ program+ .into_iter()+ .chain(system)+ .chain(windows)+ .chain(std::env::current_dir().ok())+ .chain(path.iter().flat_map(std::env::split_paths))+ .any(|folder| folder.join("dxcompiler.dll").is_file())+}++impl<'scope, 'env> Jobs<'scope, 'env> {+ /// Start `work` on a thread of its own (or later, on the calling thread: see the module).+ /// `work` may run twice, so it only builds what it returns.+ #[cfg(not(target_arch = "wasm32"))]+ pub fn spawn<T, F>(&self, work: F) -> Job<'scope, T, F>+ where+ T: Send + 'scope,+ F: Fn() -> T + Copy + Send + 'scope,+ {+ let device = self.device;+ let worker = self.threads.and_then(|s| std::thread::Builder::new().name(WORKER.into()).spawn_scoped(s, move || checked(device, work)).ok());+ Job { work, worker }+ }++ /// Run `work` when it is joined: the browser has no threads.+ #[cfg(target_arch = "wasm32")]+ pub fn spawn<T, F: Fn() -> T>(&self, work: F) -> Job<'scope, T, F> {+ let _ = self.device;+ Job { work, worker: PhantomData }+ }+}++impl<T, F: Fn() -> T> Job<'_, T, F> {+ /// What the job built: on its thread, or now on this one (see the module).+ #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] // Only native jobs have a thread to take.+ pub fn join(mut self) -> T {+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(built) = self.worker.take().and_then(|w| w.join().ok().flatten()) {+ return built;+ }+ (self.work)()+ }+}++/// A job dropped unjoined still waits for its thread: the scope would otherwise panic at its end+/// if that thread had panicked.+#[cfg(not(target_arch = "wasm32"))]+impl<T, F> Drop for Job<'_, T, F> {+ fn drop(&mut self) {+ if let Some(worker) = self.worker.take() {+ let _ = worker.join();+ }+ }+}++/// `work`'s result, or `None` when it raised a GPU error on this thread (logged: the job runs+/// again on the calling thread, where the error may not recur).+#[cfg(not(target_arch = "wasm32"))]+fn checked<T>(device: &wgpu::Device, work: impl Fn() -> T) -> Option<T> {+ let scopes = crate::error_scopes(device);+ let built = work();+ match crate::caught(scopes) {+ Some(e) => {+ log::warn!("GPU pipelines built again on the calling thread: {e}");+ None+ }+ None => Some(built),+ }+}++#[cfg(all(test, not(target_arch = "wasm32")))]+mod tests {+ use std::sync::atomic::{AtomicUsize, Ordering};++ use super::*;++ #[test]+ fn only_backends_that_make_pipelines_on_any_thread_get_threads() {+ for fxc in [true, false] {+ assert!(threaded(wgpu::Backend::Vulkan, || fxc));+ assert!(threaded(wgpu::Backend::Metal, || fxc));+ assert!(!threaded(wgpu::Backend::Gl, || fxc));+ assert!(!threaded(wgpu::Backend::BrowserWebGpu, || fxc));+ assert!(!threaded(wgpu::Backend::Noop, || fxc));+ }+ assert!(threaded(wgpu::Backend::Dx12, || true), "D3D12 with FXC");+ assert!(!threaded(wgpu::Backend::Dx12, || false), "D3D12 with DXC");+ }++ #[test]+ fn d3d12_compiles_with_fxc_unless_dxc_is_chosen_or_found() {+ for setting in [Some("fxc"), Some("FXC")] {+ assert!(fxc_chosen(setting, || true), "{setting:?} keeps FXC even with a DLL around");+ }+ for setting in [Some("dxc"), Some("DynamicDxc"), Some("staticdxc")] {+ assert!(!fxc_chosen(setting, || false), "{setting:?} chooses DXC");+ }+ // wgpu does not trim the value: " fxc " is a value it does not know, so `auto`.+ for setting in [None, Some("auto"), Some(""), Some("unknown"), Some(" fxc ")] {+ assert!(fxc_chosen(setting, || false), "{setting:?} without a DLL: FXC");+ assert!(!fxc_chosen(setting, || true), "{setting:?} with a DLL: DXC");+ }+ }++ /// A buffer wgpu refuses: mapped for reading and for writing at once.+ fn refused_buffer(device: &wgpu::Device) -> wgpu::Buffer {+ device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("refused"),+ size: 16,+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::MAP_WRITE,+ mapped_at_creation: false,+ })+ }++ #[test]+ fn jobs_hand_back_what_they_built() {+ let Ok((_, device, _)) = crate::open_headless() else {+ eprintln!("skipped: no GPU adapter");+ return;+ };+ let runs = AtomicUsize::new(0);+ let built = scope(&device, |jobs| {+ let a = jobs.spawn(|| {+ runs.fetch_add(1, Ordering::Relaxed);+ 1+ });+ let b = jobs.spawn(|| {+ runs.fetch_add(1, Ordering::Relaxed);+ 2+ });+ (a.join(), b.join())+ });+ assert_eq!(built, (1, 2));+ assert_eq!(runs.load(Ordering::Relaxed), 2, "a job that went well runs once");+ }++ #[test]+ fn an_error_on_a_job_reaches_the_callers_error_scope() {+ let Ok((_, device, _)) = crate::open_headless() else {+ eprintln!("skipped: no GPU adapter");+ return;+ };+ let runs = AtomicUsize::new(0);+ let caller = device.push_error_scope(wgpu::ErrorFilter::Validation);+ let device_ref = &device;+ let runs_ref = &runs;+ scope(&device, |jobs| {+ let job = jobs.spawn(move || {+ runs_ref.fetch_add(1, Ordering::Relaxed);+ refused_buffer(device_ref)+ });+ drop(job.join());+ });+ let error = crate::popped(caller.pop());+ assert!(error.is_some(), "the caller's scope catches the job's error");+ let expected = if threaded(device.adapter_info().backend, dx12_compiles_with_fxc) { 2 } else { 1 };+ assert_eq!(runs.load(Ordering::Relaxed), expected, "the job ran again on the calling thread");+ }++ #[test]+ fn a_job_dropped_unjoined_whose_thread_panicked_does_not_panic_the_scope() {+ let Ok((_, device, _)) = crate::open_headless() else {+ eprintln!("skipped: no GPU adapter");+ return;+ };+ let finished = scope(&device, |jobs| {+ drop(jobs.spawn(|| {+ if std::thread::current().name() == Some(WORKER) {+ panic!("a job's thread panicked");+ }+ }));+ true+ });+ assert!(finished);+ }++ #[test]+ fn a_job_whose_thread_panicked_runs_again_on_the_calling_thread() {+ let Ok((_, device, _)) = crate::open_headless() else {+ eprintln!("skipped: no GPU adapter");+ return;+ };+ let built = scope(&device, |jobs| {+ let job = jobs.spawn(|| {+ if std::thread::current().name() == Some(WORKER) {+ panic!("a job's thread panicked");+ }+ 7+ });+ job.join()+ });+ assert_eq!(built, 7);+ }+}diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsindex 25f0fc06a5..58517e8355 100644--- a/crates/gpu/src/lib.rs+++ b/crates/gpu/src/lib.rs@@ -20,6 +20,7 @@ use solidcraft_geom::tess::{EvalCurve, EvalSurface, TessPlan};use wgpu::util::DeviceExt;pub mod capture;+pub mod concurrent;#[cfg(not(target_arch = "wasm32"))]pub mod path;mod pbr;@@ -60,6 +61,22 @@ fn popped(f: impl std::future::Future<Output = Option<wgpu::Error>>) -> Option<w}}+/// Error scopes catching what GPU work may raise (popped by [`caught`]).+fn error_scopes(device: &wgpu::Device) -> [wgpu::ErrorScopeGuard; 3] {+ [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation].map(|f| device.push_error_scope(f))+}++/// The first error the scopes caught.+fn caught(scopes: [wgpu::ErrorScopeGuard; 3]) -> Option<String> {+ let mut failed = None;+ for scope in scopes.into_iter().rev() {+ if let Some(e) = popped(scope.pop()) {+ failed.get_or_insert(e.to_string());+ }+ }+ failed+}+/// An adapter and device without a window (native only): the adapter [`select::pick`] chooses/// under the `SOLIDCRAFT_GPU` policy. The environment may narrow the backends and pick the D3D12/// shader compiler (`WGPU_BACKEND`, `WGPU_DX12_COMPILER`).@@ -141,6 +158,7 @@ pub struct Part {}/// The compute pipeline, ready to evaluate plans on one device.+#[derive(Clone)]pub struct TessGpu {adapter: String,device: wgpu::Device,diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rsindex f7a8249cf2..467e1a0c27 100644--- a/crates/gpu/src/view.rs+++ b/crates/gpu/src/view.rs@@ -1942,6 +1942,10 @@ pub struct Renderer {tri_cut_instanced_flat: Option<Cut>,/// The tessellation compute pipeline, where the device runs compute shaders.tess: Option<crate::TessGpu>,+ /// The tessellation compute pipeline while it compiles beside the window ([`TessLater`]):+ /// `tess` once it is ready.+ #[cfg(not(target_arch = "wasm32"))]+ tess_later: Option<TessLater>,/// While a section is shown (when the depth buffer has a stencil), in place of `tri`: the/// faces marking where the cap shows, their depth pushed back, then the cap again at the/// section plane's depth, so it hides the inside ([`Cut`]).@@ -2448,12 +2452,6 @@ impl Renderer {cache: None,})};- let both = |label: &str, cull: Option<wgpu::Face>| {- (see_through(label, TriSource::Instanced, cull), see_through(&format!("{label}_flat"), TriSource::InstancedFlat, cull))- };- let glass_far_instanced = both("sc_glass_far_instanced", Some(wgpu::Face::Front));- let glass_near_instanced = both("sc_glass_near_instanced", Some(wgpu::Face::Back));- let trans_instanced = both("sc_trans_instanced", None);let image_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {label: Some("sc_image"),entries: &[@@ -2481,31 +2479,33 @@ impl Renderer {immediate_size: 0,});const IA: [wgpu::VertexAttribute; 3] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32];- let image = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("sc_image"),- layout: Some(&image_layout),- vertex: wgpu::VertexState {- module: &module,- entry_point: Some("vs_img"),- buffers: &[Some(wgpu::VertexBufferLayout {- array_stride: IMG_SIZE as u64,- step_mode: wgpu::VertexStepMode::Vertex,- attributes: &IA,- })],- compilation_options: Default::default(),- },- primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },- depth_stencil: depth(wgpu::CompareFunction::LessEqual, false),- multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false },- fragment: Some(wgpu::FragmentState {- module: &module,- entry_point: Some("fs_img"),- targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })],- compilation_options: Default::default(),- }),- multiview_mask: None,- cache: None,- });+ let image = || {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("sc_image"),+ layout: Some(&image_layout),+ vertex: wgpu::VertexState {+ module: &module,+ entry_point: Some("vs_img"),+ buffers: &[Some(wgpu::VertexBufferLayout {+ array_stride: IMG_SIZE as u64,+ step_mode: wgpu::VertexStepMode::Vertex,+ attributes: &IA,+ })],+ compilation_options: Default::default(),+ },+ primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },+ depth_stencil: depth(wgpu::CompareFunction::LessEqual, false),+ multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false },+ fragment: Some(wgpu::FragmentState {+ module: &module,+ entry_point: Some("fs_img"),+ targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: alpha, write_mask: wgpu::ColorWrites::ALL })],+ compilation_options: Default::default(),+ }),+ multiview_mask: None,+ cache: None,+ })+ };let access_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {label: Some("sc_access"),entries: &[wgpu::BindGroupLayoutEntry {@@ -2519,10 +2519,11 @@ impl Renderer {count: None,}],});- let ao = ao::Resources::new(device, &bgl, &module, reversed);+ let ao_layout = ao::Resources::layout(device);+ let ao = || ao::Resources::new(device, &ao_layout, &bgl, &module, reversed);let solid_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {label: Some("sc_solid"),- bind_group_layouts: &[Some(&bgl), Some(&access_bgl), Some(&ao.layout)],+ bind_group_layouts: &[Some(&bgl), Some(&access_bgl), Some(&ao_layout)],immediate_size: 0,});let built = [Some(tri_layout())];@@ -2564,39 +2565,49 @@ impl Renderer {let solid = |label: &str, fs: &str, cull: Option<wgpu::Face>, ds: Option<wgpu::DepthStencilState>, source: TriSource| {solid_writes(label, fs, cull, ds, source, true)};- // While a section is shown: the stencil marking and the cap (see `Renderer::tri_cut`).- let cut = |source: TriSource| {- t.depth.filter(|f| f.has_stencil_aspect()).map(|format| {- // The visible surface, by its true depth, marks the stencil: 1 where it is a back face (the cap).- use wgpu::StencilOperation::{Keep, Replace, Zero};- let face = |pass_op| wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: Keep, depth_fail_op: Keep, pass_op };- let mark = wgpu::DepthStencilState {- format,- depth_write_enabled: Some(true),- depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)),- stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff },- bias: Default::default(),- };- // Then the cap's back faces again, only there, at the section plane's depth.- let only = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Equal, ..face(Keep) };- let cap = wgpu::DepthStencilState {- format,- depth_write_enabled: Some(true),- depth_compare: Some(wgpu::CompareFunction::Always),- stencil: wgpu::StencilState { front: only, back: only, read_mask: 0xff, write_mask: 0 },- bias: Default::default(),- };- Cut {- mark: solid("sc_tris_mark", "fs_solid", None, Some(mark), source),- push: solid_writes("sc_tris_push", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), source, false),- // Depth only: every back face behind a marked pixel draws here, so writing- // colour let the last one drawn paint the cut, other bodies behind it- // included (their colours and outlines showed through it, #6328). The- // marking pass already drew the nearest back face's colour.- cap: solid_writes("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap), source, false),- }+ // While a section is shown, the depth states of the stencil marking and of the cap (see+ // `Renderer::tri_cut`), where the depth buffer has a stencil.+ let cut_states = t.depth.filter(|f| f.has_stencil_aspect()).map(|format| {+ // The visible surface, by its true depth, marks the stencil: 1 where it is a back face (the cap).+ use wgpu::StencilOperation::{Keep, Replace, Zero};+ let face = |pass_op| wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: Keep, depth_fail_op: Keep, pass_op };+ let mark = wgpu::DepthStencilState {+ format,+ depth_write_enabled: Some(true),+ depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)),+ stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff },+ bias: Default::default(),+ };+ // Then the cap's back faces again, only there, at the section plane's depth.+ let only = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Equal, ..face(Keep) };+ let cap = wgpu::DepthStencilState {+ format,+ depth_write_enabled: Some(true),+ depth_compare: Some(wgpu::CompareFunction::Always),+ stencil: wgpu::StencilState { front: only, back: only, read_mask: 0xff, write_mask: 0 },+ bias: Default::default(),+ };+ (mark, cap)+ });+ // `Cut::mark` and `Cut::push` use `tri`'s fragment shader; `Cut::cap` has its own.+ let marks = |source: TriSource| {+ cut_states.as_ref().map(|(mark, _)| {+ (+ solid("sc_tris_mark", "fs_solid", None, Some(mark.clone()), source),+ solid_writes("sc_tris_push", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), source, false),+ )})};+ // Depth only: every back face behind a marked pixel draws here, so writing colour let the+ // last one drawn paint the cut, other bodies behind it included (their colours and+ // outlines showed through it, #6328). The marking pass already drew the nearest back+ // face's colour.+ let cap = |source: TriSource| {+ cut_states.as_ref().map(|(_, cap)| solid_writes("sc_tris_cap", "fs_solid_cut", Some(wgpu::Face::Front), Some(cap.clone()), source, false))+ };+ let cut = |marks: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, cap: Option<wgpu::RenderPipeline>| {+ marks.zip(cap).map(|((mark, push), cap)| Cut { mark, push, cap })+ };let access_bind = access_texture(device, None, &access_bgl, 1, &[]);let sampler = device.create_sampler(&wgpu::SamplerDescriptor {label: Some("sc_image"),@@ -2657,86 +2668,195 @@ impl Renderer {})};let pass_depth = window_depth(wgpu::CompareFunction::Always);- let (ss_blit, copy_blit) = (blit("fs", window.samples.max(1), pass_depth.clone()), blit("fs_copy", window.samples.max(1), pass_depth));- // Into the cached picture's own texture: no depth, one sample.- let ss_filter = blit("fs", 1, None);- let oit = oit::Pipelines::new(device, &module, &layout, t.format, t.depth, t.samples);- let depth_reset = window.reversed_depth().then(|| depth_reset_pipeline(device, window)).flatten();- Renderer {- ao,- depth_reset,- section_reset: t.depth.filter(|f| f.has_stencil_aspect()).and_then(|_| depth_reset_pipeline(device, t)),- target: GpuTarget { oit: oit.is_some(), ..t },- window,- max_texture: device.limits().max_texture_dimension_2d,- ss_blit,- ss_filter,- copy_blit,- ss_scaled: false,- oit,- oit_targets: None,- ss_bgl,- ss: None,- ss_ready: false,- stats: DrawStatsHandle::default(),- ss_stats: DrawStats::default(),- ss_key: None,- cached: None,- image,- image_bgl,- sampler,- textures: Default::default(),- quads: Vec::new(),- tri: solid("sc_tris", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), TriSource::Built),- tri_cut: cut(TriSource::Built),- tri_planned: solid("sc_tris_planned", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), TriSource::Planned),- tri_cut_planned: cut(TriSource::Planned),- tri_instanced: solid("sc_tris_instanced", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), TriSource::Instanced),- tri_cut_instanced: cut(TriSource::Instanced),- tri_instanced_flat: solid(- "sc_tris_instanced_flat",- "fs_solid",- None,- pushed(wgpu::CompareFunction::Less, true, FACE_BIAS),- TriSource::InstancedFlat,- ),- tri_cut_instanced_flat: cut(TriSource::InstancedFlat),- glass_far_instanced,- glass_near_instanced,- trans_instanced,- tess,- access_bgl,- access_bind,- access_version: 0,- tri_hl: pipeline("sc_tris_hl", "vs_tri", "fs_tri", tri_layout(), highlight_depth(t.depth), alpha),- tri_hl_hover: solid("sc_tris_hl_hover", "fs_hl_hover", None, highlight_depth(t.depth), TriSource::Planned),- tri_hl_selected: solid("sc_tris_hl_selected", "fs_hl_selected", None, highlight_depth(t.depth), TriSource::Planned),- tri_hl_hover_built: solid("sc_tris_hl_hover_built", "fs_hl_hover", None, highlight_depth(t.depth), TriSource::Built),- tri_hl_selected_built: solid("sc_tris_hl_selected_built", "fs_hl_selected", None, highlight_depth(t.depth), TriSource::Built),- tri_hl_instanced: solid("sc_tris_hl_instanced", "fs_tri", None, highlight_depth(t.depth), TriSource::Instanced),- tri_hl_instanced_flat: solid("sc_tris_hl_instanced_flat", "fs_tri", None, highlight_depth(t.depth), TriSource::InstancedFlat),- pbr: pipeline("sc_pbr", "vs_pbr", "fs_pbr", pbr_layout(), pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), None),- trans: pipeline("sc_trans", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),- glass_far: glass("sc_glass_far", wgpu::Face::Front),- glass_near: glass("sc_glass_near", wgpu::Face::Back),- ghost: pipeline("sc_ghost", "vs_tri", "fs_tri", tri_layout(), pushed(wgpu::CompareFunction::LessEqual, false, GHOST_BIAS), alpha),- xray: pipeline("sc_xray", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::Always, false), alpha),- line: pipeline("sc_lines", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),- line_hidden: pipeline("sc_lines_hidden", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::Greater, false), alpha),- overlay: pipeline("sc_overlay", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::Always, false), alpha),- guide_trans: pipeline("sc_guide_trans", "vs_tri", "fs_tri_all", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),- guide_line: pipeline("sc_guide_lines", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),- uniform,- uniform_bgl: bgl,- bind,- linear_out: t.format.is_srgb(),- model: Batches::default(),- product: Batches::default(),- empty: Batches::default(),- sketch: Batches::default(),- highlight: Batches::default(),- preview: Batches::default(),- }+ let blits = || {+ (+ blit("fs", window.samples.max(1), pass_depth.clone()),+ blit("fs_copy", window.samples.max(1), pass_depth.clone()),+ // Into the cached picture's own texture: no depth, one sample.+ blit("fs", 1, None),+ )+ };+ let oit = || oit::Pipelines::new(device, &module, &layout, t.format, t.depth, t.samples);+ let resets = || {+ (+ window.reversed_depth().then(|| depth_reset_pipeline(device, window)).flatten(),+ t.depth.filter(|f| f.has_stencil_aspect()).and_then(|_| depth_reset_pipeline(device, t)),+ )+ };+ let opaque = || pushed(wgpu::CompareFunction::Less, true, FACE_BIAS);+ // One job per fragment shader, the costly part: wgpu compiles a shader for the first+ // pipeline that uses it and reuses it for the next, so each is still compiled once. A+ // vertex shader two jobs share may be compiled by both; those are small.+ let tris = || {+ (+ solid("sc_tris", "fs_solid", None, opaque(), TriSource::Built),+ marks(TriSource::Built),+ solid("sc_tris_planned", "fs_solid", None, opaque(), TriSource::Planned),+ marks(TriSource::Planned),+ solid("sc_tris_instanced", "fs_solid", None, opaque(), TriSource::Instanced),+ marks(TriSource::Instanced),+ )+ };+ let caps = || (cap(TriSource::Built), cap(TriSource::Planned), cap(TriSource::Instanced));+ let flat = || (solid("sc_tris_instanced_flat", "fs_solid", None, opaque(), TriSource::InstancedFlat), marks(TriSource::InstancedFlat));+ let flat_cap = || cap(TriSource::InstancedFlat);+ let hover = || {+ (+ solid("sc_tris_hl_hover", "fs_hl_hover", None, highlight_depth(t.depth), TriSource::Planned),+ solid("sc_tris_hl_hover_built", "fs_hl_hover", None, highlight_depth(t.depth), TriSource::Built),+ )+ };+ let selected = || {+ (+ solid("sc_tris_hl_selected", "fs_hl_selected", None, highlight_depth(t.depth), TriSource::Planned),+ solid("sc_tris_hl_selected_built", "fs_hl_selected", None, highlight_depth(t.depth), TriSource::Built),+ )+ };+ // `glass_far_instanced`, `glass_near_instanced` and `trans_instanced`, smooth or flat.+ let see_through_instanced = |source: TriSource, suffix: &str| {+ (+ see_through(&format!("sc_glass_far_instanced{suffix}"), source, Some(wgpu::Face::Front)),+ see_through(&format!("sc_glass_near_instanced{suffix}"), source, Some(wgpu::Face::Back)),+ see_through(&format!("sc_trans_instanced{suffix}"), source, None),+ )+ };+ let see_through_tris = || {+ (+ pipeline("sc_tris_hl", "vs_tri", "fs_tri", tri_layout(), highlight_depth(t.depth), alpha),+ pipeline("sc_trans", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),+ glass("sc_glass_far", wgpu::Face::Front),+ glass("sc_glass_near", wgpu::Face::Back),+ pipeline("sc_ghost", "vs_tri", "fs_tri", tri_layout(), pushed(wgpu::CompareFunction::LessEqual, false, GHOST_BIAS), alpha),+ pipeline("sc_xray", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::Always, false), alpha),+ see_through_instanced(TriSource::Instanced, ""),+ solid("sc_tris_hl_instanced", "fs_tri", None, highlight_depth(t.depth), TriSource::Instanced),+ )+ };+ let see_through_flat = || {+ (+ see_through_instanced(TriSource::InstancedFlat, "_flat"),+ solid("sc_tris_hl_instanced_flat", "fs_tri", None, highlight_depth(t.depth), TriSource::InstancedFlat),+ )+ };+ let pbr = || pipeline("sc_pbr", "vs_pbr", "fs_pbr", pbr_layout(), opaque(), None);+ let lines = || {+ (+ pipeline("sc_lines", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),+ pipeline("sc_lines_hidden", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::Greater, false), alpha),+ )+ };+ let lines_all = || {+ (+ pipeline("sc_overlay", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::Always, false), alpha),+ pipeline("sc_guide_lines", "vs_line", "fs_line_all", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),+ )+ };+ let guide_trans = || pipeline("sc_guide_trans", "vs_tri", "fs_tri_all", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha);+ // Each job on a thread of its own where the device allows it: D3D12 compiles every shader+ // as its pipeline is made, which took seconds one after another (#4860).+ crate::concurrent::scope(device, |jobs| {+ let tris = jobs.spawn(tris);+ let caps = jobs.spawn(caps);+ let flat = jobs.spawn(flat);+ let flat_cap = jobs.spawn(flat_cap);+ let hover = jobs.spawn(hover);+ let selected = jobs.spawn(selected);+ let see_through_tris = jobs.spawn(see_through_tris);+ let see_through_flat = jobs.spawn(see_through_flat);+ let pbr = jobs.spawn(pbr);+ let lines = jobs.spawn(lines);+ let lines_all = jobs.spawn(lines_all);+ let guide_trans = jobs.spawn(guide_trans);+ let image = jobs.spawn(image);+ let ao = jobs.spawn(ao);+ let oit = jobs.spawn(oit);+ let blits = jobs.spawn(blits);+ let resets = jobs.spawn(resets);+ let (tri, tri_marks, tri_planned, planned_marks, tri_instanced, instanced_marks) = tris.join();+ let (tri_cap, planned_cap, instanced_cap) = caps.join();+ let (tri_instanced_flat, flat_marks) = flat.join();+ let (tri_hl_hover, tri_hl_hover_built) = hover.join();+ let (tri_hl_selected, tri_hl_selected_built) = selected.join();+ let (tri_hl, trans, glass_far, glass_near, ghost, xray, (glass_far_smooth, glass_near_smooth, trans_smooth), tri_hl_instanced) =+ see_through_tris.join();+ let ((glass_far_flat, glass_near_flat, trans_flat), tri_hl_instanced_flat) = see_through_flat.join();+ let (line, line_hidden) = lines.join();+ let (overlay, guide_line) = lines_all.join();+ let (ss_blit, copy_blit, ss_filter) = blits.join();+ let (depth_reset, section_reset) = resets.join();+ let oit = oit.join();+ Renderer {+ ao: ao.join(),+ depth_reset,+ section_reset,+ target: GpuTarget { oit: oit.is_some(), ..t },+ window,+ max_texture: device.limits().max_texture_dimension_2d,+ ss_blit,+ ss_filter,+ copy_blit,+ ss_scaled: false,+ oit,+ oit_targets: None,+ ss_bgl,+ ss: None,+ ss_ready: false,+ stats: DrawStatsHandle::default(),+ ss_stats: DrawStats::default(),+ ss_key: None,+ cached: None,+ image: image.join(),+ image_bgl,+ sampler,+ textures: Default::default(),+ quads: Vec::new(),+ tri,+ tri_cut: cut(tri_marks, tri_cap),+ tri_planned,+ tri_cut_planned: cut(planned_marks, planned_cap),+ tri_instanced,+ tri_cut_instanced: cut(instanced_marks, instanced_cap),+ tri_instanced_flat,+ tri_cut_instanced_flat: cut(flat_marks, flat_cap.join()),+ glass_far_instanced: (glass_far_smooth, glass_far_flat),+ glass_near_instanced: (glass_near_smooth, glass_near_flat),+ trans_instanced: (trans_smooth, trans_flat),+ tess,+ #[cfg(not(target_arch = "wasm32"))]+ tess_later: None,+ access_bgl,+ access_bind,+ access_version: 0,+ tri_hl,+ tri_hl_hover,+ tri_hl_selected,+ tri_hl_hover_built,+ tri_hl_selected_built,+ tri_hl_instanced,+ tri_hl_instanced_flat,+ pbr: pbr.join(),+ trans,+ glass_far,+ glass_near,+ ghost,+ xray,+ line,+ line_hidden,+ overlay,+ guide_trans: guide_trans.join(),+ guide_line,+ uniform,+ uniform_bgl: bgl.clone(),+ bind,+ linear_out: t.format.is_srgb(),+ model: Batches::default(),+ product: Batches::default(),+ empty: Batches::default(),+ sketch: Batches::default(),+ highlight: Batches::default(),+ preview: Batches::default(),+ }+ })}}@@ -2904,6 +3024,61 @@ pub fn tessellation(adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu}}+/// The plan evaluation ([`tessellation`]) compiled on a thread of its own, so the window does not+/// wait for it: D3D12 compiles the evaluation shader in seconds, most of the viewport's start+/// (#4860). Bodies are built on the CPU until [`TessLater::ready`] holds it, and stay so where it+/// never does (a device that cannot build it), as they are where [`tessellation`] gives `None`.+#[cfg(not(target_arch = "wasm32"))]+pub struct TessLater {+ ready: Arc<std::sync::OnceLock<crate::TessGpu>>,+ /// Joined when dropped, so the app does not exit in the middle of the driver's compile.+ worker: Option<std::thread::JoinHandle<()>>,+}++#[cfg(not(target_arch = "wasm32"))]+impl TessLater {+ /// Start compiling [`tessellation`]'s pipeline (`shader`) for `device`.+ pub fn start(adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, shader: &'static str) -> TessLater {+ let ready = Arc::new(std::sync::OnceLock::new());+ let threaded = crate::concurrent::threads_allowed(device);+ let (adapter, device, queue, slot) = (adapter.clone(), device.clone(), queue.clone(), ready.clone());+ let compile = move || {+ if let Some(tess) = tessellation(&adapter, &device, &queue, shader) {+ let _ = slot.set(tess);+ }+ };+ // Where the device may not make pipelines on two threads at once (DXC, OpenGL), or no+ // thread starts, it compiles now, as before.+ let worker = threaded.then(|| std::thread::Builder::new().name("solidcraft tessellation".into()).spawn(compile.clone()).ok()).flatten();+ if worker.is_none() {+ compile();+ }+ TessLater { ready, worker }+ }++ /// The evaluation, there once it has compiled.+ pub fn ready(&self) -> Arc<std::sync::OnceLock<crate::TessGpu>> {+ self.ready.clone()+ }++ /// Wait for the compile to end.+ #[cfg(test)]+ fn wait(&mut self) {+ if let Some(worker) = self.worker.take() {+ let _ = worker.join();+ }+ }+}++#[cfg(not(target_arch = "wasm32"))]+impl Drop for TessLater {+ fn drop(&mut self) {+ if let Some(worker) = self.worker.take() {+ let _ = worker.join();+ }+ }+}+/// A device whose driver hangs on the evaluation shader, so bodies are built on the CPU there:/// the AMD FirePro D300/D500/D700 (Mac Pro 2013, Tahiti) under Metal, where macOS resets the GPU/// and the whole desktop freezes. `SOLIDCRAFT_CPU_TESS=1` forces CPU evaluation on any device.@@ -3004,6 +3179,7 @@ impl Renderer {res.ss_key = res.ss_ready.then_some(key);return;}+ res.take_ready_tessellation();res.model.take(device,queue,@@ -3139,6 +3315,21 @@ impl Renderer {pub fn target(&self) -> GpuTarget {self.target}++ /// Evaluate planned bodies with `later`'s pipeline once it has compiled (#4860).+ #[cfg(not(target_arch = "wasm32"))]+ pub fn tessellate_later(&mut self, later: TessLater) {+ self.tess_later = Some(later);+ }++ /// [`Renderer::tess`] from [`Renderer::tess_later`] once that has compiled.+ fn take_ready_tessellation(&mut self) {+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(tess) = self.tess_later.as_ref().and_then(|later| later.ready.get()) {+ self.tess = Some(tess.clone());+ self.tess_later = None;+ }+ }}impl Renderer {@@ -3772,6 +3963,29 @@ mod tests {assert!(!super::hangs_on_gpu_tessellation(wgpu::Backend::Vulkan, "AMD FirePro W5100"));}+ /// The plan evaluation compiled beside the window reaches the renderer once it is ready; one+ /// that does not compile never does, and bodies stay built on the CPU (#4860).+ #[test]+ fn a_renderer_takes_the_plan_evaluation_once_it_has_compiled() {+ let Ok((adapter, device, queue)) = crate::open_headless() else {+ eprintln!("skipped: no GPU adapter");+ return;+ };+ let depth = crate::depth_format(&device, true);+ let target = super::GpuTarget { format: wgpu::TextureFormat::Rgba8Unorm, depth: Some(depth), samples: 1, tess: false, oit: false };+ let compiles = super::tessellation(&adapter, &device, &queue, crate::SHADER).is_some();+ for (shader, expected) in [(crate::SHADER, compiles), ("not a shader", false)] {+ let mut later = super::TessLater::start(&adapter, &device, &queue, shader);+ later.wait();+ let mut renderer = super::Renderer::new(&device, target, None);+ renderer.take_ready_tessellation();+ assert!(renderer.tess.is_none(), "no evaluation before one is handed over");+ renderer.tessellate_later(later);+ renderer.take_ready_tessellation();+ assert_eq!(renderer.tess.is_some(), expected, "shader {shader:.12}");+ }+ }+/// The viewport shader parses and validates (a bad shader would only fail at run time).#[test]fn shader_is_valid() {diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rsindex e6e51525c2..850b0fac5b 100644--- a/crates/gpu/src/view/ao.rs+++ b/crates/gpu/src/view/ao.rs@@ -45,8 +45,9 @@ fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]}impl Resources {- pub fn new(device: &wgpu::Device, uniform: &wgpu::BindGroupLayout, module: &wgpu::ShaderModule, reversed: bool) -> Self {- let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ /// The layout of the depth map's bind group, which the lit pipelines' layout includes.+ pub fn layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {label: Some("sc_ao_depth"),entries: &[wgpu::BindGroupLayoutEntry {binding: 0,@@ -58,7 +59,18 @@ impl Resources {},count: None,}],- });+ })+ }++ /// The prepass's pipelines and a 1 x 1 stand-in map, bound with `layout` ([`Resources::layout`]).+ pub fn new(+ device: &wgpu::Device,+ layout: &wgpu::BindGroupLayout,+ uniform: &wgpu::BindGroupLayout,+ module: &wgpu::ShaderModule,+ reversed: bool,+ ) -> Self {+ let layout = layout.clone();let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {label: Some("sc_ao_prepass"),bind_group_layouts: &[Some(uniform)],diff --git a/crates/gpu/src/view/msaa_check.rs b/crates/gpu/src/view/msaa_check.rsindex 591c3581d8..0f392f4ba1 100644--- a/crates/gpu/src/view/msaa_check.rs+++ b/crates/gpu/src/view/msaa_check.rs@@ -40,6 +40,10 @@ impl Renderer {return Ok(MsaaCheck::FailedAtOne);}replacement.tess = self.tess.take();+ #[cfg(not(target_arch = "wasm32"))]+ {+ replacement.tess_later = self.tess_later.take();+ }*self = replacement;Ok(MsaaCheck::Fallback)}diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rsindex f5aba312f3..3195b50797 100644--- a/crates/ui-egui/src/gpu.rs+++ b/crates/ui-egui/src/gpu.rs@@ -16,22 +16,59 @@ pub use solidcraft_gpu::view::{/// A frame of the viewport as an egui paint callback.pub struct ViewportCallback(pub Frame);+/// The GPU plan evaluation compiling beside the window: there once it is ready ([`tick_tessellation`]).+pub type TessReady = std::sync::Arc<std::sync::OnceLock<solidcraft_gpu::TessGpu>>;+/// Create the pipelines. Call once with the app's render state, the scene target's depth/stencil//// MSAA settings, and the target of the pass the picture is shown in. Without a stencil the/// section cap does not hide the inside of cut bodies. Without `gpu_meshing` (safe mode) bodies/// are meshed on the CPU. When the two targets differ, the scene is drawn offscreen and blitted.-/// Also returns the handle to what each frame drew.-pub fn install(rs: &egui_wgpu::RenderState, scene: GpuTarget, window: GpuTarget, gpu_meshing: bool) -> (GpuTarget, DrawStatsHandle) {+/// Also returns the handle to what each frame drew, and the GPU plan evaluation still compiling+/// (native: the target says `tess: false` until it is ready).+pub fn install(+ rs: &egui_wgpu::RenderState,+ scene: GpuTarget,+ window: GpuTarget,+ gpu_meshing: bool,+) -> (GpuTarget, DrawStatsHandle, Option<TessReady>) {log_uncaptured_errors(&rs.device);+ // The evaluation shader compiles beside the window, which does not wait for it: on D3D12 it+ // takes seconds, most of the start (#4860). Bodies are built on the CPU until it is ready.+ #[cfg(not(target_arch = "wasm32"))]+ let later = gpu_meshing.then(|| solidcraft_gpu::view::TessLater::start(&rs.adapter, &rs.device, &rs.queue, solidcraft_gpu::SHADER));+ #[cfg(target_arch = "wasm32")]let tess = if gpu_meshing { solidcraft_gpu::view::tessellation(&rs.adapter, &rs.device, &rs.queue, solidcraft_gpu::SHADER) } else { None };- let scene = GpuTarget { tess: tess.is_some(), ..scene };- let window = GpuTarget { tess: tess.is_some(), ..window };- let res = Renderer::with_window_target(&rs.device, scene, window, tess);+ #[cfg(not(target_arch = "wasm32"))]+ let tess = None;+ let (scene, window) = (GpuTarget { tess: tess.is_some(), ..scene }, GpuTarget { tess: tess.is_some(), ..window });+ #[allow(unused_mut)] // Only native hosts hand the renderer a later evaluation.+ let mut res = Renderer::with_window_target(&rs.device, scene, window, tess);+ #[cfg(not(target_arch = "wasm32"))]+ let ready = later.map(|later| {+ let ready = later.ready();+ res.tessellate_later(later);+ ready+ });+ #[cfg(target_arch = "wasm32")]+ let ready = None;// What the renderer can do (order-independent transparency), not only what was asked for.let scene = res.target();let stats = res.stats();rs.renderer.write().callback_resources.insert(res);- (scene, stats)+ (scene, stats, ready)+}++/// Draw bodies from their plans on the GPU from the frame the evaluation shader has compiled+/// ([`install`]); until then, and where it never does, they are built on the CPU.+pub(crate) fn tick_tessellation(app: &mut crate::SolveApp) {+ if app.viewport.tess_ready.as_ref().is_some_and(|ready| ready.get().is_some()) {+ app.viewport.tess_ready = None;+ if let Some(gpu) = app.viewport.gpu.as_mut() {+ gpu.tess = true;+ #[cfg(not(target_arch = "wasm32"))]+ eprintln!("SolidCraft graphics: GPU tessellation ready; bodies are evaluated on the GPU from now on");+ }+ }}/// A GPU error no error scope caught is reported, never a panic: a device's default handler@@ -532,6 +569,28 @@ impl OffscreenFrames {#[cfg(test)]mod tests {+ /// Bodies are drawn from their plans on the GPU from the frame the evaluation shader has+ /// compiled, and built on the CPU until then (#4860).+ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn plans_are_drawn_on_the_gpu_once_the_evaluation_has_compiled() {+ let Ok(tess) = solidcraft_gpu::TessGpu::headless() else {+ eprintln!("skipped: no GPU adapter that builds the evaluation");+ return;+ };+ let mut app = crate::SolveApp::new(Default::default(), Default::default());+ app.viewport.gpu =+ Some(super::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });+ let ready = super::TessReady::default();+ app.viewport.tess_ready = Some(ready.clone());+ super::tick_tessellation(&mut app);+ assert!(app.viewport.gpu.is_some_and(|g| !g.tess), "still compiling: built on the CPU");+ assert!(ready.set(tess).is_ok());+ super::tick_tessellation(&mut app);+ assert!(app.viewport.gpu.is_some_and(|g| g.tess), "compiled: drawn from plans");+ assert!(app.viewport.tess_ready.is_none());+ }+/// The offscreen tests start the backends the app would: on Windows without `WGPU_BACKEND`/// exactly one, from the app's order (D3D12, Vulkan, OpenGL); otherwise wgpu's default.#[cfg(not(target_arch = "wasm32"))]diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex f52388589e..b6b0514d65 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -805,7 +805,7 @@ impl SolveApp {fn set_wgpu_targets(&mut self, rs: &egui_wgpu::RenderState, scene: crate::gpu::GpuTarget, window: crate::gpu::GpuTarget) {#[allow(unused_mut)] // Only native hosts can wait for the startup readback.- let (mut installed, stats) = gpu::install(rs, scene, window, !self.cpu_meshing);+ let (mut installed, stats, tess_ready) = gpu::install(rs, scene, window, !self.cpu_meshing);#[cfg(not(target_arch = "wasm32"))]if scene.depth.is_some() && window.depth.is_none() && window.samples == 1 {let mut renderer = rs.renderer.write();@@ -828,6 +828,7 @@ impl SolveApp {}}self.viewport.gpu = Some(installed);+ self.viewport.tess_ready = tess_ready;self.viewport.draw_stats = Some(stats);render_workspace::invalidate_scene(self);let (samples, has_depth) = self.viewport.gpu.map_or((1, false), |g| (g.samples.max(1), g.depth.is_some()));@@ -1971,6 +1972,7 @@ impl SolveApp {/// Per-frame logic before layout.pub fn logic(&mut self, ctx: &egui::Context) {frame_watch::begin(self);+ gpu::tick_tessellation(self);file_picker::tick(self, ctx);dialogs_save_mesh::tick_wait(self, ctx);easyprint_ui::tick(self, ctx);diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex ad90e91c1f..49ab684310 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -114,6 +114,8 @@ pub struct ViewportState {/// greys out with it.pub(crate) corner_ok: bool,pub gpu: Option<GpuTarget>,+ /// The GPU plan evaluation still compiling: `gpu.tess` once it is ready (#4860).+ pub(crate) tess_ready: Option<crate::gpu::TessReady>,/// What the GPU drew last frame, shared with the renderer (the frame-rate details, #2548).pub(crate) draw_stats: Option<crate::gpu::DrawStatsHandle>,/// The graphics backend and adapter, as the frame-rate details show them.@@ -431,6 +433,9 @@ fn scene_key(app: &SolveApp) -> u64 {solidcraft_engine::doc::display_quality::current().hash(&mut h);lod_generation(app).hash(&mut h);app.viewport.mesh_lods.generation().hash(&mut h);+ // How bodies are drawn: from their plans on the GPU, or built here (until the evaluation+ // shader has compiled, #4860).+ app.viewport.gpu.is_some_and(|g| g.tess).hash(&mut h);// The section plane (its cut outlines are part of the model scene).section_plane(app).map(|(o, n)| [o.x, o.y, o.z, n.x, n.y, n.z].map(f64::to_bits)).hash(&mut h);app.cam.up.hash(&mut h);