Skip to main content

crcbl_render/
lib.rs

1//! Renderer: the 3D frame — meshes, materials, lights, effects — built on
2//! `crcbl-frame`'s render graph and UI pass, everything above the HAL seam.
3//!
4//! The graph, the transient pool, the texture uploads, the pass timers and the
5//! UI pass are [`crcbl_frame`]'s, re-exported here under the paths they have
6//! always had ([`graph`], [`transient`], [`texture`], [`timing`], [`ui_pass`]),
7//! so a program that draws only a UI can depend on that crate alone.
8//!
9//! ```text
10//! camera + light ──▶ ForwardRenderer ──adds passes──▶ RenderGraph
11//!                                                          │ compile()
12//!                                                          ▼
13//!                            ordered passes + exact barriers + transients
14//!                                                          │ execute()
15//!                                                          ▼
16//!                                        crcbl-hal ──▶ crcbl-vk / null / …
17//! ```
18//!
19//! # The one rule
20//!
21//! **No manual barriers outside the graph, ever** — stage 2
22//! §2.4, and it is the reason this crate exists rather than the frame loop
23//! living in each sample. Passes say what they read and write;
24//! [`graph::RenderGraph::compile`] works out the transitions, the layout
25//! changes, the transient aliasing and the final states, and
26//! [`graph::CompiledGraph::execute`] is the only code in the engine that calls
27//! [`pipeline_barrier`](crcbl_hal::CommandEncoder::pipeline_barrier) during a
28//! frame.
29//!
30//! The barriers outside it are the **startup uploads**: [`mesh_pool`]'s staging
31//! copy into the geometry pools, [`texture`]'s for every image ([`ui_pass`]'s
32//! glyph atlas and [`sprite_pass`]'s sheets), and [`draw_gen`]'s copy zeroing
33//! the LOD hysteresis state, which is device-local because a shader writes it
34//! and so cannot be zeroed by a host write. Each runs before any frame exists
35//! and has no graph to belong to; each is called out at the call site.
36//! [`ForwardRenderer`]'s build records the small ones — its placeholders and
37//! tables, every view's and shadow cull's fills, and the calm wind layers —
38//! into one [`texture::UploadBatch`], submitted once and not waited for: its
39//! frames follow it on the same queue, and the first `begin_frame` past it
40//! frees its staging. The one that also runs
41//! later is [`texture`]'s — between two frames, never inside
42//! one, on an image no frame names yet, and blocking until its copy lands — when
43//! [`ForwardRenderer::replace_page`](forward::ForwardRenderer::replace_page)
44//! reloads a material page or
45//! [`ForwardRenderer::set_grass`](forward::ForwardRenderer::set_grass) replaces
46//! a field. There are no others, and a barrier recorded during a frame from
47//! anywhere but [`graph::CompiledGraph::execute`] is a bug.
48//!
49//! # Nothing here knows a backend
50//!
51//! This crate depends on `crcbl-hal`, `crcbl-core`, `crcbl-frame`,
52//! `crcbl-shaders`, `glam`, and the two description-only crates whose data it turns into pixels — `crcbl-ui`
53//! for [`ui_pass`]'s draw list and `crcbl-sprite` for [`sprite_pass`]'s sample
54//! modes, neither of which depends on a backend or on this crate.
55//! It contains no `ash`, no `crcbl-vk`, and no `#[cfg(target_os = …)]`, per
56//! the HAL rules in `docs/notes/backends.md` — which also name the render graph
57//! specifically as living above the seam rather than in it. The graph compiles
58//! identically against [`NullBackend`](crcbl_hal::null), which is what makes the
59//! graph-compile suite `docs/notes/process.md` calls a non-negotiable anchor
60//! run on every machine, with no ICD in the room.
61//!
62//! # Two tiers, one renderer
63//!
64//! Topic 03's rule is that **the lesser path (once "Tier B") is a
65//! constraint on data layout, not a separate renderer**, and no pass here reads
66//! a push constant. [`forward`]'s camera has been in a uniform buffer since P1
67//! for exactly that reason; [`sprite_pass`] followed it; and [`ui_pass`] — which
68//! draws every sample's HUD, and which WebGPU's lack of push constants had made
69//! this crate's one permutation axis, with a `ConstantDelivery` enum and a
70//! second `.slang` — joined them in 2026-08.
71//!
72//! So the tier costs one indirection where a push constant would have served,
73//! and buys one artifact per shader, one code path per pass, and nothing to
74//! select between at device-open time. [`ui_pass`]'s own docs carry the trade in
75//! full, including what the split had cost.
76//!
77//! # What this crate is *not*, at P1
78//!
79//! No backend registry (see below), no material *system*, no scene, no
80//! scheduler. [`material_table`] is §3.2's table and only that — a row of
81//! factors and one base-colour texture layer that an instance's id selects; the
82//! authoring, templates, permutations and the other texture slots a material
83//! system means are `docs/plan/37-materials.md`'s and are not here.
84//!
85//! The one thing on that list that has since moved whole is culling:
86//! [`cull`] is §3.3's frustum test and the CPU reference `cull.slang` is checked
87//! against, [`draw_gen`] runs that shader and turns its survivors into indirect
88//! draw arguments, and [`forward`] draws from those rather than recording a draw
89//! per object. The graph is still a linear pass list with computed barriers,
90//! which is what §2.4's risk list asks for by name: "No multi-queue scheduling,
91//! no reordering. Resist."
92//!
93//! ## The registry deliberately did not move here
94//!
95//! `crcbl-vk`'s crate docs floated moving the GPU backend registry into this
96//! crate at P1.3. It did not move, because it would make `crcbl-render` depend
97//! on `crcbl-vk` — and `crcbl-vk`'s end-to-end suite depends on `crcbl-render`,
98//! since the only honest way to test a render graph against real Vulkan is to
99//! run the real graph. That is a dependency cycle through dev-dependencies:
100//! legal in Cargo, and a confusing thing to have created in exchange for moving
101//! four lines out of the crate whose entire job is to be the one name a game
102//! depends on. The registry stays in `crcbl`.
103//!
104//! # Example
105//!
106//! ```
107//! use crcbl_hal::null::NullInstance;
108//! use crcbl_hal::{DeviceDesc, Instance, QueueKind, ResourceState};
109//! use crcbl_render::graph::RenderGraph;
110//! use crcbl_render::transient::{TransientImageDesc, TransientPool};
111//!
112//! let instance = NullInstance::gpu_driven();
113//! let adapter = instance.adapters().remove(0);
114//! let device = instance.create_device(&DeviceDesc::for_adapter(adapter.id))?;
115//! let queue = device.queue(QueueKind::Graphics).expect("always present");
116//!
117//! // The pool outlives the graph: it owns the physical images, and it is what
118//! // remembers what the last frame left them in.
119//! let mut pool = TransientPool::new();
120//!
121//! let mut graph = RenderGraph::new(queue);
122//! let scene = graph.create_image("scene", crcbl_render::targets::scene_color((64, 48)));
123//! graph
124//!     .add_render_pass("clear")
125//!     .clear_color(scene, [0.0, 0.0, 0.0, 1.0])
126//!     .execute(|_| {});
127//!
128//! let compiled = graph.compile(&pool)?;
129//! assert_eq!(compiled.passes().len(), 1);
130//! // Nothing has ever used this pool, so the transient really is undefined and
131//! // the graph transitions it before use. A second frame through the same pool
132//! // would start from `ColorAttachment` — which is the barrier that orders it
133//! // after this one.
134//! let barriers = compiled.passes()[0].barriers();
135//! assert_eq!(barriers.images[0].from, ResourceState::Undefined);
136//! assert_eq!(barriers.images[0].to, ResourceState::ColorAttachment);
137//! # Ok::<(), Box<dyn std::error::Error>>(())
138//! ```
139
140// The frame core's modules, under the paths this crate has always given them:
141// the graph, the transient pool, the texture uploads, the mip chains and the
142// frame counters live in `crcbl-frame`, which a program that draws only a UI
143// depends on without the rest of this crate.
144pub use crcbl_frame::{counters, graph, mip, texture, transient};
145
146mod atlas_view;
147mod bind_group_cache;
148mod bloom;
149pub mod camera;
150pub mod cluster_pool;
151mod contact_shadows;
152pub mod cull;
153pub mod cull_stats;
154pub mod debug_draw;
155pub mod draw_gen;
156pub mod effects;
157mod exposure;
158pub mod fly;
159pub mod forward;
160mod fxaa;
161pub mod grass;
162pub mod grid;
163pub mod hiz;
164pub mod instance_pool;
165pub mod layers;
166pub mod light;
167pub mod light_grid;
168pub mod material_table;
169pub mod menu;
170pub mod mesh_pool;
171pub mod nine_slice;
172pub mod occlusion_cull;
173pub mod orbit;
174mod partial;
175pub mod pass_stats;
176mod pipeline_batch;
177mod probe;
178
179/// The GPU pass that fills a probe's visibility map: a depth cube per probe,
180/// resolved into the octahedral layer `mesh.slang` reads.
181mod probe_capture;
182
183/// The compute pass that reads the irradiance probes' reflective
184/// shadow map into every probe row of a volume the scene asked to be updated.
185mod probe_gather;
186
187/// The static geometry a probe's visibility map is captured from, and the
188/// console variable that decides whether the frame reads one.
189mod probe_visibility;
190
191mod cmaa2;
192/// The reflective shadow map: the sun's near cascade drawn a second time as
193/// what it reflects, where it is and which way it faces.
194pub mod rsm;
195pub mod scene;
196pub mod shadow;
197pub mod skinning;
198mod sky_pass;
199mod split;
200pub mod sprite_pass;
201mod ssao;
202mod ssr;
203pub mod stack;
204pub mod targets;
205pub mod timing;
206pub mod ui_pass;
207mod upscale;
208mod volumetric;
209mod water;
210
211pub use camera::{Atmosphere, Camera, DirectionalLight, Fog, Projection, Sky, ViewRay};
212pub use cluster_pool::{ClusterPool, ClusterRange};
213pub use counters::{FrameCounters, INDIRECT, UNKNOWN};
214/// Re-exported because [`SheetDesc::sample`] is spelled in it: a crate whose
215/// public API names a foreign type and does not export it is one every caller
216/// has to add a dependency for.
217///
218/// [`NineSlice`] and [`Rect`] are here for the same reason —
219/// [`NineSliceSource`]'s fields are spelled in both.
220pub use crcbl_sprite::{NineSlice, Rect, SampleMode};
221/// Re-exported for the same reason: [`menu_skin`] returns a [`MenuSkin`], and
222/// a caller that can name this crate's menu art should not have to add a second
223/// dependency to lay out and draw the menu it skins. It is also what lets an
224/// end-to-end suite that depends on this crate take a golden image of the real
225/// menu rather than of a replica.
226pub use crcbl_ui::menu::{Menu, MenuItem, MenuItemLayout, MenuLayout, MenuSkin, MenuStyle};
227pub use crcbl_ui::text::FontAtlas;
228/// Re-exported for the same reason as [`Menu`]: [`MenuSkin`]'s buttons are a
229/// [`ButtonSkin`] drawn per [`ButtonState`], and its insets are
230/// [`SkinInsets`].
231pub use crcbl_ui::{ButtonSkin, ButtonState, SkinInsets};
232/// Re-exported because [`ForwardRenderer::set_water`] is spelled in them, on
233/// [`SampleMode`]'s terms below: a caller setting water should not need a
234/// dependency of its own to name what it sets.
235pub use crcbl_water::{BodyError, Medium, WaterBody};
236pub use cull::{Aabb, Frustum, visible_instances};
237pub use cull_stats::{ClusterCull, CullStats, CullStatsRing, OcclusionCull};
238pub use debug_draw::{DebugDraw, DebugVertex, frustum_corners};
239pub use draw_gen::{
240    DrawGen, DrawGenDesc, DrawGenPipelines, FrameCull, GeneratedDraws, OcclusionFrame,
241    PyramidInputs, Selection,
242};
243pub use effects::{Antialiasing, EffectOverride, EffectRequest, RenderEffects, ray_tracing_note};
244pub use exposure::{ExposureAdaptation, ExposureBuffers};
245pub use fly::{Flyer, LOOK, SPEED, TURN};
246pub use forward::{
247    DEFAULT_ANISOTROPY, DebugView, EXPOSURE_MAX, EXPOSURE_MIN, ForwardOverlayTargets,
248    ForwardRenderer, FrameTargets, MAX_VIEWS, MIN_RENDER_SCALE, SCENE_CLEAR, SHADOW_LOD_BIAS,
249    SkinnedInstanceDesc, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
250};
251pub use graph::{
252    Attachment, BufferId, CompiledGraph, CompiledPass, GraphBarriers, GraphBufferBarrier,
253    GraphError, GraphImageBarrier, ImageId, ImportField, ImportedBuffer, ImportedImage,
254    InitialClaim, PassBuilder, PassContext, PassKind, RenderGraph,
255};
256pub use instance_pool::{
257    Instance, InstanceHandle, InstancePool, InstancePoolDesc, InstancePoolError,
258};
259pub use layers::{Layer, LayerStack, Parallax};
260pub use light::{Light, PointLight, RectLight, SpotLight, sun_row};
261pub use light_grid::{FROXEL_CAPACITY, FrameView, Grid, LightGrid, LightGridDesc};
262pub use material_table::{
263    Material, MaterialHandle, MaterialTable, MaterialTableDesc, MaterialTableError,
264};
265pub use menu::menu_skin;
266pub use mesh_pool::{
267    Mesh, MeshHandle, MeshPool, MeshPoolDesc, MeshPoolError, MeshRange, MeshUpload, UPLOAD_TIMEOUT,
268};
269pub use nine_slice::{NineQuads, NineSliceSource, SliceQuad};
270pub use occlusion_cull::OcclusionCulling;
271pub use orbit::OrbitCamera;
272pub use pass_stats::PassStats;
273pub use scene::{
274    Capacities, Geometry, InstanceDesc, MeshDesc, PageDesc, PageKind, ProbeGrid, ProbeUpdate,
275    SceneBoundsError, SceneDesc,
276};
277pub use shadow::Cascades;
278pub use skinning::{
279    SkinRange, SkinnedMesh, SkinnedRegion, Skinning, SkinningDesc, SkinningError, blend,
280    normal_basis, skin_vertex,
281};
282pub use sprite_pass::{
283    ATLAS_FORMAT, ATLAS_FORMATS, AtlasDesc, AtlasSlot, CONSTANTS_SIZE, INSTANCE_STRIDE,
284    SAMPLE_PIXEL, SAMPLE_SMOOTH, SheetDesc, SheetError, SheetId, SlotCopy, Sprite, SpriteConstants,
285    SpriteInstance, SpriteRenderer, sheet_lane,
286};
287pub use ssao::{r_ssao_bent_normals, r_ssao_blur_passes, r_ssao_slices};
288pub use ssr::{MIN_SSR_RESOLUTION, r_ssr_resolution};
289pub use stack::{
290    AmbientOcclusionPass, AntialiasingPass, AutoExposurePass, BloomPass, CameraStack,
291    ContactShadowsPass, ReflectionsPass, ShadowsPass, StackError, VolumetricFogPass,
292};
293pub use texture::{
294    ClearedTextureDesc, TexturePatch, UploadBatch, UploadedTexture, upload_cleared_texture,
295    upload_texture, upload_texture_layers, upload_texture_mip_layers,
296};
297pub use timing::{FrameTimings, MAX_TIMED_PASSES, PassTimers, PassTiming};
298pub use transient::{TransientBufferDesc, TransientImageDesc, TransientPool, TransientUse};
299pub use ui_pass::{UiRenderer, UiTexture};
300pub use volumetric::FroxelBuffers;
301
302/// Everything this crate exposes to the debug console.
303///
304/// One list per crate, gathered by the engine at one seam — debug-console
305/// decision 2 in `docs/notes/tooling.md`, whose worked example in the plan was
306/// this crate. It holds [`debug_draw::r_debug_draw`], the switch the debug draw
307/// layer reads once a frame, the occlusion chain's own — `ssao::r_ssao_slices`
308/// and `ssao::r_ssao_blur_passes`, which `crate::ssao`'s header argues are two
309/// variables rather than one quality knob, `ssao::r_ssao_intensity` and
310/// `ssao::r_ssao_radius`, which that header argues are not on their ladder at
311/// all because neither moves the budget, and `ssao::r_ssao_bent_normals`, which
312/// is the one of them that is on by default because it is the rung rather than
313/// a purchase on top of it, and `ssao::r_ssao_split`, which is not a knob on the
314/// effect at all but the comparison seam `crate::split` describes — and the
315/// shadow cadence's two,
316/// `shadow::r_shadow_cadence` and `shadow::r_shadow_faces`, which
317/// `crate::shadow`'s cadence module argues are two for the same kind of reason:
318/// how long a map may be held and how many may be redrawn at once are different
319/// purchases — and the shadow filter's two, `shadow::r_shadow_filter` and
320/// `shadow::r_shadow_split`, which are that module's answer to the occlusion
321/// chain's technique pair: which rung of topic 45's filter
322/// ladder runs, and the seam that puts it beside the one that ships — and the
323/// sun's two bias counts, `shadow::r_shadow_bias` and
324/// `shadow::r_shadow_normal_offset`, which are two variables for the reason
325/// topic 45's seventh decision gives: one moves the compared
326/// depth towards the light and the other moves the receiver sideways along its
327/// own normal, so acne and peter-panning are pulled by different numbers and a
328/// single knob could not show the pair moving against each other — and
329/// `ssr::r_ssr_resolution`, the share of the scene the reflection march runs
330/// at. `tests/console_table.rs` is
331/// what keeps this list in step with what the source actually declares.
332#[must_use]
333pub fn console_table() -> crcbl_console::Table {
334    crcbl_console::table![
335        debug_draw::r_debug_draw,
336        ssao::r_ssao_slices,
337        ssao::r_ssao_blur_passes,
338        ssao::r_ssao_intensity,
339        ssao::r_ssao_bent_normals,
340        ssao::r_ssao_radius,
341        ssao::r_ssao_technique,
342        ssao::r_ssao_split,
343        occlusion_cull::r_occlusion_cull,
344        occlusion_cull::r_small_feature_px,
345        probe_visibility::r_probe_visibility,
346        rsm::r_probe_bounce,
347        shadow::r_shadow_cadence,
348        shadow::r_shadow_faces,
349        shadow::r_shadow_filter,
350        shadow::r_shadow_split,
351        shadow::r_shadow_bias,
352        shadow::r_shadow_normal_offset,
353        ssr::r_ssr_resolution
354    ]
355}