use concinnity_core::components::sdf_programs::SdfPrograms;
use concinnity_core::components::sdf_volume::SdfVolume;
use concinnity_core::gfx::mesh_payload::Vertex;
use concinnity_core::gfx::render_types;
use concinnity_core::gfx::render_types::LightUniforms;
use concinnity_core::platform::Platform;
use concinnity_core::render::backend_init::SdfVolumeSource;
use concinnity_core::render::error::{RenderError, RenderResult};
use concinnity_core::render::shader_programs::raymarch::{Family, ProxyFaces, VolumeFlags};
use std::ffi::c_void;
use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
pub(in crate::directx) use concinnity_core::render::uniforms::{
RaymarchView, RaymarchVolumeUniforms,
};
use concinnity_core::render::uniforms::{GBufferView, PassCamera};
use concinnity_core::transform::mat4_inverse;
use super::allocator::{DeviceAllocator, PooledBuffer, PooledTexture};
use super::post::gbuffer::GbufferPrepassView;
use crate::directx::com;
use crate::directx::context::{DxContext, FRAMES, align256, dump_on_err};
use crate::directx::depth::shadow_sample_compare;
use crate::directx::descriptor_slot::DescriptorTables;
use crate::directx::descriptor_slot::{SamplerSlot, SrvSlot};
use crate::directx::error::{map_hresult, map_pso_hresult};
use crate::directx::pipeline::main_input_layout;
use crate::directx::pso::{Blend, Cull, Depth, GraphicsPso, Raster};
use crate::directx::root_constants::RootConstants;
use crate::directx::root_sig::{RootSig, Visibility};
use crate::directx::texture::{
HDR_FORMAT, create_fallback_white_resource, create_hdr_resolve_target, transition_barrier,
};
use crate::shader::raymarch_source::{face_artifacts, family_artifacts};
mod swap;
fn volume_uniforms_from(v: &SdfVolume) -> RaymarchVolumeUniforms {
RaymarchVolumeUniforms {
center: v.center,
_pad0: 0.0,
extent: v.extent,
_pad1: 0.0,
cone_ratio: v.cone_ratio(),
max_distance: v.max_distance,
max_steps: v.max_steps as i32,
receive_shadows: if v.receive_shadows { 1 } else { 0 },
params: v.params,
}
}
pub(in crate::directx) struct RaymarchVolumeRecord {
pub(in crate::directx) label: String,
pub(in crate::directx) pso: ID3D12PipelineState,
pub(in crate::directx) front_pso: Option<ID3D12PipelineState>,
pub(in crate::directx) shadow_pso: Option<ID3D12PipelineState>,
pub(in crate::directx) prepass_psos: Option<FacePsos>,
#[expect(
dead_code,
reason = "held to keep the GPU memory alive; the encoder binds through volume_cbuffer_gva"
)]
volume_cbuffer: PooledBuffer,
pub(in crate::directx) volume_cbuffer_gva: u64,
pub(in crate::directx) visible: bool,
pub(in crate::directx) volumetric: bool,
pub(in crate::directx) cast_shadows: bool,
pub(in crate::directx) refractive: bool,
pub(in crate::directx) center: [f32; 3],
pub(in crate::directx) extent: [f32; 3],
}
pub(in crate::directx) struct FacePsos {
pub(in crate::directx) front: ID3D12PipelineState,
pub(in crate::directx) back: ID3D12PipelineState,
}
impl FacePsos {
fn get(&self, faces: ProxyFaces) -> &ID3D12PipelineState {
match faces {
ProxyFaces::Front => &self.front,
ProxyFaces::Back => &self.back,
}
}
}
impl RaymarchVolumeRecord {
fn faces(&self, view: &RaymarchView) -> ProxyFaces {
if self.volumetric {
ProxyFaces::Back
} else {
ProxyFaces::for_box(view, self.center, self.extent)
}
}
fn draw_pso(&self, view: &RaymarchView) -> &ID3D12PipelineState {
match (self.faces(view), &self.front_pso) {
(ProxyFaces::Front, Some(front)) => front,
_ => &self.pso,
}
}
}
pub(in crate::directx) struct RaymarchResources {
pub(in crate::directx) root_sig: ID3D12RootSignature,
pub(in crate::directx) shadow_root_sig: ID3D12RootSignature,
#[expect(
dead_code,
reason = "held to keep the cube geometry resident; the encoder binds cube_vbv"
)]
cube_vb: PooledBuffer,
#[expect(
dead_code,
reason = "held to keep the cube geometry resident; the encoder binds cube_ibv"
)]
cube_ib: PooledBuffer,
cube_vbv: D3D12_VERTEX_BUFFER_VIEW,
cube_ibv: D3D12_INDEX_BUFFER_VIEW,
view_cbuffers: Vec<PooledBuffer>,
view_ptrs: Vec<*mut u8>,
prepass_view_cbuffers: Vec<PooledBuffer>,
prepass_view_ptrs: Vec<*mut u8>,
#[expect(
dead_code,
reason = "holds the scene_color slot open during init; the live SRV is re-pointed before the first frame"
)]
scene_color_fallback: PooledTexture,
hdr_resolve_copy: ID3D12Resource,
scene_color_srv_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
pub(in crate::directx) srv_table_gpu: SrvSlot,
pub(in crate::directx) sampler_table_gpu: SamplerSlot,
pub(in crate::directx) volumes: Vec<RaymarchVolumeRecord>,
}
fn create_raymarch_root_signature(device: &ID3D12Device) -> RenderResult<ID3D12RootSignature> {
use Visibility::{All, Pixel};
RootSig::new()
.cbv(0, All)
.cbv(1, All)
.cbv(2, Pixel)
.cbv(3, Pixel)
.srv_table(0, 4, Pixel) .sampler_table(0, 3, Pixel) .input_layout()
.build(device, "raymarch root sig")
}
fn create_raymarch_pso(
device: &ID3D12Device,
root_sig: &ID3D12RootSignature,
(vs, ps): (&[u8], &[u8]),
faces: ProxyFaces,
msaa_samples: u32,
) -> RenderResult<ID3D12PipelineState> {
let input_layout = main_input_layout();
GraphicsPso::new(root_sig, vs, ps)
.input_layout(&input_layout)
.target(HDR_FORMAT, Blend::Opaque)
.depth(DXGI_FORMAT_D32_FLOAT, Depth::write_inclusive())
.samples(msaa_samples.max(1))
.raster(proxy_raster(msaa_samples > 1, faces))
.build(device, "raymarch")
}
fn proxy_raster(multisample: bool, faces: ProxyFaces) -> Raster {
Raster {
cull: match faces {
ProxyFaces::Front => Cull::Back,
ProxyFaces::Back => Cull::Front,
},
multisample,
..Raster::default()
}
}
fn compile_volume_pso(
t: &VolumePsoTargets<'_>,
programs: &SdfPrograms,
asset_label: &str,
faces: ProxyFaces,
) -> RenderResult<ID3D12PipelineState> {
let (vs, ps) = face_artifacts(
programs,
Family::Surface,
faces,
Platform::DirectX,
t.hot_reload,
asset_label,
)?;
create_raymarch_pso(t.device, t.root_sig, (&vs, &ps), faces, t.msaa_samples)
}
fn create_raymarch_volumetric_pso(
device: &ID3D12Device,
root_sig: &ID3D12RootSignature,
vs: &[u8],
ps: &[u8],
msaa_samples: u32,
) -> RenderResult<ID3D12PipelineState> {
let input_layout = main_input_layout();
let rasterizer = D3D12_RASTERIZER_DESC {
FillMode: D3D12_FILL_MODE_SOLID,
CullMode: D3D12_CULL_MODE_FRONT,
FrontCounterClockwise: windows::core::BOOL(1),
DepthBias: 0,
DepthBiasClamp: 0.0,
SlopeScaledDepthBias: 0.0,
DepthClipEnable: windows::core::BOOL(1),
MultisampleEnable: windows::core::BOOL(if msaa_samples > 1 { 1 } else { 0 }),
AntialiasedLineEnable: windows::core::BOOL(0),
ForcedSampleCount: 0,
ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF,
};
let mut blend = D3D12_BLEND_DESC {
AlphaToCoverageEnable: windows::core::BOOL(0),
IndependentBlendEnable: windows::core::BOOL(0),
RenderTarget: [D3D12_RENDER_TARGET_BLEND_DESC::default(); 8],
};
blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC {
BlendEnable: windows::core::BOOL(1),
LogicOpEnable: windows::core::BOOL(0),
SrcBlend: D3D12_BLEND_SRC_ALPHA,
DestBlend: D3D12_BLEND_INV_SRC_ALPHA,
BlendOp: D3D12_BLEND_OP_ADD,
SrcBlendAlpha: D3D12_BLEND_ONE,
DestBlendAlpha: D3D12_BLEND_INV_SRC_ALPHA,
BlendOpAlpha: D3D12_BLEND_OP_ADD,
LogicOp: D3D12_LOGIC_OP_NOOP,
RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8,
};
let depth_stencil = Depth::read_only().raw();
let mut rtv_formats = [DXGI_FORMAT_UNKNOWN; 8];
rtv_formats[0] = HDR_FORMAT;
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: com::borrowed(root_sig),
VS: D3D12_SHADER_BYTECODE {
pShaderBytecode: vs.as_ptr() as _,
BytecodeLength: vs.len(),
},
PS: D3D12_SHADER_BYTECODE {
pShaderBytecode: ps.as_ptr() as _,
BytecodeLength: ps.len(),
},
BlendState: blend,
SampleMask: u32::MAX,
RasterizerState: rasterizer,
DepthStencilState: depth_stencil,
InputLayout: D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: input_layout.as_ptr(),
NumElements: input_layout.len() as u32,
},
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 1,
RTVFormats: rtv_formats,
DSVFormat: DXGI_FORMAT_D32_FLOAT,
SampleDesc: DXGI_SAMPLE_DESC {
Count: msaa_samples.max(1),
Quality: 0,
},
..Default::default()
};
unsafe { crate::directx::pso_library::create_graphics(device, &desc) }
.map_err(|e| map_pso_hresult(e.code(), "create raymarch volumetric PSO"))
}
fn compile_volume_volumetric_pso(
device: &ID3D12Device,
root_sig: &ID3D12RootSignature,
programs: &SdfPrograms,
asset_label: &str,
msaa_samples: u32,
hot_reload: bool,
) -> RenderResult<ID3D12PipelineState> {
let (vs, ps) = family_artifacts(
programs,
Family::Volumetric,
Platform::DirectX,
hot_reload,
asset_label,
)?;
create_raymarch_volumetric_pso(device, root_sig, &vs, &ps, msaa_samples)
}
fn create_raymarch_shadow_root_signature(
device: &ID3D12Device,
) -> RenderResult<ID3D12RootSignature> {
use Visibility::{All, Pixel};
RootSig::new()
.cbv(0, All)
.cbv(1, All)
.cbv(2, Pixel)
.cbv(3, All)
.constants::<[u32; 4]>(4, All)
.input_layout()
.build(device, "raymarch shadow root sig")
}
fn create_raymarch_shadow_pso(
device: &ID3D12Device,
root_sig: &ID3D12RootSignature,
vs: &[u8],
ps: &[u8],
) -> RenderResult<ID3D12PipelineState> {
let input_layout = main_input_layout();
GraphicsPso::new(root_sig, vs, ps)
.input_layout(&input_layout)
.depth(DXGI_FORMAT_D32_FLOAT, Depth::write())
.raster(proxy_raster(false, ProxyFaces::Back))
.build(device, "raymarch shadow")
}
fn compile_volume_shadow_pso(
device: &ID3D12Device,
root_sig: &ID3D12RootSignature,
programs: &SdfPrograms,
asset_label: &str,
hot_reload: bool,
) -> RenderResult<ID3D12PipelineState> {
let (vs, ps) = family_artifacts(
programs,
Family::Shadow,
Platform::DirectX,
hot_reload,
asset_label,
)?;
create_raymarch_shadow_pso(device, root_sig, &vs, &ps)
}
fn compile_volume_prepass_pso(
t: &VolumePsoTargets<'_>,
programs: &SdfPrograms,
asset_label: &str,
faces: ProxyFaces,
) -> RenderResult<ID3D12PipelineState> {
let (vs, ps) = face_artifacts(
programs,
Family::Prepass,
faces,
Platform::DirectX,
t.hot_reload,
asset_label,
)?;
let input_layout = main_input_layout();
crate::directx::post::gbuffer::gbuffer_targets(
GraphicsPso::new(t.shadow_root_sig, &vs, &ps).input_layout(&input_layout),
)
.depth(DXGI_FORMAT_D32_FLOAT, Depth::write_inclusive())
.raster(proxy_raster(false, faces))
.build(t.device, "raymarch prepass")
}
pub(in crate::directx) struct VolumePsoTargets<'a> {
pub(in crate::directx) device: &'a ID3D12Device,
pub(in crate::directx) info_queue: Option<&'a ID3D12InfoQueue>,
pub(in crate::directx) root_sig: &'a ID3D12RootSignature,
pub(in crate::directx) shadow_root_sig: &'a ID3D12RootSignature,
pub(in crate::directx) msaa_samples: u32,
pub(in crate::directx) hot_reload: bool,
}
pub(in crate::directx) struct VolumePsos {
pub(in crate::directx) pso: ID3D12PipelineState,
pub(in crate::directx) front_pso: Option<ID3D12PipelineState>,
pub(in crate::directx) shadow_pso: Option<ID3D12PipelineState>,
pub(in crate::directx) prepass_psos: Option<FacePsos>,
}
pub(in crate::directx) fn build_volume_psos(
t: &VolumePsoTargets<'_>,
programs: &SdfPrograms,
flags: VolumeFlags,
label: &str,
) -> RenderResult<VolumePsos> {
let surface = |faces| dump_on_err(t.info_queue, compile_volume_pso(t, programs, label, faces));
let (pso, front_pso) = if flags.volumetric {
let medium = dump_on_err(
t.info_queue,
compile_volume_volumetric_pso(
t.device,
t.root_sig,
programs,
label,
t.msaa_samples,
t.hot_reload,
),
)?;
(medium, None)
} else {
(
surface(ProxyFaces::Back)?,
Some(surface(ProxyFaces::Front)?),
)
};
let shadow_pso = if flags.casts() {
Some(dump_on_err(
t.info_queue,
compile_volume_shadow_pso(t.device, t.shadow_root_sig, programs, label, t.hot_reload),
)?)
} else {
None
};
let prepass = |faces| {
dump_on_err(
t.info_queue,
compile_volume_prepass_pso(t, programs, label, faces),
)
};
let prepass_psos = if flags.volumetric {
None
} else {
Some(FacePsos {
front: prepass(ProxyFaces::Front)?,
back: prepass(ProxyFaces::Back)?,
})
};
Ok(VolumePsos {
pso,
front_pso,
shadow_pso,
prepass_psos,
})
}
fn build_cube_buffers(
alloc: &DeviceAllocator,
) -> RenderResult<(
PooledBuffer,
PooledBuffer,
D3D12_VERTEX_BUFFER_VIEW,
D3D12_INDEX_BUFFER_VIEW,
)> {
#[rustfmt::skip]
let corners: [Vertex; 8] = [
v([-1.0, -1.0, -1.0]),
v([ 1.0, -1.0, -1.0]),
v([ 1.0, 1.0, -1.0]),
v([-1.0, 1.0, -1.0]),
v([-1.0, -1.0, 1.0]),
v([ 1.0, -1.0, 1.0]),
v([ 1.0, 1.0, 1.0]),
v([-1.0, 1.0, 1.0]),
];
#[rustfmt::skip]
let indices: [u16; 36] = [
0, 2, 1, 0, 3, 2,
4, 5, 6, 4, 6, 7,
0, 4, 7, 0, 7, 3,
1, 2, 6, 1, 6, 5,
0, 1, 5, 0, 5, 4,
3, 7, 6, 3, 6, 2,
];
let vb_bytes = std::mem::size_of_val(&corners) as u64;
let ib_bytes = std::mem::size_of_val(&indices) as u64;
let vb = alloc.alloc_buffer(
vb_bytes,
D3D12_HEAP_TYPE_UPLOAD,
D3D12_RESOURCE_STATE_GENERIC_READ,
)?;
let ib = alloc.alloc_buffer(
ib_bytes,
D3D12_HEAP_TYPE_UPLOAD,
D3D12_RESOURCE_STATE_GENERIC_READ,
)?;
unsafe {
let mut p = std::ptr::null_mut::<c_void>();
vb.Map(0, None, Some(&mut p))
.map_err(|e| map_hresult(e.code(), "raymarch cube vb map"))?;
std::ptr::copy_nonoverlapping(
corners.as_ptr() as *const u8,
p as *mut u8,
vb_bytes as usize,
);
vb.Unmap(0, None);
let mut p = std::ptr::null_mut::<c_void>();
ib.Map(0, None, Some(&mut p))
.map_err(|e| map_hresult(e.code(), "raymarch cube ib map"))?;
std::ptr::copy_nonoverlapping(
indices.as_ptr() as *const u8,
p as *mut u8,
ib_bytes as usize,
);
ib.Unmap(0, None);
}
let vbv = D3D12_VERTEX_BUFFER_VIEW {
BufferLocation: com::gpu_va(&vb),
SizeInBytes: vb_bytes as u32,
StrideInBytes: std::mem::size_of::<Vertex>() as u32,
};
let ibv = D3D12_INDEX_BUFFER_VIEW {
BufferLocation: com::gpu_va(&ib),
SizeInBytes: ib_bytes as u32,
Format: DXGI_FORMAT_R16_UINT,
};
Ok((vb, ib, vbv, ibv))
}
fn v(pos: [f32; 3]) -> Vertex {
Vertex {
pos,
normal: [0.0, 0.0, 0.0],
tangent: [0.0, 0.0, 0.0],
color: [0.0, 0.0, 0.0],
uv: [0.0, 0.0],
}
}
fn write_raymarch_srvs(
device: &ID3D12Device,
shadow_resource: Option<&ID3D12Resource>,
irradiance_resource: &ID3D12Resource,
prefilter_resource: &ID3D12Resource,
base_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
descriptor_size: usize,
shadow_layers: u32,
) {
let slot_cpu = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: base_cpu.ptr + i * descriptor_size,
};
if let Some(shadow) = shadow_resource {
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32_FLOAT,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
MostDetailedMip: 0,
MipLevels: 1,
FirstArraySlice: 0,
ArraySize: shadow_layers,
PlaneSlice: 0,
ResourceMinLODClamp: 0.0,
},
},
};
unsafe { device.CreateShaderResourceView(shadow, Some(&desc), slot_cpu(0)) };
}
for (i, res) in [irradiance_resource, prefilter_resource].iter().enumerate() {
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32G32B32A32_FLOAT,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURECUBE,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
TextureCube: D3D12_TEXCUBE_SRV {
MostDetailedMip: 0,
MipLevels: u32::MAX,
ResourceMinLODClamp: 0.0,
},
},
};
unsafe { device.CreateShaderResourceView(*res, Some(&desc), slot_cpu(1 + i)) };
}
}
fn write_scene_color_srv(
device: &ID3D12Device,
scene_resource: &ID3D12Resource,
srv_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
) {
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: HDR_FORMAT,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV {
MostDetailedMip: 0,
MipLevels: 1,
PlaneSlice: 0,
ResourceMinLODClamp: 0.0,
},
},
};
unsafe { device.CreateShaderResourceView(scene_resource, Some(&desc), srv_cpu) };
}
fn write_raymarch_samplers(
device: &ID3D12Device,
base_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
descriptor_size: usize,
) {
let slot_cpu = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: base_cpu.ptr + i * descriptor_size,
};
let shadow = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
ComparisonFunc: shadow_sample_compare(),
MinLOD: 0.0,
MaxLOD: f32::MAX,
..Default::default()
};
unsafe { device.CreateSampler(&shadow, slot_cpu(0)) };
let cube = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MinLOD: 0.0,
MaxLOD: f32::MAX,
..Default::default()
};
unsafe { device.CreateSampler(&cube, slot_cpu(1)) };
let scene = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MinLOD: 0.0,
MaxLOD: f32::MAX,
..Default::default()
};
unsafe { device.CreateSampler(&scene, slot_cpu(2)) };
}
#[derive(Clone, Copy)]
pub(in crate::directx) struct RaymarchDeviceContext<'a> {
pub alloc: &'a DeviceAllocator,
pub info_queue: Option<&'a ID3D12InfoQueue>,
}
#[derive(Clone, Copy)]
pub(in crate::directx) struct RaymarchTargetConfig {
pub width: u32,
pub height: u32,
pub msaa_samples: u32,
}
#[derive(Clone, Copy)]
pub(in crate::directx) struct RaymarchSharedBindings<'a> {
pub shadow_resource: Option<&'a ID3D12Resource>,
pub shadow_layers: u32,
pub irradiance_resource: &'a ID3D12Resource,
pub prefilter_resource: &'a ID3D12Resource,
}
#[derive(Clone, Copy)]
pub(in crate::directx) struct RaymarchDescriptorHandles {
pub srv_base_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
pub srv_base_gpu: SrvSlot,
pub srv_descriptor_size: usize,
pub sampler_base_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
pub sampler_base_gpu: SamplerSlot,
pub sampler_descriptor_size: usize,
}
fn view_ring(alloc: &DeviceAllocator) -> RenderResult<(Vec<PooledBuffer>, Vec<*mut u8>)> {
let view_size = align256(std::mem::size_of::<RaymarchView>() as u64);
let mut buffers: Vec<PooledBuffer> = Vec::with_capacity(FRAMES);
let mut ptrs: Vec<*mut u8> = Vec::with_capacity(FRAMES);
for _ in 0..FRAMES {
let buf = alloc.alloc_buffer(
view_size,
D3D12_HEAP_TYPE_UPLOAD,
D3D12_RESOURCE_STATE_GENERIC_READ,
)?;
let mut p = std::ptr::null_mut::<c_void>();
unsafe { buf.Map(0, None, Some(&mut p)) }
.map_err(|e| map_hresult(e.code(), "raymarch view ubo map"))?;
ptrs.push(p as *mut u8);
buffers.push(buf);
}
Ok((buffers, ptrs))
}
impl RaymarchResources {
pub(in crate::directx) fn try_new(
ctx: RaymarchDeviceContext,
target: RaymarchTargetConfig,
bindings: RaymarchSharedBindings,
handles: RaymarchDescriptorHandles,
sdf_volumes: &[SdfVolumeSource],
hot_reload: bool,
) -> RenderResult<Option<Self>> {
let RaymarchDeviceContext { alloc, info_queue } = ctx;
let device = alloc.device();
let RaymarchTargetConfig {
width,
height,
msaa_samples,
} = target;
let RaymarchSharedBindings {
shadow_resource,
shadow_layers,
irradiance_resource,
prefilter_resource,
} = bindings;
let RaymarchDescriptorHandles {
srv_base_cpu,
srv_base_gpu,
srv_descriptor_size,
sampler_base_cpu,
sampler_base_gpu,
sampler_descriptor_size,
} = handles;
if sdf_volumes.is_empty() {
return Ok(None);
}
let root_sig = dump_on_err(info_queue, create_raymarch_root_signature(device))?;
let shadow_root_sig =
dump_on_err(info_queue, create_raymarch_shadow_root_signature(device))?;
let (cube_vb, cube_ib, cube_vbv, cube_ibv) = build_cube_buffers(alloc)?;
let (view_cbuffers, view_ptrs) = view_ring(alloc)?;
let (prepass_view_cbuffers, prepass_view_ptrs) = view_ring(alloc)?;
let scene_color_fallback = create_fallback_white_resource(alloc)?;
let hdr_resolve_copy = create_hdr_resolve_target(device, width.max(1), height.max(1))?;
let mut volumes: Vec<RaymarchVolumeRecord> = Vec::with_capacity(sdf_volumes.len());
for SdfVolumeSource {
volume: vol,
fragment_source: payload,
label,
} in sdf_volumes
{
let programs = crate::shader::raymarch_source::decode(payload, label)
.map_err(RenderError::Other)?;
let VolumePsos {
pso,
front_pso,
shadow_pso,
prepass_psos,
} = build_volume_psos(
&VolumePsoTargets {
device,
info_queue,
root_sig: &root_sig,
shadow_root_sig: &shadow_root_sig,
msaa_samples,
hot_reload,
},
&programs,
VolumeFlags::of(vol),
label,
)?;
let uniforms = volume_uniforms_from(vol);
let cb_size = align256(std::mem::size_of::<RaymarchVolumeUniforms>() as u64);
let cb = alloc.alloc_buffer(
cb_size,
D3D12_HEAP_TYPE_UPLOAD,
D3D12_RESOURCE_STATE_GENERIC_READ,
)?;
let mut p = std::ptr::null_mut::<c_void>();
unsafe { cb.Map(0, None, Some(&mut p)) }
.map_err(|e| map_hresult(e.code(), "raymarch volume cb map"))?;
unsafe {
std::ptr::copy_nonoverlapping(
&uniforms as *const RaymarchVolumeUniforms as *const u8,
p as *mut u8,
std::mem::size_of::<RaymarchVolumeUniforms>(),
);
}
let gva = com::gpu_va(&cb);
volumes.push(RaymarchVolumeRecord {
label: label.clone(),
pso,
front_pso,
shadow_pso,
prepass_psos,
volume_cbuffer: cb,
volume_cbuffer_gva: gva,
visible: vol.visible,
volumetric: vol.volumetric,
cast_shadows: vol.cast_shadows,
refractive: crate::shader::raymarch_source::taps_scene(&programs),
center: vol.center,
extent: vol.extent,
});
}
write_raymarch_srvs(
device,
shadow_resource,
irradiance_resource,
prefilter_resource,
srv_base_cpu,
srv_descriptor_size,
shadow_layers,
);
let scene_color_srv_cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: srv_base_cpu.ptr + 3 * srv_descriptor_size,
};
write_scene_color_srv(device, &hdr_resolve_copy, scene_color_srv_cpu);
write_raymarch_samplers(device, sampler_base_cpu, sampler_descriptor_size);
Ok(Some(Self {
root_sig,
shadow_root_sig,
cube_vb,
cube_ib,
cube_vbv,
cube_ibv,
view_cbuffers,
view_ptrs,
prepass_view_cbuffers,
prepass_view_ptrs,
scene_color_fallback,
hdr_resolve_copy,
scene_color_srv_cpu,
srv_table_gpu: srv_base_gpu,
sampler_table_gpu: sampler_base_gpu,
volumes,
}))
}
pub(in crate::directx) fn resize_to(
&mut self,
device: &ID3D12Device,
width: u32,
height: u32,
) -> RenderResult<()> {
self.hdr_resolve_copy = create_hdr_resolve_target(device, width.max(1), height.max(1))?;
write_scene_color_srv(device, &self.hdr_resolve_copy, self.scene_color_srv_cpu);
Ok(())
}
pub(in crate::directx) fn any_visible(&self) -> bool {
self.volumes.iter().any(|v| v.visible)
}
fn any_refractive_visible(&self) -> bool {
self.volumes.iter().any(|v| v.visible && v.refractive)
}
}
unsafe impl Send for RaymarchResources {}
unsafe impl Sync for RaymarchResources {}
impl DxContext {
pub(in crate::directx) fn encode_raymarch(
&self,
cmd: &ID3D12GraphicsCommandList,
frame_idx: usize,
view: &RaymarchView,
) -> RenderResult<()> {
let Some(rm) = self.raymarch.as_ref() else {
return Ok(());
};
if !rm.any_visible() {
return Ok(());
}
let view_ptr = rm
.view_ptrs
.get(frame_idx)
.copied()
.ok_or_else(|| RenderError::Other("raymarch: view_ptrs index OOB".to_string()))?;
unsafe {
std::ptr::copy_nonoverlapping(
view as *const RaymarchView as *const u8,
view_ptr,
std::mem::size_of::<RaymarchView>(),
);
}
let view_gva = com::gpu_va(&rm.view_cbuffers[frame_idx]);
let light_gva = com::gpu_va(&self.uniforms.light_ubo_resources[frame_idx]);
let shadow_gva = com::gpu_va(&self.uniforms.shadow_ubo_resources[frame_idx]);
let msaa = self.targets.hdr.resolve.is_some();
if rm.any_refractive_visible() {
let snapshot_src_to_copy = transition_barrier(
self.hdr_scene_target(),
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_COPY_SOURCE,
);
let snapshot_dst_to_copy = transition_barrier(
&rm.hdr_resolve_copy,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
D3D12_RESOURCE_STATE_COPY_DEST,
);
let snapshot_src_back = transition_barrier(
self.hdr_scene_target(),
D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_RENDER_TARGET,
);
let snapshot_dst_to_psr = transition_barrier(
&rm.hdr_resolve_copy,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
);
unsafe {
cmd.ResourceBarrier(&[snapshot_src_to_copy, snapshot_dst_to_copy]);
cmd.CopyResource(&rm.hdr_resolve_copy, self.hdr_scene_target());
cmd.ResourceBarrier(&[snapshot_src_back, snapshot_dst_to_psr]);
}
}
let w = self.targets.extent.render_width;
let h = self.targets.extent.render_height;
unsafe {
cmd.OMSetRenderTargets(
1,
Some(&self.targets.hdr.color_rtv),
false,
Some(&self.targets.depth.dsv),
);
let vp = D3D12_VIEWPORT {
TopLeftX: 0.0,
TopLeftY: 0.0,
Width: w as f32,
Height: h as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
};
cmd.RSSetViewports(&[vp]);
let scissor = windows::Win32::Foundation::RECT {
left: 0,
top: 0,
right: w as i32,
bottom: h as i32,
};
cmd.RSSetScissorRects(&[scissor]);
cmd.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
cmd.IASetVertexBuffers(0, Some(&[rm.cube_vbv]));
cmd.IASetIndexBuffer(Some(&rm.cube_ibv));
cmd.SetGraphicsRootSignature(&rm.root_sig);
cmd.SetDescriptorHeaps(&[
Some(self.descriptors.srv_heap.clone()),
Some(self.descriptors.sampler_heap.clone()),
]);
cmd.SetGraphicsRootConstantBufferView(0, view_gva);
cmd.SetGraphicsRootConstantBufferView(2, light_gva);
cmd.SetGraphicsRootConstantBufferView(3, shadow_gva);
cmd.set_graphics_srv_table(4, rm.srv_table_gpu);
cmd.set_graphics_sampler_table(5, rm.sampler_table_gpu);
}
for vol in &rm.volumes {
if !vol.visible {
continue;
}
unsafe {
cmd.SetPipelineState(vol.draw_pso(view));
cmd.SetGraphicsRootConstantBufferView(1, vol.volume_cbuffer_gva);
cmd.DrawIndexedInstanced(36, 1, 0, 0, 0);
}
self.inc_draw_calls(1);
}
if msaa {
let hdr_color_to_resolve_src = transition_barrier(
&self.targets.hdr.color,
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
);
let resolve_to_dst = transition_barrier(
self.hdr_scene_target(),
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_RESOLVE_DEST,
);
unsafe {
cmd.ResourceBarrier(&[hdr_color_to_resolve_src, resolve_to_dst]);
cmd.ResolveSubresource(
self.hdr_scene_target(),
0,
&self.targets.hdr.color,
0,
HDR_FORMAT,
);
}
let resolve_back = transition_barrier(
self.hdr_scene_target(),
D3D12_RESOURCE_STATE_RESOLVE_DEST,
D3D12_RESOURCE_STATE_RENDER_TARGET,
);
let hdr_color_back_to_rt = transition_barrier(
&self.targets.hdr.color,
D3D12_RESOURCE_STATE_RESOLVE_SOURCE,
D3D12_RESOURCE_STATE_RENDER_TARGET,
);
unsafe { cmd.ResourceBarrier(&[resolve_back, hdr_color_back_to_rt]) };
}
Ok(())
}
}
impl DxContext {
pub(in crate::directx) fn encode_raymarch_prepass(
&self,
cmd: &ID3D12GraphicsCommandList,
frame_idx: usize,
prepass: &GbufferPrepassView,
gbuffer: &GBufferView,
) {
let Some(rm) = self.raymarch.as_ref() else {
return;
};
let surfaces = || {
rm.volumes
.iter()
.filter(|v| v.visible)
.filter_map(|v| v.prepass_psos.as_ref().map(|psos| (v, psos)))
};
if surfaces().next().is_none() {
return;
}
let camera = PassCamera {
vp: prepass.jittered_vp,
inv_vp: mat4_inverse(prepass.jittered_vp),
cam_pos: prepass.cam_pos,
viewport: [
self.targets.extent.render_width as f32,
self.targets.extent.render_height as f32,
],
time: prepass.elapsed,
prefilter_mip_count: self.scene.env_map.prefilter_mip_count as f32,
sky_rot: self.state.view.sky_rot,
};
let view = &RaymarchView::for_gbuffer(&camera, gbuffer);
let draws = surfaces().map(|(v, psos)| (psos.get(v.faces(view)), v.volume_cbuffer_gva));
let (Some(&view_ptr), Some(view_cb), Some(lights), Some(shadow)) = (
rm.prepass_view_ptrs.get(frame_idx),
rm.prepass_view_cbuffers.get(frame_idx),
self.uniforms.light_ubo_resources.get(frame_idx),
self.uniforms.shadow_ubo_resources.get(frame_idx),
) else {
return;
};
unsafe {
std::ptr::copy_nonoverlapping(
view as *const RaymarchView as *const u8,
view_ptr,
std::mem::size_of::<RaymarchView>(),
);
}
unsafe {
cmd.SetGraphicsRootSignature(&rm.shadow_root_sig);
cmd.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
cmd.IASetVertexBuffers(0, Some(&[rm.cube_vbv]));
cmd.IASetIndexBuffer(Some(&rm.cube_ibv));
cmd.SetGraphicsRootConstantBufferView(0, com::gpu_va(view_cb));
cmd.SetGraphicsRootConstantBufferView(2, com::gpu_va(lights));
cmd.SetGraphicsRootConstantBufferView(3, com::gpu_va(shadow));
cmd.set_graphics_root_constants(4, &[0u32; 4]);
}
for (pso, volume_gva) in draws {
unsafe {
cmd.SetPipelineState(pso);
cmd.SetGraphicsRootConstantBufferView(1, volume_gva);
cmd.DrawIndexedInstanced(36, 1, 0, 0, 0);
}
self.inc_draw_calls(1);
}
}
}
impl RaymarchResources {
pub(in crate::directx) fn any_shadow_casters(&self) -> bool {
self.volumes
.iter()
.any(|v| v.visible && v.cast_shadows && v.shadow_pso.is_some())
}
}
impl DxContext {
pub(in crate::directx) fn encode_sdf_shadow_casters(
&self,
cmd: &ID3D12GraphicsCommandList,
frame_idx: usize,
shadow_ubo_gva: u64,
view: &RaymarchView,
) -> RenderResult<()> {
let Some(rm) = self.raymarch.as_ref() else {
return Ok(());
};
if !rm.any_shadow_casters() {
return Ok(());
}
if self.shadow.dsvs.is_empty() {
return Ok(());
}
let view_ptr = rm.view_ptrs.get(frame_idx).copied().ok_or_else(|| {
RenderError::Other("raymarch shadow: view_ptrs index OOB".to_string())
})?;
unsafe {
std::ptr::copy_nonoverlapping(
view as *const RaymarchView as *const u8,
view_ptr,
std::mem::size_of::<RaymarchView>(),
);
}
let view_gva = com::gpu_va(&rm.view_cbuffers[frame_idx]);
let light_gva = com::gpu_va(&self.uniforms.light_ubo_resources[frame_idx]);
let sm = self.shadow.map_size;
unsafe {
cmd.SetGraphicsRootSignature(&rm.shadow_root_sig);
cmd.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
cmd.IASetVertexBuffers(0, Some(&[rm.cube_vbv]));
cmd.IASetIndexBuffer(Some(&rm.cube_ibv));
let vp = D3D12_VIEWPORT {
TopLeftX: 0.0,
TopLeftY: 0.0,
Width: sm as f32,
Height: sm as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
};
cmd.RSSetViewports(&[vp]);
let scissor = windows::Win32::Foundation::RECT {
left: 0,
top: 0,
right: sm as i32,
bottom: sm as i32,
};
cmd.RSSetScissorRects(&[scissor]);
cmd.SetGraphicsRootConstantBufferView(0, view_gva);
cmd.SetGraphicsRootConstantBufferView(2, light_gva);
cmd.SetGraphicsRootConstantBufferView(3, shadow_ubo_gva);
}
let all_cascades = (1u32 << render_types::NUM_SHADOW_CASCADES) - 1;
let render_mask = if self.shadow.render_mask == 0 {
all_cascades
} else {
self.shadow.render_mask
};
for cascade_idx in 0..render_types::NUM_SHADOW_CASCADES {
if render_mask & (1u32 << cascade_idx) == 0 {
continue;
}
let dsv = self.shadow.dsvs[cascade_idx];
unsafe {
cmd.OMSetRenderTargets(0, None, false, Some(&dsv));
let constants = [cascade_idx as u32, 0u32, 0u32, 0u32];
cmd.set_graphics_root_constants(4, &constants);
}
for vol in &rm.volumes {
if !vol.visible || !vol.cast_shadows {
continue;
}
let Some(pso) = vol.shadow_pso.as_ref() else {
continue;
};
unsafe {
cmd.SetPipelineState(pso);
cmd.SetGraphicsRootConstantBufferView(1, vol.volume_cbuffer_gva);
cmd.DrawIndexedInstanced(36, 1, 0, 0, 0);
}
self.inc_draw_calls(1);
}
}
Ok(())
}
}
const _LIGHT_LAYOUT_REF: usize = std::mem::size_of::<LightUniforms>();