use super::SceneError;
use crate::content::identity::{DecalImageId, Identity};
use crate::content::static_lighting::{half_value, irradiance_half};
const MIPS: u32 = 5;
const BORDER: u32 = 1 << MIPS;
const TEXEL_BYTES: usize = 8;
#[cfg(target_arch = "wasm32")]
const MAX_BUILD_BYTES: u64 = 2 << 30;
#[cfg(not(target_arch = "wasm32"))]
const MAX_BUILD_BYTES: u64 = 8 << 30;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Sampling {
Color,
Data,
}
pub(crate) type AtlasKey = (DecalImageId, Sampling);
pub(crate) struct AtlasLayout {
size: [u32; 2],
places: Vec<(AtlasKey, [u32; 2], [u32; 2])>,
}
impl AtlasLayout {
fn empty() -> Self {
Self {
size: [1, 1],
places: Vec::new(),
}
}
pub fn place(images: &[(AtlasKey, [u32; 2])], limit: u32) -> Result<Self, SceneError> {
if images.is_empty() {
return Ok(Self::empty());
}
if images
.iter()
.any(|(_, size)| size.iter().any(|side| side.saturating_add(BORDER) > limit))
{
return Err(SceneError::DeviceLimit);
}
let mut items: Vec<Item> = images
.iter()
.map(|&(key, size)| Item::new(key, size))
.collect();
let size = place(&mut items);
if size[0] > limit
|| size[1] > limit
|| build_bytes(size).is_none_or(|bytes| bytes > MAX_BUILD_BYTES)
{
return Err(SceneError::DeviceLimit);
}
Ok(Self {
size,
places: items
.iter()
.map(|item| {
let corner = item.position.map(|cell| cell * BORDER + BORDER / 2);
(item.key, corner, item.pixel_size)
})
.collect(),
})
}
pub fn rect(&self, key: AtlasKey) -> Option<[f32; 4]> {
let &(_, corner, pixel_size) = self.places.iter().find(|(place, ..)| *place == key)?;
let [width, height] = self.size.map(|side| side as f32);
Some([
corner[0] as f32 / width,
corner[1] as f32 / height,
pixel_size[0] as f32 / width,
pixel_size[1] as f32 / height,
])
}
}
pub(crate) struct DecalAtlas {
pub view: wgpu::TextureView,
pub layout: AtlasLayout,
}
struct Item {
key: AtlasKey,
pixel_size: [u32; 2],
size: [u32; 2],
position: [u32; 2],
}
impl Item {
fn new(key: AtlasKey, pixel_size: [u32; 2]) -> Self {
Self {
key,
pixel_size,
size: pixel_size.map(|side| side.div_ceil(BORDER) + 1),
position: [0; 2],
}
}
}
impl DecalAtlas {
pub fn empty(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
Self {
view: upload(device, queue, [1, 1], &[vec![0; TEXEL_BYTES]]),
layout: AtlasLayout::empty(),
}
}
pub fn fill<'a>(
device: &wgpu::Device,
queue: &wgpu::Queue,
layout: AtlasLayout,
texels: impl Fn(AtlasKey) -> Option<&'a image::RgbaImage>,
) -> Self {
let size = layout.size;
let width = size[0] as usize;
let mut level = vec![0u8; width * size[1] as usize * TEXEL_BYTES];
for &(key, corner, _) in &layout.places {
let Some(image) = texels(key) else {
continue;
};
let color = key.1 == Sampling::Color;
for (x, y, texel) in image.enumerate_pixels() {
let at =
((corner[1] + y) as usize * width + (corner[0] + x) as usize) * TEXEL_BYTES;
for channel in 0..4 {
let value = f32::from(texel[channel]) / 255.;
let value = if color && channel < 3 {
crate::shading::srgb::to_linear(value)
} else {
value
};
level[at + channel * 2..][..2]
.copy_from_slice(&irradiance_half(value).to_le_bytes());
}
}
}
let mut levels = vec![level];
if !layout.places.is_empty() {
for mip in 1..MIPS {
let [width, height] = size.map(|side| (side >> (mip - 1)) as usize);
let previous = levels.last().unwrap();
let texel = |x: usize, y: usize, channel: usize| {
let at = (y * width + x) * TEXEL_BYTES + channel * 2;
half_value(u16::from_le_bytes([previous[at], previous[at + 1]]))
};
let mut halved = Vec::with_capacity(width / 2 * (height / 2) * TEXEL_BYTES);
for y in (0..height).step_by(2) {
for x in (0..width).step_by(2) {
for channel in 0..4 {
let mean = (texel(x, y, channel)
+ texel(x + 1, y, channel)
+ texel(x, y + 1, channel)
+ texel(x + 1, y + 1, channel))
/ 4.;
halved.extend_from_slice(&irradiance_half(mean).to_le_bytes());
}
}
}
levels.push(halved);
}
}
Self {
view: upload(device, queue, size, &levels),
layout,
}
}
}
fn place(items: &mut [Item]) -> [u32; 2] {
items.sort_by_key(|item| {
let (image, sampling) = item.key;
(
std::cmp::Reverse(item.size[1]),
std::cmp::Reverse(item.size[0]),
image.index(),
image.generation(),
sampling == Sampling::Data,
)
});
let mut base_size = items
.iter()
.map(|item| item.size[0].next_power_of_two())
.fold(8, u32::max);
let atlas_height = loop {
let mut offsets = vec![0u32; base_size as usize];
let mut max_height = 2;
for item in items.iter_mut() {
let [width, height] = item.size;
let (mut best_index, mut best_height) = (0, u32::MAX);
for start in 0..=base_size - width {
let mut lowest = 0;
for &offset in &offsets[start as usize..(start + width) as usize] {
lowest = lowest.max(offset);
if lowest > best_height {
break;
}
}
if lowest < best_height {
best_height = lowest;
best_index = start;
}
}
for offset in &mut offsets[best_index as usize..(best_index + width) as usize] {
*offset = best_height + height;
}
item.position = [best_index, best_height];
max_height = max_height.max(best_height + height);
}
if max_height <= base_size * 2 {
break max_height;
}
base_size *= 2;
};
[
base_size * BORDER,
(atlas_height * BORDER).next_power_of_two(),
]
}
fn build_bytes(size: [u32; 2]) -> Option<u64> {
(0..MIPS).try_fold(0u64, |sum, mip| {
let [width, height] = size.map(|side| u64::from(side >> mip));
width
.checked_mul(height)?
.checked_mul(TEXEL_BYTES as u64)?
.checked_add(sum)
})
}
fn upload(
device: &wgpu::Device,
queue: &wgpu::Queue,
size: [u32; 2],
levels: &[Vec<u8>],
) -> wgpu::TextureView {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("decal atlas"),
size: wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: levels.len() as u32,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
for (mip, bytes) in levels.iter().enumerate() {
let [width, height] = size.map(|side| (side >> mip).max(1));
crate::counters::write_texture(
queue,
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: mip as u32,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width * TEXEL_BYTES as u32),
rows_per_image: Some(height),
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
}
texture.create_view(&Default::default())
}
#[cfg(test)]
mod tests;