758 lines
24 KiB
Rust
758 lines
24 KiB
Rust
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::Mutex;
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
use windows::Win32::Graphics::Direct3D12::*;
|
|
|
|
use crate::host::Host;
|
|
|
|
const TILE_BYTES: u64 = 64 << 10;
|
|
|
|
const CHUNK_TILES: u32 = 256;
|
|
const CHUNK_BYTES: u64 = CHUNK_TILES as u64 * TILE_BYTES;
|
|
|
|
const OVERFLOW_CHUNK_TILES: u32 = 64;
|
|
const MAX_OVERFLOW_TILES: usize = 32;
|
|
|
|
const MAX_SECTION_BYTES: u64 = 2 << 30;
|
|
|
|
static STATS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
|
|
const ST_COUNT: usize = 0;
|
|
const ST_VIRTUAL: usize = 1;
|
|
const ST_PHYSICAL: usize = 2;
|
|
const ST_OVERFLOW: usize = 3;
|
|
const ST_FALLBACK: usize = 4;
|
|
|
|
pub(crate) fn on() -> bool {
|
|
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
|
*ON.get_or_init(|| std::env::var_os("EONACAT_XS_ALIAS_TARGETS").is_some_and(|v| v == "1"))
|
|
}
|
|
|
|
pub(crate) fn allocated_bytes() -> u64 {
|
|
STATS[ST_PHYSICAL].load(Ordering::Relaxed)
|
|
}
|
|
|
|
fn tiers(device: &ID3D12Device) -> (bool, i32) {
|
|
static TIERS: std::sync::OnceLock<(bool, i32)> = std::sync::OnceLock::new();
|
|
*TIERS.get_or_init(|| {
|
|
let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default();
|
|
|
|
let ok = unsafe {
|
|
device.CheckFeatureSupport(
|
|
D3D12_FEATURE_D3D12_OPTIONS,
|
|
(&raw mut opts).cast(),
|
|
std::mem::size_of_val(&opts) as u32,
|
|
)
|
|
}
|
|
.is_ok();
|
|
let heap2 = ok && opts.ResourceHeapTier.0 >= D3D12_RESOURCE_HEAP_TIER_2.0;
|
|
let tiled = if ok { opts.TiledResourcesTier.0 } else { 0 };
|
|
tracing::info!(
|
|
enabled = on(),
|
|
heap_tier = opts.ResourceHeapTier.0,
|
|
tiled_tier = tiled,
|
|
supported = heap2 && tiled >= D3D12_TILED_RESOURCES_TIER_2.0,
|
|
"physical-page transient RT aliasing (EONACAT_XS_ALIAS_TARGETS=0: off)"
|
|
);
|
|
(heap2, tiled)
|
|
})
|
|
}
|
|
|
|
struct HeapChunk {
|
|
heap: ID3D12Heap,
|
|
}
|
|
|
|
unsafe impl Send for HeapChunk {}
|
|
|
|
struct OverflowSlots {
|
|
chunks: usize,
|
|
next_tile: u32,
|
|
free: Vec<(usize, u32)>,
|
|
}
|
|
|
|
impl OverflowSlots {
|
|
fn new() -> Self {
|
|
Self { chunks: 0, next_tile: OVERFLOW_CHUNK_TILES, free: Vec::new() }
|
|
}
|
|
|
|
fn pop_free(&mut self) -> Option<(usize, u32)> {
|
|
self.free.pop()
|
|
}
|
|
|
|
fn needs_chunk(&self) -> bool {
|
|
self.next_tile >= OVERFLOW_CHUNK_TILES
|
|
}
|
|
|
|
fn push_chunk(&mut self) {
|
|
self.chunks += 1;
|
|
self.next_tile = 0;
|
|
}
|
|
|
|
fn take_fresh(&mut self) -> (usize, u32) {
|
|
let tile = self.next_tile;
|
|
self.next_tile += 1;
|
|
(self.chunks - 1, tile)
|
|
}
|
|
|
|
fn release(&mut self, tiles: &mut Vec<(usize, u32)>) {
|
|
self.free.append(tiles);
|
|
}
|
|
}
|
|
|
|
struct OverflowPool {
|
|
heaps: Vec<ID3D12Heap>,
|
|
slots: OverflowSlots,
|
|
}
|
|
|
|
unsafe impl Send for OverflowPool {}
|
|
|
|
pub(crate) struct OverflowLease(Vec<(usize, u32)>);
|
|
|
|
impl Drop for OverflowLease {
|
|
fn drop(&mut self) {
|
|
if !self.0.is_empty() {
|
|
release_overflow_tiles(&mut self.0);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) const WRITE_STATES: u32 = 0x4 | 0x8 | 0x10 | 0x400 | 0x1000;
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub(crate) struct AliasFootprint {
|
|
pub(crate) section: usize,
|
|
pub(crate) ranges: Vec<(u32, u32)>,
|
|
}
|
|
|
|
impl AliasFootprint {
|
|
pub(crate) fn new(section: usize, pages: &[u32]) -> Self {
|
|
let mut sorted = pages.to_vec();
|
|
sorted.sort_unstable();
|
|
sorted.dedup();
|
|
Self { section, ranges: coalesce_runs(&sorted) }
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct OwnerTable {
|
|
sections: HashMap<usize, Vec<u64>>,
|
|
}
|
|
|
|
impl OwnerTable {
|
|
|
|
pub(crate) fn needs_barrier(&self, fp: &AliasFootprint, serial: u64) -> bool {
|
|
let Some(owners) = self.sections.get(&fp.section) else {
|
|
return false;
|
|
};
|
|
for &(start, count) in &fp.ranges {
|
|
let lo = start as usize;
|
|
let hi = lo.saturating_add(count as usize).min(owners.len());
|
|
if lo < hi && owners[lo..hi].iter().any(|&o| o != 0 && o != serial) {
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
pub(crate) fn set_owner(&mut self, fp: &AliasFootprint, serial: u64) {
|
|
let max_end = fp
|
|
.ranges
|
|
.iter()
|
|
.map(|&(s, c)| (s as usize).saturating_add(c as usize))
|
|
.max()
|
|
.unwrap_or(0);
|
|
if max_end == 0 {
|
|
return;
|
|
}
|
|
let owners = self.sections.entry(fp.section).or_default();
|
|
if owners.len() < max_end {
|
|
owners.resize(max_end, 0);
|
|
}
|
|
for &(start, count) in &fp.ranges {
|
|
let lo = start as usize;
|
|
let hi = lo.saturating_add(count as usize);
|
|
owners[lo..hi].fill(serial);
|
|
}
|
|
}
|
|
|
|
pub(crate) fn section_gone(&mut self, section: usize) {
|
|
self.sections.remove(§ion);
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
struct Span {
|
|
section: usize,
|
|
start: u32,
|
|
end: u32,
|
|
serial: u64,
|
|
}
|
|
|
|
struct FirstWrite<T> {
|
|
serial: u64,
|
|
footprint: AliasFootprint,
|
|
handle: T,
|
|
}
|
|
|
|
struct FinalWrite {
|
|
serial: u64,
|
|
footprint: AliasFootprint,
|
|
}
|
|
|
|
pub(crate) struct ListAliasTracker<T = std::sync::Arc<crate::resource::HostTexture>> {
|
|
touched: Vec<Span>,
|
|
prelude_candidates: Vec<FirstWrite<T>>,
|
|
writes: Vec<FinalWrite>,
|
|
}
|
|
|
|
impl<T> Default for ListAliasTracker<T> {
|
|
fn default() -> Self {
|
|
Self { touched: Vec::new(), prelude_candidates: Vec::new(), writes: Vec::new() }
|
|
}
|
|
}
|
|
|
|
impl<T: Clone> ListAliasTracker<T> {
|
|
pub(crate) fn clear(&mut self) {
|
|
self.touched.clear();
|
|
self.prelude_candidates.clear();
|
|
self.writes.clear();
|
|
}
|
|
|
|
pub(crate) fn has_writes(&self) -> bool {
|
|
!self.writes.is_empty() || !self.prelude_candidates.is_empty()
|
|
}
|
|
|
|
pub(crate) fn record_touch(
|
|
&mut self,
|
|
serial: u64,
|
|
handle: &T,
|
|
fp: &AliasFootprint,
|
|
wanted_state: u32,
|
|
) -> bool {
|
|
let is_write = wanted_state & WRITE_STATES != 0;
|
|
let (mut had_other, mut had_same) = (false, false);
|
|
for &(start, count) in &fp.ranges {
|
|
if count == 0 {
|
|
continue;
|
|
}
|
|
let end = start.saturating_add(count);
|
|
for s in &self.touched {
|
|
if s.section < fp.section {
|
|
continue;
|
|
}
|
|
if s.section > fp.section || s.start >= end {
|
|
break;
|
|
}
|
|
if s.end > start {
|
|
if s.serial == serial {
|
|
had_same = true;
|
|
} else {
|
|
had_other = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for &(start, count) in &fp.ranges {
|
|
insert_range(&mut self.touched, fp.section, start, start.saturating_add(count), serial);
|
|
}
|
|
if !is_write {
|
|
return false;
|
|
}
|
|
if self.writes.last().is_none_or(|w| w.serial != serial) {
|
|
self.writes.push(FinalWrite { serial, footprint: fp.clone() });
|
|
}
|
|
if had_other {
|
|
return true;
|
|
}
|
|
if !had_same {
|
|
self.prelude_candidates.push(FirstWrite {
|
|
serial,
|
|
footprint: fp.clone(),
|
|
handle: handle.clone(),
|
|
});
|
|
}
|
|
false
|
|
}
|
|
|
|
pub(crate) fn resolve_prelude(&self, owners: &mut OwnerTable) -> Vec<T> {
|
|
let mut need = Vec::new();
|
|
for cand in &self.prelude_candidates {
|
|
if owners.needs_barrier(&cand.footprint, cand.serial) {
|
|
need.push(cand.handle.clone());
|
|
}
|
|
}
|
|
for w in &self.writes {
|
|
owners.set_owner(&w.footprint, w.serial);
|
|
}
|
|
need
|
|
}
|
|
}
|
|
|
|
fn insert_range(spans: &mut Vec<Span>, section: usize, start: u32, end: u32, serial: u64) {
|
|
if start >= end {
|
|
return;
|
|
}
|
|
let mut out = Vec::with_capacity(spans.len() + 2);
|
|
let mut inserted = false;
|
|
for &s in spans.iter() {
|
|
if s.section < section || (s.section == section && s.end <= start) {
|
|
out.push(s);
|
|
continue;
|
|
}
|
|
if !inserted && (s.section > section || s.start >= end) {
|
|
out.push(Span { section, start, end, serial });
|
|
inserted = true;
|
|
}
|
|
if s.section > section || s.start >= end {
|
|
out.push(s);
|
|
continue;
|
|
}
|
|
if s.start < start {
|
|
out.push(Span { section, start: s.start, end: start, serial: s.serial });
|
|
}
|
|
if !inserted {
|
|
out.push(Span { section, start, end, serial });
|
|
inserted = true;
|
|
}
|
|
if s.end > end {
|
|
out.push(Span { section, start: end, end: s.end, serial: s.serial });
|
|
}
|
|
}
|
|
if !inserted {
|
|
out.push(Span { section, start, end, serial });
|
|
}
|
|
spans.clear();
|
|
for s in out {
|
|
match spans.last_mut() {
|
|
Some(last)
|
|
if last.section == s.section && last.end == s.start && last.serial == s.serial =>
|
|
{
|
|
last.end = s.end;
|
|
}
|
|
_ => spans.push(s),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) fn aliasing_barrier(texture: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER {
|
|
D3D12_RESOURCE_BARRIER {
|
|
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
|
|
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
|
|
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
|
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
|
|
pResourceBefore: std::mem::ManuallyDrop::new(None),
|
|
|
|
pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
|
|
}),
|
|
},
|
|
}
|
|
}
|
|
|
|
pub(crate) fn resolve_prelude(
|
|
tracker: &ListAliasTracker,
|
|
) -> Vec<std::sync::Arc<crate::resource::HostTexture>> {
|
|
if !tracker.has_writes() {
|
|
return Vec::new();
|
|
}
|
|
let mut st = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
|
tracker.resolve_prelude(&mut st.owners)
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct State {
|
|
|
|
sections: HashMap<usize, HashMap<u32, HeapChunk>>,
|
|
overflow: Option<OverflowPool>,
|
|
owners: OwnerTable,
|
|
}
|
|
|
|
static STATE: std::sync::LazyLock<Mutex<State>> = std::sync::LazyLock::new(Default::default);
|
|
|
|
pub(crate) fn section_gone(section: usize) {
|
|
let removed = {
|
|
let mut st = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
|
st.owners.section_gone(section);
|
|
st.sections.remove(§ion)
|
|
};
|
|
if let Some(chunks) = removed {
|
|
let bytes = chunks.len() as u64 * CHUNK_BYTES;
|
|
STATS[ST_PHYSICAL].fetch_sub(bytes, Ordering::Relaxed);
|
|
drop(chunks);
|
|
}
|
|
}
|
|
|
|
fn create_tier2_heap(device: &ID3D12Device, size: u64) -> Option<ID3D12Heap> {
|
|
let desc = D3D12_HEAP_DESC {
|
|
SizeInBytes: size,
|
|
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
|
|
Alignment: 0,
|
|
|
|
Flags: D3D12_HEAP_FLAG_NONE | crate::host::not_resident(),
|
|
};
|
|
let mut heap: Option<ID3D12Heap> = None;
|
|
|
|
if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
|
|
crate::residency::allocation_error(&e);
|
|
tracing::warn!(error = %e, size_mb = size >> 20, "alias_rt: failed to create Tier-2 heap chunk");
|
|
return None;
|
|
}
|
|
let heap = heap?;
|
|
|
|
crate::host::prioritise_target_heap(device, &heap);
|
|
if let Err(e) = crate::host::resident(device, &heap).and_then(|()| crate::host::mapped(device)) {
|
|
tracing::warn!(error = %e, "alias_rt: heap chunk failed residency");
|
|
return None;
|
|
}
|
|
crate::host::name(&heap, || format!("aliased RT physical chunk ({} MiB)", size >> 20));
|
|
Some(heap)
|
|
}
|
|
|
|
fn ensure_chunks(
|
|
device: &ID3D12Device,
|
|
section: usize,
|
|
pages: &[u32],
|
|
) -> Option<HashMap<u32, ID3D12Heap>> {
|
|
let mut needed: Vec<u32> = pages.iter().map(|&p| p / CHUNK_TILES).collect();
|
|
needed.sort_unstable();
|
|
needed.dedup();
|
|
let mut out = HashMap::with_capacity(needed.len());
|
|
let mut missing = Vec::new();
|
|
{
|
|
let st = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
|
if let Some(sec) = st.sections.get(§ion) {
|
|
for &c in &needed {
|
|
if let Some(chunk) = sec.get(&c) {
|
|
out.insert(c, chunk.heap.clone());
|
|
} else {
|
|
missing.push(c);
|
|
}
|
|
}
|
|
} else {
|
|
missing = needed;
|
|
}
|
|
}
|
|
if missing.is_empty() {
|
|
return Some(out);
|
|
}
|
|
|
|
let mut created = Vec::with_capacity(missing.len());
|
|
for c in missing {
|
|
let heap = create_tier2_heap(device, CHUNK_BYTES)?;
|
|
created.push((c, heap));
|
|
}
|
|
let mut st = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
|
let sec = st.sections.entry(section).or_default();
|
|
let mut added_bytes = 0u64;
|
|
for (c, heap) in created {
|
|
if let Some(existing) = sec.get(&c) {
|
|
out.insert(c, existing.heap.clone());
|
|
} else {
|
|
out.insert(c, heap.clone());
|
|
sec.insert(c, HeapChunk { heap });
|
|
added_bytes += CHUNK_BYTES;
|
|
}
|
|
}
|
|
drop(st);
|
|
if added_bytes > 0 {
|
|
STATS[ST_PHYSICAL].fetch_add(added_bytes, Ordering::Relaxed);
|
|
}
|
|
Some(out)
|
|
}
|
|
|
|
fn release_overflow_tiles(tiles: &mut Vec<(usize, u32)>) {
|
|
let mut st = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
|
if let Some(pool) = st.overflow.as_mut() {
|
|
let count = tiles.len() as u64;
|
|
pool.slots.release(tiles);
|
|
STATS[ST_OVERFLOW].fetch_sub(count, Ordering::Relaxed);
|
|
}
|
|
}
|
|
|
|
fn take_overflow_tiles(device: &ID3D12Device, count: usize) -> Option<(Vec<(usize, ID3D12Heap, u32)>, OverflowLease)> {
|
|
if count == 0 {
|
|
return Some((Vec::new(), OverflowLease(Vec::new())));
|
|
}
|
|
let mut out = Vec::with_capacity(count);
|
|
let mut leased = Vec::with_capacity(count);
|
|
{
|
|
let mut st = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
|
let pool = st.overflow.get_or_insert_with(|| OverflowPool {
|
|
heaps: Vec::new(),
|
|
slots: OverflowSlots::new(),
|
|
});
|
|
for _ in 0..count {
|
|
let (heap_idx, tile) = if let Some(reused) = pool.slots.pop_free() {
|
|
reused
|
|
} else {
|
|
if pool.slots.needs_chunk() {
|
|
let Some(heap) = create_tier2_heap(device, u64::from(OVERFLOW_CHUNK_TILES) * TILE_BYTES) else {
|
|
pool.slots.release(&mut leased);
|
|
return None;
|
|
};
|
|
STATS[ST_PHYSICAL].fetch_add(u64::from(OVERFLOW_CHUNK_TILES) * TILE_BYTES, Ordering::Relaxed);
|
|
pool.heaps.push(heap);
|
|
pool.slots.push_chunk();
|
|
}
|
|
pool.slots.take_fresh()
|
|
};
|
|
let heap = pool.heaps[heap_idx].clone();
|
|
out.push((heap_idx, heap, tile));
|
|
leased.push((heap_idx, tile));
|
|
}
|
|
}
|
|
STATS[ST_OVERFLOW].fetch_add(count as u64, Ordering::Relaxed);
|
|
Some((out, OverflowLease(leased)))
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct TileTarget {
|
|
heap_key: usize,
|
|
heap: ID3D12Heap,
|
|
tile: u32,
|
|
}
|
|
|
|
fn coalesce_runs(tiles: &[u32]) -> Vec<(u32, u32)> {
|
|
let mut runs: Vec<(u32, u32)> = Vec::new();
|
|
for &t in tiles {
|
|
match runs.last_mut() {
|
|
Some(last) if last.0 + last.1 == t => last.1 += 1,
|
|
_ => runs.push((t, 1)),
|
|
}
|
|
}
|
|
runs
|
|
}
|
|
|
|
pub(crate) fn try_create(
|
|
host: &Host,
|
|
desc: &D3D12_RESOURCE_DESC,
|
|
state: D3D12_RESOURCE_STATES,
|
|
clear: Option<&D3D12_CLEAR_VALUE>,
|
|
address: usize,
|
|
xbox_bytes: u64,
|
|
) -> Option<(ID3D12Resource, AliasFootprint, OverflowLease)> {
|
|
if !on() || address == 0 || xbox_bytes < TILE_BYTES || desc.SampleDesc.Count > 1 {
|
|
return None;
|
|
}
|
|
let (heap2, tiled_tier) = tiers(&host.device);
|
|
if !heap2 || tiled_tier < D3D12_TILED_RESOURCES_TIER_2.0 {
|
|
return None;
|
|
}
|
|
match desc.Dimension {
|
|
D3D12_RESOURCE_DIMENSION_TEXTURE2D => {}
|
|
D3D12_RESOURCE_DIMENSION_TEXTURE3D if tiled_tier >= D3D12_TILED_RESOURCES_TIER_3.0 => {}
|
|
_ => return None,
|
|
}
|
|
let (section, section_bytes, pages) = crate::inplace::aliased_section_pages(address, xbox_bytes as usize)?;
|
|
if section_bytes == 0 || section_bytes > MAX_SECTION_BYTES || pages.is_empty() {
|
|
return None;
|
|
}
|
|
let mut d = *desc;
|
|
d.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
|
|
d.Alignment = 0;
|
|
let mut texture: Option<ID3D12Resource> = None;
|
|
|
|
let made = unsafe {
|
|
host.device.CreateReservedResource(
|
|
&d,
|
|
state,
|
|
clear.map(|c| c as *const D3D12_CLEAR_VALUE),
|
|
&mut texture,
|
|
)
|
|
};
|
|
if made.is_err() {
|
|
STATS[ST_FALLBACK].fetch_add(1, Ordering::Relaxed);
|
|
return None;
|
|
}
|
|
let texture = texture?;
|
|
|
|
let subresource_count = u32::from(d.MipLevels.max(1))
|
|
* if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { u32::from(d.DepthOrArraySize.max(1)) };
|
|
let mut total_tiles = 0u32;
|
|
let mut packed = D3D12_PACKED_MIP_INFO::default();
|
|
let mut tile_shape = D3D12_TILE_SHAPE::default();
|
|
let mut num_sub = subresource_count;
|
|
let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); subresource_count as usize];
|
|
|
|
unsafe {
|
|
host.device.GetResourceTiling(
|
|
&texture,
|
|
Some(&mut total_tiles),
|
|
Some(&mut packed),
|
|
Some(&mut tile_shape),
|
|
Some(&mut num_sub),
|
|
0,
|
|
tilings.as_mut_ptr(),
|
|
);
|
|
}
|
|
if total_tiles == 0 {
|
|
STATS[ST_FALLBACK].fetch_add(1, Ordering::Relaxed);
|
|
return None;
|
|
}
|
|
let total = total_tiles as usize;
|
|
let overflow_needed = total.saturating_sub(pages.len());
|
|
if overflow_needed > MAX_OVERFLOW_TILES {
|
|
STATS[ST_FALLBACK].fetch_add(1, Ordering::Relaxed);
|
|
tracing::debug!(
|
|
total_tiles,
|
|
xbox_pages = pages.len(),
|
|
width = d.Width,
|
|
height = d.Height,
|
|
format = d.Format.0,
|
|
"alias_rt: tile count exceeds xbox pages by >32, falling back to committed"
|
|
);
|
|
return None;
|
|
}
|
|
let chunks = ensure_chunks(&host.device, section, &pages[..total.min(pages.len())])?;
|
|
let (overflow, overflow_lease) = take_overflow_tiles(&host.device, overflow_needed)?;
|
|
let mut targets: Vec<TileTarget> = Vec::with_capacity(total);
|
|
for &p in &pages[..total.min(pages.len())] {
|
|
let c = p / CHUNK_TILES;
|
|
let h = chunks.get(&c)?;
|
|
targets.push(TileTarget { heap_key: c as usize, heap: h.clone(), tile: p % CHUNK_TILES });
|
|
}
|
|
for (heap_idx, h, tile) in overflow {
|
|
let key = usize::MAX - heap_idx - 1;
|
|
targets.push(TileTarget { heap_key: key, heap: h, tile });
|
|
}
|
|
|
|
struct SubPlan {
|
|
subresource: u32,
|
|
w: u32,
|
|
h: u32,
|
|
packed: bool,
|
|
start_tile: usize,
|
|
count: usize,
|
|
}
|
|
let mut plans: Vec<SubPlan> = Vec::new();
|
|
let mut cursor = 0usize;
|
|
let mips = u32::from(d.MipLevels.max(1));
|
|
let slices = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { u32::from(d.DepthOrArraySize.max(1)) };
|
|
let std_mips = u32::from(packed.NumStandardMips);
|
|
for slice in 0..slices {
|
|
for mip in 0..std_mips.min(mips) {
|
|
let sub = slice * mips + mip;
|
|
let t = tilings.get(sub as usize)?;
|
|
let cnt = (t.WidthInTiles * u32::from(t.HeightInTiles) * u32::from(t.DepthInTiles)) as usize;
|
|
if cnt > 0 && t.StartTileIndexInOverallResource != D3D12_PACKED_TILE {
|
|
let start = t.StartTileIndexInOverallResource as usize;
|
|
if start + cnt > total {
|
|
return None;
|
|
}
|
|
plans.push(SubPlan {
|
|
subresource: sub,
|
|
w: t.WidthInTiles.max(1),
|
|
h: u32::from(t.HeightInTiles).max(1),
|
|
packed: false,
|
|
start_tile: start,
|
|
count: cnt,
|
|
});
|
|
cursor = cursor.max(start + cnt);
|
|
}
|
|
}
|
|
if packed.NumTilesForPackedMips > 0 && std_mips < mips {
|
|
let sub = slice * mips + std_mips;
|
|
let cnt = packed.NumTilesForPackedMips as usize;
|
|
|
|
let start = if slices == 1 {
|
|
packed.StartTileIndexInOverallResource as usize
|
|
} else {
|
|
cursor
|
|
};
|
|
if start + cnt > total {
|
|
return None;
|
|
}
|
|
plans.push(SubPlan {
|
|
subresource: sub,
|
|
w: cnt as u32,
|
|
h: 1,
|
|
packed: true,
|
|
start_tile: start,
|
|
count: cnt,
|
|
});
|
|
cursor = cursor.max(start + cnt);
|
|
}
|
|
}
|
|
if plans.is_empty() {
|
|
return None;
|
|
}
|
|
|
|
let mapped = crate::host::with_copy_queue_sync(&host.device, |queue| {
|
|
for plan in &plans {
|
|
let mut off = 0usize;
|
|
while off < plan.count {
|
|
let first = &targets[plan.start_tile + off];
|
|
let key = first.heap_key;
|
|
let mut span = 1usize;
|
|
while off + span < plan.count && targets[plan.start_tile + off + span].heap_key == key {
|
|
span += 1;
|
|
}
|
|
let tile_indices: Vec<u32> = (0..span).map(|k| targets[plan.start_tile + off + k].tile).collect();
|
|
let runs = coalesce_runs(&tile_indices);
|
|
let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; runs.len()];
|
|
let starts: Vec<u32> = runs.iter().map(|r| r.0).collect();
|
|
let counts: Vec<u32> = runs.iter().map(|r| r.1).collect();
|
|
let (x, y, z) = if plan.packed {
|
|
(off as u32, 0, 0)
|
|
} else {
|
|
let o = off as u32;
|
|
let wh = plan.w * plan.h;
|
|
(o % plan.w, (o / plan.w) % plan.h, o / wh)
|
|
};
|
|
let coord = D3D12_TILED_RESOURCE_COORDINATE {
|
|
X: x,
|
|
Y: y,
|
|
Z: z,
|
|
Subresource: plan.subresource,
|
|
};
|
|
let region = D3D12_TILE_REGION_SIZE {
|
|
NumTiles: span as u32,
|
|
UseBox: false.into(),
|
|
..Default::default()
|
|
};
|
|
|
|
unsafe {
|
|
queue.UpdateTileMappings(
|
|
&texture,
|
|
1,
|
|
Some(&raw const coord),
|
|
Some(&raw const region),
|
|
&first.heap,
|
|
runs.len() as u32,
|
|
Some(flags.as_ptr()),
|
|
Some(starts.as_ptr()),
|
|
Some(counts.as_ptr()),
|
|
D3D12_TILE_MAPPING_FLAG_NONE,
|
|
);
|
|
}
|
|
off += span;
|
|
}
|
|
}
|
|
});
|
|
if let Err(e) = mapped {
|
|
tracing::warn!(error = %e, "alias_rt: UpdateTileMappings failed, falling back to committed");
|
|
STATS[ST_FALLBACK].fetch_add(1, Ordering::Relaxed);
|
|
return None;
|
|
}
|
|
|
|
let n = STATS[ST_COUNT].fetch_add(1, Ordering::Relaxed) + 1;
|
|
let virt = STATS[ST_VIRTUAL].fetch_add(u64::from(total_tiles) * TILE_BYTES, Ordering::Relaxed)
|
|
+ u64::from(total_tiles) * TILE_BYTES;
|
|
let phys = STATS[ST_PHYSICAL].load(Ordering::Relaxed);
|
|
if n == 1 || n.is_power_of_two() || n.is_multiple_of(50) {
|
|
tracing::info!(
|
|
aliased_rts = n,
|
|
virtual_mb = virt >> 20,
|
|
physical_mb = phys >> 20,
|
|
saved_mb = virt.saturating_sub(phys) >> 20,
|
|
overflow_tiles = STATS[ST_OVERFLOW].load(Ordering::Relaxed),
|
|
fallbacks = STATS[ST_FALLBACK].load(Ordering::Relaxed),
|
|
"physical-page transient RT aliasing active"
|
|
);
|
|
}
|
|
let footprint = AliasFootprint::new(section, &pages[..total.min(pages.len())]);
|
|
Some((texture, footprint, overflow_lease))
|
|
}
|
|
|